str_error_r.c 998 B

123456789101112131415161718192021222324252627
  1. #undef _GNU_SOURCE
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <linux/string.h>
  5. /*
  6. * The tools so far have been using the strerror_r() GNU variant, that returns
  7. * a string, be it the buffer passed or something else.
  8. *
  9. * But that, besides being tricky in cases where we expect that the function
  10. * using strerror_r() returns the error formatted in a provided buffer (we have
  11. * to check if it returned something else and copy that instead), breaks the
  12. * build on systems not using glibc, like Alpine Linux, where musl libc is
  13. * used.
  14. *
  15. * So, introduce yet another wrapper, str_error_r(), that has the GNU
  16. * interface, but uses the portable XSI variant of strerror_r(), so that users
  17. * rest asured that the provided buffer is used and it is what is returned.
  18. */
  19. char *str_error_r(int errnum, char *buf, size_t buflen)
  20. {
  21. int err = strerror_r(errnum, buf, buflen);
  22. if (err)
  23. snprintf(buf, buflen, "INTERNAL ERROR: strerror_r(%d, [buf], %zd)=%d", errnum, buflen, err);
  24. return buf;
  25. }