fs.c 2.0 KB

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