Debian Codegraph @

src/libc/musl/string.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 /* MAX_ERRNO is defined as 4095 in linux/err.h. We use the same value here. */
8 #define ERRNO_MAX 4095
9
10 /* strerror(3) says that glibc uses a maximum length of 1024 bytes. */
11 #define ERRNO_BUF_LEN 1024
12
13 /* The header string.h overrides strerror_r with strerror_r_gnu, hence we need to undef it here. */
14 #undef strerror_r
15
16 char* strerror_r_gnu(int errnum, char *buf, size_t buflen) {
17 /* musl provides spurious catchall error message "No error information" for unknown errno
18 * (including errno == 0). Let's patch it to glibc style. */
19
20 if (errnum == 0)
21 return (char*) "Success";
22
23 if (buflen == 0)
24 return (char*) "Unknown error";
25
26 if (errnum < 0 || errnum > ERRNO_MAX)
27 goto fallback;
28
29 if (strerror_r(errnum, buf, buflen) != 0)
30 goto fallback;
31
32 char buf_0[ERRNO_BUF_LEN];
33 if (strerror_r(0, buf_0, sizeof buf_0) != 0) /* Wut?? */
34 goto fallback;
35
36 /* strerror_r() may truncate the result. In that case, let's not compare the trailing NUL. */
37 size_t n = (buflen < ERRNO_BUF_LEN ? buflen : ERRNO_BUF_LEN) - 1;
38 if (strncmp(buf, buf_0, n) != 0)
39 return buf;
40
41 fallback:
42 snprintf(buf, buflen, "Unknown error %i", errnum);
43 return buf;
44 }