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 "path.h"
  15. #include "cache.h"
  16. #include <linux/kernel.h>
  17. #include <limits.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. #include <dirent.h>
  23. #include <unistd.h>
  24. static char bad_path[] = "/bad-path/";
  25. /*
  26. * One hack:
  27. */
  28. static char *get_pathname(void)
  29. {
  30. static char pathname_array[4][PATH_MAX];
  31. static int idx;
  32. return pathname_array[3 & ++idx];
  33. }
  34. static char *cleanup_path(char *path)
  35. {
  36. /* Clean it up */
  37. if (!memcmp(path, "./", 2)) {
  38. path += 2;
  39. while (*path == '/')
  40. path++;
  41. }
  42. return path;
  43. }
  44. char *mkpath(const char *fmt, ...)
  45. {
  46. va_list args;
  47. unsigned len;
  48. char *pathname = get_pathname();
  49. va_start(args, fmt);
  50. len = vsnprintf(pathname, PATH_MAX, fmt, args);
  51. va_end(args);
  52. if (len >= PATH_MAX)
  53. return bad_path;
  54. return cleanup_path(pathname);
  55. }
  56. int path__join(char *bf, size_t size, const char *path1, const char *path2)
  57. {
  58. return scnprintf(bf, size, "%s%s%s", path1, path1[0] ? "/" : "", path2);
  59. }
  60. int path__join3(char *bf, size_t size, const char *path1, const char *path2, const char *path3)
  61. {
  62. return scnprintf(bf, size, "%s%s%s%s%s", path1, path1[0] ? "/" : "",
  63. path2, path2[0] ? "/" : "", path3);
  64. }
  65. bool is_regular_file(const char *file)
  66. {
  67. struct stat st;
  68. if (stat(file, &st))
  69. return false;
  70. return S_ISREG(st.st_mode);
  71. }
  72. /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
  73. bool is_directory(const char *base_path, const struct dirent *dent)
  74. {
  75. char path[PATH_MAX];
  76. struct stat st;
  77. sprintf(path, "%s/%s", base_path, dent->d_name);
  78. if (stat(path, &st))
  79. return false;
  80. return S_ISDIR(st.st_mode);
  81. }