Debian Codegraph @

Source/Core/Common/FileUtil.cpp

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/FileUtil.h"
5
6 #include <cstddef>
7 #include <cstdint>
8 #include <cstdio>
9 #include <cstring>
10 #include <fcntl.h>
11 #include <filesystem>
12 #include <limits.h>
13 #include <stack>
14 #include <string>
15 #include <system_error>
16 #include <vector>
17
18 #include "Common/CommonFuncs.h"
19 #include "Common/CommonPaths.h"
20 #include "Common/CommonTypes.h"
21 #ifdef ANDROID
22 #include "Common/Assert.h"
23 #endif
24 #ifdef __APPLE__
25 #include "Common/DynamicLibrary.h"
26 #endif
27 #include "Common/IOFile.h"
28 #include "Common/Logging/Log.h"
29 #include "Common/StringUtil.h"
30
31 #ifdef _WIN32
32 #include <Windows.h>
33 #include <Shlwapi.h>
34 #include <commdlg.h> // for GetSaveFileName
35 #include <direct.h> // getcwd
36 #include <io.h>
37 #include <objbase.h> // guid stuff
38 #include <shellapi.h>
39 #else
40 #include <libgen.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #endif
44
45 #if defined(__APPLE__)
46 #include <CoreFoundation/CFBundle.h>
47 #include <CoreFoundation/CFString.h>
48 #include <CoreFoundation/CFURL.h>
49 #include <mach-o/dyld.h>
50 #include <sys/param.h>
51 #endif
52
53 #ifdef ANDROID
54 #include "jni/AndroidCommon/AndroidCommon.h"
55 #endif
56
57 #if defined(__FreeBSD__)
58 #include <sys/sysctl.h>
59 #endif
60
61 namespace fs = std::filesystem;
62
63 namespace File
64 {
65 #ifdef ANDROID
66 static std::string s_android_sys_directory;
67 static std::string s_android_driver_directory;
68 static std::string s_android_lib_directory;
69 #endif
70
71 #ifdef __APPLE__
72 static Common::DynamicLibrary s_security_framework;
73
74 using DolSecTranslocateIsTranslocatedURL = Boolean (*)(CFURLRef path, bool* isTranslocated,
75 CFErrorRef* __nullable error);
76 using DolSecTranslocateCreateOriginalPathForURL = CFURLRef
77 __nullable (*)(CFURLRef translocatedPath, CFErrorRef* __nullable error);
78
79 static DolSecTranslocateIsTranslocatedURL s_is_translocated_url;
80 static DolSecTranslocateCreateOriginalPathForURL s_create_orig_path;
81 #endif
82
83 FileInfo::FileInfo(const std::string& path) : FileInfo(path.c_str())
84 {
85 }
86
87 FileInfo::FileInfo(const char* path)
88 {
89 #ifdef ANDROID
90 if (IsPathAndroidContent(path))
91 {
92 const jlong result = GetAndroidContentSizeAndIsDirectory(path);
93 m_status.type((result == -2) ? fs::file_type::directory : fs::file_type::regular);
94 m_size = (result >= 0) ? result : 0;
95 m_exists = result != -1;
96 }
97 else
98 #endif
99 {
100 const auto fs_path = StringToPath(path);
101 std::error_code error;
102 m_status = fs::status(fs_path, error);
103 m_size = fs::file_size(fs_path, error);
104 if (error)
105 m_size = 0;
106 m_exists = fs::exists(m_status);
107 }
108 }
109
110 bool FileInfo::Exists() const
111 {
112 return m_exists;
113 }
114
115 bool FileInfo::IsDirectory() const
116 {
117 return fs::is_directory(m_status);
118 }
119
120 bool FileInfo::IsFile() const
121 {
122 return Exists() ? !fs::is_directory(m_status) : false;
123 }
124
125 u64 FileInfo::GetSize() const
126 {
127 if (!IsFile())
128 return 0;
129 return m_size;
130 }
131
132 // Returns true if the path exists
133 bool Exists(const std::string& path)
134 {
135 return FileInfo(path).Exists();
136 }
137
138 // Returns true if the path exists and is a directory
139 bool IsDirectory(const std::string& path)
140 {
141 return FileInfo(path).IsDirectory();
142 }
143
144 // Returns true if the path exists and is a file
145 bool IsFile(const std::string& path)
146 {
147 return FileInfo(path).IsFile();
148 }
149
150 // Deletes a given filename, return true on success
151 // Doesn't supports deleting a directory
152 bool Delete(const std::string& filename, IfAbsentBehavior behavior)
153 {
154 DEBUG_LOG_FMT(COMMON, "{}: file {}", __func__, filename);
155
156 #ifdef ANDROID
157 if (filename.starts_with("content://"))
158 {
159 const bool success = DeleteAndroidContent(filename);
160 if (!success)
161 WARN_LOG_FMT(COMMON, "{} failed on {}", __func__, filename);
162 return success;
163 }
164 #endif
165
166 auto native_path = StringToPath(filename);
167 std::error_code error;
168 auto status = fs::status(native_path, error);
169
170 // Return true because we care about the file not being there, not the actual delete.
171 if (!fs::exists(status))
172 {
173 if (behavior == IfAbsentBehavior::ConsoleWarning)
174 {
175 WARN_LOG_FMT(COMMON, "{}: {} does not exist", __func__, filename);
176 }
177 return true;
178 }
179
180 // fs::remove can only delete an empty directory. Legacy dolphin behavior is just to bail.
181 if (fs::is_directory(status))
182 {
183 WARN_LOG_FMT(COMMON, "{} failed: {} is a directory", __func__, filename);
184 return false;
185 }
186
187 if (!fs::remove(native_path, error))
188 {
189 WARN_LOG_FMT(COMMON, "{}: failed on {}: {}", __func__, filename, error.message());
190 return false;
191 }
192
193 return true;
194 }
195
196 bool CreateDir(const std::string& path)
197 {
198 DEBUG_LOG_FMT(COMMON, "{}: directory {}", __func__, path);
199
200 std::error_code error;
201 auto native_path = StringToPath(path);
202 bool success = fs::create_directory(native_path, error);
203 // If the path was not created, check if it was a pre-existing directory
204 std::error_code error_ignored;
205 if (!success && fs::is_directory(native_path, error_ignored))
206 success = true;
207 if (!success)
208 ERROR_LOG_FMT(COMMON, "{}: failed on {}: {}", __func__, path, error.message());
209 return success;
210 }
211
212 bool CreateDirs(std::string_view path)
213 {
214 DEBUG_LOG_FMT(COMMON, "{}: directory {}", __func__, path);
215
216 std::error_code error;
217 auto native_path = StringToPath(path);
218 bool success = fs::create_directories(native_path, error);
219 // If the path was not created, check if it was a pre-existing directory
220 std::error_code error_ignored;
221 if (!success && fs::is_directory(native_path, error_ignored))
222 success = true;
223 if (!success)
224 ERROR_LOG_FMT(COMMON, "{}: failed on {}: {}", __func__, path, error.message());
225 return success;
226 }
227
228 bool CreateFullPath(std::string_view fullPath)
229 {
230 DEBUG_LOG_FMT(COMMON, "{}: path {}", __func__, fullPath);
231
232 std::error_code error;
233 auto native_path = StringToPath(fullPath).parent_path();
234 bool success = fs::create_directories(native_path, error);
235 // If the path was not created, check if it was a pre-existing directory
236 std::error_code error_ignored;
237 if (!success && fs::is_directory(native_path, error_ignored))
238 success = true;
239 if (!success)
240 ERROR_LOG_FMT(COMMON, "{}: failed on {}: {}", __func__, fullPath, error.message());
241 return success;
242 }
243
244 // Deletes a directory filename, returns true on success
245 bool DeleteDir(const std::string& filename, IfAbsentBehavior behavior)
246 {
247 DEBUG_LOG_FMT(COMMON, "{}: directory {}", __func__, filename);
248
249 auto native_path = StringToPath(filename);
250 std::error_code error;
251 auto status = fs::status(native_path, error);
252
253 // Return true because we care about the directory not being there, not the actual delete.
254 if (!fs::exists(status))
255 {
256 if (behavior == IfAbsentBehavior::ConsoleWarning)
257 {
258 WARN_LOG_FMT(COMMON, "{}: {} does not exist", __func__, filename);
259 }
260 return true;
261 }
262
263 // check if a directory
264 if (!fs::is_directory(status))
265 {
266 ERROR_LOG_FMT(COMMON, "{}: Not a directory {}", __func__, filename);
267 return false;
268 }
269
270 if (!fs::remove(native_path, error))
271 {
272 WARN_LOG_FMT(COMMON, "{}: failed on {}: {}", __func__, filename, error.message());
273 return false;
274 }
275
276 return true;
277 }
278
279 // renames file srcFilename to destFilename, returns true on success
280 bool Rename(const std::string& srcFilename, const std::string& destFilename)
281 {
282 DEBUG_LOG_FMT(COMMON, "{}: {} --> {}", __func__, srcFilename, destFilename);
283 std::error_code error;
284 std::filesystem::rename(StringToPath(srcFilename), StringToPath(destFilename), error);
285 if (error)
286 {
287 ERROR_LOG_FMT(COMMON, "{} failed: {} --> {}: {}", __func__, srcFilename, destFilename,
288 error.message());
289 }
290 return !error;
291 }
292
293 #ifndef _WIN32
294 static void FSyncPath(const char* path)
295 {
296 int fd = open(path, O_RDONLY);
297 if (fd != -1)
298 {
299 fsync(fd);
300 close(fd);
301 }
302 }
303 #endif
304
305 bool RenameSync(const std::string& srcFilename, const std::string& destFilename)
306 {
307 if (!Rename(srcFilename, destFilename))
308 return false;
309 #ifdef _WIN32
310 int fd = -1;
311 // XXX is this really needed?
312 errno_t err = _wsopen_s(&fd, UTF8ToWString(srcFilename).c_str(), _O_RDONLY, _SH_DENYNO,
313 _S_IREAD | _S_IWRITE);
314 if (!err && fd >= 0)
315 {
316 if (_commit(fd) != 0)
317 ERROR_LOG_FMT(COMMON, "{} sync failed on {}: {}", __func__, srcFilename, err);
318 close(fd);
319 }
320 #else
321 char* path = strdup(srcFilename.c_str());
322 FSyncPath(path);
323 FSyncPath(dirname(path));
324 free(path);
325 path = strdup(destFilename.c_str());
326 FSyncPath(dirname(path));
327 free(path);
328 #endif
329 return true;
330 }
331
332 bool CopyRegularFile(std::string_view source_path, std::string_view destination_path)
333 {
334 DEBUG_LOG_FMT(COMMON, "{}: {} --> {}", __func__, source_path, destination_path);
335
336 auto src_path = StringToPath(source_path);
337 auto dst_path = StringToPath(destination_path);
338 std::error_code error;
339 bool copied = fs::copy_file(src_path, dst_path, fs::copy_options::overwrite_existing, error);
340 if (!copied)
341 {
342 ERROR_LOG_FMT(COMMON, "{}: failed {} --> {}: {}", __func__, source_path, destination_path,
343 error.message());
344 }
345 return copied;
346 }
347
348 // Returns the size of a file (or returns 0 if the path isn't a file that exists)
349 u64 GetSize(const std::string& path)
350 {
351 return FileInfo(path).GetSize();
352 }
353
354 // Overloaded GetSize, accepts FILE*
355 u64 GetSize(FILE* f)
356 {
357 // can't use off_t here because it can be 32-bit
358 const u64 pos = ftello(f);
359 if (fseeko(f, 0, SEEK_END) != 0)
360 {
361 ERROR_LOG_FMT(COMMON, "GetSize: seek failed {}: {}", fmt::ptr(f), Common::LastStrerrorString());
362 return 0;
363 }
364
365 const u64 size = ftello(f);
366 if ((size != pos) && (fseeko(f, pos, SEEK_SET) != 0))
367 {
368 ERROR_LOG_FMT(COMMON, "GetSize: seek failed {}: {}", fmt::ptr(f), Common::LastStrerrorString());
369 return 0;
370 }
371
372 return size;
373 }
374
375 // creates an empty file filename, returns true on success
376 bool CreateEmptyFile(const std::string& filename)
377 {
378 DEBUG_LOG_FMT(COMMON, "CreateEmptyFile: {}", filename);
379
380 if (!File::IOFile(filename, "wb"))
381 {
382 ERROR_LOG_FMT(COMMON, "CreateEmptyFile: failed {}: {}", filename, Common::LastStrerrorString());
383 return false;
384 }
385
386 return true;
387 }
388
389 #ifdef ANDROID
390 static FSTEntry ScanDirectoryTreeAndroidContent(std::string directory, bool recursive)
391 {
392 FSTEntry parent_entry;
393 parent_entry.physicalName = directory;
394 parent_entry.isDirectory = true;
395 parent_entry.size = 0;
396
397 for (const auto& child_name : GetAndroidContentChildNames(directory))
398 {
399 const auto physical_name = directory + DIR_SEP + child_name;
400 const FileInfo file_info(physical_name);
401 FSTEntry entry;
402
403 entry.isDirectory = file_info.IsDirectory();
404 if (entry.isDirectory)
405 {
406 if (recursive)
407 entry = ScanDirectoryTreeAndroidContent(physical_name, true);
408 else
409 entry.size = 0;
410 parent_entry.size += entry.size;
411 }
412 else
413 {
414 entry.size = file_info.GetSize();
415 }
416 entry.virtualName = child_name;
417 entry.physicalName = physical_name;
418
419 ++parent_entry.size;
420 parent_entry.children.push_back(entry);
421 }
422
423 return parent_entry;
424 }
425 #endif
426
427 // Recursive or non-recursive list of files and directories under directory.
428 FSTEntry ScanDirectoryTree(const std::string& directory, bool recursive)
429 {
430 DEBUG_LOG_FMT(COMMON, "{}: directory {}", __func__, directory);
431
432 #ifdef ANDROID
433 if (IsPathAndroidContent(directory))
434 return ScanDirectoryTreeAndroidContent(directory, recursive);
435 #endif
436
437 auto path_to_physical_name = [](const fs::path& path) {
438 #ifdef _WIN32
439 return WStringToUTF8(path.generic_wstring());
440 #else
441 return PathToString(path);
442 #endif
443 };
444
445 auto dirent_to_fstent = [&](const fs::directory_entry& entry) {
446 return FSTEntry{
447 .isDirectory = entry.is_directory(),
448 .size = entry.is_directory() || entry.is_fifo() ? 0 : entry.file_size(),
449 .physicalName = path_to_physical_name(entry.path()),
450 .virtualName = PathToString(entry.path().filename()),
451 };
452 };
453
454 auto calc_dir_size = [](FSTEntry* dir) {
455 dir->size += dir->children.size();
456 for (auto& child : dir->children)
457 if (child.isDirectory)
458 dir->size += child.size;
459 };
460
461 const auto directory_path = StringToPath(directory);
462
463 FSTEntry parent_entry;
464 parent_entry.physicalName = path_to_physical_name(directory_path);
465 parent_entry.isDirectory = fs::is_directory(directory_path);
466 parent_entry.size = 0;
467
468 std::error_code error;
469 if (recursive)
470 {
471 int prev_depth = 0;
472 std::stack<FSTEntry*> dir_fsts;
473 dir_fsts.push(&parent_entry);
474 for (auto it = fs::recursive_directory_iterator(directory_path, error);
475 it != fs::recursive_directory_iterator(); it.increment(error))
476 {
477 const int cur_depth = it.depth();
478 if (cur_depth > prev_depth)
479 {
480 dir_fsts.push(&dir_fsts.top()->children.back());
481 }
482 else if (cur_depth < prev_depth)
483 {
484 while (dir_fsts.size() != static_cast<size_t>(cur_depth) + 1u)
485 {
486 calc_dir_size(dir_fsts.top());
487 dir_fsts.pop();
488 }
489 }
490 dir_fsts.top()->children.emplace_back(dirent_to_fstent(*it));
491 prev_depth = cur_depth;
492 }
493 while (dir_fsts.size())
494 {
495 calc_dir_size(dir_fsts.top());
496 dir_fsts.pop();
497 }
498 }
499 else
500 {
501 for (auto it = fs::directory_iterator(directory_path, error); it != fs::directory_iterator();
502 it.increment(error))
503 {
504 parent_entry.children.emplace_back(dirent_to_fstent(*it));
505 }
506 calc_dir_size(&parent_entry);
507 }
508
509 if (error)
510 {
511 // NOTE Possibly partial file list still returned
512 ERROR_LOG_FMT(COMMON, "{} error on {}: {}", __func__, directory, error.message());
513 }
514
515 return parent_entry;
516 }
517
518 // Deletes the given directory and anything under it. Returns true on success.
519 bool DeleteDirRecursively(const std::string& directory)
520 {
521 DEBUG_LOG_FMT(COMMON, "{}: {}", __func__, directory);
522
523 std::error_code error;
524 const std::uintmax_t num_removed = std::filesystem::remove_all(StringToPath(directory), error);
525 const bool success = num_removed != static_cast<std::uintmax_t>(-1) && !error;
526 if (!success)
527 ERROR_LOG_FMT(COMMON, "{}: {} failed. {}", __func__, directory, error.message());
528 return success;
529 }
530
531 bool Copy(std::string_view source_path, std::string_view dest_path, bool overwrite_existing)
532 {
533 DEBUG_LOG_FMT(COMMON, "{}: {} --> {} ({})", __func__, source_path, dest_path,
534 overwrite_existing ? "overwrite" : "preserve");
535
536 auto src_path = StringToPath(source_path);
537 auto dst_path = StringToPath(dest_path);
538 std::error_code error;
539 auto options = fs::copy_options::recursive;
540 if (overwrite_existing)
541 options |= fs::copy_options::overwrite_existing;
542 fs::copy(src_path, dst_path, options, error);
543 if (error)
544 {
545 std::error_code error_ignored;
546 if (fs::equivalent(src_path, dst_path, error_ignored))
547 return true;
548
549 ERROR_LOG_FMT(COMMON, "{}: failed {} --> {} ({}): {}", __func__, source_path, dest_path,
550 overwrite_existing ? "overwrite" : "preserve", error.message());
551 return false;
552 }
553 return true;
554 }
555
556 static bool MoveWithOverwrite(const std::filesystem::path& src, const std::filesystem::path& dst,
557 std::error_code& error)
558 {
559 fs::rename(src, dst, error);
560 if (!error)
561 return true;
562
563 // rename failed, try fallbacks
564
565 if (!fs::is_directory(src))
566 {
567 // src is not a directory (ie, probably a file), try to copy file + delete
568 if (!fs::copy_file(src, dst, fs::copy_options::overwrite_existing, error))
569 return false;
570 if (!fs::remove(src, error))
571 return false;
572 return true;
573 }
574
575 // src is a directory, recurse into it and try to move all sub-elements one by one
576 // this usually happens because the target is a non-empty directory
577 for (fs::directory_iterator it(src, error); it != fs::directory_iterator(); it.increment(error))
578 {
579 if (error)
580 return false;
581 if (!MoveWithOverwrite(it->path(), dst / it->path().filename(), error))
582 return false;
583 }
584 if (error)
585 return false;
586
587 // all sub-elements moved, remove top directory
588 if (!fs::remove(src, error))
589 return false;
590
591 return true;
592 }
593
594 bool MoveWithOverwrite(std::string_view source_path, std::string_view dest_path)
595 {
596 DEBUG_LOG_FMT(COMMON, "{}: {} --> {}", __func__, source_path, dest_path);
597 auto src_path = StringToPath(source_path);
598 auto dst_path = StringToPath(dest_path);
599 std::error_code error;
600 if (!MoveWithOverwrite(src_path, dst_path, error))
601 {
602 ERROR_LOG_FMT(COMMON, "{}: failed {} --> {}: {}", __func__, source_path, dest_path,
603 error.message());
604 }
605 return true;
606 }
607
608 // Returns the current directory
609 std::string GetCurrentDir()
610 {
611 std::error_code error;
612 auto directory = PathToString(fs::current_path(error));
613 if (error)
614 {
615 ERROR_LOG_FMT(COMMON, "{} failed: {}", __func__, error.message());
616 return {};
617 }
618 return directory;
619 }
620
621 // Sets the current directory to the given directory
622 bool SetCurrentDir(const std::string& directory)
623 {
624 std::error_code error;
625 fs::current_path(StringToPath(directory), error);
626 if (error)
627 {
628 ERROR_LOG_FMT(COMMON, "{} failed: {}", __func__, error.message());
629 return false;
630 }
631 return true;
632 }
633
634 std::string CreateTempDir()
635 {
636 #ifdef _WIN32
637 TCHAR temp[MAX_PATH];
638 if (!GetTempPath(MAX_PATH, temp))
639 return "";
640
641 GUID guid;
642 if (FAILED(CoCreateGuid(&guid)))
643 {
644 return "";
645 }
646 OLECHAR tguid[40]{};
647 if (!StringFromGUID2(guid, tguid, _countof(tguid)))
648 {
649 return "";
650 }
651 std::string dir = TStrToUTF8(temp) + "/" + TStrToUTF8(tguid);
652 if (!CreateDir(dir))
653 return "";
654 dir = ReplaceAll(dir, "\\", DIR_SEP);
655 return dir;
656 #else
657 const char* base = getenv("TMPDIR") ?: "/tmp";
658 std::string path = std::string(base) + "/DolphinWii.XXXXXX";
659 if (!mkdtemp(&path[0]))
660 return "";
661 return path;
662 #endif
663 }
664
665 std::string GetTempFilenameForAtomicWrite(std::string path)
666 {
667 std::error_code error;
668 auto absolute_path = fs::absolute(StringToPath(path), error);
669 if (!error)
670 path = PathToString(absolute_path);
671 return std::move(path) + ".xxx";
672 }
673
674 #if defined(__APPLE__)
675 std::string GetBundleDirectory()
676 {
677 CFURLRef bundle_ref = CFBundleCopyBundleURL(CFBundleGetMainBundle());
678
679 // Starting in macOS Sierra, apps downloaded from the Internet may be
680 // "translocated" to a read-only DMG and executed from there. This is
681 // done to prevent a scenario where an attacker can replace a trusted
682 // app's resources to load untrusted code.
683 //
684 // We should return Dolphin's actual location on the filesystem in
685 // this function, so bundle_ref will be untranslocated if necessary.
686 //
687 // More information: https://objective-see.com/blog/blog_0x15.html
688
689 // The APIs to deal with translocated paths are private, so we have
690 // to dynamically load them from the Security framework.
691 //
692 // The headers can be found under "Security" on opensource.apple.com:
693 // Security/OSX/libsecurity_translocate/lib/SecTranslocate.h
694 if (!s_security_framework.IsOpen())
695 {
696 s_security_framework.Open("/System/Library/Frameworks/Security.framework/Security");
697 s_security_framework.GetSymbol("SecTranslocateIsTranslocatedURL", &s_is_translocated_url);
698 s_security_framework.GetSymbol("SecTranslocateCreateOriginalPathForURL", &s_create_orig_path);
699 }
700
701 bool is_translocated = false;
702 s_is_translocated_url(bundle_ref, &is_translocated, nullptr);
703
704 if (is_translocated)
705 {
706 CFURLRef untranslocated_ref = s_create_orig_path(bundle_ref, nullptr);
707 CFRelease(bundle_ref);
708 bundle_ref = untranslocated_ref;
709 }
710
711 char app_bundle_path[MAXPATHLEN];
712 CFStringRef bundle_path = CFURLCopyFileSystemPath(bundle_ref, kCFURLPOSIXPathStyle);
713 CFStringGetFileSystemRepresentation(bundle_path, app_bundle_path, sizeof(app_bundle_path));
714 CFRelease(bundle_ref);
715 CFRelease(bundle_path);
716
717 return app_bundle_path;
718 }
719 #endif
720
721 std::string GetExePath()
722 {
723 #ifdef _WIN32
724 auto exe_path = Common::GetModuleName(nullptr);
725 if (!exe_path)
726 return {};
727 std::error_code error;
728 auto exe_path_absolute = fs::absolute(exe_path.value(), error);
729 if (error)
730 return {};
731 return PathToString(exe_path_absolute);
732 #elif defined(__APPLE__)
733 return GetBundleDirectory();
734 #elif defined(__FreeBSD__)
735 int name[4]{CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
736 size_t length = 0;
737 if (sysctl(name, 4, nullptr, &length, nullptr, 0) != 0 || length == 0)
738 return {};
739 std::string dolphin_exe_path(length, '\0');
740 if (sysctl(name, 4, dolphin_exe_path.data(), &length, nullptr, 0) != 0)
741 return {};
742 return dolphin_exe_path;
743 #else
744 char dolphin_exe_path[PATH_MAX];
745 ssize_t len = ::readlink("/proc/self/exe", dolphin_exe_path, sizeof(dolphin_exe_path));
746 if (len == -1 || len == sizeof(dolphin_exe_path))
747 {
748 len = 0;
749 }
750 dolphin_exe_path[len] = '\0';
751 return dolphin_exe_path;
752 #endif
753 }
754
755 std::string GetExeDirectory()
756 {
757 return PathToString(StringToPath(GetExePath()).parent_path());
758 }
759
760 static std::string CreateSysDirectoryPath()
761 {
762 #if defined(_WIN32) || defined(LINUX_LOCAL_DEV)
763 #define SYSDATA_DIR "Sys"
764 #elif defined __APPLE__
765 #define SYSDATA_DIR "Contents/Resources/Sys"
766 #else
767 #ifdef DATA_DIR
768 #define SYSDATA_DIR DATA_DIR "sys"
769 #else
770 #define SYSDATA_DIR "sys"
771 #endif
772 #endif
773
774 #if defined(__APPLE__)
775 const std::string sys_directory = GetBundleDirectory() + DIR_SEP SYSDATA_DIR DIR_SEP;
776 #elif defined(_WIN32) || defined(LINUX_LOCAL_DEV)
777 const std::string sys_directory = GetExeDirectory() + DIR_SEP SYSDATA_DIR DIR_SEP;
778 #elif defined ANDROID
779 const std::string sys_directory = s_android_sys_directory + DIR_SEP;
780 ASSERT_MSG(COMMON, !s_android_sys_directory.empty(), "Sys directory has not been set");
781 #else
782 const std::string sys_directory = SYSDATA_DIR DIR_SEP;
783 #endif
784
785 INFO_LOG_FMT(COMMON, "CreateSysDirectoryPath: Setting to {}", sys_directory);
786 return sys_directory;
787 }
788
789 const std::string& GetSysDirectory()
790 {
791 static const std::string sys_directory = CreateSysDirectoryPath();
792 return sys_directory;
793 }
794
795 #ifdef ANDROID
796 void SetSysDirectory(const std::string& path)
797 {
798 INFO_LOG_FMT(COMMON, "Setting Sys directory to {}", path);
799 ASSERT_MSG(COMMON, s_android_sys_directory.empty(), "Sys directory already set to {}",
800 s_android_sys_directory);
801 s_android_sys_directory = path;
802 }
803
804 void SetGpuDriverDirectories(const std::string& path, const std::string& lib_path)
805 {
806 INFO_LOG_FMT(COMMON, "Setting Driver directory to {} and library path to {}", path, lib_path);
807 ASSERT_MSG(COMMON, s_android_driver_directory.empty(), "Driver directory already set to {}",
808 s_android_driver_directory);
809 ASSERT_MSG(COMMON, s_android_lib_directory.empty(), "Library directory already set to {}",
810 s_android_lib_directory);
811 s_android_driver_directory = path;
812 s_android_lib_directory = lib_path;
813 }
814
815 const std::string GetGpuDriverDirectory(unsigned int dir_index)
816 {
817 switch (dir_index)
818 {
819 case D_GPU_DRIVERS_EXTRACTED:
820 return s_android_driver_directory + DIR_SEP GPU_DRIVERS_EXTRACTED DIR_SEP;
821 case D_GPU_DRIVERS_TMP:
822 return s_android_driver_directory + DIR_SEP GPU_DRIVERS_TMP DIR_SEP;
823 case D_GPU_DRIVERS_HOOKS:
824 return s_android_lib_directory;
825 case D_GPU_DRIVERS_FILE_REDIRECT:
826 return s_android_driver_directory + DIR_SEP GPU_DRIVERS_FILE_REDIRECT DIR_SEP;
827 }
828 return "";
829 }
830
831 #endif
832
833 static std::string s_user_paths[NUM_PATH_INDICES];
834 static void RebuildUserDirectories(unsigned int dir_index)
835 {
836 switch (dir_index)
837 {
838 case D_USER_IDX:
839 s_user_paths[D_GCUSER_IDX] = s_user_paths[D_USER_IDX] + GC_USER_DIR DIR_SEP;
840 s_user_paths[D_WIIROOT_IDX] = s_user_paths[D_USER_IDX] + WII_USER_DIR DIR_SEP;
841 s_user_paths[D_TRIUSER_IDX] = s_user_paths[D_USER_IDX] + TRI_USER_DIR DIR_SEP;
842 s_user_paths[D_CONFIG_IDX] = s_user_paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
843 s_user_paths[D_GAMESETTINGS_IDX] = s_user_paths[D_USER_IDX] + GAMESETTINGS_DIR DIR_SEP;
844 s_user_paths[D_MAPS_IDX] = s_user_paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
845 s_user_paths[D_CACHE_IDX] = s_user_paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
846 s_user_paths[D_COVERCACHE_IDX] = s_user_paths[D_CACHE_IDX] + COVERCACHE_DIR DIR_SEP;
847 s_user_paths[D_REDUMPCACHE_IDX] = s_user_paths[D_CACHE_IDX] + REDUMPCACHE_DIR DIR_SEP;
848 s_user_paths[D_SHADERCACHE_IDX] = s_user_paths[D_CACHE_IDX] + SHADERCACHE_DIR DIR_SEP;
849 s_user_paths[D_RETROACHIEVEMENTSCACHE_IDX] =
850 s_user_paths[D_CACHE_IDX] + RETROACHIEVEMENTSCACHE_DIR DIR_SEP;
851 s_user_paths[D_SHADERS_IDX] = s_user_paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
852 s_user_paths[D_STATESAVES_IDX] = s_user_paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
853 s_user_paths[D_SCREENSHOTS_IDX] = s_user_paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
854 s_user_paths[D_LOAD_IDX] = s_user_paths[D_USER_IDX] + LOAD_DIR DIR_SEP;
855 s_user_paths[D_HIRESTEXTURES_IDX] = s_user_paths[D_LOAD_IDX] + HIRES_TEXTURES_DIR DIR_SEP;
856 s_user_paths[D_RIIVOLUTION_IDX] = s_user_paths[D_LOAD_IDX] + RIIVOLUTION_DIR DIR_SEP;
857 s_user_paths[D_DUMP_IDX] = s_user_paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
858 s_user_paths[D_DUMPFRAMES_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
859 s_user_paths[D_DUMPOBJECTS_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_OBJECTS_DIR DIR_SEP;
860 s_user_paths[D_DUMPAUDIO_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
861 s_user_paths[D_DUMPTEXTURES_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
862 s_user_paths[D_DUMPDSP_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_DSP_DIR DIR_SEP;
863 s_user_paths[D_DUMPSSL_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_SSL_DIR DIR_SEP;
864 s_user_paths[D_DUMPDEBUG_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_DEBUG_DIR DIR_SEP;
865 s_user_paths[D_DUMPDEBUG_BRANCHWATCH_IDX] =
866 s_user_paths[D_DUMPDEBUG_IDX] + DUMP_DEBUG_BRANCHWATCH_DIR DIR_SEP;
867 s_user_paths[D_DUMPDEBUG_JITBLOCKS_IDX] =
868 s_user_paths[D_DUMPDEBUG_IDX] + DUMP_DEBUG_JITBLOCKS_DIR DIR_SEP;
869 s_user_paths[D_LOGS_IDX] = s_user_paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
870 s_user_paths[D_THEMES_IDX] = s_user_paths[D_USER_IDX] + THEMES_DIR DIR_SEP;
871 s_user_paths[D_STYLES_IDX] = s_user_paths[D_USER_IDX] + STYLES_DIR DIR_SEP;
872 s_user_paths[D_PIPES_IDX] = s_user_paths[D_USER_IDX] + PIPES_DIR DIR_SEP;
873 s_user_paths[D_WFSROOT_IDX] = s_user_paths[D_USER_IDX] + WFSROOT_DIR DIR_SEP;
874 s_user_paths[D_BACKUP_IDX] = s_user_paths[D_USER_IDX] + BACKUP_DIR DIR_SEP;
875 s_user_paths[D_RESOURCEPACK_IDX] = s_user_paths[D_USER_IDX] + RESOURCEPACK_DIR DIR_SEP;
876 s_user_paths[D_DYNAMICINPUT_IDX] = s_user_paths[D_LOAD_IDX] + DYNAMICINPUT_DIR DIR_SEP;
877 s_user_paths[D_GRAPHICSMOD_IDX] = s_user_paths[D_LOAD_IDX] + GRAPHICSMOD_DIR DIR_SEP;
878 s_user_paths[D_BANNERS_WIIROOT_IDX] = s_user_paths[D_LOAD_IDX] + WIIBANNERS_DIR DIR_SEP;
879 s_user_paths[D_FIRMWARE_IDX] = s_user_paths[D_LOAD_IDX] + FIRMWARE_DIR DIR_SEP;
880 s_user_paths[D_WIISYSCONF_IDX] = s_user_paths[D_WIIROOT_IDX] + WII_SYSCONF_DIR DIR_SEP;
881 s_user_paths[D_WIISDCARDSYNCFOLDER_IDX] = s_user_paths[D_LOAD_IDX] + WIISDSYNC_DIR DIR_SEP;
882 s_user_paths[F_DOLPHINCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + DOLPHIN_CONFIG;
883 s_user_paths[F_GCPADCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GCPAD_CONFIG;
884 s_user_paths[F_WIIPADCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + WIIPAD_CONFIG;
885 s_user_paths[F_GCKEYBOARDCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GCKEYBOARD_CONFIG;
886 s_user_paths[F_GFXCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GFX_CONFIG;
887 s_user_paths[F_LOGGERCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + LOGGER_CONFIG;
888 s_user_paths[F_DUALSHOCKUDPCLIENTCONFIG_IDX] =
889 s_user_paths[D_CONFIG_IDX] + DUALSHOCKUDPCLIENT_CONFIG;
890 s_user_paths[F_FREELOOKCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + FREELOOK_CONFIG;
891 s_user_paths[F_RETROACHIEVEMENTSCONFIG_IDX] =
892 s_user_paths[D_CONFIG_IDX] + RETROACHIEVEMENTS_CONFIG;
893 s_user_paths[F_MAINLOG_IDX] = s_user_paths[D_LOGS_IDX] + MAIN_LOG;
894 s_user_paths[F_MEM1DUMP_IDX] = s_user_paths[D_DUMP_IDX] + MEM1_DUMP;
895 s_user_paths[F_MEM2DUMP_IDX] = s_user_paths[D_DUMP_IDX] + MEM2_DUMP;
896 s_user_paths[F_ARAMDUMP_IDX] = s_user_paths[D_DUMP_IDX] + ARAM_DUMP;
897 s_user_paths[F_FAKEVMEMDUMP_IDX] = s_user_paths[D_DUMP_IDX] + FAKEVMEM_DUMP;
898 s_user_paths[F_GCSRAM_IDX] = s_user_paths[D_GCUSER_IDX] + GC_SRAM;
899 s_user_paths[F_WIISDCARDIMAGE_IDX] = s_user_paths[D_LOAD_IDX] + WII_SD_CARD_IMAGE;
900 s_user_paths[F_WIISYSCONF_IDX] = s_user_paths[D_WIISYSCONF_IDX] + WII_SYSCONF;
901
902 s_user_paths[D_MEMORYWATCHER_IDX] = s_user_paths[D_USER_IDX] + MEMORYWATCHER_DIR DIR_SEP;
903 s_user_paths[F_MEMORYWATCHERLOCATIONS_IDX] =
904 s_user_paths[D_MEMORYWATCHER_IDX] + MEMORYWATCHER_LOCATIONS;
905 s_user_paths[F_MEMORYWATCHERSOCKET_IDX] =
906 s_user_paths[D_MEMORYWATCHER_IDX] + MEMORYWATCHER_SOCKET;
907
908 s_user_paths[D_GBAUSER_IDX] = s_user_paths[D_USER_IDX] + GBA_USER_DIR DIR_SEP;
909 s_user_paths[D_GBASAVES_IDX] = s_user_paths[D_GBAUSER_IDX] + GBASAVES_DIR DIR_SEP;
910 s_user_paths[F_GBABIOS_IDX] = s_user_paths[D_GBAUSER_IDX] + GBA_BIOS;
911
912 s_user_paths[D_ASM_ROOT_IDX] = s_user_paths[D_USER_IDX] + ASSEMBLY_DIR DIR_SEP;
913
914 // The shader cache has moved to the cache directory, so remove the old one.
915 // TODO: remove that someday.
916 File::DeleteDirRecursively(s_user_paths[D_USER_IDX] + SHADERCACHE_LEGACY_DIR DIR_SEP);
917 break;
918
919 case D_CONFIG_IDX:
920 s_user_paths[F_DOLPHINCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + DOLPHIN_CONFIG;
921 s_user_paths[F_GCPADCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GCPAD_CONFIG;
922 s_user_paths[F_GCKEYBOARDCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GCKEYBOARD_CONFIG;
923 s_user_paths[F_WIIPADCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + WIIPAD_CONFIG;
924 s_user_paths[F_GFXCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + GFX_CONFIG;
925 s_user_paths[F_LOGGERCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + LOGGER_CONFIG;
926 s_user_paths[F_DUALSHOCKUDPCLIENTCONFIG_IDX] =
927 s_user_paths[D_CONFIG_IDX] + DUALSHOCKUDPCLIENT_CONFIG;
928 s_user_paths[F_FREELOOKCONFIG_IDX] = s_user_paths[D_CONFIG_IDX] + FREELOOK_CONFIG;
929 s_user_paths[F_RETROACHIEVEMENTSCONFIG_IDX] =
930 s_user_paths[D_CONFIG_IDX] + RETROACHIEVEMENTS_CONFIG;
931 break;
932
933 case D_CACHE_IDX:
934 s_user_paths[D_COVERCACHE_IDX] = s_user_paths[D_CACHE_IDX] + COVERCACHE_DIR DIR_SEP;
935 s_user_paths[D_REDUMPCACHE_IDX] = s_user_paths[D_CACHE_IDX] + REDUMPCACHE_DIR DIR_SEP;
936 s_user_paths[D_SHADERCACHE_IDX] = s_user_paths[D_CACHE_IDX] + SHADERCACHE_DIR DIR_SEP;
937 s_user_paths[D_RETROACHIEVEMENTSCACHE_IDX] =
938 s_user_paths[D_CACHE_IDX] + RETROACHIEVEMENTSCACHE_DIR DIR_SEP;
939 break;
940
941 case D_GCUSER_IDX:
942 s_user_paths[F_GCSRAM_IDX] = s_user_paths[D_GCUSER_IDX] + GC_SRAM;
943 break;
944
945 case D_DUMP_IDX:
946 s_user_paths[D_DUMPFRAMES_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
947 s_user_paths[D_DUMPOBJECTS_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_OBJECTS_DIR DIR_SEP;
948 s_user_paths[D_DUMPAUDIO_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
949 s_user_paths[D_DUMPTEXTURES_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
950 s_user_paths[D_DUMPDSP_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_DSP_DIR DIR_SEP;
951 s_user_paths[D_DUMPSSL_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_SSL_DIR DIR_SEP;
952 s_user_paths[D_DUMPDEBUG_IDX] = s_user_paths[D_DUMP_IDX] + DUMP_DEBUG_DIR DIR_SEP;
953 s_user_paths[D_DUMPDEBUG_BRANCHWATCH_IDX] =
954 s_user_paths[D_DUMPDEBUG_IDX] + DUMP_DEBUG_BRANCHWATCH_DIR DIR_SEP;
955 s_user_paths[D_DUMPDEBUG_JITBLOCKS_IDX] =
956 s_user_paths[D_DUMPDEBUG_IDX] + DUMP_DEBUG_JITBLOCKS_DIR DIR_SEP;
957 s_user_paths[F_MEM1DUMP_IDX] = s_user_paths[D_DUMP_IDX] + MEM1_DUMP;
958 s_user_paths[F_MEM2DUMP_IDX] = s_user_paths[D_DUMP_IDX] + MEM2_DUMP;
959 s_user_paths[F_ARAMDUMP_IDX] = s_user_paths[D_DUMP_IDX] + ARAM_DUMP;
960 s_user_paths[F_FAKEVMEMDUMP_IDX] = s_user_paths[D_DUMP_IDX] + FAKEVMEM_DUMP;
961 break;
962
963 case D_LOGS_IDX:
964 s_user_paths[F_MAINLOG_IDX] = s_user_paths[D_LOGS_IDX] + MAIN_LOG;
965 break;
966
967 case D_LOAD_IDX:
968 s_user_paths[D_HIRESTEXTURES_IDX] = s_user_paths[D_LOAD_IDX] + HIRES_TEXTURES_DIR DIR_SEP;
969 s_user_paths[D_RIIVOLUTION_IDX] = s_user_paths[D_LOAD_IDX] + RIIVOLUTION_DIR DIR_SEP;
970 s_user_paths[D_DYNAMICINPUT_IDX] = s_user_paths[D_LOAD_IDX] + DYNAMICINPUT_DIR DIR_SEP;
971 s_user_paths[D_GRAPHICSMOD_IDX] = s_user_paths[D_LOAD_IDX] + GRAPHICSMOD_DIR DIR_SEP;
972 s_user_paths[D_BANNERS_WIIROOT_IDX] = s_user_paths[D_LOAD_IDX] + WIIBANNERS_DIR DIR_SEP;
973 break;
974 }
975 }
976
977 // Gets a set user directory path
978 // Don't call prior to setting the base user directory
979 const std::string& GetUserPath(unsigned int dir_index)
980 {
981 return s_user_paths[dir_index];
982 }
983
984 // Sets a user directory path
985 // Rebuilds internal directory structure to compensate for the new directory
986 void SetUserPath(unsigned int dir_index, std::string path)
987 {
988 if (path.empty())
989 return;
990
991 #ifdef _WIN32
992 // On Windows, replace all '\' with '/' since we assume the latter in various places in the
993 // codebase.
994 for (char& c : path)
995 {
996 if (c == '\\')
997 c = '/';
998 }
999 #endif
1000
1001 // Directories should end with a separator, files should not.
1002 while (path.ends_with('/'))
1003 path.pop_back();
1004 if (path.empty())
1005 return;
1006 const bool is_directory = dir_index < FIRST_FILE_USER_PATH_IDX;
1007 if (is_directory)
1008 path.push_back('/');
1009
1010 s_user_paths[dir_index] = std::move(path);
1011 RebuildUserDirectories(dir_index);
1012 }
1013
1014 std::string GetThemeDir(const std::string& theme_name)
1015 {
1016 std::string dir = File::GetUserPath(D_THEMES_IDX) + theme_name + "/";
1017 if (Exists(dir))
1018 return dir;
1019
1020 // If the theme doesn't exist in the user dir, load from shared directory
1021 dir = GetSysDirectory() + THEMES_DIR "/" + theme_name + "/";
1022 if (Exists(dir))
1023 return dir;
1024
1025 // If the theme doesn't exist at all, load the default theme
1026 return GetSysDirectory() + THEMES_DIR "/" DEFAULT_THEME_DIR "/";
1027 }
1028
1029 bool WriteStringToFile(const std::string& filename, std::string_view str)
1030 {
1031 return File::IOFile(filename, "wb").WriteBytes(str.data(), str.size());
1032 }
1033
1034 bool ReadFileToString(const std::string& filename, std::string& str)
1035 {
1036 File::IOFile file(filename, "rb");
1037
1038 if (!file)
1039 return false;
1040
1041 str.resize(file.GetSize());
1042 return file.ReadArray(str.data(), str.size());
1043 }
1044
1045 } // namespace File