1 /** @file errno_to_string.cc
2 * @brief Convert errno value to std::string, thread-safely if possible
4 /* Copyright (C) 2014,2015,2016 Olly Betts
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 #include "errno_to_string.h"
30 // <cstring> doesn't give us strerror_r() with Sun C++ 5.9.
32 #if defined HAVE__SYS_ERRLIST_AND__SYS_NERR || \
33 defined HAVE_SYS_ERRLIST_AND_SYS_NERR
35 // Under mingw, these are in stdlib.h.
44 errno_to_string(int e
, string
& s
) {
45 #if defined HAVE__SYS_ERRLIST_AND__SYS_NERR
46 if (e
>= 0 && e
< _sys_nerr
&& _sys_errlist
[e
]) {
49 s
+= "Unknown error ";
52 #elif defined HAVE_SYS_ERRLIST_AND_SYS_NERR
53 if (e
>= 0 && e
< sys_nerr
&& sys_errlist
[e
]) {
56 s
+= "Unknown error ";
59 #elif defined HAVE_STRERROR_R
60 // Actual longest on Linux in English is EILSEQ which needs 50 bytes.
62 # ifdef STRERROR_R_CHAR_P
63 // Returns char* containing string.
64 s
+= strerror_r(e
, buf
, sizeof(buf
));
66 // XSI-compliant strerror_r returns int: 0 means success; a positive error
67 // number should be returned on error, but glibc < 2.13 returns -1 and sets
69 int r
= strerror_r(e
, buf
, sizeof(buf
));
73 s
+= "Unknown error ";
78 // Not thread safe. "C99 and POSIX.1-2008 require the return value to be
79 // non-NULL" and we require C++11 which incorporates C99.