vfs_real.cpp 16 KB

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