blob: 8c087a8cd84c7dff150eefa6fabd52106599565f [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
Brian Silvermanb47f5552020-10-01 15:08:14 -07003#include <sys/types.h>
4
Tyler Chatowbf0609c2021-07-31 16:13:27 -07005#include <cassert>
6#include <cstdio>
7#include <cstring>
8
Brian Silvermanb47f5552020-10-01 15:08:14 -07009#include "aos/thread_local.h"
Brian Silverman01be0002014-05-10 15:44:38 -070010
Brian Silverman01be0002014-05-10 15:44:38 -070011// This code uses an overloaded function to handle the result from either
12// version of strerror_r correctly without needing a way to get the choice out
13// of the compiler/glibc/whatever explicitly.
14
15namespace {
16
17const size_t kBufferSize = 128;
18
19// Handle the result from the GNU version of strerror_r. It never fails, so
20// that's pretty easy...
Brian Silvermanb47f5552020-10-01 15:08:14 -070021__attribute__((unused)) char *aos_strerror_handle_result(int /*error*/,
22 char *ret,
23 char * /*buffer*/) {
Brian Silverman01be0002014-05-10 15:44:38 -070024 return ret;
25}
26
27// Handle the result from the POSIX version of strerror_r.
Brian Silvermanb47f5552020-10-01 15:08:14 -070028__attribute__((unused)) char *aos_strerror_handle_result(int error, int ret,
29 char *buffer) {
Brian Silverman01be0002014-05-10 15:44:38 -070030 if (ret != 0) {
Austin Schuh7a41be62015-10-31 13:06:55 -070031#ifndef NDEBUG
32 // assert doesn't use the return value when building optimized.
33 const int r =
34#endif
35 snprintf(buffer, kBufferSize, "Unknown error %d", error);
Brian Silvermanfe457de2014-05-26 22:04:08 -070036 assert(r > 0);
Brian Silverman01be0002014-05-10 15:44:38 -070037 }
38 return buffer;
39}
40
41} // namespace
42
Brian Silvermanaf784862014-05-13 08:14:55 -070043const char *aos_strerror(int error) {
Brian Silvermanb47f5552020-10-01 15:08:14 -070044 AOS_THREAD_LOCAL char buffer[kBufferSize];
Brian Silverman01be0002014-05-10 15:44:38 -070045
46 // Call the overload for whichever version we're using.
47 return aos_strerror_handle_result(
48 error, strerror_r(error, buffer, sizeof(buffer)), buffer);
49}