|
23 | 23 | #include <errno.h> |
24 | 24 | #include <fcntl.h> |
25 | 25 | #include <string.h> |
| 26 | +#include <filesystem> |
| 27 | +#include <fstream> |
| 28 | + |
| 29 | +#include <fmt/format.h> |
26 | 30 |
|
27 | 31 | #include "PMEMDevice.h" |
28 | 32 | #include "libpmem.h" |
@@ -66,51 +70,31 @@ int PMEMDevice::_lock() |
66 | 70 |
|
67 | 71 | static int pmem_check_file_type(int fd, const char *pmem_file, uint64_t *total_size) |
68 | 72 | { |
69 | | - int rc = 0; |
70 | | - struct stat file_stat; |
71 | | - |
72 | | - rc = ::fstat(fd, &file_stat); |
73 | | - if (rc) { |
74 | | - return -1; |
75 | | - } |
76 | | - |
77 | | - if ((file_stat.st_mode & S_IFCHR) != S_IFCHR) { |
78 | | - return -1; |
| 73 | + namespace fs = std::filesystem; |
| 74 | + if (!fs::is_character_file(pmem_file)) { |
| 75 | + return -EINVAL; |
79 | 76 | } |
80 | | - |
81 | | - char spath[PATH_MAX], npath[PATH_MAX]; |
82 | | - snprintf(spath, PATH_MAX, "/sys/dev/char/%d:%d/subsystem", |
83 | | - major(file_stat.st_rdev), minor(file_stat.st_rdev)); |
84 | | - |
85 | | - char *real_path = realpath(spath, npath); |
86 | | - if (!real_path) { |
87 | | - return -1; |
| 77 | + struct stat file_stat; |
| 78 | + if (::fstat(fd, &file_stat)) { |
| 79 | + return -EINVAL; |
88 | 80 | } |
89 | | - |
| 81 | + fs::path char_dir = fmt::format("/sys/dev/char/{}:{}", |
| 82 | + major(file_stat.st_rdev), |
| 83 | + minor(file_stat.st_rdev)); |
90 | 84 | // Need to check if it is a DAX device |
91 | | - char *base_name = strrchr(real_path, '/'); |
92 | | - if (!base_name || strcmp("dax", base_name + 1)) { |
93 | | - return -1; |
| 85 | + if (auto subsys_path = char_dir / "subsystem"; |
| 86 | + fs::read_symlink(subsys_path).filename().string() != "dax") { |
| 87 | + return -EINVAL; |
94 | 88 | } |
95 | | - |
96 | | - snprintf(spath, PATH_MAX, "/sys/dev/char/%d:%d/size", |
97 | | - major(file_stat.st_rdev), minor(file_stat.st_rdev)); |
98 | | - FILE *sfile = fopen(spath, "r"); |
99 | | - if (!sfile) { |
100 | | - return -1; |
| 89 | + if (total_size == nullptr) { |
| 90 | + return 0; |
101 | 91 | } |
102 | | - |
103 | | - if (total_size != nullptr) { |
104 | | - rc = fscanf(sfile, "%lu", total_size); |
105 | | - if (rc < 0) { |
106 | | - rc = -1; |
107 | | - } else { |
108 | | - rc = 0; |
109 | | - } |
| 92 | + if (std::ifstream size_file(char_dir / "size"); size_file) { |
| 93 | + size_file >> *total_size; |
| 94 | + return size_file ? 0 : -EINVAL; |
| 95 | + } else { |
| 96 | + return -EINVAL; |
110 | 97 | } |
111 | | - |
112 | | - fclose(sfile); |
113 | | - return rc; |
114 | 98 | } |
115 | 99 |
|
116 | 100 | int PMEMDevice::open(const std::string& p) |
|
0 commit comments