_strerror.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright (C) 1991-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <libintl.h>
  15. #include <stdbool.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <sys/param.h>
  20. #include <_itoa.h>
  21. /* It is critical here that we always use the `dcgettext' function for
  22. the message translation. Since <libintl.h> only defines the macro
  23. `dgettext' to use `dcgettext' for optimizing programs this is not
  24. always guaranteed. */
  25. #ifndef dgettext
  26. # include <locale.h> /* We need LC_MESSAGES. */
  27. # define dgettext(domainname, msgid) dcgettext (domainname, msgid, LC_MESSAGES)
  28. #endif
  29. /* Return a string describing the errno code in ERRNUM. */
  30. char *
  31. __strerror_r (int errnum, char *buf, size_t buflen)
  32. {
  33. if (__builtin_expect (errnum < 0 || errnum >= _sys_nerr_internal
  34. || _sys_errlist_internal[errnum] == NULL, 0))
  35. {
  36. /* Buffer we use to print the number in. For a maximum size for
  37. `int' of 8 bytes we never need more than 20 digits. */
  38. char numbuf[21];
  39. const char *unk = _("Unknown error ");
  40. size_t unklen = strlen (unk);
  41. char *p, *q;
  42. bool negative = errnum < 0;
  43. numbuf[20] = '\0';
  44. p = _itoa_word (abs (errnum), &numbuf[20], 10, 0);
  45. /* Now construct the result while taking care for the destination
  46. buffer size. */
  47. q = __mempcpy (buf, unk, MIN (unklen, buflen));
  48. if (negative && unklen < buflen)
  49. {
  50. *q++ = '-';
  51. ++unklen;
  52. }
  53. if (unklen < buflen)
  54. memcpy (q, p, MIN ((size_t) (&numbuf[21] - p), buflen - unklen));
  55. /* Terminate the string in any case. */
  56. if (buflen > 0)
  57. buf[buflen - 1] = '\0';
  58. return buf;
  59. }
  60. return (char *) _(_sys_errlist_internal[errnum]);
  61. }
  62. weak_alias (__strerror_r, strerror_r)
  63. libc_hidden_def (__strerror_r)