vfs_real.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <cstddef>
  5. #include <iterator>
  6. #include <utility>
  7. #include "common/assert.h"
  8. #include "common/fs/file.h"
  9. #include "common/fs/fs.h"
  10. #include "common/fs/path_util.h"
  11. #include "common/logging/log.h"
  12. #include "core/file_sys/vfs/vfs.h"
  13. #include "core/file_sys/vfs/vfs_real.h"
  14. // For FileTimeStampRaw
  15. #include <sys/stat.h>
  16. #ifdef _MSC_VER
  17. #define stat _stat64
  18. #endif
  19. namespace FileSys {
  20. namespace FS = Common::FS;
  21. namespace {
  22. constexpr size_t MaxOpenFiles = 512;
  23. constexpr FS::FileAccessMode ModeFlagsToFileAccessMode(OpenMode mode) {
  24. switch (mode) {
  25. case OpenMode::Read:
  26. return FS::FileAccessMode::Read;
  27. case OpenMode::Write:
  28. case OpenMode::ReadWrite:
  29. case OpenMode::AllowAppend:
  30. case OpenMode::All:
  31. return FS::FileAccessMode::ReadWrite;
  32. default:
  33. return {};
  34. }
  35. }
  36. } // Anonymous namespace
  37. RealVfsFilesystem::RealVfsFilesystem() : VfsFilesystem(nullptr) {}
  38. RealVfsFilesystem::~RealVfsFilesystem() = default;
  39. std::string RealVfsFilesystem::GetName() const {
  40. return "Real";
  41. }
  42. bool RealVfsFilesystem::IsReadable() const {
  43. return true;
  44. }
  45. bool RealVfsFilesystem::IsWritable() const {
  46. return true;
  47. }
  48. VfsEntryType RealVfsFilesystem::GetEntryType(std::string_view path_) const {
  49. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  50. if (!FS::Exists(path)) {
  51. return VfsEntryType::None;
  52. }
  53. if (FS::IsDir(path)) {
  54. return VfsEntryType::Directory;
  55. }
  56. return VfsEntryType::File;
  57. }
  58. VirtualFile RealVfsFilesystem::OpenFileFromEntry(std::string_view path_, std::optional<u64> size,
  59. OpenMode perms) {
  60. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  61. std::scoped_lock lk{list_lock};
  62. if (auto it = cache.find(path); it != cache.end()) {
  63. if (auto file = it->second.lock(); file) {
  64. return file;
  65. }
  66. }
  67. if (!size && !FS::IsFile(path)) {
  68. return nullptr;
  69. }
  70. auto reference = std::make_unique<FileReference>();
  71. this->InsertReferenceIntoListLocked(*reference);
  72. auto file = std::shared_ptr<RealVfsFile>(
  73. new RealVfsFile(*this, std::move(reference), path, perms, size));
  74. cache[path] = file;
  75. return file;
  76. }
  77. VirtualFile RealVfsFilesystem::OpenFile(std::string_view path_, OpenMode perms) {
  78. return OpenFileFromEntry(path_, {}, perms);
  79. }
  80. VirtualFile RealVfsFilesystem::CreateFile(std::string_view path_, OpenMode perms) {
  81. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  82. {
  83. std::scoped_lock lk{list_lock};
  84. cache.erase(path);
  85. }
  86. // Current usages of CreateFile expect to delete the contents of an existing file.
  87. if (FS::IsFile(path)) {
  88. FS::IOFile temp{path, FS::FileAccessMode::Write, FS::FileType::BinaryFile};
  89. if (!temp.IsOpen()) {
  90. return nullptr;
  91. }
  92. temp.Close();
  93. return OpenFile(path, perms);
  94. }
  95. if (!FS::NewFile(path)) {
  96. return nullptr;
  97. }
  98. return OpenFile(path, perms);
  99. }
  100. VirtualFile RealVfsFilesystem::CopyFile(std::string_view old_path_, std::string_view new_path_) {
  101. // Unused
  102. return nullptr;
  103. }
  104. VirtualFile RealVfsFilesystem::MoveFile(std::string_view old_path_, std::string_view new_path_) {
  105. const auto old_path = FS::SanitizePath(old_path_, FS::DirectorySeparator::PlatformDefault);
  106. const auto new_path = FS::SanitizePath(new_path_, FS::DirectorySeparator::PlatformDefault);
  107. {
  108. std::scoped_lock lk{list_lock};
  109. cache.erase(old_path);
  110. cache.erase(new_path);
  111. }
  112. if (!FS::RenameFile(old_path, new_path)) {
  113. return nullptr;
  114. }
  115. return OpenFile(new_path, OpenMode::ReadWrite);
  116. }
  117. bool RealVfsFilesystem::DeleteFile(std::string_view path_) {
  118. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  119. {
  120. std::scoped_lock lk{list_lock};
  121. cache.erase(path);
  122. }
  123. return FS::RemoveFile(path);
  124. }
  125. VirtualDir RealVfsFilesystem::OpenDirectory(std::string_view path_, OpenMode perms) {
  126. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  127. return std::shared_ptr<RealVfsDirectory>(new RealVfsDirectory(*this, path, perms));
  128. }
  129. VirtualDir RealVfsFilesystem::CreateDirectory(std::string_view path_, OpenMode perms) {
  130. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  131. if (!FS::CreateDirs(path)) {
  132. return nullptr;
  133. }
  134. return std::shared_ptr<RealVfsDirectory>(new RealVfsDirectory(*this, path, perms));
  135. }
  136. VirtualDir RealVfsFilesystem::CopyDirectory(std::string_view old_path_,
  137. std::string_view new_path_) {
  138. // Unused
  139. return nullptr;
  140. }
  141. VirtualDir RealVfsFilesystem::MoveDirectory(std::string_view old_path_,
  142. std::string_view new_path_) {
  143. const auto old_path = FS::SanitizePath(old_path_, FS::DirectorySeparator::PlatformDefault);
  144. const auto new_path = FS::SanitizePath(new_path_, FS::DirectorySeparator::PlatformDefault);
  145. if (!FS::RenameDir(old_path, new_path)) {
  146. return nullptr;
  147. }
  148. return OpenDirectory(new_path, OpenMode::ReadWrite);
  149. }
  150. bool RealVfsFilesystem::DeleteDirectory(std::string_view path_) {
  151. const auto path = FS::SanitizePath(path_, FS::DirectorySeparator::PlatformDefault);
  152. return FS::RemoveDirRecursively(path);
  153. }
  154. std::unique_lock<std::mutex> RealVfsFilesystem::RefreshReference(const std::string& path,
  155. OpenMode perms,
  156. FileReference& reference) {
  157. std::unique_lock lk{list_lock};
  158. // Temporarily remove from list.
  159. this->RemoveReferenceFromListLocked(reference);
  160. // Restore file if needed.
  161. if (!reference.file) {
  162. this->EvictSingleReferenceLocked();
  163. reference.file =
  164. FS::FileOpen(path, ModeFlagsToFileAccessMode(perms), FS::FileType::BinaryFile);
  165. if (reference.file) {
  166. num_open_files++;
  167. }
  168. }
  169. // Reinsert into list.
  170. this->InsertReferenceIntoListLocked(reference);
  171. return lk;
  172. }
  173. void RealVfsFilesystem::DropReference(std::unique_ptr<FileReference>&& reference) {
  174. std::scoped_lock lk{list_lock};
  175. // Remove from list.
  176. this->RemoveReferenceFromListLocked(*reference);
  177. // Close the file.
  178. if (reference->file) {
  179. reference->file.reset();
  180. num_open_files--;
  181. }
  182. }
  183. void RealVfsFilesystem::EvictSingleReferenceLocked() {
  184. if (num_open_files < MaxOpenFiles || open_references.empty()) {
  185. return;
  186. }
  187. // Get and remove from list.
  188. auto& reference = open_references.back();
  189. this->RemoveReferenceFromListLocked(reference);
  190. // Close the file.
  191. if (reference.file) {
  192. reference.file.reset();
  193. num_open_files--;
  194. }
  195. // Reinsert into closed list.
  196. this->InsertReferenceIntoListLocked(reference);
  197. }
  198. void RealVfsFilesystem::InsertReferenceIntoListLocked(FileReference& reference) {
  199. if (reference.file) {
  200. open_references.push_front(reference);
  201. } else {
  202. closed_references.push_front(reference);
  203. }
  204. }
  205. void RealVfsFilesystem::RemoveReferenceFromListLocked(FileReference& reference) {
  206. if (reference.file) {
  207. open_references.erase(open_references.iterator_to(reference));
  208. } else {
  209. closed_references.erase(closed_references.iterator_to(reference));
  210. }
  211. }
  212. RealVfsFile::RealVfsFile(RealVfsFilesystem& base_, std::unique_ptr<FileReference> reference_,
  213. const std::string& path_, OpenMode perms_, std::optional<u64> size_)
  214. : base(base_), reference(std::move(reference_)), path(path_),
  215. parent_path(FS::GetParentPath(path_)), path_components(FS::SplitPathComponentsCopy(path_)),
  216. size(size_), perms(perms_) {}
  217. RealVfsFile::~RealVfsFile() {
  218. base.DropReference(std::move(reference));
  219. }
  220. std::string RealVfsFile::GetName() const {
  221. return path_components.empty() ? "" : std::string(path_components.back());
  222. }
  223. std::size_t RealVfsFile::GetSize() const {
  224. if (size) {
  225. return *size;
  226. }
  227. auto lk = base.RefreshReference(path, perms, *reference);
  228. return reference->file ? reference->file->GetSize() : 0;
  229. }
  230. bool RealVfsFile::Resize(std::size_t new_size) {
  231. size.reset();
  232. auto lk = base.RefreshReference(path, perms, *reference);
  233. return reference->file ? reference->file->SetSize(new_size) : false;
  234. }
  235. VirtualDir RealVfsFile::GetContainingDirectory() const {
  236. return base.OpenDirectory(parent_path, perms);
  237. }
  238. bool RealVfsFile::IsWritable() const {
  239. return True(perms & OpenMode::Write);
  240. }
  241. bool RealVfsFile::IsReadable() const {
  242. return True(perms & OpenMode::Read);
  243. }
  244. std::size_t RealVfsFile::Read(u8* data, std::size_t length, std::size_t offset) const {
  245. auto lk = base.RefreshReference(path, perms, *reference);
  246. if (!reference->file || !reference->file->Seek(static_cast<s64>(offset))) {
  247. return 0;
  248. }
  249. return reference->file->ReadSpan(std::span{data, length});
  250. }
  251. std::size_t RealVfsFile::Write(const u8* data, std::size_t length, std::size_t offset) {
  252. size.reset();
  253. auto lk = base.RefreshReference(path, perms, *reference);
  254. if (!reference->file || !reference->file->Seek(static_cast<s64>(offset))) {
  255. return 0;
  256. }
  257. return reference->file->WriteSpan(std::span{data, length});
  258. }
  259. bool RealVfsFile::Rename(std::string_view name) {
  260. return base.MoveFile(path, parent_path + '/' + std::string(name)) != nullptr;
  261. }
  262. // TODO(DarkLordZach): MSVC would not let me combine the following two functions using 'if
  263. // constexpr' because there is a compile error in the branch not used.
  264. template <>
  265. std::vector<VirtualFile> RealVfsDirectory::IterateEntries<RealVfsFile, VfsFile>() const {
  266. if (perms == OpenMode::AllowAppend) {
  267. return {};
  268. }
  269. std::vector<VirtualFile> out;
  270. const FS::DirEntryCallable callback = [this,
  271. &out](const std::filesystem::directory_entry& entry) {
  272. const auto full_path_string = FS::PathToUTF8String(entry.path());
  273. out.emplace_back(base.OpenFileFromEntry(full_path_string, entry.file_size(), perms));
  274. return true;
  275. };
  276. FS::IterateDirEntries(path, callback, FS::DirEntryFilter::File);
  277. return out;
  278. }
  279. template <>
  280. std::vector<VirtualDir> RealVfsDirectory::IterateEntries<RealVfsDirectory, VfsDirectory>() const {
  281. if (perms == OpenMode::AllowAppend) {
  282. return {};
  283. }
  284. std::vector<VirtualDir> out;
  285. const FS::DirEntryCallable callback = [this,
  286. &out](const std::filesystem::directory_entry& entry) {
  287. const auto full_path_string = FS::PathToUTF8String(entry.path());
  288. out.emplace_back(base.OpenDirectory(full_path_string, perms));
  289. return true;
  290. };
  291. FS::IterateDirEntries(path, callback, FS::DirEntryFilter::Directory);
  292. return out;
  293. }
  294. RealVfsDirectory::RealVfsDirectory(RealVfsFilesystem& base_, const std::string& path_,
  295. OpenMode perms_)
  296. : base(base_), path(FS::RemoveTrailingSlash(path_)), parent_path(FS::GetParentPath(path)),
  297. path_components(FS::SplitPathComponentsCopy(path)), perms(perms_) {
  298. if (!FS::Exists(path) && True(perms & OpenMode::Write)) {
  299. void(FS::CreateDirs(path));
  300. }
  301. }
  302. RealVfsDirectory::~RealVfsDirectory() = default;
  303. VirtualFile RealVfsDirectory::GetFileRelative(std::string_view relative_path) const {
  304. const auto full_path = FS::SanitizePath(path + '/' + std::string(relative_path));
  305. if (!FS::Exists(full_path) || FS::IsDir(full_path)) {
  306. return nullptr;
  307. }
  308. return base.OpenFile(full_path, perms);
  309. }
  310. VirtualDir RealVfsDirectory::GetDirectoryRelative(std::string_view relative_path) const {
  311. const auto full_path = FS::SanitizePath(path + '/' + std::string(relative_path));
  312. if (!FS::Exists(full_path) || !FS::IsDir(full_path)) {
  313. return nullptr;
  314. }
  315. return base.OpenDirectory(full_path, perms);
  316. }
  317. VirtualFile RealVfsDirectory::GetFile(std::string_view name) const {
  318. return GetFileRelative(name);
  319. }
  320. VirtualDir RealVfsDirectory::GetSubdirectory(std::string_view name) const {
  321. return GetDirectoryRelative(name);
  322. }
  323. VirtualFile RealVfsDirectory::CreateFileRelative(std::string_view relative_path) {
  324. const auto full_path = FS::SanitizePath(path + '/' + std::string(relative_path));
  325. if (!FS::CreateParentDirs(full_path)) {
  326. return nullptr;
  327. }
  328. return base.CreateFile(full_path, perms);
  329. }
  330. VirtualDir RealVfsDirectory::CreateDirectoryRelative(std::string_view relative_path) {
  331. const auto full_path = FS::SanitizePath(path + '/' + std::string(relative_path));
  332. return base.CreateDirectory(full_path, perms);
  333. }
  334. bool RealVfsDirectory::DeleteSubdirectoryRecursive(std::string_view name) {
  335. const auto full_path = FS::SanitizePath(this->path + '/' + std::string(name));
  336. return base.DeleteDirectory(full_path);
  337. }
  338. std::vector<VirtualFile> RealVfsDirectory::GetFiles() const {
  339. return IterateEntries<RealVfsFile, VfsFile>();
  340. }
  341. FileTimeStampRaw RealVfsDirectory::GetFileTimeStamp(std::string_view path_) const {
  342. const auto full_path = FS::SanitizePath(path + '/' + std::string(path_));
  343. const auto fs_path = std::filesystem::path{FS::ToU8String(full_path)};
  344. struct stat file_status;
  345. #ifdef _WIN32
  346. const auto stat_result = _wstat64(fs_path.c_str(), &file_status);
  347. #else
  348. const auto stat_result = stat(fs_path.c_str(), &file_status);
  349. #endif
  350. if (stat_result != 0) {
  351. return {};
  352. }
  353. return {
  354. .created{static_cast<u64>(file_status.st_ctime)},
  355. .accessed{static_cast<u64>(file_status.st_atime)},
  356. .modified{static_cast<u64>(file_status.st_mtime)},
  357. };
  358. }
  359. std::vector<VirtualDir> RealVfsDirectory::GetSubdirectories() const {
  360. return IterateEntries<RealVfsDirectory, VfsDirectory>();
  361. }
  362. bool RealVfsDirectory::IsWritable() const {
  363. return True(perms & OpenMode::Write);
  364. }
  365. bool RealVfsDirectory::IsReadable() const {
  366. return True(perms & OpenMode::Read);
  367. }
  368. std::string RealVfsDirectory::GetName() const {
  369. return path_components.empty() ? "" : std::string(path_components.back());
  370. }
  371. VirtualDir RealVfsDirectory::GetParentDirectory() const {
  372. if (path_components.size() <= 1) {
  373. return nullptr;
  374. }
  375. return base.OpenDirectory(parent_path, perms);
  376. }
  377. VirtualDir RealVfsDirectory::CreateSubdirectory(std::string_view name) {
  378. const std::string subdir_path = (path + '/').append(name);
  379. return base.CreateDirectory(subdir_path, perms);
  380. }
  381. VirtualFile RealVfsDirectory::CreateFile(std::string_view name) {
  382. const std::string file_path = (path + '/').append(name);
  383. return base.CreateFile(file_path, perms);
  384. }
  385. bool RealVfsDirectory::DeleteSubdirectory(std::string_view name) {
  386. const std::string subdir_path = (path + '/').append(name);
  387. return base.DeleteDirectory(subdir_path);
  388. }
  389. bool RealVfsDirectory::DeleteFile(std::string_view name) {
  390. const std::string file_path = (path + '/').append(name);
  391. return base.DeleteFile(file_path);
  392. }
  393. bool RealVfsDirectory::Rename(std::string_view name) {
  394. const std::string new_name = (parent_path + '/').append(name);
  395. return base.MoveFile(path, new_name) != nullptr;
  396. }
  397. std::string RealVfsDirectory::GetFullPath() const {
  398. auto out = path;
  399. std::replace(out.begin(), out.end(), '\\', '/');
  400. return out;
  401. }
  402. std::map<std::string, VfsEntryType, std::less<>> RealVfsDirectory::GetEntries() const {
  403. if (perms == OpenMode::AllowAppend) {
  404. return {};
  405. }
  406. std::map<std::string, VfsEntryType, std::less<>> out;
  407. const FS::DirEntryCallable callback = [&out](const std::filesystem::directory_entry& entry) {
  408. const auto filename = FS::PathToUTF8String(entry.path().filename());
  409. out.insert_or_assign(filename,
  410. entry.is_directory() ? VfsEntryType::Directory : VfsEntryType::File);
  411. return true;
  412. };
  413. FS::IterateDirEntries(path, callback);
  414. return out;
  415. }
  416. } // namespace FileSys