blob: b045f249bd76fb4f2759e3cdd9780d6b2761db2a [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
3#include <assert.h>
Brian Silverman01be0002014-05-10 15:44:38 -07004#include <stdio.h>
Brian Silvermanb47f5552020-10-01 15:08:14 -07005#include <string.h>
6#include <sys/types.h>
7
8#include "aos/thread_local.h"
Brian Silverman01be0002014-05-10 15:44:38 -07009
Brian Silverman01be0002014-05-10 15:44:38 -070010// This code uses an overloaded function to handle the result from either
11// version of strerror_r correctly without needing a way to get the choice out
12// of the compiler/glibc/whatever explicitly.
13
14namespace {
15
16const size_t kBufferSize = 128;
17
18// Handle the result from the GNU version of strerror_r. It never fails, so
19// that's pretty easy...
Brian Silvermanb47f5552020-10-01 15:08:14 -070020__attribute__((unused)) char *aos_strerror_handle_result(int /*error*/,
21 char *ret,
22 char * /*buffer*/) {
Brian Silverman01be0002014-05-10 15:44:38 -070023 return ret;
24}
25
26// Handle the result from the POSIX version of strerror_r.
Brian Silvermanb47f5552020-10-01 15:08:14 -070027__attribute__((unused)) char *aos_strerror_handle_result(int error, int ret,
28 char *buffer) {
Brian Silverman01be0002014-05-10 15:44:38 -070029 if (ret != 0) {
Austin Schuh7a41be62015-10-31 13:06:55 -070030#ifndef NDEBUG
31 // assert doesn't use the return value when building optimized.
32 const int r =
33#endif
34 snprintf(buffer, kBufferSize, "Unknown error %d", error);
Brian Silvermanfe457de2014-05-26 22:04:08 -070035 assert(r > 0);
Brian Silverman01be0002014-05-10 15:44:38 -070036 }
37 return buffer;
38}
39
40} // namespace
41
Brian Silvermanaf784862014-05-13 08:14:55 -070042const char *aos_strerror(int error) {
Brian Silvermanb47f5552020-10-01 15:08:14 -070043 AOS_THREAD_LOCAL char buffer[kBufferSize];
Brian Silverman01be0002014-05-10 15:44:38 -070044
45 // Call the overload for whichever version we're using.
46 return aos_strerror_handle_result(
47 error, strerror_r(error, buffer, sizeof(buffer)), buffer);
48}