file_util.cpp 29 KB

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