file_util.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <array>
  5. #include <limits>
  6. #include <memory>
  7. #include <sstream>
  8. #include <unordered_map>
  9. #include "common/assert.h"
  10. #include "common/common_funcs.h"
  11. #include "common/common_paths.h"
  12. #include "common/file_util.h"
  13. #include "common/logging/log.h"
  14. #ifdef _WIN32
  15. #include <windows.h>
  16. // windows.h needs to be included before other windows headers
  17. #include <direct.h> // getcwd
  18. #include <io.h>
  19. #include <shellapi.h>
  20. #include <shlobj.h> // for SHGetFolderPath
  21. #include <tchar.h>
  22. #include "common/string_util.h"
  23. #ifdef _MSC_VER
  24. // 64 bit offsets for MSVC
  25. #define fseeko _fseeki64
  26. #define ftello _ftelli64
  27. #define fileno _fileno
  28. #endif
  29. // 64 bit offsets for MSVC and MinGW. MinGW also needs this for using _wstat64
  30. #define stat _stat64
  31. #define fstat _fstat64
  32. #else
  33. #ifdef __APPLE__
  34. #include <sys/param.h>
  35. #endif
  36. #include <cctype>
  37. #include <cerrno>
  38. #include <cstdlib>
  39. #include <cstring>
  40. #include <dirent.h>
  41. #include <pwd.h>
  42. #include <unistd.h>
  43. #endif
  44. #if defined(__APPLE__)
  45. // CFURL contains __attribute__ directives that gcc does not know how to parse, so we need to just
  46. // ignore them if we're not using clang. The macro is only used to prevent linking against
  47. // functions that don't exist on older versions of macOS, and the worst case scenario is a linker
  48. // error, so this is perfectly safe, just inconvenient.
  49. #ifndef __clang__
  50. #define availability(...)
  51. #endif
  52. #include <CoreFoundation/CFBundle.h>
  53. #include <CoreFoundation/CFString.h>
  54. #include <CoreFoundation/CFURL.h>
  55. #ifdef availability
  56. #undef availability
  57. #endif
  58. #endif
  59. #include <algorithm>
  60. #include <sys/stat.h>
  61. #ifndef S_ISDIR
  62. #define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
  63. #endif
  64. // This namespace has various generic functions related to files and paths.
  65. // The code still needs a ton of cleanup.
  66. // REMEMBER: strdup considered harmful!
  67. namespace FileUtil {
  68. // Remove any ending forward slashes from directory paths
  69. // Modifies argument.
  70. static void StripTailDirSlashes(std::string& fname) {
  71. if (fname.length() <= 1) {
  72. return;
  73. }
  74. std::size_t i = fname.length();
  75. while (i > 0 && fname[i - 1] == DIR_SEP_CHR) {
  76. --i;
  77. }
  78. fname.resize(i);
  79. }
  80. bool Exists(const std::string& filename) {
  81. struct stat file_info;
  82. std::string copy(filename);
  83. StripTailDirSlashes(copy);
  84. #ifdef _WIN32
  85. // Windows needs a slash to identify a driver root
  86. if (copy.size() != 0 && copy.back() == ':')
  87. copy += DIR_SEP_CHR;
  88. int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info);
  89. #else
  90. int result = stat(copy.c_str(), &file_info);
  91. #endif
  92. return (result == 0);
  93. }
  94. bool IsDirectory(const std::string& filename) {
  95. struct stat file_info;
  96. std::string copy(filename);
  97. StripTailDirSlashes(copy);
  98. #ifdef _WIN32
  99. // Windows needs a slash to identify a driver root
  100. if (copy.size() != 0 && copy.back() == ':')
  101. copy += DIR_SEP_CHR;
  102. int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info);
  103. #else
  104. int result = stat(copy.c_str(), &file_info);
  105. #endif
  106. if (result < 0) {
  107. LOG_DEBUG(Common_Filesystem, "stat failed on {}: {}", filename, GetLastErrorMsg());
  108. return false;
  109. }
  110. return S_ISDIR(file_info.st_mode);
  111. }
  112. bool Delete(const std::string& filename) {
  113. LOG_TRACE(Common_Filesystem, "file {}", filename);
  114. // Return true because we care about the file no
  115. // being there, not the actual delete.
  116. if (!Exists(filename)) {
  117. LOG_DEBUG(Common_Filesystem, "{} does not exist", filename);
  118. return true;
  119. }
  120. // We can't delete a directory
  121. if (IsDirectory(filename)) {
  122. LOG_ERROR(Common_Filesystem, "Failed: {} is a directory", filename);
  123. return false;
  124. }
  125. #ifdef _WIN32
  126. if (!DeleteFileW(Common::UTF8ToUTF16W(filename).c_str())) {
  127. LOG_ERROR(Common_Filesystem, "DeleteFile failed on {}: {}", filename, GetLastErrorMsg());
  128. return false;
  129. }
  130. #else
  131. if (unlink(filename.c_str()) == -1) {
  132. LOG_ERROR(Common_Filesystem, "unlink failed on {}: {}", filename, GetLastErrorMsg());
  133. return false;
  134. }
  135. #endif
  136. return true;
  137. }
  138. bool CreateDir(const std::string& path) {
  139. LOG_TRACE(Common_Filesystem, "directory {}", path);
  140. #ifdef _WIN32
  141. if (::CreateDirectoryW(Common::UTF8ToUTF16W(path).c_str(), nullptr))
  142. return true;
  143. DWORD error = GetLastError();
  144. if (error == ERROR_ALREADY_EXISTS) {
  145. LOG_DEBUG(Common_Filesystem, "CreateDirectory failed on {}: already exists", path);
  146. return true;
  147. }
  148. LOG_ERROR(Common_Filesystem, "CreateDirectory failed on {}: {}", path, error);
  149. return false;
  150. #else
  151. if (mkdir(path.c_str(), 0755) == 0)
  152. return true;
  153. int err = errno;
  154. if (err == EEXIST) {
  155. LOG_DEBUG(Common_Filesystem, "mkdir failed on {}: already exists", path);
  156. return true;
  157. }
  158. LOG_ERROR(Common_Filesystem, "mkdir failed on {}: {}", path, strerror(err));
  159. return false;
  160. #endif
  161. }
  162. bool CreateFullPath(const std::string& fullPath) {
  163. int panicCounter = 100;
  164. LOG_TRACE(Common_Filesystem, "path {}", fullPath);
  165. if (FileUtil::Exists(fullPath)) {
  166. LOG_DEBUG(Common_Filesystem, "path exists {}", fullPath);
  167. return true;
  168. }
  169. std::size_t position = 0;
  170. while (true) {
  171. // Find next sub path
  172. position = fullPath.find(DIR_SEP_CHR, position);
  173. // we're done, yay!
  174. if (position == fullPath.npos)
  175. return true;
  176. // Include the '/' so the first call is CreateDir("/") rather than CreateDir("")
  177. std::string const subPath(fullPath.substr(0, position + 1));
  178. if (!FileUtil::IsDirectory(subPath) && !FileUtil::CreateDir(subPath)) {
  179. LOG_ERROR(Common, "CreateFullPath: directory creation failed");
  180. return false;
  181. }
  182. // A safety check
  183. panicCounter--;
  184. if (panicCounter <= 0) {
  185. LOG_ERROR(Common, "CreateFullPath: directory structure is too deep");
  186. return false;
  187. }
  188. position++;
  189. }
  190. }
  191. bool DeleteDir(const std::string& filename) {
  192. LOG_TRACE(Common_Filesystem, "directory {}", filename);
  193. // check if a directory
  194. if (!FileUtil::IsDirectory(filename)) {
  195. LOG_ERROR(Common_Filesystem, "Not a directory {}", filename);
  196. return false;
  197. }
  198. #ifdef _WIN32
  199. if (::RemoveDirectoryW(Common::UTF8ToUTF16W(filename).c_str()))
  200. return true;
  201. #else
  202. if (rmdir(filename.c_str()) == 0)
  203. return true;
  204. #endif
  205. LOG_ERROR(Common_Filesystem, "failed {}: {}", filename, GetLastErrorMsg());
  206. return false;
  207. }
  208. bool Rename(const std::string& srcFilename, const std::string& destFilename) {
  209. LOG_TRACE(Common_Filesystem, "{} --> {}", srcFilename, destFilename);
  210. #ifdef _WIN32
  211. if (_wrename(Common::UTF8ToUTF16W(srcFilename).c_str(),
  212. Common::UTF8ToUTF16W(destFilename).c_str()) == 0)
  213. return true;
  214. #else
  215. if (rename(srcFilename.c_str(), destFilename.c_str()) == 0)
  216. return true;
  217. #endif
  218. LOG_ERROR(Common_Filesystem, "failed {} --> {}: {}", srcFilename, destFilename,
  219. GetLastErrorMsg());
  220. return false;
  221. }
  222. bool Copy(const std::string& srcFilename, const std::string& destFilename) {
  223. LOG_TRACE(Common_Filesystem, "{} --> {}", srcFilename, destFilename);
  224. #ifdef _WIN32
  225. if (CopyFileW(Common::UTF8ToUTF16W(srcFilename).c_str(),
  226. Common::UTF8ToUTF16W(destFilename).c_str(), FALSE))
  227. return true;
  228. LOG_ERROR(Common_Filesystem, "failed {} --> {}: {}", srcFilename, destFilename,
  229. GetLastErrorMsg());
  230. return false;
  231. #else
  232. using CFilePointer = std::unique_ptr<FILE, decltype(&std::fclose)>;
  233. // Open input file
  234. CFilePointer input{fopen(srcFilename.c_str(), "rb"), std::fclose};
  235. if (!input) {
  236. LOG_ERROR(Common_Filesystem, "opening input failed {} --> {}: {}", srcFilename,
  237. destFilename, GetLastErrorMsg());
  238. return false;
  239. }
  240. // open output file
  241. CFilePointer output{fopen(destFilename.c_str(), "wb"), std::fclose};
  242. if (!output) {
  243. LOG_ERROR(Common_Filesystem, "opening output failed {} --> {}: {}", srcFilename,
  244. destFilename, GetLastErrorMsg());
  245. return false;
  246. }
  247. // copy loop
  248. std::array<char, 1024> buffer;
  249. while (!feof(input.get())) {
  250. // read input
  251. std::size_t rnum = fread(buffer.data(), sizeof(char), buffer.size(), input.get());
  252. if (rnum != buffer.size()) {
  253. if (ferror(input.get()) != 0) {
  254. LOG_ERROR(Common_Filesystem, "failed reading from source, {} --> {}: {}",
  255. srcFilename, destFilename, GetLastErrorMsg());
  256. return false;
  257. }
  258. }
  259. // write output
  260. std::size_t wnum = fwrite(buffer.data(), sizeof(char), rnum, output.get());
  261. if (wnum != rnum) {
  262. LOG_ERROR(Common_Filesystem, "failed writing to output, {} --> {}: {}", srcFilename,
  263. destFilename, GetLastErrorMsg());
  264. return false;
  265. }
  266. }
  267. return true;
  268. #endif
  269. }
  270. u64 GetSize(const std::string& filename) {
  271. if (!Exists(filename)) {
  272. LOG_ERROR(Common_Filesystem, "failed {}: No such file", filename);
  273. return 0;
  274. }
  275. if (IsDirectory(filename)) {
  276. LOG_ERROR(Common_Filesystem, "failed {}: is a directory", filename);
  277. return 0;
  278. }
  279. struct stat buf;
  280. #ifdef _WIN32
  281. if (_wstat64(Common::UTF8ToUTF16W(filename).c_str(), &buf) == 0)
  282. #else
  283. if (stat(filename.c_str(), &buf) == 0)
  284. #endif
  285. {
  286. LOG_TRACE(Common_Filesystem, "{}: {}", filename, buf.st_size);
  287. return buf.st_size;
  288. }
  289. LOG_ERROR(Common_Filesystem, "Stat failed {}: {}", filename, GetLastErrorMsg());
  290. return 0;
  291. }
  292. u64 GetSize(const int fd) {
  293. struct stat buf;
  294. if (fstat(fd, &buf) != 0) {
  295. LOG_ERROR(Common_Filesystem, "GetSize: stat failed {}: {}", fd, GetLastErrorMsg());
  296. return 0;
  297. }
  298. return buf.st_size;
  299. }
  300. u64 GetSize(FILE* f) {
  301. // can't use off_t here because it can be 32-bit
  302. u64 pos = ftello(f);
  303. if (fseeko(f, 0, SEEK_END) != 0) {
  304. LOG_ERROR(Common_Filesystem, "GetSize: seek failed {}: {}", fmt::ptr(f), GetLastErrorMsg());
  305. return 0;
  306. }
  307. u64 size = ftello(f);
  308. if ((size != pos) && (fseeko(f, pos, SEEK_SET) != 0)) {
  309. LOG_ERROR(Common_Filesystem, "GetSize: seek failed {}: {}", fmt::ptr(f), GetLastErrorMsg());
  310. return 0;
  311. }
  312. return size;
  313. }
  314. bool CreateEmptyFile(const std::string& filename) {
  315. LOG_TRACE(Common_Filesystem, "{}", filename);
  316. if (!FileUtil::IOFile(filename, "wb").IsOpen()) {
  317. LOG_ERROR(Common_Filesystem, "failed {}: {}", filename, GetLastErrorMsg());
  318. return false;
  319. }
  320. return true;
  321. }
  322. bool ForeachDirectoryEntry(u64* num_entries_out, const std::string& directory,
  323. DirectoryEntryCallable callback) {
  324. LOG_TRACE(Common_Filesystem, "directory {}", directory);
  325. // How many files + directories we found
  326. u64 found_entries = 0;
  327. // Save the status of callback function
  328. bool callback_error = false;
  329. #ifdef _WIN32
  330. // Find the first file in the directory.
  331. WIN32_FIND_DATAW ffd;
  332. HANDLE handle_find = FindFirstFileW(Common::UTF8ToUTF16W(directory + "\\*").c_str(), &ffd);
  333. if (handle_find == INVALID_HANDLE_VALUE) {
  334. FindClose(handle_find);
  335. return false;
  336. }
  337. // windows loop
  338. do {
  339. const std::string virtual_name(Common::UTF16ToUTF8(ffd.cFileName));
  340. #else
  341. DIR* dirp = opendir(directory.c_str());
  342. if (!dirp)
  343. return false;
  344. // non windows loop
  345. while (struct dirent* result = readdir(dirp)) {
  346. const std::string virtual_name(result->d_name);
  347. #endif
  348. if (virtual_name == "." || virtual_name == "..")
  349. continue;
  350. u64 ret_entries = 0;
  351. if (!callback(&ret_entries, directory, virtual_name)) {
  352. callback_error = true;
  353. break;
  354. }
  355. found_entries += ret_entries;
  356. #ifdef _WIN32
  357. } while (FindNextFileW(handle_find, &ffd) != 0);
  358. FindClose(handle_find);
  359. #else
  360. }
  361. closedir(dirp);
  362. #endif
  363. if (callback_error)
  364. return false;
  365. // num_entries_out is allowed to be specified nullptr, in which case we shouldn't try to set it
  366. if (num_entries_out != nullptr)
  367. *num_entries_out = found_entries;
  368. return true;
  369. }
  370. u64 ScanDirectoryTree(const std::string& directory, FSTEntry& parent_entry,
  371. unsigned int recursion) {
  372. const auto callback = [recursion, &parent_entry](u64* num_entries_out,
  373. const std::string& directory,
  374. const std::string& virtual_name) -> bool {
  375. FSTEntry entry;
  376. entry.virtualName = virtual_name;
  377. entry.physicalName = directory + DIR_SEP + virtual_name;
  378. if (IsDirectory(entry.physicalName)) {
  379. entry.isDirectory = true;
  380. // is a directory, lets go inside if we didn't recurse to often
  381. if (recursion > 0) {
  382. entry.size = ScanDirectoryTree(entry.physicalName, entry, recursion - 1);
  383. *num_entries_out += entry.size;
  384. } else {
  385. entry.size = 0;
  386. }
  387. } else { // is a file
  388. entry.isDirectory = false;
  389. entry.size = GetSize(entry.physicalName);
  390. }
  391. (*num_entries_out)++;
  392. // Push into the tree
  393. parent_entry.children.push_back(std::move(entry));
  394. return true;
  395. };
  396. u64 num_entries;
  397. return ForeachDirectoryEntry(&num_entries, directory, callback) ? num_entries : 0;
  398. }
  399. bool DeleteDirRecursively(const std::string& directory, unsigned int recursion) {
  400. const auto callback = [recursion](u64* num_entries_out, const std::string& directory,
  401. const std::string& virtual_name) -> bool {
  402. std::string new_path = directory + DIR_SEP_CHR + virtual_name;
  403. if (IsDirectory(new_path)) {
  404. if (recursion == 0)
  405. return false;
  406. return DeleteDirRecursively(new_path, recursion - 1);
  407. }
  408. return Delete(new_path);
  409. };
  410. if (!ForeachDirectoryEntry(nullptr, directory, callback))
  411. return false;
  412. // Delete the outermost directory
  413. FileUtil::DeleteDir(directory);
  414. return true;
  415. }
  416. void CopyDir(const std::string& source_path, const std::string& dest_path) {
  417. #ifndef _WIN32
  418. if (source_path == dest_path)
  419. return;
  420. if (!FileUtil::Exists(source_path))
  421. return;
  422. if (!FileUtil::Exists(dest_path))
  423. FileUtil::CreateFullPath(dest_path);
  424. DIR* dirp = opendir(source_path.c_str());
  425. if (!dirp)
  426. return;
  427. while (struct dirent* result = readdir(dirp)) {
  428. const std::string virtualName(result->d_name);
  429. // check for "." and ".."
  430. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  431. ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0')))
  432. continue;
  433. std::string source, dest;
  434. source = source_path + virtualName;
  435. dest = dest_path + virtualName;
  436. if (IsDirectory(source)) {
  437. source += '/';
  438. dest += '/';
  439. if (!FileUtil::Exists(dest))
  440. FileUtil::CreateFullPath(dest);
  441. CopyDir(source, dest);
  442. } else if (!FileUtil::Exists(dest))
  443. FileUtil::Copy(source, dest);
  444. }
  445. closedir(dirp);
  446. #endif
  447. }
  448. std::optional<std::string> GetCurrentDir() {
  449. // Get the current working directory (getcwd uses malloc)
  450. #ifdef _WIN32
  451. wchar_t* dir = _wgetcwd(nullptr, 0);
  452. if (!dir) {
  453. #else
  454. char* dir = getcwd(nullptr, 0);
  455. if (!dir) {
  456. #endif
  457. LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: {}", GetLastErrorMsg());
  458. return {};
  459. }
  460. #ifdef _WIN32
  461. std::string strDir = Common::UTF16ToUTF8(dir);
  462. #else
  463. std::string strDir = dir;
  464. #endif
  465. free(dir);
  466. return strDir;
  467. }
  468. bool SetCurrentDir(const std::string& directory) {
  469. #ifdef _WIN32
  470. return _wchdir(Common::UTF8ToUTF16W(directory).c_str()) == 0;
  471. #else
  472. return chdir(directory.c_str()) == 0;
  473. #endif
  474. }
  475. #if defined(__APPLE__)
  476. std::string GetBundleDirectory() {
  477. CFURLRef BundleRef;
  478. char AppBundlePath[MAXPATHLEN];
  479. // Get the main bundle for the app
  480. BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  481. CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
  482. CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
  483. CFRelease(BundleRef);
  484. CFRelease(BundlePath);
  485. return AppBundlePath;
  486. }
  487. #endif
  488. #ifdef _WIN32
  489. const std::string& GetExeDirectory() {
  490. static std::string exe_path;
  491. if (exe_path.empty()) {
  492. wchar_t wchar_exe_path[2048];
  493. GetModuleFileNameW(nullptr, wchar_exe_path, 2048);
  494. exe_path = Common::UTF16ToUTF8(wchar_exe_path);
  495. exe_path = exe_path.substr(0, exe_path.find_last_of('\\'));
  496. }
  497. return exe_path;
  498. }
  499. std::string AppDataRoamingDirectory() {
  500. PWSTR pw_local_path = nullptr;
  501. // Only supported by Windows Vista or later
  502. SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &pw_local_path);
  503. std::string local_path = Common::UTF16ToUTF8(pw_local_path);
  504. CoTaskMemFree(pw_local_path);
  505. return local_path;
  506. }
  507. #else
  508. /**
  509. * @return The user’s home directory on POSIX systems
  510. */
  511. static const std::string& GetHomeDirectory() {
  512. static std::string home_path;
  513. if (home_path.empty()) {
  514. const char* envvar = getenv("HOME");
  515. if (envvar) {
  516. home_path = envvar;
  517. } else {
  518. auto pw = getpwuid(getuid());
  519. ASSERT_MSG(pw,
  520. "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");
  521. home_path = pw->pw_dir;
  522. }
  523. }
  524. return home_path;
  525. }
  526. /**
  527. * Follows the XDG Base Directory Specification to get a directory path
  528. * @param envvar The XDG environment variable to get the value from
  529. * @return The directory path
  530. * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  531. */
  532. static const std::string GetUserDirectory(const std::string& envvar) {
  533. const char* directory = getenv(envvar.c_str());
  534. std::string user_dir;
  535. if (directory) {
  536. user_dir = directory;
  537. } else {
  538. std::string subdirectory;
  539. if (envvar == "XDG_DATA_HOME")
  540. subdirectory = DIR_SEP ".local" DIR_SEP "share";
  541. else if (envvar == "XDG_CONFIG_HOME")
  542. subdirectory = DIR_SEP ".config";
  543. else if (envvar == "XDG_CACHE_HOME")
  544. subdirectory = DIR_SEP ".cache";
  545. else
  546. ASSERT_MSG(false, "Unknown XDG variable {}.", envvar);
  547. user_dir = GetHomeDirectory() + subdirectory;
  548. }
  549. ASSERT_MSG(!user_dir.empty(), "User directory {} mustn’t be empty.", envvar);
  550. ASSERT_MSG(user_dir[0] == '/', "User directory {} must be absolute.", envvar);
  551. return user_dir;
  552. }
  553. #endif
  554. std::string GetSysDirectory() {
  555. std::string sysDir;
  556. #if defined(__APPLE__)
  557. sysDir = GetBundleDirectory();
  558. sysDir += DIR_SEP;
  559. sysDir += SYSDATA_DIR;
  560. #else
  561. sysDir = SYSDATA_DIR;
  562. #endif
  563. sysDir += DIR_SEP;
  564. LOG_DEBUG(Common_Filesystem, "Setting to {}:", sysDir);
  565. return sysDir;
  566. }
  567. const std::string& GetUserPath(UserPath path, const std::string& new_path) {
  568. static std::unordered_map<UserPath, std::string> paths;
  569. auto& user_path = paths[UserPath::UserDir];
  570. // Set up all paths and files on the first run
  571. if (user_path.empty()) {
  572. #ifdef _WIN32
  573. user_path = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
  574. if (!FileUtil::IsDirectory(user_path)) {
  575. user_path = AppDataRoamingDirectory() + DIR_SEP EMU_DATA_DIR DIR_SEP;
  576. } else {
  577. LOG_INFO(Common_Filesystem, "Using the local user directory");
  578. }
  579. paths.emplace(UserPath::ConfigDir, user_path + CONFIG_DIR DIR_SEP);
  580. paths.emplace(UserPath::CacheDir, user_path + CACHE_DIR DIR_SEP);
  581. #else
  582. if (FileUtil::Exists(ROOT_DIR DIR_SEP USERDATA_DIR)) {
  583. user_path = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
  584. paths.emplace(UserPath::ConfigDir, user_path + CONFIG_DIR DIR_SEP);
  585. paths.emplace(UserPath::CacheDir, user_path + CACHE_DIR DIR_SEP);
  586. } else {
  587. std::string data_dir = GetUserDirectory("XDG_DATA_HOME");
  588. std::string config_dir = GetUserDirectory("XDG_CONFIG_HOME");
  589. std::string cache_dir = GetUserDirectory("XDG_CACHE_HOME");
  590. user_path = data_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
  591. paths.emplace(UserPath::ConfigDir, config_dir + DIR_SEP EMU_DATA_DIR DIR_SEP);
  592. paths.emplace(UserPath::CacheDir, cache_dir + DIR_SEP EMU_DATA_DIR DIR_SEP);
  593. }
  594. #endif
  595. paths.emplace(UserPath::SDMCDir, user_path + SDMC_DIR DIR_SEP);
  596. paths.emplace(UserPath::NANDDir, user_path + NAND_DIR DIR_SEP);
  597. paths.emplace(UserPath::LoadDir, user_path + LOAD_DIR DIR_SEP);
  598. paths.emplace(UserPath::DumpDir, user_path + DUMP_DIR DIR_SEP);
  599. paths.emplace(UserPath::ShaderDir, user_path + SHADER_DIR DIR_SEP);
  600. paths.emplace(UserPath::SysDataDir, user_path + SYSDATA_DIR DIR_SEP);
  601. paths.emplace(UserPath::KeysDir, user_path + KEYS_DIR DIR_SEP);
  602. // TODO: Put the logs in a better location for each OS
  603. paths.emplace(UserPath::LogDir, user_path + LOG_DIR DIR_SEP);
  604. }
  605. if (!new_path.empty()) {
  606. if (!FileUtil::IsDirectory(new_path)) {
  607. LOG_ERROR(Common_Filesystem, "Invalid path specified {}", new_path);
  608. return paths[path];
  609. } else {
  610. paths[path] = new_path;
  611. }
  612. switch (path) {
  613. case UserPath::RootDir:
  614. user_path = paths[UserPath::RootDir] + DIR_SEP;
  615. break;
  616. case UserPath::UserDir:
  617. user_path = paths[UserPath::RootDir] + DIR_SEP;
  618. paths[UserPath::ConfigDir] = user_path + CONFIG_DIR DIR_SEP;
  619. paths[UserPath::CacheDir] = user_path + CACHE_DIR DIR_SEP;
  620. paths[UserPath::SDMCDir] = user_path + SDMC_DIR DIR_SEP;
  621. paths[UserPath::NANDDir] = user_path + NAND_DIR DIR_SEP;
  622. break;
  623. default:
  624. break;
  625. }
  626. }
  627. return paths[path];
  628. }
  629. std::string GetHactoolConfigurationPath() {
  630. #ifdef _WIN32
  631. PWSTR pw_local_path = nullptr;
  632. if (SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &pw_local_path) != S_OK)
  633. return "";
  634. std::string local_path = Common::UTF16ToUTF8(pw_local_path);
  635. CoTaskMemFree(pw_local_path);
  636. return local_path + "\\.switch";
  637. #else
  638. return GetHomeDirectory() + "/.switch";
  639. #endif
  640. }
  641. std::string GetNANDRegistrationDir(bool system) {
  642. if (system)
  643. return GetUserPath(UserPath::NANDDir) + "system/Contents/registered/";
  644. return GetUserPath(UserPath::NANDDir) + "user/Contents/registered/";
  645. }
  646. std::size_t WriteStringToFile(bool text_file, const std::string& filename, std::string_view str) {
  647. return IOFile(filename, text_file ? "w" : "wb").WriteString(str);
  648. }
  649. std::size_t ReadFileToString(bool text_file, const std::string& filename, std::string& str) {
  650. IOFile file(filename, text_file ? "r" : "rb");
  651. if (!file.IsOpen())
  652. return 0;
  653. str.resize(static_cast<u32>(file.GetSize()));
  654. return file.ReadArray(&str[0], str.size());
  655. }
  656. void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
  657. std::array<char, 4>& extension) {
  658. const std::string forbidden_characters = ".\"/\\[]:;=, ";
  659. // On a FAT32 partition, 8.3 names are stored as a 11 bytes array, filled with spaces.
  660. short_name = {{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'}};
  661. extension = {{' ', ' ', ' ', '\0'}};
  662. std::string::size_type point = filename.rfind('.');
  663. if (point == filename.size() - 1)
  664. point = filename.rfind('.', point);
  665. // Get short name.
  666. int j = 0;
  667. for (char letter : filename.substr(0, point)) {
  668. if (forbidden_characters.find(letter, 0) != std::string::npos)
  669. continue;
  670. if (j == 8) {
  671. // TODO(Link Mauve): also do that for filenames containing a space.
  672. // TODO(Link Mauve): handle multiple files having the same short name.
  673. short_name[6] = '~';
  674. short_name[7] = '1';
  675. break;
  676. }
  677. short_name[j++] = toupper(letter);
  678. }
  679. // Get extension.
  680. if (point != std::string::npos) {
  681. j = 0;
  682. for (char letter : filename.substr(point + 1, 3))
  683. extension[j++] = toupper(letter);
  684. }
  685. }
  686. std::vector<std::string> SplitPathComponents(std::string_view filename) {
  687. std::string copy(filename);
  688. std::replace(copy.begin(), copy.end(), '\\', '/');
  689. std::vector<std::string> out;
  690. std::stringstream stream(copy);
  691. std::string item;
  692. while (std::getline(stream, item, '/')) {
  693. out.push_back(std::move(item));
  694. }
  695. return out;
  696. }
  697. std::string_view GetParentPath(std::string_view path) {
  698. const auto name_bck_index = path.rfind('\\');
  699. const auto name_fwd_index = path.rfind('/');
  700. std::size_t name_index;
  701. if (name_bck_index == std::string_view::npos || name_fwd_index == std::string_view::npos) {
  702. name_index = std::min(name_bck_index, name_fwd_index);
  703. } else {
  704. name_index = std::max(name_bck_index, name_fwd_index);
  705. }
  706. return path.substr(0, name_index);
  707. }
  708. std::string_view GetPathWithoutTop(std::string_view path) {
  709. if (path.empty()) {
  710. return path;
  711. }
  712. while (path[0] == '\\' || path[0] == '/') {
  713. path.remove_prefix(1);
  714. if (path.empty()) {
  715. return path;
  716. }
  717. }
  718. const auto name_bck_index = path.find('\\');
  719. const auto name_fwd_index = path.find('/');
  720. return path.substr(std::min(name_bck_index, name_fwd_index) + 1);
  721. }
  722. std::string_view GetFilename(std::string_view path) {
  723. const auto name_index = path.find_last_of("\\/");
  724. if (name_index == std::string_view::npos) {
  725. return {};
  726. }
  727. return path.substr(name_index + 1);
  728. }
  729. std::string_view GetExtensionFromFilename(std::string_view name) {
  730. const std::size_t index = name.rfind('.');
  731. if (index == std::string_view::npos) {
  732. return {};
  733. }
  734. return name.substr(index + 1);
  735. }
  736. std::string_view RemoveTrailingSlash(std::string_view path) {
  737. if (path.empty()) {
  738. return path;
  739. }
  740. if (path.back() == '\\' || path.back() == '/') {
  741. path.remove_suffix(1);
  742. return path;
  743. }
  744. return path;
  745. }
  746. std::string SanitizePath(std::string_view path_, DirectorySeparator directory_separator) {
  747. std::string path(path_);
  748. char type1 = directory_separator == DirectorySeparator::BackwardSlash ? '/' : '\\';
  749. char type2 = directory_separator == DirectorySeparator::BackwardSlash ? '\\' : '/';
  750. if (directory_separator == DirectorySeparator::PlatformDefault) {
  751. #ifdef _WIN32
  752. type1 = '/';
  753. type2 = '\\';
  754. #endif
  755. }
  756. std::replace(path.begin(), path.end(), type1, type2);
  757. path.erase(std::unique(path.begin(), path.end(),
  758. [type2](char c1, char c2) { return c1 == type2 && c2 == type2; }),
  759. path.end());
  760. return std::string(RemoveTrailingSlash(path));
  761. }
  762. IOFile::IOFile() {}
  763. IOFile::IOFile(const std::string& filename, const char openmode[], int flags) {
  764. Open(filename, openmode, flags);
  765. }
  766. IOFile::~IOFile() {
  767. Close();
  768. }
  769. IOFile::IOFile(IOFile&& other) noexcept {
  770. Swap(other);
  771. }
  772. IOFile& IOFile::operator=(IOFile&& other) noexcept {
  773. Swap(other);
  774. return *this;
  775. }
  776. void IOFile::Swap(IOFile& other) noexcept {
  777. std::swap(m_file, other.m_file);
  778. }
  779. bool IOFile::Open(const std::string& filename, const char openmode[], int flags) {
  780. Close();
  781. bool m_good;
  782. #ifdef _WIN32
  783. if (flags != 0) {
  784. m_file = _wfsopen(Common::UTF8ToUTF16W(filename).c_str(),
  785. Common::UTF8ToUTF16W(openmode).c_str(), flags);
  786. m_good = m_file != nullptr;
  787. } else {
  788. m_good = _wfopen_s(&m_file, Common::UTF8ToUTF16W(filename).c_str(),
  789. Common::UTF8ToUTF16W(openmode).c_str()) == 0;
  790. }
  791. #else
  792. m_file = std::fopen(filename.c_str(), openmode);
  793. m_good = m_file != nullptr;
  794. #endif
  795. return m_good;
  796. }
  797. bool IOFile::Close() {
  798. if (!IsOpen() || 0 != std::fclose(m_file))
  799. return false;
  800. m_file = nullptr;
  801. return true;
  802. }
  803. u64 IOFile::GetSize() const {
  804. if (IsOpen())
  805. return FileUtil::GetSize(m_file);
  806. return 0;
  807. }
  808. bool IOFile::Seek(s64 off, int origin) const {
  809. return IsOpen() && 0 == fseeko(m_file, off, origin);
  810. }
  811. u64 IOFile::Tell() const {
  812. if (IsOpen())
  813. return ftello(m_file);
  814. return std::numeric_limits<u64>::max();
  815. }
  816. bool IOFile::Flush() {
  817. return IsOpen() && 0 == std::fflush(m_file);
  818. }
  819. std::size_t IOFile::ReadImpl(void* data, std::size_t length, std::size_t data_size) const {
  820. if (!IsOpen()) {
  821. return std::numeric_limits<std::size_t>::max();
  822. }
  823. if (length == 0) {
  824. return 0;
  825. }
  826. DEBUG_ASSERT(data != nullptr);
  827. return std::fread(data, data_size, length, m_file);
  828. }
  829. std::size_t IOFile::WriteImpl(const void* data, std::size_t length, std::size_t data_size) {
  830. if (!IsOpen()) {
  831. return std::numeric_limits<std::size_t>::max();
  832. }
  833. if (length == 0) {
  834. return 0;
  835. }
  836. DEBUG_ASSERT(data != nullptr);
  837. return std::fwrite(data, data_size, length, m_file);
  838. }
  839. bool IOFile::Resize(u64 size) {
  840. return IsOpen() && 0 ==
  841. #ifdef _WIN32
  842. // ector: _chsize sucks, not 64-bit safe
  843. // F|RES: changed to _chsize_s. i think it is 64-bit safe
  844. _chsize_s(_fileno(m_file), size)
  845. #else
  846. // TODO: handle 64bit and growing
  847. ftruncate(fileno(m_file), size)
  848. #endif
  849. ;
  850. }
  851. } // namespace FileUtil