1 // Copyright 2020 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/base/internal/strerror.h"
16 
17 #include <cerrno>
18 #include <cstddef>
19 #include <cstdio>
20 #include <cstring>
21 #include <string>
22 #include <type_traits>
23 
24 #include "absl/base/attributes.h"
25 #include "absl/base/internal/errno_saver.h"
26 
27 namespace absl {
28 ABSL_NAMESPACE_BEGIN
29 namespace base_internal {
30 namespace {
StrErrorAdaptor(int errnum,char * buf,size_t buflen)31 const char* StrErrorAdaptor(int errnum, char* buf, size_t buflen) {
32 #if defined(_WIN32)
33   int rc = strerror_s(buf, buflen, errnum);
34   buf[buflen - 1] = '\0';  // guarantee NUL termination
35   if (rc == 0 && strncmp(buf, "Unknown error", buflen) == 0) *buf = '\0';
36   return buf;
37 #else
38 #if defined(__GLIBC__) || defined(__APPLE__)
39   // Use the BSD sys_errlist API provided by GNU glibc and others to
40   // avoid any need to copy the message into the local buffer first.
41   if (0 <= errnum && errnum < sys_nerr) {
42     if (const char* p = sys_errlist[errnum]) {
43       return p;
44     }
45   }
46 #endif
47   // The type of `ret` is platform-specific; both of these branches must compile
48   // either way but only one will execute on any given platform:
49   auto ret = strerror_r(errnum, buf, buflen);
50   if (std::is_same<decltype(ret), int>::value) {
51     // XSI `strerror_r`; `ret` is `int`:
52     if (ret) *buf = '\0';
53     return buf;
54   } else {
55     // GNU `strerror_r`; `ret` is `char *`:
56     return reinterpret_cast<const char*>(ret);
57   }
58 #endif
59 }
60 }  // namespace
61 
StrError(int errnum)62 std::string StrError(int errnum) {
63   absl::base_internal::ErrnoSaver errno_saver;
64   char buf[100];
65   const char* str = StrErrorAdaptor(errnum, buf, sizeof buf);
66   if (*str == '\0') {
67     snprintf(buf, sizeof buf, "Unknown error %d", errnum);
68     str = buf;
69   }
70   return str;
71 }
72 
73 }  // namespace base_internal
74 ABSL_NAMESPACE_END
75 }  // namespace absl
76