John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 1 | #include "aos/libc/aos_strerror.h" |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 2 | |
| 3 | #include <assert.h> |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 4 | #include <stdio.h> |
Brian Silverman | b47f555 | 2020-10-01 15:08:14 -0700 | [diff] [blame] | 5 | #include <string.h> |
| 6 | #include <sys/types.h> |
| 7 | |
| 8 | #include "aos/thread_local.h" |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 9 | |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 10 | // 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 | |
| 14 | namespace { |
| 15 | |
| 16 | const 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 Silverman | b47f555 | 2020-10-01 15:08:14 -0700 | [diff] [blame] | 20 | __attribute__((unused)) char *aos_strerror_handle_result(int /*error*/, |
| 21 | char *ret, |
| 22 | char * /*buffer*/) { |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 23 | return ret; |
| 24 | } |
| 25 | |
| 26 | // Handle the result from the POSIX version of strerror_r. |
Brian Silverman | b47f555 | 2020-10-01 15:08:14 -0700 | [diff] [blame] | 27 | __attribute__((unused)) char *aos_strerror_handle_result(int error, int ret, |
| 28 | char *buffer) { |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 29 | if (ret != 0) { |
Austin Schuh | 7a41be6 | 2015-10-31 13:06:55 -0700 | [diff] [blame] | 30 | #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 Silverman | fe457de | 2014-05-26 22:04:08 -0700 | [diff] [blame] | 35 | assert(r > 0); |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 36 | } |
| 37 | return buffer; |
| 38 | } |
| 39 | |
| 40 | } // namespace |
| 41 | |
Brian Silverman | af78486 | 2014-05-13 08:14:55 -0700 | [diff] [blame] | 42 | const char *aos_strerror(int error) { |
Brian Silverman | b47f555 | 2020-10-01 15:08:14 -0700 | [diff] [blame] | 43 | AOS_THREAD_LOCAL char buffer[kBufferSize]; |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame] | 44 | |
| 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 | } |