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 Status &rhs) = default;
51 
52 Status::Status(const char *format, ...)
53     : m_code(0), m_type(eErrorTypeInvalid), m_string() {
54   va_list args;
55   va_start(args, format);
56   SetErrorToGenericError();
57   SetErrorStringWithVarArg(format, args);
58   va_end(args);
59 }
60 
61 const Status &Status::operator=(llvm::Error error) {
62   if (!error) {
63     Clear();
64     return *this;
65   }
66 
67   // if the error happens to be a errno error, preserve the error code
68   error = llvm::handleErrors(
69       std::move(error), [&](std::unique_ptr<llvm::ECError> e) -> llvm::Error {
70         std::error_code ec = e->convertToErrorCode();
71         if (ec.category() == std::generic_category()) {
72           m_code = ec.value();
73           m_type = ErrorType::eErrorTypePOSIX;
74           return llvm::Error::success();
75         }
76         return llvm::Error(std::move(e));
77       });
78 
79   // Otherwise, just preserve the message
80   if (error) {
81     SetErrorToGenericError();
82     SetErrorString(llvm::toString(std::move(error)));
83   }
84 
85   return *this;
86 }
87 
88 llvm::Error Status::ToError() const {
89   if (Success())
90     return llvm::Error::success();
91   if (m_type == ErrorType::eErrorTypePOSIX)
92     return llvm::errorCodeToError(
93         std::error_code(m_code, std::generic_category()));
94   return llvm::make_error<llvm::StringError>(AsCString(),
95                                              llvm::inconvertibleErrorCode());
96 }
97 
98 //----------------------------------------------------------------------
99 // Assignment operator
100 //----------------------------------------------------------------------
101 const Status &Status::operator=(const Status &rhs) {
102   if (this != &rhs) {
103     m_code = rhs.m_code;
104     m_type = rhs.m_type;
105     m_string = rhs.m_string;
106   }
107   return *this;
108 }
109 
110 Status::~Status() = default;
111 
112 #ifdef _WIN32
113 static std::string RetrieveWin32ErrorString(uint32_t error_code) {
114   char *buffer = nullptr;
115   std::string message;
116   // Retrieve win32 system error.
117   if (::FormatMessageA(
118           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
119               FORMAT_MESSAGE_MAX_WIDTH_MASK,
120           NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
121           (LPSTR)&buffer, 0, NULL)) {
122     message.assign(buffer);
123     ::LocalFree(buffer);
124   }
125   return message;
126 }
127 #endif
128 
129 //----------------------------------------------------------------------
130 // Get the error value as a NULL C string. The error string will be fetched and
131 // cached on demand. The cached error string value will remain until the error
132 // value is changed or cleared.
133 //----------------------------------------------------------------------
134 const char *Status::AsCString(const char *default_error_str) const {
135   if (Success())
136     return nullptr;
137 
138   if (m_string.empty()) {
139     switch (m_type) {
140     case eErrorTypeMachKernel:
141 #if defined(__APPLE__)
142       if (const char *s = ::mach_error_string(m_code))
143         m_string.assign(s);
144 #endif
145       break;
146 
147     case eErrorTypePOSIX:
148       m_string = llvm::sys::StrError(m_code);
149       break;
150 
151     case eErrorTypeWin32:
152 #if defined(_WIN32)
153       m_string = RetrieveWin32ErrorString(m_code);
154 #endif
155       break;
156 
157     default:
158       break;
159     }
160   }
161   if (m_string.empty()) {
162     if (default_error_str)
163       m_string.assign(default_error_str);
164     else
165       return nullptr; // User wanted a nullptr string back...
166   }
167   return m_string.c_str();
168 }
169 
170 //----------------------------------------------------------------------
171 // Clear the error and any cached error string that it might contain.
172 //----------------------------------------------------------------------
173 void Status::Clear() {
174   m_code = 0;
175   m_type = eErrorTypeInvalid;
176   m_string.clear();
177 }
178 
179 //----------------------------------------------------------------------
180 // Access the error value.
181 //----------------------------------------------------------------------
182 Status::ValueType Status::GetError() const { return m_code; }
183 
184 //----------------------------------------------------------------------
185 // Access the error type.
186 //----------------------------------------------------------------------
187 ErrorType Status::GetType() const { return m_type; }
188 
189 //----------------------------------------------------------------------
190 // Returns true if this object contains a value that describes an error or
191 // otherwise non-success result.
192 //----------------------------------------------------------------------
193 bool Status::Fail() const { return m_code != 0; }
194 
195 //----------------------------------------------------------------------
196 // Set accessor for the error value to "err" and the type to
197 // "eErrorTypeMachKernel"
198 //----------------------------------------------------------------------
199 void Status::SetMachError(uint32_t err) {
200   m_code = err;
201   m_type = eErrorTypeMachKernel;
202   m_string.clear();
203 }
204 
205 void Status::SetExpressionError(lldb::ExpressionResults result,
206                                 const char *mssg) {
207   m_code = result;
208   m_type = eErrorTypeExpression;
209   m_string = mssg;
210 }
211 
212 int Status::SetExpressionErrorWithFormat(lldb::ExpressionResults result,
213                                          const char *format, ...) {
214   int length = 0;
215 
216   if (format != nullptr && format[0]) {
217     va_list args;
218     va_start(args, format);
219     length = SetErrorStringWithVarArg(format, args);
220     va_end(args);
221   } else {
222     m_string.clear();
223   }
224   m_code = result;
225   m_type = eErrorTypeExpression;
226   return length;
227 }
228 
229 //----------------------------------------------------------------------
230 // Set accessor for the error value and type.
231 //----------------------------------------------------------------------
232 void Status::SetError(ValueType err, ErrorType type) {
233   m_code = err;
234   m_type = type;
235   m_string.clear();
236 }
237 
238 //----------------------------------------------------------------------
239 // Update the error value to be "errno" and update the type to be "POSIX".
240 //----------------------------------------------------------------------
241 void Status::SetErrorToErrno() {
242   m_code = errno;
243   m_type = eErrorTypePOSIX;
244   m_string.clear();
245 }
246 
247 //----------------------------------------------------------------------
248 // Update the error value to be LLDB_GENERIC_ERROR and update the type to be
249 // "Generic".
250 //----------------------------------------------------------------------
251 void Status::SetErrorToGenericError() {
252   m_code = LLDB_GENERIC_ERROR;
253   m_type = eErrorTypeGeneric;
254   m_string.clear();
255 }
256 
257 //----------------------------------------------------------------------
258 // Set accessor for the error string value for a specific error. This allows
259 // any string to be supplied as an error explanation. The error string value
260 // will remain until the error value is cleared or a new error value/type is
261 // assigned.
262 //----------------------------------------------------------------------
263 void Status::SetErrorString(llvm::StringRef err_str) {
264   if (!err_str.empty()) {
265     // If we have an error string, we should always at least have an error set
266     // to a generic value.
267     if (Success())
268       SetErrorToGenericError();
269   }
270   m_string = err_str;
271 }
272 
273 //------------------------------------------------------------------
274 /// Set the current error string to a formatted error string.
275 ///
276 /// @param format
277 ///     A printf style format string
278 //------------------------------------------------------------------
279 int Status::SetErrorStringWithFormat(const char *format, ...) {
280   if (format != nullptr && format[0]) {
281     va_list args;
282     va_start(args, format);
283     int length = SetErrorStringWithVarArg(format, args);
284     va_end(args);
285     return length;
286   } else {
287     m_string.clear();
288   }
289   return 0;
290 }
291 
292 int Status::SetErrorStringWithVarArg(const char *format, va_list args) {
293   if (format != nullptr && format[0]) {
294     // If we have an error string, we should always at least have an error set
295     // to a generic value.
296     if (Success())
297       SetErrorToGenericError();
298 
299     llvm::SmallString<1024> buf;
300     VASprintf(buf, format, args);
301     m_string = buf.str();
302     return buf.size();
303   } else {
304     m_string.clear();
305   }
306   return 0;
307 }
308 
309 //----------------------------------------------------------------------
310 // Returns true if the error code in this object is considered a successful
311 // return value.
312 //----------------------------------------------------------------------
313 bool Status::Success() const { return m_code == 0; }
314 
315 bool Status::WasInterrupted() const {
316   return (m_type == eErrorTypePOSIX && m_code == EINTR);
317 }
318 
319 void llvm::format_provider<lldb_private::Status>::format(
320     const lldb_private::Status &error, llvm::raw_ostream &OS,
321     llvm::StringRef Options) {
322   llvm::format_provider<llvm::StringRef>::format(error.AsCString(), OS,
323                                                  Options);
324 }
325