Debian Codegraph @

libstdc++-v3/src/c++11/system_error.cc

raw
1 // <system_error> implementation file
2
3 // Copyright (C) 2007-2025 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24
25
26 #define _GLIBCXX_USE_CXX11_ABI 1
27 #define __sso_string __sso_stringxxx
28 #include <cstring>
29 #include <system_error>
30 #include <bits/functexcept.h>
31 #include <limits>
32 #include <errno.h>
33 #undef __sso_string
34
35 #if defined(_WIN32) && !defined(__CYGWIN__)
36 #define WIN32_LEAN_AND_MEAN
37 #include <memory>
38 #include <windows.h>
39 #endif
40
41 #if __has_cpp_attribute(clang::require_constant_initialization)
42 # define __constinit [[clang::require_constant_initialization]]
43 #endif
44
45 namespace
46 {
47 using std::string;
48
49 #if _GLIBCXX_HAVE_STRERROR_R
50 // Handle the result of POSIX strerror_r.
51 inline std::size_t
52 use_strerror_result(int res, char* buf, std::size_t bufsz,
53 std::size_t& nextbufsz)
54 {
55 if (res == 0) // Success.
56 return std::strlen(buf);
57
58 if (res == ERANGE) // Buffer too small to hold result string.
59 {
60 nextbufsz = 2 * bufsz;
61 return 0;
62 }
63 // else res == EINVAL, unknown error.
64 if (*buf == '\0') // No result string written to buffer.
65 {
66 const char msg[] = "Unknown error";
67 std::memcpy(buf, msg, sizeof(msg) - 1);
68 return sizeof(msg) - 1;
69 }
70 else // An "unknown error" string was already written to the buffer.
71 return std::strlen(buf);
72 }
73
74 // Handle the result of GNU strerror_r.
75 inline std::size_t
76 use_strerror_result(char* res, char* buf, std::size_t bufsz,
77 std::size_t& nextbufsz)
78 {
79 if (res == buf) // Result string written to the buffer.
80 return std::strlen(res);
81
82 // Static result string returned, must be copied to the buffer.
83 std::size_t len = std::strlen(res);
84 if (len <= bufsz)
85 {
86 std::strcpy(buf, res);
87 return len;
88 }
89
90 // Reallocate and try again:
91 nextbufsz = len;
92 return 0;
93 }
94
95 string strerror_string(int err)
96 {
97 // Estimate maximum length of strerror strings (including "Unknown error").
98 // Any excess capacity here can be used by std::system_error constructors
99 // when concatenating strings.
100 std::size_t len = 60;
101 string s;
102 do
103 s.__resize_and_overwrite(len, [err, &len](char* p, std::size_t n) {
104 *p = '\0';
105 return use_strerror_result(strerror_r(err, p, n), p, n, len);
106 });
107 while (s.empty());
108 return s;
109 }
110 #else
111 string strerror_string(int err)
112 {
113 auto str = strerror(err); // XXX Not thread-safe.
114 if (str) [[__likely__]]
115 return str;
116 // strerror should not return NULL, but some implementations do.
117 return "Unknown error";
118 }
119 #endif
120
121 template<typename T>
122 struct constant_init
123 {
124 union {
125 T obj;
126 };
127 constexpr constant_init() : obj() { }
128
129 ~constant_init() { /* do nothing, union member is not destroyed */ }
130 };
131
132 struct generic_error_category final : public std::error_category
133 {
134 const char*
135 name() const noexcept final
136 { return "generic"; }
137
138 _GLIBCXX_DEFAULT_ABI_TAG
139 string
140 message(int i) const final
141 { return strerror_string(i); }
142
143 // Override this to avoid a virtual call to default_error_condition(i).
144 bool
145 equivalent(int i, const std::error_condition& cond) const noexcept final
146 { return i == cond.value() && *this == cond.category(); }
147 };
148
149 __constinit constant_init<generic_error_category> generic_category_instance{};
150
151 struct system_error_category final : public std::error_category
152 {
153 const char*
154 name() const noexcept final
155 { return "system"; }
156
157 _GLIBCXX_DEFAULT_ABI_TAG
158 string
159 message(int i) const final
160 {
161 #if defined(_WIN32) && !defined(__CYGWIN__)
162 char* buf = nullptr;
163 auto len
164 = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
165 | FORMAT_MESSAGE_ALLOCATE_BUFFER
166 | FORMAT_MESSAGE_IGNORE_INSERTS,
167 nullptr,
168 i,
169 LANG_USER_DEFAULT,
170 reinterpret_cast<LPTSTR>(&buf),
171 0,
172 nullptr);
173 if (len > 0)
174 {
175 struct deleter {
176 void operator()(void* p) const { ::LocalFree(p); }
177 };
178 std::unique_ptr<char[], deleter> guard(buf);
179 if (len > 2 && !__builtin_memcmp (buf + len - 2, "\r\n", 2)) [[likely]]
180 len -= 2 + (buf[len - 3] == '.');
181 return string(buf, len);
182 }
183 return string("Unknown error code");
184 #else
185 return strerror_string(i);
186 #endif
187 }
188
189 std::error_condition
190 default_error_condition(int ev) const noexcept final
191 {
192 // Use generic category for all known POSIX errno values (including zero)
193 // and system category otherwise.
194 switch (ev)
195 {
196 #if defined(_WIN32) && !defined(__CYGWIN__)
197 case 0:
198 return {0, generic_category_instance.obj};
199 // Convert Windows error code into a corresponding POSIX errno value.
200 #define X(w, e) case ERROR_##w: return {e, generic_category_instance.obj};
201 // This list is based on Cygwin's winsup/cygwin/errno.cc
202 X (ACCESS_DENIED, EACCES);
203 X (ACTIVE_CONNECTIONS, EAGAIN);
204 X (ALREADY_EXISTS, EEXIST);
205 X (BAD_DEVICE, ENODEV);
206 X (BAD_EXE_FORMAT, ENOEXEC);
207 X (BAD_NETPATH, ENOENT);
208 X (BAD_NET_NAME, ENOENT);
209 X (BAD_NET_RESP, ENOSYS);
210 X (BAD_PATHNAME, ENOENT);
211 X (BAD_PIPE, EINVAL);
212 X (BAD_UNIT, ENODEV);
213 X (BAD_USERNAME, EINVAL);
214 X (BEGINNING_OF_MEDIA, EIO);
215 X (BROKEN_PIPE, EPIPE);
216 X (BUSY, EBUSY);
217 X (BUS_RESET, EIO);
218 X (CALL_NOT_IMPLEMENTED, ENOSYS);
219 X (CANCELLED, EINTR);
220 X (CANNOT_MAKE, EPERM);
221 X (CHILD_NOT_COMPLETE, EBUSY);
222 X (COMMITMENT_LIMIT, EAGAIN);
223 X (CONNECTION_REFUSED, ECONNREFUSED);
224 X (CRC, EIO);
225 X (DEVICE_DOOR_OPEN, EIO);
226 X (DEVICE_IN_USE, EAGAIN);
227 X (DEVICE_REQUIRES_CLEANING, EIO);
228 X (DEV_NOT_EXIST, ENOENT);
229 X (DIRECTORY, ENOTDIR);
230 X (DIR_NOT_EMPTY, ENOTEMPTY);
231 X (DISK_CORRUPT, EIO);
232 #ifdef ENOSPC
233 X (DISK_FULL, ENOSPC);
234 #endif
235 X (DS_GENERIC_ERROR, EIO);
236 #ifdef ENOSPC
237 X (END_OF_MEDIA, ENOSPC);
238 #endif
239 X (EOM_OVERFLOW, EIO);
240 X (EXE_MACHINE_TYPE_MISMATCH, ENOEXEC);
241 X (EXE_MARKED_INVALID, ENOEXEC);
242 X (FILEMARK_DETECTED, EIO);
243 X (FILENAME_EXCED_RANGE, ENAMETOOLONG);
244 X (FILE_CORRUPT, EEXIST);
245 X (FILE_EXISTS, EEXIST);
246 X (FILE_INVALID, ENXIO);
247 X (FILE_NOT_FOUND, ENOENT);
248 #ifdef ENOSPC
249 X (HANDLE_DISK_FULL, ENOSPC);
250 #endif
251 X (INVALID_ADDRESS, EINVAL);
252 X (INVALID_AT_INTERRUPT_TIME, EINTR);
253 X (INVALID_BLOCK_LENGTH, EIO);
254 X (INVALID_DATA, EINVAL);
255 X (INVALID_DRIVE, ENODEV);
256 X (INVALID_EA_NAME, EINVAL);
257 X (INVALID_EXE_SIGNATURE, ENOEXEC);
258 X (INVALID_HANDLE, EBADF);
259 X (INVALID_NAME, ENOENT);
260 X (INVALID_PARAMETER, EINVAL);
261 X (INVALID_SIGNAL_NUMBER, EINVAL);
262 X (IOPL_NOT_ENABLED, ENOEXEC);
263 X (IO_DEVICE, EIO);
264 X (IO_INCOMPLETE, EAGAIN);
265 X (IO_PENDING, EAGAIN);
266 X (LOCK_VIOLATION, EBUSY);
267 X (MAX_THRDS_REACHED, EAGAIN);
268 X (META_EXPANSION_TOO_LONG, EINVAL);
269 X (MOD_NOT_FOUND, ENOENT);
270 X (MORE_DATA, EMSGSIZE);
271 X (NEGATIVE_SEEK, EINVAL);
272 X (NETNAME_DELETED, ENOENT);
273 X (NOACCESS, EFAULT);
274 X (NONE_MAPPED, EINVAL);
275 X (NONPAGED_SYSTEM_RESOURCES, EAGAIN);
276 X (NOT_ENOUGH_MEMORY, ENOMEM);
277 X (NOT_ENOUGH_QUOTA, EIO);
278 #ifdef EPERM
279 X (NOT_OWNER, EPERM);
280 #else
281 X (NOT_OWNER, EACCES);
282 #endif
283 X (NOT_SAME_DEVICE, EXDEV);
284 X (NOT_SUPPORTED, ENOSYS);
285 X (NO_DATA, EPIPE);
286 X (NO_DATA_DETECTED, EIO);
287 X (NO_MORE_SEARCH_HANDLES, ENFILE);
288 X (NO_PROC_SLOTS, EAGAIN);
289 X (NO_SIGNAL_SENT, EIO);
290 X (NO_SYSTEM_RESOURCES, EFBIG);
291 X (NO_TOKEN, EINVAL);
292 X (OPEN_FAILED, EIO);
293 X (OPEN_FILES, EAGAIN);
294 X (OUTOFMEMORY, ENOMEM);
295 X (PAGED_SYSTEM_RESOURCES, EAGAIN);
296 X (PAGEFILE_QUOTA, EAGAIN);
297 X (PATH_NOT_FOUND, ENOENT);
298 X (PIPE_BUSY, EBUSY);
299 X (PIPE_CONNECTED, EBUSY);
300 X (POSSIBLE_DEADLOCK, EDEADLK);
301 X (PRIVILEGE_NOT_HELD, EPERM);
302 X (PROCESS_ABORTED, EFAULT);
303 X (PROC_NOT_FOUND, ESRCH);
304 X (SECTOR_NOT_FOUND, EINVAL);
305 X (SEEK, EINVAL);
306 X (SERVICE_REQUEST_TIMEOUT, EBUSY);
307 X (SETMARK_DETECTED, EIO);
308 X (SHARING_BUFFER_EXCEEDED, ENOLCK);
309 X (SHARING_VIOLATION, EBUSY);
310 X (SIGNAL_PENDING, EBUSY);
311 X (SIGNAL_REFUSED, EIO);
312 X (THREAD_1_INACTIVE, EINVAL);
313 X (TIMEOUT, EBUSY);
314 X (TOO_MANY_LINKS, EMLINK);
315 X (TOO_MANY_OPEN_FILES, EMFILE);
316 X (UNEXP_NET_ERR, EIO);
317 X (WORKING_SET_QUOTA, EAGAIN);
318 X (WRITE_PROTECT, EROFS);
319 #undef X
320
321 #elif defined __AVR__
322 // avr-libc only defines a few distinct error numbers. Most <errno.h>
323 // constants are not usable in #if directives and have the same value.
324 case EDOM:
325 case ERANGE:
326 case ENOSYS:
327 case EINTR:
328 case 0:
329 return std::error_condition(ev, generic_category_instance.obj);
330 #else
331 // List of errno macros from [cerrno.syn].
332 // C11 only defines EDOM, EILSEQ and ERANGE, the rest are from POSIX.
333 // They expand to integer constant expressions with type int,
334 // and distinct positive values, suitable for use in #if directives.
335 // POSIX adds more macros (but they're not defined on all targets,
336 // see config/os/.../error_constants.h), and POSIX allows
337 // EAGAIN == EWOULDBLOCK and ENOTSUP == EOPNOTSUPP.
338
339 #ifdef E2BIG
340 case E2BIG:
341 #endif
342 #ifdef EACCES
343 case EACCES:
344 #endif
345 #ifdef EADDRINUSE
346 case EADDRINUSE:
347 #endif
348 #ifdef EADDRNOTAVAIL
349 case EADDRNOTAVAIL:
350 #endif
351 #ifdef EAFNOSUPPORT
352 case EAFNOSUPPORT:
353 #endif
354 #ifdef EAGAIN
355 case EAGAIN:
356 #endif
357 #ifdef EALREADY
358 case EALREADY:
359 #endif
360 #ifdef EBADF
361 case EBADF:
362 #endif
363 #ifdef EBADMSG
364 case EBADMSG:
365 #endif
366 #ifdef EBUSY
367 case EBUSY:
368 #endif
369 #ifdef ECANCELED
370 case ECANCELED:
371 #endif
372 #ifdef ECHILD
373 case ECHILD:
374 #endif
375 #ifdef ECONNABORTED
376 case ECONNABORTED:
377 #endif
378 #ifdef ECONNREFUSED
379 case ECONNREFUSED:
380 #endif
381 #ifdef ECONNRESET
382 case ECONNRESET:
383 #endif
384 #ifdef EDEADLK
385 case EDEADLK:
386 #endif
387 #ifdef EDESTADDRREQ
388 case EDESTADDRREQ:
389 #endif
390 case EDOM:
391 #ifdef EEXIST
392 case EEXIST:
393 #endif
394 #ifdef EFAULT
395 case EFAULT:
396 #endif
397 #ifdef EFBIG
398 case EFBIG:
399 #endif
400 #ifdef EHOSTUNREACH
401 case EHOSTUNREACH:
402 #endif
403 #ifdef EIDRM
404 case EIDRM:
405 #endif
406 case EILSEQ:
407 #ifdef EINPROGRESS
408 case EINPROGRESS:
409 #endif
410 #ifdef EINTR
411 case EINTR:
412 #endif
413 #ifdef EINVAL
414 case EINVAL:
415 #endif
416 #ifdef EIO
417 case EIO:
418 #endif
419 #ifdef EISCONN
420 case EISCONN:
421 #endif
422 #ifdef EISDIR
423 case EISDIR:
424 #endif
425 #ifdef ELOOP
426 case ELOOP:
427 #endif
428 #ifdef EMFILE
429 case EMFILE:
430 #endif
431 #ifdef EMLINK
432 case EMLINK:
433 #endif
434 #ifdef EMSGSIZE
435 case EMSGSIZE:
436 #endif
437 #ifdef ENAMETOOLONG
438 case ENAMETOOLONG:
439 #endif
440 #ifdef ENETDOWN
441 case ENETDOWN:
442 #endif
443 #ifdef ENETRESET
444 case ENETRESET:
445 #endif
446 #ifdef ENETUNREACH
447 case ENETUNREACH:
448 #endif
449 #ifdef ENFILE
450 case ENFILE:
451 #endif
452 #ifdef ENOBUFS
453 case ENOBUFS:
454 #endif
455 #ifdef ENODATA
456 case ENODATA:
457 #endif
458 #ifdef ENODEV
459 case ENODEV:
460 #endif
461 #ifdef ENOENT
462 case ENOENT:
463 #endif
464 #ifdef ENOEXEC
465 case ENOEXEC:
466 #endif
467 #ifdef ENOLCK
468 case ENOLCK:
469 #endif
470 #ifdef ENOLINK
471 case ENOLINK:
472 #endif
473 #ifdef ENOMEM
474 case ENOMEM:
475 #endif
476 #ifdef ENOMSG
477 case ENOMSG:
478 #endif
479 #ifdef ENOPROTOOPT
480 case ENOPROTOOPT:
481 #endif
482 #ifdef ENOSPC
483 case ENOSPC:
484 #endif
485 #ifdef ENOSR
486 case ENOSR:
487 #endif
488 #ifdef ENOSTR
489 case ENOSTR:
490 #endif
491 #ifdef ENOSYS
492 case ENOSYS:
493 #endif
494 #ifdef ENOTCONN
495 case ENOTCONN:
496 #endif
497 #ifdef ENOTDIR
498 case ENOTDIR:
499 #endif
500 #if defined ENOTEMPTY && (!defined EEXIST || ENOTEMPTY != EEXIST)
501 // AIX sometimes uses the same value for EEXIST and ENOTEMPTY
502 case ENOTEMPTY:
503 #endif
504 #ifdef ENOTRECOVERABLE
505 case ENOTRECOVERABLE:
506 #endif
507 #ifdef ENOTSOCK
508 case ENOTSOCK:
509 #endif
510 #if defined ENOTSUP && (!defined ENOSYS || ENOTSUP != ENOSYS)
511 // zTPF uses the same value for ENOSYS and ENOTSUP
512 case ENOTSUP:
513 #endif
514 #ifdef ENOTTY
515 case ENOTTY:
516 #endif
517 #ifdef ENXIO
518 case ENXIO:
519 #endif
520 #if defined EOPNOTSUPP && (!defined ENOTSUP || EOPNOTSUPP != ENOTSUP)
521 case EOPNOTSUPP:
522 #endif
523 #ifdef EOVERFLOW
524 case EOVERFLOW:
525 #endif
526 #ifdef EOWNERDEAD
527 case EOWNERDEAD:
528 #endif
529 #ifdef EPERM
530 case EPERM:
531 #endif
532 #ifdef EPIPE
533 case EPIPE:
534 #endif
535 #ifdef EPROTO
536 case EPROTO:
537 #endif
538 #ifdef EPROTONOSUPPORT
539 case EPROTONOSUPPORT:
540 #endif
541 #ifdef EPROTOTYPE
542 case EPROTOTYPE:
543 #endif
544 case ERANGE:
545 #ifdef EROFS
546 case EROFS:
547 #endif
548 #ifdef ESPIPE
549 case ESPIPE:
550 #endif
551 #ifdef ESRCH
552 case ESRCH:
553 #endif
554 #ifdef ETIME
555 case ETIME:
556 #endif
557 #ifdef ETIMEDOUT
558 case ETIMEDOUT:
559 #endif
560 #ifdef ETXTBSY
561 case ETXTBSY:
562 #endif
563 #if defined EWOULDBLOCK && (!defined EAGAIN || EWOULDBLOCK != EAGAIN)
564 case EWOULDBLOCK:
565 #endif
566 #ifdef EXDEV
567 case EXDEV:
568 #endif
569 case 0:
570 return std::error_condition(ev, generic_category_instance.obj);
571
572 /* Additional system-dependent mappings from non-standard error codes
573 * to one of the POSIX values above would go here, e.g.
574 case EBLAH:
575 return std::error_condition(EINVAL, std::generic_category());
576 */
577
578 #endif
579 default:
580 return std::error_condition(ev, *this);
581 }
582 }
583
584 // Override this to avoid a virtual call to default_error_condition(i).
585 bool
586 equivalent(int i, const std::error_condition& cond) const noexcept final
587 { return system_error_category::default_error_condition(i) == cond; }
588 };
589
590 __constinit constant_init<system_error_category> system_category_instance{};
591 }
592
593 namespace std _GLIBCXX_VISIBILITY(default)
594 {
595 _GLIBCXX_BEGIN_NAMESPACE_VERSION
596
597 void
598 __throw_system_error(int __i __attribute__((unused)))
599 {
600 _GLIBCXX_THROW_OR_ABORT(system_error(__i, generic_category_instance.obj));
601 }
602
603 error_category::~error_category() = default;
604
605 _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
606
607 const error_category&
608 system_category() noexcept { return system_category_instance.obj; }
609
610 const error_category&
611 generic_category() noexcept { return generic_category_instance.obj; }
612
613 _GLIBCXX_END_INLINE_ABI_NAMESPACE(_V2)
614
615 system_error::~system_error() = default;
616
617 error_condition
618 error_category::default_error_condition(int __i) const noexcept
619 { return error_condition(__i, *this); }
620
621 bool
622 error_category::equivalent(int __i,
623 const error_condition& __cond) const noexcept
624 { return default_error_condition(__i) == __cond; }
625
626 bool
627 error_category::equivalent(const error_code& __code, int __i) const noexcept
628 { return *this == __code.category() && __code.value() == __i; }
629
630 error_condition
631 error_code::default_error_condition() const noexcept
632 { return category().default_error_condition(value()); }
633
634 #if _GLIBCXX_USE_CXX11_ABI
635 // Return error_category::message() as a COW string
636 __cow_string
637 error_category::_M_message(int i) const
638 {
639 string msg = this->message(i);
640 return {msg.c_str(), msg.length()};
641 }
642 #endif
643
644 _GLIBCXX_END_NAMESPACE_VERSION
645 } // namespace