|
37 | 37 | #include <lwip/err.h> |
38 | 38 | #endif // CHIP_SYSTEM_CONFIG_USE_LWIP |
39 | 39 |
|
40 | | -#include "StrErrorUtil.h" |
41 | 40 | #include <limits> |
42 | 41 | #include <stddef.h> |
43 | 42 | #include <string.h> |
| 43 | +#include <mutex> |
| 44 | +#define CHIP_HAVE_STD_MUTEX 1 |
44 | 45 |
|
45 | 46 | namespace chip { |
46 | 47 | namespace System { |
@@ -91,9 +92,44 @@ DLL_EXPORT const char * DescribeErrorPOSIX(CHIP_ERROR aError) |
91 | 92 | #else |
92 | 93 | static char errBuf[128]; |
93 | 94 | #endif // CHIP_SYSTEM_CONFIG_THREAD_LOCAL_STORAGE |
94 | | - const char * res = chip::System::PlatformStrError(lError, errBuf, sizeof(errBuf)); |
95 | | - if (res != nullptr) |
96 | | - return res; |
| 95 | + // Try the POSIX/XSI strerror_r variant (int strerror_r(int, char*, size_t)). |
| 96 | +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L && !defined(_GNU_SOURCE) |
| 97 | + if (strerror_r(lError, errBuf, sizeof(errBuf)) == 0) |
| 98 | + { |
| 99 | + return errBuf; |
| 100 | + } |
| 101 | +#elif defined(_GNU_SOURCE) || defined(__GLIBC__) |
| 102 | + { |
| 103 | + // GNU variant: char *strerror_r(int, char*, size_t) |
| 104 | + char * s = strerror_r(lError, errBuf, sizeof(errBuf)); |
| 105 | + if (s != nullptr) |
| 106 | + { |
| 107 | + if (s != errBuf) |
| 108 | + { |
| 109 | + strncpy(errBuf, s, sizeof(errBuf) - 1); |
| 110 | + errBuf[sizeof(errBuf) - 1] = '\0'; |
| 111 | + } |
| 112 | + return errBuf; |
| 113 | + } |
| 114 | + } |
| 115 | +#else |
| 116 | + // No strerror_r declared: fall back to strerror(). To make this safe in |
| 117 | + // multi-threaded builds, serialize access to strerror() if std::mutex is |
| 118 | + // available; otherwise do an unprotected copy (best-effort). |
| 119 | +# ifdef CHIP_HAVE_STD_MUTEX |
| 120 | + static std::mutex s_strerror_mutex; |
| 121 | + std::lock_guard<std::mutex> lock(s_strerror_mutex); |
| 122 | +# endif |
| 123 | + { |
| 124 | + const char * s = strerror(lError); |
| 125 | + if (s != nullptr) |
| 126 | + { |
| 127 | + strncpy(errBuf, s, sizeof(errBuf) - 1); |
| 128 | + errBuf[sizeof(errBuf) - 1] = '\0'; |
| 129 | + return errBuf; |
| 130 | + } |
| 131 | + } |
| 132 | +#endif |
97 | 133 |
|
98 | 134 | return "Unknown platform error"; |
99 | 135 | } |
|
0 commit comments