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