fs.c 2.0 KB

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