strerror.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* strerror.c --- POSIX compatible system error routine
  2. Copyright (C) 2007-2021 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program 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
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <string.h>
  16. #include <errno.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include "intprops.h"
  21. #include "strerror-override.h"
  22. #include "verify.h"
  23. /* Use the system functions, not the gnulib overrides in this file. */
  24. #undef sprintf
  25. char *
  26. strerror (int n)
  27. #undef strerror
  28. {
  29. static char buf[STACKBUF_LEN];
  30. size_t len;
  31. /* Cast away const, due to the historical signature of strerror;
  32. callers should not be modifying the string. */
  33. const char *msg = strerror_override (n);
  34. if (msg)
  35. return (char *) msg;
  36. msg = strerror (n);
  37. /* Our strerror_r implementation might use the system's strerror
  38. buffer, so all other clients of strerror have to see the error
  39. copied into a buffer that we manage. This is not thread-safe,
  40. even if the system strerror is, but portable programs shouldn't
  41. be using strerror if they care about thread-safety. */
  42. if (!msg || !*msg)
  43. {
  44. static char const fmt[] = "Unknown error %d";
  45. verify (sizeof buf >= sizeof (fmt) + INT_STRLEN_BOUND (n));
  46. sprintf (buf, fmt, n);
  47. errno = EINVAL;
  48. return buf;
  49. }
  50. /* Fix STACKBUF_LEN if this ever aborts. */
  51. len = strlen (msg);
  52. if (sizeof buf <= len)
  53. abort ();
  54. memcpy (buf, msg, len + 1);
  55. return buf;
  56. }