areadlink.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* areadlink.c -- readlink wrapper to return the link name in malloc'd storage
  2. Unlike xreadlink and xreadlink_with_size, don't ever call exit.
  3. Copyright (C) 2001, 2003-2007, 2009-2020 Free Software Foundation, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. /* Written by Jim Meyering <jim@meyering.net>
  15. and Bruno Haible <bruno@clisp.org>. */
  16. #include <config.h>
  17. /* Specification. */
  18. #include "areadlink.h"
  19. #include "careadlinkat.h"
  20. #include <stdlib.h>
  21. #include <unistd.h>
  22. /* Get the symbolic link value of FILENAME and put it into BUFFER, with
  23. size BUFFER_SIZE. This function acts like readlink but has
  24. readlinkat's signature. */
  25. static ssize_t
  26. careadlinkatcwd (int fd, char const *filename, char *buffer,
  27. size_t buffer_size)
  28. {
  29. /* FD must be AT_FDCWD here, otherwise the caller is using this
  30. function in contexts it was not meant for. */
  31. if (fd != AT_FDCWD)
  32. abort ();
  33. return readlink (filename, buffer, buffer_size);
  34. }
  35. /* Call readlink to get the symbolic link value of FILENAME.
  36. Return a pointer to that NUL-terminated string in malloc'd storage.
  37. If readlink fails, return NULL and set errno.
  38. If allocation fails, or if the link value is longer than SIZE_MAX :-),
  39. return NULL and set errno to ENOMEM. */
  40. char *
  41. areadlink (char const *filename)
  42. {
  43. return careadlinkat (AT_FDCWD, filename, NULL, 0, NULL, careadlinkatcwd);
  44. }