tep_strerror.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // SPDX-License-Identifier: LGPL-2.1
  2. #undef _GNU_SOURCE
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include "event-parse.h"
  6. #undef _PE
  7. #define _PE(code, str) str
  8. static const char * const tep_error_str[] = {
  9. TEP_ERRORS
  10. };
  11. #undef _PE
  12. /*
  13. * The tools so far have been using the strerror_r() GNU variant, that returns
  14. * a string, be it the buffer passed or something else.
  15. *
  16. * But that, besides being tricky in cases where we expect that the function
  17. * using strerror_r() returns the error formatted in a provided buffer (we have
  18. * to check if it returned something else and copy that instead), breaks the
  19. * build on systems not using glibc, like Alpine Linux, where musl libc is
  20. * used.
  21. *
  22. * So, introduce yet another wrapper, str_error_r(), that has the GNU
  23. * interface, but uses the portable XSI variant of strerror_r(), so that users
  24. * rest asured that the provided buffer is used and it is what is returned.
  25. */
  26. int tep_strerror(struct tep_handle *tep __maybe_unused,
  27. enum tep_errno errnum, char *buf, size_t buflen)
  28. {
  29. const char *msg;
  30. int idx;
  31. if (!buflen)
  32. return 0;
  33. if (errnum >= 0) {
  34. int err = strerror_r(errnum, buf, buflen);
  35. buf[buflen - 1] = 0;
  36. return err;
  37. }
  38. if (errnum <= __TEP_ERRNO__START ||
  39. errnum >= __TEP_ERRNO__END)
  40. return -1;
  41. idx = errnum - __TEP_ERRNO__START - 1;
  42. msg = tep_error_str[idx];
  43. snprintf(buf, buflen, "%s", msg);
  44. return 0;
  45. }