file_util.cpp 27 KB

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