realpath_chk.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* Copyright (C) 2005-2026 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. <https://www.gnu.org/licenses/>. */
  14. #include <limits.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <errno.h>
  19. char *
  20. __realpath_chk (const char *buf, char *resolved, size_t resolvedlen)
  21. {
  22. #ifdef PATH_MAX
  23. if (resolvedlen < PATH_MAX)
  24. __chk_fail ();
  25. return __realpath (buf, resolved);
  26. #else
  27. long int pathmax;
  28. if (buf == NULL)
  29. {
  30. __set_errno (EINVAL);
  31. return NULL;
  32. }
  33. pathmax = __pathconf (buf, _PC_PATH_MAX);
  34. if (pathmax != -1)
  35. {
  36. /* We do have a fixed limit. */
  37. if (resolvedlen < pathmax)
  38. __chk_fail ();
  39. return __realpath (buf, resolved);
  40. }
  41. /* Since there is no fixed limit we check whether the size is large
  42. enough. */
  43. char *res = __realpath (buf, NULL);
  44. if (res != NULL)
  45. {
  46. size_t actlen = strlen (res) + 1;
  47. if (actlen > resolvedlen)
  48. __chk_fail ();
  49. memcpy (resolved, res, actlen);
  50. free (res);
  51. res = resolved;
  52. }
  53. return res;
  54. #endif
  55. }