3
0

xreadlink.c 973 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * xreadlink.c - safe implementation of readlink.
  4. * Returns a NULL on failure...
  5. */
  6. #include "libbb.h"
  7. /*
  8. * NOTE: This function returns a malloced char* that you will have to free
  9. * yourself. You have been warned.
  10. */
  11. char *xreadlink(const char *path)
  12. {
  13. enum { GROWBY = 80 }; /* how large we will grow strings by */
  14. char *buf = NULL;
  15. int bufsize = 0, readsize = 0;
  16. do {
  17. buf = xrealloc(buf, bufsize += GROWBY);
  18. readsize = readlink(path, buf, bufsize); /* 1st try */
  19. if (readsize == -1) {
  20. bb_perror_msg("%s", path);
  21. free(buf);
  22. return NULL;
  23. }
  24. }
  25. while (bufsize < readsize + 1);
  26. buf[readsize] = '\0';
  27. return buf;
  28. }
  29. char *xmalloc_realpath(const char *path)
  30. {
  31. #if defined(__GLIBC__) && !defined(__UCLIBC__)
  32. /* glibc provides a non-standard extension */
  33. return realpath(path, NULL);
  34. #else
  35. char buf[PATH_MAX+1];
  36. /* on error returns NULL (xstrdup(NULL) ==NULL) */
  37. return xstrdup(realpath(path, buf));
  38. #endif
  39. }