blob: 3c37a19e2c3b8d3cd94cb110c644377c1cef426c [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/libc/aos_strerror.h"
Brian Silverman01be0002014-05-10 15:44:38 -07002
Tyler Chatowbf0609c2021-07-31 16:13:27 -07003#include <cassert>
4#include <cstdio>
5#include <cstring>
6
Brian Silverman01be0002014-05-10 15:44:38 -07007// This code uses an overloaded function to handle the result from either
8// version of strerror_r correctly without needing a way to get the choice out
9// of the compiler/glibc/whatever explicitly.
10
11namespace {
12
13const size_t kBufferSize = 128;
14
15// Handle the result from the GNU version of strerror_r. It never fails, so
16// that's pretty easy...
Brian Silvermanb47f5552020-10-01 15:08:14 -070017__attribute__((unused)) char *aos_strerror_handle_result(int /*error*/,
18 char *ret,
19 char * /*buffer*/) {
Brian Silverman01be0002014-05-10 15:44:38 -070020 return ret;
21}
22
23// Handle the result from the POSIX version of strerror_r.
Brian Silvermanb47f5552020-10-01 15:08:14 -070024__attribute__((unused)) char *aos_strerror_handle_result(int error, int ret,
25 char *buffer) {
Brian Silverman01be0002014-05-10 15:44:38 -070026 if (ret != 0) {
Austin Schuh7a41be62015-10-31 13:06:55 -070027#ifndef NDEBUG
28 // assert doesn't use the return value when building optimized.
29 const int r =
30#endif
31 snprintf(buffer, kBufferSize, "Unknown error %d", error);
Brian Silvermanfe457de2014-05-26 22:04:08 -070032 assert(r > 0);
Brian Silverman01be0002014-05-10 15:44:38 -070033 }
34 return buffer;
35}
36
37} // namespace
38
Brian Silvermanaf784862014-05-13 08:14:55 -070039const char *aos_strerror(int error) {
Austin Schuhf7bfb652023-08-25 14:22:50 -070040 thread_local char buffer[kBufferSize];
Brian Silverman01be0002014-05-10 15:44:38 -070041
42 // Call the overload for whichever version we're using.
43 return aos_strerror_handle_result(
44 error, strerror_r(error, buffer, sizeof(buffer)), buffer);
45}