1//===----------------------------------------------------------------------===//
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 <__assert>
10#include <__config>
11#include <__system_error/throw_system_error.h>
12#include <__verbose_abort>
13#include <cerrno>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <optional>
18#include <string.h>
19#include <string>
20#include <system_error>
21
22#include "include/config_elast.h"
23
24#if defined(_LIBCPP_WIN32API)
25# include <windows.h>
26# include <winerror.h>
27#endif
28
29_LIBCPP_BEGIN_NAMESPACE_STD
30
31#if defined(_LIBCPP_WIN32API)
32
33namespace {
34std::optional<errc> __win_err_to_errc(int err) {
35 switch (err) {
36 case ERROR_ACCESS_DENIED:
37 return errc::permission_denied;
38 case ERROR_ALREADY_EXISTS:
39 return errc::file_exists;
40 case ERROR_BAD_NETPATH:
41 return errc::no_such_file_or_directory;
42 case ERROR_BAD_PATHNAME:
43 return errc::no_such_file_or_directory;
44 case ERROR_BAD_UNIT:
45 return errc::no_such_device;
46 case ERROR_BROKEN_PIPE:
47 return errc::broken_pipe;
48 case ERROR_BUFFER_OVERFLOW:
49 return errc::filename_too_long;
50 case ERROR_BUSY:
51 return errc::device_or_resource_busy;
52 case ERROR_BUSY_DRIVE:
53 return errc::device_or_resource_busy;
54 case ERROR_CANNOT_MAKE:
55 return errc::permission_denied;
56 case ERROR_CANTOPEN:
57 return errc::io_error;
58 case ERROR_CANTREAD:
59 return errc::io_error;
60 case ERROR_CANTWRITE:
61 return errc::io_error;
62 case ERROR_CURRENT_DIRECTORY:
63 return errc::permission_denied;
64 case ERROR_DEV_NOT_EXIST:
65 return errc::no_such_device;
66 case ERROR_DEVICE_IN_USE:
67 return errc::device_or_resource_busy;
68 case ERROR_DIR_NOT_EMPTY:
69 return errc::directory_not_empty;
70 case ERROR_DIRECTORY:
71 return errc::invalid_argument;
72 case ERROR_DISK_FULL:
73 return errc::no_space_on_device;
74 case ERROR_FILE_EXISTS:
75 return errc::file_exists;
76 case ERROR_FILE_NOT_FOUND:
77 return errc::no_such_file_or_directory;
78 case ERROR_HANDLE_DISK_FULL:
79 return errc::no_space_on_device;
80 case ERROR_INVALID_ACCESS:
81 return errc::permission_denied;
82 case ERROR_INVALID_DRIVE:
83 return errc::no_such_device;
84 case ERROR_INVALID_FUNCTION:
85 return errc::function_not_supported;
86 case ERROR_INVALID_HANDLE:
87 return errc::invalid_argument;
88 case ERROR_INVALID_NAME:
89 return errc::no_such_file_or_directory;
90 case ERROR_INVALID_PARAMETER:
91 return errc::invalid_argument;
92 case ERROR_LOCK_VIOLATION:
93 return errc::no_lock_available;
94 case ERROR_LOCKED:
95 return errc::no_lock_available;
96 case ERROR_NEGATIVE_SEEK:
97 return errc::invalid_argument;
98 case ERROR_NETNAME_DELETED:
99 return errc::no_such_file_or_directory;
100 case ERROR_NOACCESS:
101 return errc::permission_denied;
102 case ERROR_NOT_ENOUGH_MEMORY:
103 return errc::not_enough_memory;
104 case ERROR_NOT_READY:
105 return errc::resource_unavailable_try_again;
106 case ERROR_NOT_SAME_DEVICE:
107 return errc::cross_device_link;
108 case ERROR_NOT_SUPPORTED:
109 return errc::not_supported;
110 case ERROR_OPEN_FAILED:
111 return errc::io_error;
112 case ERROR_OPEN_FILES:
113 return errc::device_or_resource_busy;
114 case ERROR_OPERATION_ABORTED:
115 return errc::operation_canceled;
116 case ERROR_OUTOFMEMORY:
117 return errc::not_enough_memory;
118 case ERROR_PATH_NOT_FOUND:
119 return errc::no_such_file_or_directory;
120 case ERROR_READ_FAULT:
121 return errc::io_error;
122 case ERROR_REPARSE_TAG_INVALID:
123 return errc::invalid_argument;
124 case ERROR_RETRY:
125 return errc::resource_unavailable_try_again;
126 case ERROR_SEEK:
127 return errc::io_error;
128 case ERROR_SHARING_VIOLATION:
129 return errc::permission_denied;
130 case ERROR_TOO_MANY_OPEN_FILES:
131 return errc::too_many_files_open;
132 case ERROR_WRITE_FAULT:
133 return errc::io_error;
134 case ERROR_WRITE_PROTECT:
135 return errc::permission_denied;
136 default:
137 return {};
138 }
139}
140} // namespace
141#endif
142
143namespace {
144#if _LIBCPP_HAS_THREADS
145
146// GLIBC also uses 1024 as the maximum buffer size internally.
147constexpr size_t strerror_buff_size = 1024;
148
149string do_strerror_r(int ev);
150
151# if defined(_LIBCPP_MSVCRT_LIKE)
152string do_strerror_r(int ev) {
153 char buffer[strerror_buff_size];
154 if (::strerror_s(buffer, strerror_buff_size, ev) == 0)
155 return string(buffer);
156 std::snprintf(buffer, strerror_buff_size, "unknown error %d", ev);
157 return string(buffer);
158}
159# else
160
161// Only one of the two following functions will be used, depending on
162// the return type of strerror_r:
163
164// For the GNU variant, a char* return value:
165__attribute__((unused)) const char* handle_strerror_r_return(char* strerror_return, char* buffer) {
166 // GNU always returns a string pointer in its return value. The
167 // string might point to either the input buffer, or a static
168 // buffer, but we don't care which.
169 return strerror_return;
170}
171
172// For the POSIX variant: an int return value.
173__attribute__((unused)) const char* handle_strerror_r_return(int strerror_return, char* buffer) {
174 // The POSIX variant either:
175 // - fills in the provided buffer and returns 0
176 // - returns a positive error value, or
177 // - returns -1 and fills in errno with an error value.
178 if (strerror_return == 0)
179 return buffer;
180
181 // Only handle EINVAL. Other errors abort.
182 int new_errno = strerror_return == -1 ? errno : strerror_return;
183 if (new_errno == EINVAL)
184 return "";
185
186 _LIBCPP_ASSERT_INTERNAL(new_errno == ERANGE, "unexpected error from ::strerror_r");
187 // FIXME maybe? 'strerror_buff_size' is likely to exceed the
188 // maximum error size so ERANGE shouldn't be returned.
189 std::abort();
190}
191
192// This function handles both GNU and POSIX variants, dispatching to
193// one of the two above functions.
194string do_strerror_r(int ev) {
195 char buffer[strerror_buff_size];
196 // Preserve errno around the call. (The C++ standard requires that
197 // system_error functions not modify errno).
198 const int old_errno = errno;
199 const char* error_message = handle_strerror_r_return(strerror_return: ::strerror_r(errnum: ev, buf: buffer, buflen: strerror_buff_size), buffer);
200 // If we didn't get any message, print one now.
201 if (!error_message[0]) {
202 std::snprintf(s: buffer, maxlen: strerror_buff_size, format: "Unknown error %d", ev);
203 error_message = buffer;
204 }
205 errno = old_errno;
206 return string(error_message);
207}
208# endif
209
210#endif // _LIBCPP_HAS_THREADS
211
212string make_error_str(const error_code& ec, string what_arg) {
213 if (ec) {
214 if (!what_arg.empty()) {
215 what_arg += ": ";
216 }
217 what_arg += ec.message();
218 }
219 return what_arg;
220}
221
222string make_error_str(const error_code& ec) {
223 if (ec) {
224 return ec.message();
225 }
226 return string();
227}
228} // namespace
229
230string __do_message::message(int ev) const {
231#if !_LIBCPP_HAS_THREADS
232 return string(::strerror(ev));
233#else
234 return do_strerror_r(ev);
235#endif
236}
237
238class _LIBCPP_HIDDEN __generic_error_category : public __do_message {
239public:
240 virtual const char* name() const noexcept;
241 virtual string message(int ev) const;
242};
243
244const char* __generic_error_category::name() const noexcept { return "generic"; }
245
246string __generic_error_category::message(int ev) const {
247#ifdef _LIBCPP_ELAST
248 if (ev > _LIBCPP_ELAST)
249 return string("unspecified generic_category error");
250#endif // _LIBCPP_ELAST
251 return __do_message::message(ev);
252}
253
254const error_category& generic_category() noexcept {
255 union AvoidDestroyingGenericCategory {
256 __generic_error_category generic_error_category;
257 constexpr explicit AvoidDestroyingGenericCategory() : generic_error_category() {}
258 ~AvoidDestroyingGenericCategory() {}
259 };
260 constinit static AvoidDestroyingGenericCategory helper;
261 return helper.generic_error_category;
262}
263
264class _LIBCPP_HIDDEN __system_error_category : public __do_message {
265public:
266 virtual const char* name() const noexcept;
267 virtual string message(int ev) const;
268 virtual error_condition default_error_condition(int ev) const noexcept;
269};
270
271const char* __system_error_category::name() const noexcept { return "system"; }
272
273string __system_error_category::message(int ev) const {
274#ifdef _LIBCPP_WIN32API
275 std::string result;
276 char* str = nullptr;
277 unsigned long num_chars = ::FormatMessageA(
278 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
279 nullptr,
280 ev,
281 0,
282 reinterpret_cast<char*>(&str),
283 0,
284 nullptr);
285 auto is_whitespace = [](char ch) { return ch == '\n' || ch == '\r' || ch == ' '; };
286 while (num_chars > 0 && is_whitespace(str[num_chars - 1]))
287 --num_chars;
288
289 if (num_chars)
290 result = std::string(str, num_chars);
291 else
292 result = "Unknown error";
293
294 LocalFree(str);
295 return result;
296#else
297# ifdef _LIBCPP_ELAST
298 if (ev > _LIBCPP_ELAST)
299 return string("unspecified system_category error");
300# endif // _LIBCPP_ELAST
301 return __do_message::message(ev);
302#endif
303}
304
305error_condition __system_error_category::default_error_condition(int ev) const noexcept {
306#ifdef _LIBCPP_WIN32API
307 // Remap windows error codes to generic error codes if possible.
308 if (ev == 0)
309 return error_condition(0, generic_category());
310 if (auto maybe_errc = __win_err_to_errc(ev))
311 return error_condition(static_cast<int>(*maybe_errc), generic_category());
312 return error_condition(ev, system_category());
313#else
314# ifdef _LIBCPP_ELAST
315 if (ev > _LIBCPP_ELAST)
316 return error_condition(ev, system_category());
317# endif // _LIBCPP_ELAST
318 return error_condition(ev, generic_category());
319#endif
320}
321
322const error_category& system_category() noexcept {
323 union AvoidDestroyingSystemCategory {
324 __system_error_category system_error_category;
325 constexpr explicit AvoidDestroyingSystemCategory() : system_error_category() {}
326 ~AvoidDestroyingSystemCategory() {}
327 };
328 constinit static AvoidDestroyingSystemCategory helper;
329 return helper.system_error_category;
330}
331
332// error_condition
333
334string error_condition::message() const { return __cat_->message(ev: __val_); }
335
336// error_code
337
338string error_code::message() const { return __cat_->message(ev: __val_); }
339
340// system_error
341
342system_error::system_error(error_code ec, const string& what_arg)
343 : runtime_error(make_error_str(ec, what_arg)), __ec_(ec) {}
344
345system_error::system_error(error_code ec, const char* what_arg)
346 : runtime_error(make_error_str(ec, what_arg)), __ec_(ec) {}
347
348system_error::system_error(error_code ec) : runtime_error(make_error_str(ec)), __ec_(ec) {}
349
350system_error::system_error(int ev, const error_category& ecat, const string& what_arg)
351 : runtime_error(make_error_str(ec: error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) {}
352
353system_error::system_error(int ev, const error_category& ecat, const char* what_arg)
354 : runtime_error(make_error_str(ec: error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) {}
355
356system_error::system_error(int ev, const error_category& ecat)
357 : runtime_error(make_error_str(ec: error_code(ev, ecat))), __ec_(error_code(ev, ecat)) {}
358
359system_error::~system_error() noexcept {}
360
361void __throw_system_error(int ev, const char* what_arg) {
362#if _LIBCPP_HAS_EXCEPTIONS
363 std::__throw_system_error(ec: error_code(ev, generic_category()), what_arg: what_arg);
364#else
365 // The above could also handle the no-exception case, but for size, avoid referencing system_category() unnecessarily.
366 _LIBCPP_VERBOSE_ABORT(
367 "system_error was thrown in -fno-exceptions mode with error %i and message \"%s\"", ev, what_arg);
368#endif
369}
370
371_LIBCPP_END_NAMESPACE_STD
372