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