fs.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /* TODO merge/factor into tools/lib/lk/debugfs.c */
  2. #include "util.h"
  3. #include "util/fs.h"
  4. static const char * const sysfs__fs_known_mountpoints[] = {
  5. "/sys",
  6. 0,
  7. };
  8. struct fs {
  9. const char *name;
  10. const char * const *mounts;
  11. char path[PATH_MAX + 1];
  12. bool found;
  13. long magic;
  14. };
  15. enum {
  16. FS__SYSFS = 0,
  17. };
  18. static struct fs fs__entries[] = {
  19. [FS__SYSFS] = {
  20. .name = "sysfs",
  21. .mounts = sysfs__fs_known_mountpoints,
  22. .magic = SYSFS_MAGIC,
  23. },
  24. };
  25. static bool fs__read_mounts(struct fs *fs)
  26. {
  27. bool found = false;
  28. char type[100];
  29. FILE *fp;
  30. fp = fopen("/proc/mounts", "r");
  31. if (fp == NULL)
  32. return NULL;
  33. while (!found &&
  34. fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n",
  35. fs->path, type) == 2) {
  36. if (strcmp(type, fs->name) == 0)
  37. found = true;
  38. }
  39. fclose(fp);
  40. return fs->found = found;
  41. }
  42. static int fs__valid_mount(const char *fs, long magic)
  43. {
  44. struct statfs st_fs;
  45. if (statfs(fs, &st_fs) < 0)
  46. return -ENOENT;
  47. else if (st_fs.f_type != magic)
  48. return -ENOENT;
  49. return 0;
  50. }
  51. static bool fs__check_mounts(struct fs *fs)
  52. {
  53. const char * const *ptr;
  54. ptr = fs->mounts;
  55. while (*ptr) {
  56. if (fs__valid_mount(*ptr, fs->magic) == 0) {
  57. fs->found = true;
  58. strcpy(fs->path, *ptr);
  59. return true;
  60. }
  61. ptr++;
  62. }
  63. return false;
  64. }
  65. static const char *fs__get_mountpoint(struct fs *fs)
  66. {
  67. if (fs__check_mounts(fs))
  68. return fs->path;
  69. return fs__read_mounts(fs) ? fs->path : NULL;
  70. }
  71. static const char *fs__mountpoint(int idx)
  72. {
  73. struct fs *fs = &fs__entries[idx];
  74. if (fs->found)
  75. return (const char *)fs->path;
  76. return fs__get_mountpoint(fs);
  77. }
  78. #define FS__MOUNTPOINT(name, idx) \
  79. const char *name##__mountpoint(void) \
  80. { \
  81. return fs__mountpoint(idx); \
  82. }
  83. FS__MOUNTPOINT(sysfs, FS__SYSFS);