path.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * I'm tired of doing "vsnprintf()" etc just to open a
  4. * file, so here's a "return static buffer with printf"
  5. * interface for paths.
  6. *
  7. * It's obviously not thread-safe. Sue me. But it's quite
  8. * useful for doing things like
  9. *
  10. * f = open(mkpath("%s/%s.perf", base, name), O_RDONLY);
  11. *
  12. * which is what it's designed for.
  13. */
  14. #include "cache.h"
  15. #include "path.h"
  16. #include <linux/kernel.h>
  17. #include <limits.h>
  18. #include <stdio.h>
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <dirent.h>
  22. #include <unistd.h>
  23. static char bad_path[] = "/bad-path/";
  24. /*
  25. * One hack:
  26. */
  27. static char *get_pathname(void)
  28. {
  29. static char pathname_array[4][PATH_MAX];
  30. static int idx;
  31. return pathname_array[3 & ++idx];
  32. }
  33. static char *cleanup_path(char *path)
  34. {
  35. /* Clean it up */
  36. if (!memcmp(path, "./", 2)) {
  37. path += 2;
  38. while (*path == '/')
  39. path++;
  40. }
  41. return path;
  42. }
  43. char *mkpath(const char *fmt, ...)
  44. {
  45. va_list args;
  46. unsigned len;
  47. char *pathname = get_pathname();
  48. va_start(args, fmt);
  49. len = vsnprintf(pathname, PATH_MAX, fmt, args);
  50. va_end(args);
  51. if (len >= PATH_MAX)
  52. return bad_path;
  53. return cleanup_path(pathname);
  54. }
  55. int path__join(char *bf, size_t size, const char *path1, const char *path2)
  56. {
  57. return scnprintf(bf, size, "%s%s%s", path1, path1[0] ? "/" : "", path2);
  58. }
  59. int path__join3(char *bf, size_t size, const char *path1, const char *path2, const char *path3)
  60. {
  61. return scnprintf(bf, size, "%s%s%s%s%s", path1, path1[0] ? "/" : "",
  62. path2, path2[0] ? "/" : "", path3);
  63. }
  64. bool is_regular_file(const char *file)
  65. {
  66. struct stat st;
  67. if (stat(file, &st))
  68. return false;
  69. return S_ISREG(st.st_mode);
  70. }
  71. /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
  72. bool is_directory(const char *base_path, const struct dirent *dent)
  73. {
  74. char path[PATH_MAX];
  75. struct stat st;
  76. sprintf(path, "%s/%s", base_path, dent->d_name);
  77. if (stat(path, &st))
  78. return false;
  79. return S_ISDIR(st.st_mode);
  80. }