From 60b831f3699b303c2ba0dc002aacdcef409bc2e6 Mon Sep 17 00:00:00 2001 From: Michael Scire Date: Thu, 20 Jun 2019 04:04:33 -0700 Subject: [PATCH] ams_mitm: refactor for R_TRY --- stratosphere/ams_mitm/Makefile | 2 +- stratosphere/ams_mitm/source/amsmitm_main.cpp | 41 +- .../ams_mitm/source/amsmitm_modules.cpp | 12 +- .../ams_mitm/source/fs_mitm/fs_dir_utils.cpp | 50 +-- .../ams_mitm/source/fs_mitm/fs_dir_utils.hpp | 44 +-- .../fs_directory_redirection_filesystem.cpp | 126 +----- .../fs_directory_redirection_filesystem.hpp | 10 +- .../fs_directory_savedata_filesystem.cpp | 190 +++------- .../fs_directory_savedata_filesystem.hpp | 15 +- .../source/fs_mitm/fs_file_storage.cpp | 22 +- .../ams_mitm/source/fs_mitm/fs_idirectory.hpp | 9 +- .../ams_mitm/source/fs_mitm/fs_ifile.hpp | 9 +- .../source/fs_mitm/fs_ifilesystem.hpp | 156 ++------ .../ams_mitm/source/fs_mitm/fs_path_utils.cpp | 41 +- .../ams_mitm/source/fs_mitm/fs_save_utils.cpp | 6 +- .../fs_mitm/fs_subdirectory_filesystem.cpp | 152 ++------ .../fs_mitm/fs_subdirectory_filesystem.hpp | 16 +- .../source/fs_mitm/fsmitm_boot0storage.cpp | 33 +- .../source/fs_mitm/fsmitm_boot0storage.hpp | 80 ++-- .../source/fs_mitm/fsmitm_layeredrom.cpp | 42 +- .../source/fs_mitm/fsmitm_romfsbuild.cpp | 177 +++++---- .../source/fs_mitm/fsmitm_romstorage.hpp | 10 +- .../source/fs_mitm/fsmitm_service.cpp | 358 +++++++----------- .../source/ns_mitm/nsmitm_am_service.cpp | 9 +- .../ams_mitm/source/ns_mitm/nsmitm_main.cpp | 14 +- .../source/ns_mitm/nsmitm_web_service.cpp | 36 +- .../source/set_mitm/set_mitm_service.cpp | 13 +- .../source/set_mitm/set_mitm_service.hpp | 2 +- .../set_mitm/setsys_firmware_version.cpp | 10 +- .../source/set_mitm/setsys_mitm_service.cpp | 77 ++-- .../source/set_mitm/setsys_settings_items.cpp | 95 +++-- stratosphere/ams_mitm/source/utils.cpp | 51 +-- 32 files changed, 662 insertions(+), 1246 deletions(-) diff --git a/stratosphere/ams_mitm/Makefile b/stratosphere/ams_mitm/Makefile index ebe142e0b..a29d84a8a 100644 --- a/stratosphere/ams_mitm/Makefile +++ b/stratosphere/ams_mitm/Makefile @@ -31,7 +31,7 @@ DATA := data INCLUDES := include ../../common/include EXEFS_SRC := exefs_src -DEFINES := -DDISABLE_IPC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\" -DATMOSPHERE_GIT_REV=\"$(AMSREV)\" +DEFINES := -DRESULT_ABORT_ON_ASSERT -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\" -DATMOSPHERE_GIT_REV=\"$(AMSREV)\" #--------------------------------------------------------------------------------- # options for code generation diff --git a/stratosphere/ams_mitm/source/amsmitm_main.cpp b/stratosphere/ams_mitm/source/amsmitm_main.cpp index 1ce809199..608b5e584 100644 --- a/stratosphere/ams_mitm/source/amsmitm_main.cpp +++ b/stratosphere/ams_mitm/source/amsmitm_main.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include #include @@ -34,7 +34,7 @@ extern "C" { #define INNER_HEAP_SIZE 0x1000000 size_t nx_inner_heap_size = INNER_HEAP_SIZE; char nx_inner_heap[INNER_HEAP_SIZE]; - + void __libnx_initheap(void); void __appInit(void); void __appExit(void); @@ -69,27 +69,14 @@ void __libnx_initheap(void) { } void __appInit(void) { - Result rc; - SetFirmwareVersionForLibnx(); - + DoWithSmSession([&]() { - rc = fsInitialize(); - if (R_FAILED(rc)) { - std::abort(); - } - - rc = pmdmntInitialize(); - if (R_FAILED(rc)) { - std::abort(); - } - - rc = pminfoInitialize(); - if (R_FAILED(rc)) { - std::abort(); - } + R_ASSERT(fsInitialize()); + R_ASSERT(pmdmntInitialize()); + R_ASSERT(pminfoInitialize()); }); - + CheckAtmosphereVersion(CURRENT_ATMOSPHERE_VERSION); } @@ -102,19 +89,15 @@ int main(int argc, char **argv) { consoleDebugInit(debugDevice_SVC); HosThread initializer_thread; - + LaunchAllMitmModules(); - if (R_FAILED(initializer_thread.Initialize(&Utils::InitializeThreadFunc, NULL, 0x4000, 0x15))) { - std::abort(); - } - if (R_FAILED(initializer_thread.Start())) { - std::abort(); - } - + R_ASSERT(initializer_thread.Initialize(&Utils::InitializeThreadFunc, NULL, 0x4000, 0x15)); + R_ASSERT(initializer_thread.Start()); + /* Wait for all mitm modules to end. */ WaitAllMitmModules(); - + return 0; } diff --git a/stratosphere/ams_mitm/source/amsmitm_modules.cpp b/stratosphere/ams_mitm/source/amsmitm_modules.cpp index 50f3c60ef..b91e891b2 100644 --- a/stratosphere/ams_mitm/source/amsmitm_modules.cpp +++ b/stratosphere/ams_mitm/source/amsmitm_modules.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include #include @@ -43,16 +43,12 @@ void LaunchAllMitmModules() { /* Create thread for each module. */ for (u32 i = 0; i < static_cast(MitmModuleId_Count); i++) { const auto cur_module = &g_module_definitions[i]; - if (R_FAILED(g_module_threads[i].Initialize(cur_module->main, nullptr, cur_module->stack_size, cur_module->priority))) { - std::abort(); - } + R_ASSERT(g_module_threads[i].Initialize(cur_module->main, nullptr, cur_module->stack_size, cur_module->priority)); } - + /* Start thread for each module. */ for (u32 i = 0; i < static_cast(MitmModuleId_Count); i++) { - if (R_FAILED(g_module_threads[i].Start())) { - std::abort(); - } + R_ASSERT(g_module_threads[i].Start()); } } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.cpp index cf11c17f7..8d924971b 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.cpp @@ -21,15 +21,12 @@ #include "fs_ifile.hpp" Result FsDirUtils::CopyFile(IFileSystem *dst_fs, IFileSystem *src_fs, const FsPath &dst_parent_path, const FsPath &src_path, const FsDirectoryEntry *dir_ent, void *work_buf, size_t work_buf_size) { - Result rc; std::unique_ptr src_file; std::unique_ptr dst_file; const u64 file_size = dir_ent->fileSize; /* Open source file for reading. */ - if (R_FAILED((rc = src_fs->OpenFile(src_file, src_path, OpenMode_Read)))) { - return rc; - } + R_TRY(src_fs->OpenFile(src_file, src_path, OpenMode_Read)); /* Create and open destination file. */ { @@ -39,24 +36,16 @@ Result FsDirUtils::CopyFile(IFileSystem *dst_fs, IFileSystem *src_fs, const FsPa std::abort(); } - if (R_FAILED((rc = dst_fs->CreateFile(dst_path, file_size)))) { - return rc; - } - if (R_FAILED((rc = dst_fs->OpenFile(dst_file, dst_path, OpenMode_Write)))) { - return rc; - } + R_TRY(dst_fs->CreateFile(dst_path, file_size)); + R_TRY(dst_fs->OpenFile(dst_file, dst_path, OpenMode_Write)); } /* Read/Write work_buf_size chunks. */ u64 offset = 0; while (offset < file_size) { u64 read_size; - if (R_FAILED((rc = src_file->Read(&read_size, offset, work_buf, work_buf_size)))) { - return rc; - } - if (R_FAILED((rc = dst_file->Write(offset, work_buf, read_size)))) { - return rc; - } + R_TRY(src_file->Read(&read_size, offset, work_buf, work_buf_size)); + R_TRY(dst_file->Write(offset, work_buf, read_size)); offset += read_size; } @@ -99,12 +88,9 @@ Result FsDirUtils::CopyDirectoryRecursively(IFileSystem *dst_fs, IFileSystem *sr Result FsDirUtils::EnsureDirectoryExists(IFileSystem *fs, const FsPath &path) { FsPath normal_path; size_t normal_path_len; - Result rc; /* Normalize the path. */ - if (R_FAILED((rc = FsPathUtils::Normalize(normal_path.str, sizeof(normal_path.str) - 1, path.str, &normal_path_len)))) { - return rc; - } + R_TRY(FsPathUtils::Normalize(normal_path.str, sizeof(normal_path.str) - 1, path.str, &normal_path_len)); /* Repeatedly call CreateDirectory on each directory leading to the target. */ for (size_t i = 1; i < normal_path_len; i++) { @@ -112,22 +98,22 @@ Result FsDirUtils::EnsureDirectoryExists(IFileSystem *fs, const FsPath &path) { if (normal_path.str[i] == '/') { normal_path.str[i] = 0; { - rc = fs->CreateDirectory(normal_path); - if (rc == ResultFsPathAlreadyExists) { - rc = ResultSuccess; - } - if (R_FAILED(rc)) { - return rc; - } + R_TRY_CATCH(fs->CreateDirectory(normal_path)) { + R_CATCH(ResultFsPathAlreadyExists) { + /* If path already exists, there's no problem. */ + } + } R_END_TRY_CATCH; } normal_path.str[i] = '/'; } } /* Call CreateDirectory on the final path. */ - rc = fs->CreateDirectory(normal_path); - if (rc == ResultFsPathAlreadyExists) { - rc = ResultSuccess; - } - return rc; + R_TRY_CATCH(fs->CreateDirectory(normal_path)) { + R_CATCH(ResultFsPathAlreadyExists) { + /* If path already exists, there's no problem. */ + } + } R_END_TRY_CATCH; + + return ResultSuccess; } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.hpp index e41b02a2b..814cdc47b 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_dir_utils.hpp @@ -24,13 +24,10 @@ class FsDirUtils { private: template static Result IterateDirectoryRecursivelyInternal(IFileSystem *fs, FsPath &work_path, FsDirectoryEntry *ent_buf, OnEnterDir on_enter_dir, OnExitDir on_exit_dir, OnFile on_file) { - Result rc; std::unique_ptr dir; /* Open the directory. */ - if (R_FAILED((rc = fs->OpenDirectory(dir, work_path, DirectoryOpenMode_All)))) { - return rc; - } + R_TRY(fs->OpenDirectory(dir, work_path, DirectoryOpenMode_All)); const size_t parent_len = strnlen(work_path.str, sizeof(work_path.str) - 1); @@ -38,9 +35,7 @@ class FsDirUtils { while (true) { /* Read a single entry. */ u64 read_count; - if (R_FAILED((rc = dir->Read(&read_count, ent_buf, 1)))) { - return rc; - } + R_TRY(dir->Read(&read_count, ent_buf, 1)); /* If we're out of entries, we're done. */ if (read_count == 0) { @@ -59,25 +54,17 @@ class FsDirUtils { strncat(work_path.str, ent_buf->name, sizeof(work_path.str) - 1 - parent_len); if (is_dir) { /* Enter directory. */ - if (R_FAILED((rc = on_enter_dir(work_path, ent_buf)))) { - return rc; - } + R_TRY(on_enter_dir(work_path, ent_buf)); /* Append separator, recurse. */ strncat(work_path.str, "/", sizeof(work_path.str) - 1 - parent_len - child_name_len); - if (R_FAILED((rc = IterateDirectoryRecursivelyInternal(fs, work_path, ent_buf, on_enter_dir, on_exit_dir, on_file)))) { - return rc; - } + R_TRY(IterateDirectoryRecursivelyInternal(fs, work_path, ent_buf, on_enter_dir, on_exit_dir, on_file)); /* Exit directory. */ - if (R_FAILED((rc = on_exit_dir(work_path, ent_buf)))) { - return rc; - } + R_TRY(on_exit_dir(work_path, ent_buf)); } else { /* Call file handler. */ - if (R_FAILED((rc = on_file(work_path, ent_buf)))) { - return rc; - } + R_TRY(on_file(work_path, ent_buf)); } /* Restore parent path. */ @@ -132,7 +119,7 @@ class FsDirUtils { static Result CopyDirectoryRecursively(IFileSystem *fs, const FsPath &dst_path, const FsPath &src_path, void *work_buf, size_t work_buf_size) { return CopyDirectoryRecursively(fs, fs, dst_path, src_path, work_buf, work_buf_size); } - + /* Ensure directory existence. */ static Result EnsureDirectoryExists(IFileSystem *fs, const FsPath &path); @@ -140,19 +127,16 @@ class FsDirUtils { template static Result RetryUntilTargetNotLocked(F f) { const size_t MaxRetries = 10; - Result rc = ResultSuccess; for (size_t i = 0; i < MaxRetries; i++) { - rc = f(); - - if (rc != ResultFsTargetLocked) { - break; - } - - /* If target is locked, wait 100ms and try again. */ - svcSleepThread(100'000'000ul); + R_TRY_CATCH(f()) { + R_CATCH(ResultFsTargetLocked) { + /* If target is locked, wait 100ms and try again. */ + svcSleepThread(100'000'000ul); + } + } R_END_TRY_CATCH; } - return rc; + return ResultSuccess; } }; diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.cpp index 52f0a71ca..3268e2b07 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.cpp @@ -26,11 +26,7 @@ static char *GetNormalizedDirectory(const char *dir_prefix) { /* Normalize the path. */ char normal_path[FS_MAX_PATH + 1]; size_t normal_path_len; - Result rc = FsPathUtils::Normalize(normal_path, sizeof(normal_path), dir_prefix, &normal_path_len); - if (R_FAILED(rc)) { - /* N calls svcBreak here. */ - std::abort(); - } + R_ASSERT(FsPathUtils::Normalize(normal_path, sizeof(normal_path), dir_prefix, &normal_path_len)); /* Ensure terminating '/' */ if (normal_path[normal_path_len-1] != '/') { @@ -69,10 +65,7 @@ Result DirectoryRedirectionFileSystem::Initialize(const char *before, const char Result DirectoryRedirectionFileSystem::GetFullPath(char *out, size_t out_size, const char *relative_path) { FsPath tmp_rel_path; - Result rc = FsPathUtils::Normalize(tmp_rel_path.str, sizeof(tmp_rel_path), relative_path, nullptr); - if (R_FAILED(rc)) { - return rc; - } + R_TRY(FsPathUtils::Normalize(tmp_rel_path.str, sizeof(tmp_rel_path), relative_path, nullptr)); if (std::strncmp(tmp_rel_path.str, this->before_dir, this->before_dir_len) == 0) { if (this->after_dir_len + strnlen(tmp_rel_path.str, FS_MAX_PATH) - this->before_dir_len > out_size) { @@ -99,120 +92,64 @@ Result DirectoryRedirectionFileSystem::GetFullPath(char *out, size_t out_size, c } Result DirectoryRedirectionFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->CreateFile(full_path, size, flags); } Result DirectoryRedirectionFileSystem::DeleteFileImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->DeleteFile(full_path); } Result DirectoryRedirectionFileSystem::CreateDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->CreateDirectory(full_path); } Result DirectoryRedirectionFileSystem::DeleteDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->DeleteDirectory(full_path); } Result DirectoryRedirectionFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->DeleteDirectoryRecursively(full_path); } Result DirectoryRedirectionFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); return this->base_fs->RenameFile(full_old_path, full_new_path); } Result DirectoryRedirectionFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); return this->base_fs->RenameDirectory(full_old_path, full_new_path); } Result DirectoryRedirectionFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->GetEntryType(out, full_path); } Result DirectoryRedirectionFileSystem::OpenFileImpl(std::unique_ptr &out_file, const FsPath &path, OpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->OpenFile(out_file, full_path, mode); } Result DirectoryRedirectionFileSystem::OpenDirectoryImpl(std::unique_ptr &out_dir, const FsPath &path, DirectoryOpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->OpenDirectory(out_dir, full_path, mode); } @@ -221,56 +158,31 @@ Result DirectoryRedirectionFileSystem::CommitImpl() { } Result DirectoryRedirectionFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->GetFreeSpaceSize(out, full_path); } Result DirectoryRedirectionFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->GetTotalSpaceSize(out, full_path); } Result DirectoryRedirectionFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->CleanDirectoryRecursively(full_path); } Result DirectoryRedirectionFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->GetFileTimeStampRaw(out, full_path); } Result DirectoryRedirectionFileSystem::QueryEntryImpl(char *out, uint64_t out_size, const char *in, uint64_t in_size, int query, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path); } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.hpp index 95d7b342b..7fba385de 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_redirection_filesystem.hpp @@ -31,17 +31,11 @@ class DirectoryRedirectionFileSystem : public IFileSystem { public: DirectoryRedirectionFileSystem(IFileSystem *fs, const char *before, const char *after) : base_fs(fs) { - Result rc = this->Initialize(before, after); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize(before, after)); } DirectoryRedirectionFileSystem(std::shared_ptr fs, const char *before, const char *after) : base_fs(fs) { - Result rc = this->Initialize(before, after); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize(before, after)); } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.cpp index 5ba3747ae..eac720069 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.cpp @@ -62,59 +62,44 @@ class DirectorySaveDataFile : public IFile { /* ================================================================================================ */ Result DirectorySaveDataFileSystem::Initialize() { - Result rc; DirectoryEntryType ent_type; /* Check that the working directory exists. */ - if (R_FAILED((rc = this->fs->GetEntryType(&ent_type, WorkingDirectoryPath)))) { + R_TRY_CATCH(this->fs->GetEntryType(&ent_type, WorkingDirectoryPath)) { /* If path isn't found, create working directory and committed directory. */ - if (rc == ResultFsPathNotFound) { - if (R_FAILED((rc = this->fs->CreateDirectory(WorkingDirectoryPath)))) { - return rc; - } - if (R_FAILED((rc = this->fs->CreateDirectory(CommittedDirectoryPath)))) { - return rc; - } - } else { - return rc; + R_CATCH(ResultFsPathNotFound) { + R_TRY(this->fs->CreateDirectory(WorkingDirectoryPath)); + R_TRY(this->fs->CreateDirectory(CommittedDirectoryPath)); } - } + } R_END_TRY_CATCH; /* Now check for the committed directory. */ - rc = this->fs->GetEntryType(&ent_type, CommittedDirectoryPath); - if (R_SUCCEEDED(rc)) { - /* If committed exists, synchronize it to the working directory. */ - return this->SynchronizeDirectory(WorkingDirectoryPath, CommittedDirectoryPath); - } else if (rc == ResultFsPathNotFound) { - if (R_FAILED((rc = this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath)))) { - return rc; + R_TRY_CATCH(this->fs->GetEntryType(&ent_type, CommittedDirectoryPath)) { + /* Committed doesn't exist, so synchronize and rename. */ + R_CATCH(ResultFsPathNotFound) { + R_TRY(this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath)); + return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); } - return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); - } else { - return rc; - } + } R_END_TRY_CATCH; + + /* If committed exists, synchronize it to the working directory. */ + return this->SynchronizeDirectory(WorkingDirectoryPath, CommittedDirectoryPath); } Result DirectorySaveDataFileSystem::SynchronizeDirectory(const FsPath &dst_dir, const FsPath &src_dir) { - Result rc; - /* Delete destination dir and recreate it. */ - if (R_FAILED((rc = this->fs->DeleteDirectoryRecursively(dst_dir)))) { - /* Nintendo returns error unconditionally, but I think that's a bug in their code. */ - if (rc != ResultFsPathNotFound) { - return rc; + R_TRY_CATCH(this->fs->DeleteDirectoryRecursively(dst_dir)) { + R_CATCH(ResultFsPathNotFound) { + /* Nintendo returns error unconditionally, but I think that's a bug in their code. */ } - } - if (R_FAILED((rc = this->fs->CreateDirectory(dst_dir)))) { - return rc; - } + } R_END_TRY_CATCH; + + R_TRY(this->fs->CreateDirectory(dst_dir)); /* Get a buffer to work with. */ void *work_buf = nullptr; size_t work_buf_size = 0; - if (R_FAILED((rc = this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)))) { - return rc; - } + R_TRY(this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)); ON_SCOPE_EXIT { free(work_buf); }; return FsDirUtils::CopyDirectoryRecursively(this->fs, dst_dir, src_dir, work_buf, work_buf_size); @@ -149,11 +134,11 @@ Result DirectorySaveDataFileSystem::GetFullPath(char *out, size_t out_size, cons if (relative_path[0] != '/') { return ResultFsInvalidPath; } - + /* Copy working directory path. */ std::strncpy(out, WorkingDirectoryPath.str, out_size); out[out_size-1] = 0; - + /* Normalize it. */ constexpr size_t working_len = WorkingDirectoryPathLen - 1; return FsPathUtils::Normalize(out + working_len, out_size - working_len, relative_path, nullptr); @@ -168,20 +153,13 @@ void DirectorySaveDataFileSystem::OnWritableFileClose() { Result DirectorySaveDataFileSystem::CopySaveFromProxy() { if (this->proxy_save_fs != nullptr) { - Result rc; - /* Get a buffer to work with. */ void *work_buf = nullptr; size_t work_buf_size = 0; - if (R_FAILED((rc = this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)))) { - return rc; - } + R_TRY(this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)); ON_SCOPE_EXIT { free(work_buf); }; - rc = FsDirUtils::CopyDirectoryRecursively(this, this->proxy_save_fs.get(), FsPathUtils::RootPath, FsPathUtils::RootPath, work_buf, work_buf_size); - if (R_FAILED(rc)) { - return rc; - } + R_TRY(FsDirUtils::CopyDirectoryRecursively(this, this->proxy_save_fs.get(), FsPathUtils::RootPath, FsPathUtils::RootPath, work_buf, work_buf_size)); return this->Commit(); } return ResultSuccess; @@ -190,125 +168,81 @@ Result DirectorySaveDataFileSystem::CopySaveFromProxy() { /* ================================================================================================ */ Result DirectorySaveDataFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->CreateFile(full_path, size, flags); } Result DirectorySaveDataFileSystem::DeleteFileImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->DeleteFile(full_path); } Result DirectorySaveDataFileSystem::CreateDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->CreateDirectory(full_path); } Result DirectorySaveDataFileSystem::DeleteDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->DeleteDirectory(full_path); } Result DirectorySaveDataFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->DeleteDirectoryRecursively(full_path); } Result DirectorySaveDataFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); + std::scoped_lock lk(this->lock); return this->fs->RenameFile(full_old_path, full_new_path); } Result DirectorySaveDataFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); + std::scoped_lock lk(this->lock); return this->fs->RenameDirectory(full_old_path, full_new_path); } Result DirectorySaveDataFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } + R_TRY(GetFullPath(full_path, path)); std::scoped_lock lk(this->lock); return this->fs->GetEntryType(out, full_path); } Result DirectorySaveDataFileSystem::OpenFileImpl(std::unique_ptr &out_file, const FsPath &path, OpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } + R_TRY(GetFullPath(full_path, path)); std::scoped_lock lk(this->lock); { /* Open the raw file. */ std::unique_ptr file; - if (R_FAILED((rc = this->fs->OpenFile(file, full_path, mode)))) { - return rc; - } + R_TRY(this->fs->OpenFile(file, full_path, mode)); /* Create DirectorySaveDataFile wrapper. */ out_file = std::make_unique(std::move(file), this, mode); @@ -328,13 +262,9 @@ Result DirectorySaveDataFileSystem::OpenFileImpl(std::unique_ptr &out_fil } Result DirectorySaveDataFileSystem::OpenDirectoryImpl(std::unique_ptr &out_dir, const FsPath &path, DirectoryOpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->OpenDirectory(out_dir, full_path, mode); } @@ -349,7 +279,6 @@ Result DirectorySaveDataFileSystem::CommitImpl() { /* Instead, we will synchronize first, then delete committed, then rename. */ std::scoped_lock lk(this->lock); - Result rc; /* Ensure we don't have any open writable files. */ if (this->open_writable_files != 0) { @@ -361,25 +290,20 @@ Result DirectorySaveDataFileSystem::CommitImpl() { const auto RenameSynchDir = [&]() { return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); }; /* Synchronize working directory. */ - if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(SynchronizeWorkingDir))))) { - return rc; - } + R_TRY(FsDirUtils::RetryUntilTargetNotLocked(std::move(SynchronizeWorkingDir))); /* Delete committed directory. */ - if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(DeleteCommittedDir))))) { - /* It is okay for us to not have a committed directory here. */ - if (rc != ResultFsPathNotFound) { - return rc; + R_TRY_CATCH(FsDirUtils::RetryUntilTargetNotLocked(std::move(DeleteCommittedDir))) { + R_CATCH(ResultFsPathNotFound) { + /* It is okay for us to not have a committed directory here. */ } - } + } R_END_TRY_CATCH; /* Rename synchronizing directory to committed directory. */ - if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(RenameSynchDir))))) { - return rc; - } + R_TRY(FsDirUtils::RetryUntilTargetNotLocked(std::move(RenameSynchDir))); /* TODO: Should I call this->fs->Commit()? Nintendo does not. */ - return rc; + return ResultSuccess; } Result DirectorySaveDataFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) { @@ -393,13 +317,9 @@ Result DirectorySaveDataFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const F } Result DirectorySaveDataFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + std::scoped_lock lk(this->lock); return this->fs->CleanDirectoryRecursively(full_path); } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.hpp index 4f1a74ac7..104ba12e7 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_directory_savedata_filesystem.hpp @@ -43,26 +43,17 @@ class DirectorySaveDataFileSystem : public IFileSystem { public: DirectorySaveDataFileSystem(IFileSystem *fs, std::unique_ptr pfs) : unique_fs(fs), proxy_save_fs(std::move(pfs)) { this->fs = this->unique_fs.get(); - Result rc = this->Initialize(); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize()); } DirectorySaveDataFileSystem(std::unique_ptr fs, std::unique_ptr pfs) : unique_fs(std::move(fs)), proxy_save_fs(std::move(pfs)) { this->fs = this->unique_fs.get(); - Result rc = this->Initialize(); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize()); } DirectorySaveDataFileSystem(std::shared_ptr fs, std::unique_ptr pfs) : shared_fs(fs), proxy_save_fs(std::move(pfs)) { this->fs = this->shared_fs.get(); - Result rc = this->Initialize(); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize()); } virtual ~DirectorySaveDataFileSystem() { } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_file_storage.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_file_storage.cpp index 55fecc95b..351389100 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_file_storage.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_file_storage.cpp @@ -29,7 +29,6 @@ Result FileStorage::UpdateSize() { } Result FileStorage::Read(void *buffer, size_t size, u64 offset) { - Result rc; u64 read_size; if (size == 0) { @@ -38,9 +37,7 @@ Result FileStorage::Read(void *buffer, size_t size, u64 offset) { if (buffer == nullptr) { return ResultFsNullptrArgument; } - if (R_FAILED((rc = this->UpdateSize()))) { - return rc; - } + R_TRY(this->UpdateSize()); if (!IStorage::IsRangeValid(offset, size, this->size)) { return ResultFsOutOfRange; } @@ -54,17 +51,13 @@ Result FileStorage::Read(void *buffer, size_t size, u64 offset) { } Result FileStorage::Write(void *buffer, size_t size, u64 offset) { - Result rc; - if (size == 0) { return ResultSuccess; } if (buffer == nullptr) { return ResultFsNullptrArgument; } - if (R_FAILED((rc = this->UpdateSize()))) { - return rc; - } + R_TRY(this->UpdateSize()); if (!IStorage::IsRangeValid(offset, size, this->size)) { return ResultFsOutOfRange; } @@ -77,10 +70,7 @@ Result FileStorage::Flush() { } Result FileStorage::GetSize(u64 *out_size) { - Result rc = this->UpdateSize(); - if (R_FAILED(rc)) { - return rc; - } + R_TRY(this->UpdateSize()); *out_size = this->size; return ResultSuccess; } @@ -91,8 +81,6 @@ Result FileStorage::SetSize(u64 size) { } Result FileStorage::OperateRange(FsOperationId operation_type, u64 offset, u64 size, FsRangeInfo *out_range_info) { - Result rc; - switch (operation_type) { case FsOperationId_InvalidateCache: case FsOperationId_QueryRange: @@ -106,9 +94,7 @@ Result FileStorage::OperateRange(FsOperationId operation_type, u64 offset, u64 s } return ResultSuccess; } - if (R_FAILED((rc = this->UpdateSize()))) { - return rc; - } + R_TRY(this->UpdateSize()); /* N checks for positivity + signed overflow on offset/size here, but we're using unsigned types... */ return this->file->OperateRange(operation_type, offset, size, out_range_info); default: diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_idirectory.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_idirectory.hpp index 70d803c0a..fa8ee1570 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_idirectory.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_idirectory.hpp @@ -104,13 +104,10 @@ class ProxyDirectory : public IDirectory { public: virtual Result ReadImpl(uint64_t *out_count, FsDirectoryEntry *out_entries, uint64_t max_entries) { size_t count; + R_TRY(fsDirRead(this->base_dir.get(), 0, &count, max_entries, out_entries)); - Result rc = fsDirRead(this->base_dir.get(), 0, &count, max_entries, out_entries); - if (R_SUCCEEDED(rc)) { - *out_count = count; - } - - return rc; + *out_count = count; + return ResultSuccess; } virtual Result GetEntryCountImpl(uint64_t *count) { return fsDirGetEntryCount(this->base_dir.get(), count); diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_ifile.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_ifile.hpp index f07cb0d03..d292e468f 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_ifile.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_ifile.hpp @@ -172,13 +172,10 @@ class ProxyFile : public IFile { public: virtual Result ReadImpl(u64 *out, u64 offset, void *buffer, u64 size) override { size_t out_sz; + R_TRY(fsFileRead(this->base_file.get(), offset, buffer, size, FS_READOPTION_NONE, &out_sz)); - Result rc = fsFileRead(this->base_file.get(), offset, buffer, size, FS_READOPTION_NONE, &out_sz); - if (R_SUCCEEDED(rc)) { - *out = out_sz; - } - - return rc; + *out = out_sz; + return ResultSuccess; } virtual Result GetSizeImpl(u64 *out) override { return fsFileGetSize(this->base_file.get(), out); diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_ifilesystem.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_ifilesystem.hpp index 507b20d0a..0feef616d 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_ifilesystem.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_ifilesystem.hpp @@ -216,55 +216,35 @@ class IFileSystemInterface : public IServiceObject { /* Actual command API. */ virtual Result CreateFile(InPointer in_path, uint64_t size, int flags) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->CreateFile(path, size, flags); } virtual Result DeleteFile(InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->DeleteFile(path); } virtual Result CreateDirectory(InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->CreateDirectory(path); } virtual Result DeleteDirectory(InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->DeleteDirectory(path); } virtual Result DeleteDirectoryRecursively(InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->DeleteDirectoryRecursively(path); } @@ -272,14 +252,8 @@ class IFileSystemInterface : public IServiceObject { virtual Result RenameFile(InPointer in_old_path, InPointer in_new_path) final { FsPath old_path; FsPath new_path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer)))) { - return rc; - } - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer)); + R_TRY(FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer)); return this->base_fs->RenameFile(old_path, new_path); } @@ -287,14 +261,8 @@ class IFileSystemInterface : public IServiceObject { virtual Result RenameDirectory(InPointer in_old_path, InPointer in_new_path) final { FsPath old_path; FsPath new_path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer)))) { - return rc; - } - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer)); + R_TRY(FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer)); return this->base_fs->RenameDirectory(old_path, new_path); } @@ -302,54 +270,35 @@ class IFileSystemInterface : public IServiceObject { virtual Result GetEntryType(Out out_type, InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); DirectoryEntryType type; - rc = this->base_fs->GetEntryType(&type, path); - if (R_SUCCEEDED(rc)) { - out_type.SetValue(type); - } - return rc; + R_TRY(this->base_fs->GetEntryType(&type, path)); + + out_type.SetValue(type); + return ResultSuccess; } virtual Result OpenFile(Out> out_intf, InPointer in_path, uint32_t mode) final { FsPath path; + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); + std::unique_ptr out_file; + R_TRY(this->base_fs->OpenFile(out_file, path, static_cast(mode))); - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } - - rc = this->base_fs->OpenFile(out_file, path, static_cast(mode)); - if (R_SUCCEEDED(rc)) { - out_intf.SetValue(std::make_shared(std::move(out_file))); - /* TODO: Nintendo checks allocation success here, should we?. */ - } - return rc; + out_intf.SetValue(std::make_shared(std::move(out_file))); + return ResultSuccess; } virtual Result OpenDirectory(Out> out_intf, InPointer in_path, uint32_t mode) final { FsPath path; + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); + std::unique_ptr out_dir; + R_TRY(this->base_fs->OpenDirectory(out_dir, path, static_cast(mode))); - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } - - rc = this->base_fs->OpenDirectory(out_dir, path, static_cast(mode)); - - if (R_SUCCEEDED(rc)) { - out_intf.SetValue(std::make_shared(std::move(out_dir))); - /* TODO: Nintendo checks allocation success here, should we?. */ - } - - return rc; + out_intf.SetValue(std::make_shared(std::move(out_dir))); + return ResultSuccess; } virtual Result Commit() final { @@ -358,55 +307,35 @@ class IFileSystemInterface : public IServiceObject { virtual Result GetFreeSpaceSize(Out out_size, InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->GetFreeSpaceSize(out_size.GetPointer(), path); } virtual Result GetTotalSpaceSize(Out out_size, InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->GetTotalSpaceSize(out_size.GetPointer(), path); } virtual Result CleanDirectoryRecursively(InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->CleanDirectoryRecursively(path); } virtual Result GetFileTimeStampRaw(Out out_timestamp, InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->GetFileTimeStampRaw(out_timestamp.GetPointer(), path); } virtual Result QueryEntry(OutBuffer out_buffer, InBuffer in_buffer, int query, InPointer in_path) final { FsPath path; - - Result rc; - if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { - return rc; - } + R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)); return this->base_fs->QueryEntry(out_buffer.buffer, out_buffer.num_elements, in_buffer.buffer, in_buffer.num_elements, query, path); } @@ -487,34 +416,25 @@ class ProxyFileSystem : public IFileSystem { virtual Result GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { FsEntryType type; + R_TRY(fsFsGetEntryType(this->base_fs.get(), path.str, &type)); - Result rc = fsFsGetEntryType(this->base_fs.get(), path.str, &type); - if (R_SUCCEEDED(rc)) { - *out = static_cast(static_cast(type)); - } - - return rc; + *out = static_cast(static_cast(type)); + return ResultSuccess; } virtual Result OpenFileImpl(std::unique_ptr &out_file, const FsPath &path, OpenMode mode) { FsFile f; + R_TRY(fsFsOpenFile(this->base_fs.get(), path.str, static_cast(mode), &f)); - Result rc = fsFsOpenFile(this->base_fs.get(), path.str, static_cast(mode), &f); - if (R_SUCCEEDED(rc)) { - out_file = std::make_unique(f); - } - - return rc; + out_file = std::make_unique(f); + return ResultSuccess; } virtual Result OpenDirectoryImpl(std::unique_ptr &out_dir, const FsPath &path, DirectoryOpenMode mode) { FsDir d; + R_TRY(fsFsOpenDirectory(this->base_fs.get(), path.str, static_cast(mode), &d)); - Result rc = fsFsOpenDirectory(this->base_fs.get(), path.str, static_cast(mode), &d); - if (R_SUCCEEDED(rc)) { - out_dir = std::make_unique(d); - } - - return rc; + out_dir = std::make_unique(d); + return ResultSuccess; } virtual Result CommitImpl() { diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_path_utils.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_path_utils.cpp index ab028967d..b3d282334 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_path_utils.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_path_utils.cpp @@ -85,9 +85,9 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) { ParentDir, WindowsDriveLetter, }; - + PathState state = PathState::Start; - + for (const char *cur = path; *cur != 0; cur++) { const char c = *cur; switch (state) { @@ -145,7 +145,7 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) { break; } } - + switch (state) { case PathState::Start: case PathState::WindowsDriveLetter: @@ -160,7 +160,7 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) { *out = false; break; } - + return ResultSuccess; } @@ -169,11 +169,11 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s if (src[0] != '/') { return ResultFsInvalidPathFormat; } - + bool skip_next_sep = false; size_t i = 0; size_t len = 0; - + while (src[i] != 0) { if (src[i] == '/') { /* Swallow separators. */ @@ -181,7 +181,7 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s if (src[i] == 0) { break; } - + /* Handle skip if needed */ if (!skip_next_sep) { if (len + 1 == max_out_size) { @@ -191,28 +191,28 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s } return ResultFsTooLongPath; } - + out[len++] = '/'; - + /* TODO: N has some weird windows support stuff here under a bool. */ /* Boolean is normally false though? */ } skip_next_sep = false; } - + /* See length of current dir. */ size_t dir_len = 0; while (src[i+dir_len] != '/' && src[i+dir_len] != 0) { dir_len++; } - + if (FsPathUtils::IsCurrentDirectory(&src[i])) { skip_next_sep = true; } else if (FsPathUtils::IsParentDirectory(&src[i])) { if (len == 1) { return ResultFsDirectoryUnobtainable; } - + /* Walk up a directory. */ len -= 2; while (out[len] != '/') { @@ -236,33 +236,34 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s return ResultFsTooLongPath; } } - + i += dir_len; } - + if (skip_next_sep) { len--; } - + if (len == 0 && max_out_size) { out[len++] = '/'; } - + if (max_out_size < len - 1) { return ResultFsTooLongPath; } - + /* NULL terminate. */ out[len] = 0; if (out_len != nullptr) { *out_len = len; } - + /* Assert normalized. */ bool normalized = false; - if (R_FAILED(FsPathUtils::IsNormalized(&normalized, out)) || !normalized) { + R_ASSERT(FsPathUtils::IsNormalized(&normalized, out)); + if (!normalized) { std::abort(); } - + return ResultSuccess; } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_save_utils.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_save_utils.cpp index 0afcd181a..2390f6816 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_save_utils.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_save_utils.cpp @@ -100,12 +100,10 @@ Result FsSaveUtils::GetSaveDataTypeString(const char **out_str, u8 save_data_typ Result FsSaveUtils::GetSaveDataDirectoryPath(FsPath &out_path, u8 space_id, u8 save_data_type, u64 title_id, u128 user_id, u64 save_id) { const char *space_id_str, *save_type_str; - Result rc; /* Get space_id, save_data_type strings. */ - if (R_FAILED((rc = GetSaveDataSpaceIdString(&space_id_str, space_id))) || R_FAILED((rc = GetSaveDataTypeString(&save_type_str, save_data_type)))) { - return rc; - } + R_TRY(GetSaveDataSpaceIdString(&space_id_str, space_id)); + R_TRY(GetSaveDataTypeString(&save_type_str, save_data_type)); /* Clear and initialize the path. */ std::memset(&out_path, 0, sizeof(out_path)); diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.cpp b/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.cpp index d68ff2b91..6da23c798 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.cpp @@ -26,33 +26,29 @@ Result SubDirectoryFileSystem::Initialize(const char *bp) { if (strnlen(bp, FS_MAX_PATH) >= FS_MAX_PATH) { return ResultFsTooLongPath; } - + /* Normalize the path. */ char normal_path[FS_MAX_PATH + 1]; size_t normal_path_len; - Result rc = FsPathUtils::Normalize(normal_path, sizeof(normal_path), bp, &normal_path_len); - if (R_FAILED(rc)) { - /* N calls svcBreak here. */ - std::abort(); - } - + R_ASSERT(FsPathUtils::Normalize(normal_path, sizeof(normal_path), bp, &normal_path_len)); + /* Ensure terminating '/' */ if (normal_path[normal_path_len-1] != '/') { if (normal_path_len + 2 > sizeof(normal_path)) { std::abort(); } - + strncat(normal_path, "/", 2); normal_path[sizeof(normal_path)-1] = 0; normal_path_len++; } - + this->base_path_len = normal_path_len + 1; this->base_path = reinterpret_cast(malloc(this->base_path_len)); if (this->base_path == nullptr) { return ResultFsAllocationFailureInSubDirectoryFileSystem; } - + std::strncpy(this->base_path, normal_path, this->base_path_len); this->base_path[this->base_path_len-1] = 0; return ResultSuccess; @@ -62,130 +58,84 @@ Result SubDirectoryFileSystem::GetFullPath(char *out, size_t out_size, const cha if (this->base_path_len + strnlen(relative_path, FS_MAX_PATH) > out_size) { return ResultFsTooLongPath; } - + /* Copy base path. */ std::strncpy(out, this->base_path, out_size); out[out_size-1] = 0; - + /* Normalize it. */ return FsPathUtils::Normalize(out + this->base_path_len - 2, out_size - (this->base_path_len - 2), relative_path, nullptr); } Result SubDirectoryFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->CreateFile(full_path, size, flags); } Result SubDirectoryFileSystem::DeleteFileImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->DeleteFile(full_path); } Result SubDirectoryFileSystem::CreateDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->CreateDirectory(full_path); } Result SubDirectoryFileSystem::DeleteDirectoryImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->DeleteDirectory(full_path); } Result SubDirectoryFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->DeleteDirectoryRecursively(full_path); } Result SubDirectoryFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); + return this->base_fs->RenameFile(full_old_path, full_new_path); } Result SubDirectoryFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) { - Result rc; FsPath full_old_path, full_new_path; - - if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { - return rc; - } - - if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) { - return rc; - } - + R_TRY(GetFullPath(full_old_path, old_path)); + R_TRY(GetFullPath(full_new_path, new_path)); + return this->base_fs->RenameDirectory(full_old_path, full_new_path); } Result SubDirectoryFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->GetEntryType(out, full_path); } Result SubDirectoryFileSystem::OpenFileImpl(std::unique_ptr &out_file, const FsPath &path, OpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->OpenFile(out_file, full_path, mode); } Result SubDirectoryFileSystem::OpenDirectoryImpl(std::unique_ptr &out_dir, const FsPath &path, DirectoryOpenMode mode) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->OpenDirectory(out_dir, full_path, mode); } @@ -194,56 +144,36 @@ Result SubDirectoryFileSystem::CommitImpl() { } Result SubDirectoryFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->GetFreeSpaceSize(out, full_path); } Result SubDirectoryFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->GetTotalSpaceSize(out, full_path); -} +} Result SubDirectoryFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->CleanDirectoryRecursively(full_path); } Result SubDirectoryFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->GetFileTimeStampRaw(out, full_path); } Result SubDirectoryFileSystem::QueryEntryImpl(char *out, uint64_t out_size, const char *in, uint64_t in_size, int query, const FsPath &path) { - Result rc; FsPath full_path; - - if (R_FAILED((rc = GetFullPath(full_path, path)))) { - return rc; - } - + R_TRY(GetFullPath(full_path, path)); + return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path); } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.hpp b/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.hpp index 132f05bd5..4fc599fdc 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fs_subdirectory_filesystem.hpp @@ -26,20 +26,14 @@ class SubDirectoryFileSystem : public IFileSystem { std::shared_ptr base_fs; char *base_path = nullptr; size_t base_path_len = 0; - + public: SubDirectoryFileSystem(IFileSystem *fs, const char *bp) : base_fs(fs) { - Result rc = this->Initialize(bp); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize(bp)); } SubDirectoryFileSystem(std::shared_ptr fs, const char *bp) : base_fs(fs) { - Result rc = this->Initialize(bp); - if (R_FAILED(rc)) { - fatalSimple(rc); - } + R_ASSERT(this->Initialize(bp)); } @@ -48,7 +42,7 @@ class SubDirectoryFileSystem : public IFileSystem { free(this->base_path); } } - + private: Result Initialize(const char *bp); protected: @@ -56,7 +50,7 @@ class SubDirectoryFileSystem : public IFileSystem { Result GetFullPath(FsPath &full_path, const FsPath &relative_path) { return GetFullPath(full_path.str, sizeof(full_path.str), relative_path.str); } - + public: virtual Result CreateFileImpl(const FsPath &path, uint64_t size, int flags) override; virtual Result DeleteFileImpl(const FsPath &path) override; diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.cpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.cpp index eb501dff3..1d4b4cf11 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include #include @@ -38,16 +38,15 @@ bool Boot0Storage::CanModifyBctPubks() { Result Boot0Storage::Read(void *_buffer, size_t size, u64 offset) { std::scoped_lock lk{g_boot0_mutex}; - + return Base::Read(_buffer, size, offset); } Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) { std::scoped_lock lk{g_boot0_mutex}; - - Result rc = ResultSuccess; + u8 *buffer = static_cast(_buffer); - + /* Protect the keyblob region from writes. */ if (offset <= EksStart) { if (offset + size < EksStart) { @@ -59,9 +58,7 @@ Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) { } else { /* Perform portion of write falling past end of keyblobs. */ const u64 diff = EksEnd - offset; - if (R_FAILED((rc = Base::Write(buffer + diff, size - diff, EksEnd)))) { - return rc; - } + R_TRY(Base::Write(buffer + diff, size - diff, EksEnd)); /* Adjust size to avoid writing end of data. */ size = EksStart - offset; } @@ -81,30 +78,26 @@ Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) { /* Fall through, no need to do anything here. */ } } - + if (size == 0) { return ResultSuccess; } - + /* We care about protecting autorcm from NS. */ if (CanModifyBctPubks() || offset >= BctEndOffset || (offset + BctSize >= BctEndOffset && offset % BctSize >= BctPubkEnd)) { return Base::Write(buffer, size, offset); } - + /* First, let's deal with the data past the end. */ if (offset + size >= BctEndOffset) { const u64 diff = BctEndOffset - offset; - if (R_FAILED((rc = ProxyStorage::Write(buffer + diff, size - diff, BctEndOffset)))) { - return rc; - } + R_TRY(ProxyStorage::Write(buffer + diff, size - diff, BctEndOffset)); size = diff; } - + /* Read in the current BCT region. */ - if (R_FAILED((rc = ProxyStorage::Read(g_boot0_bct_buffer, BctEndOffset, 0)))) { - return rc; - } - + R_TRY(ProxyStorage::Read(g_boot0_bct_buffer, BctEndOffset, 0)); + /* Update the bct buffer. */ for (u64 cur_ofs = offset; cur_ofs < BctEndOffset && cur_ofs < offset + size; cur_ofs++) { const u64 cur_bct_rel_ofs = cur_ofs % BctSize; @@ -112,6 +105,6 @@ Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) { g_boot0_bct_buffer[cur_ofs] = buffer[cur_ofs - offset]; } } - + return ProxyStorage::Write(g_boot0_bct_buffer, BctEndOffset, 0); } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.hpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.hpp index b0e164810..4f0afadda 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_boot0storage.hpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #pragma once #include #include @@ -22,7 +22,7 @@ #include "fs_istorage.hpp" /* Represents a sectored storage. */ -template +template class SectoredProxyStorage : public ProxyStorage { private: u64 cur_seek = 0; @@ -39,19 +39,16 @@ class SectoredProxyStorage : public ProxyStorage { SectoredProxyStorage(FsStorage s) : ProxyStorage(s) { } public: virtual Result Read(void *_buffer, size_t size, u64 offset) override { - Result rc = ResultSuccess; u8 *buffer = static_cast(_buffer); this->Seek(offset); - + if (this->cur_sector_ofs == 0 && size % SectorSize == 0) { /* Fast case. */ return ProxyStorage::Read(buffer, size, offset); } - - if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)))) { - return rc; - } - + + R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)); + if (size + this->cur_sector_ofs <= SectorSize) { memcpy(buffer, sector_buf + this->cur_sector_ofs, size); } else { @@ -59,90 +56,77 @@ class SectoredProxyStorage : public ProxyStorage { size_t ofs = SectorSize - this->cur_sector_ofs; memcpy(buffer, sector_buf + this->cur_sector_ofs, ofs); size -= ofs; - + /* We're guaranteed alignment, here. */ const size_t aligned_remaining_size = size - (size % SectorSize); if (aligned_remaining_size) { - if (R_FAILED((rc = ProxyStorage::Read(buffer + ofs, aligned_remaining_size, offset + ofs)))) { - return rc; - } + R_TRY(ProxyStorage::Read(buffer + ofs, aligned_remaining_size, offset + ofs)); ofs += aligned_remaining_size; size -= aligned_remaining_size; } - + /* Read any leftover data. */ if (size) { - if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)))) { - return rc; - } + R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)); memcpy(buffer + ofs, sector_buf, size); } } - - return rc; - }; + + return ResultSuccess; + } + virtual Result Write(void *_buffer, size_t size, u64 offset) override { - Result rc = ResultSuccess; u8 *buffer = static_cast(_buffer); this->Seek(offset); - + if (this->cur_sector_ofs == 0 && size % SectorSize == 0) { /* Fast case. */ return ProxyStorage::Write(buffer, size, offset); } - - if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)))) { - return rc; - } - - + + R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)); + if (size + this->cur_sector_ofs <= SectorSize) { memcpy(this->sector_buf + this->cur_sector_ofs, buffer, size); - rc = ProxyStorage::Write(this->sector_buf, SectorSize, this->cur_seek); + R_TRY(ProxyStorage::Write(this->sector_buf, SectorSize, this->cur_seek)); } else { /* Leaving the sector... */ size_t ofs = SectorSize - this->cur_sector_ofs; memcpy(this->sector_buf + this->cur_sector_ofs, buffer, ofs); - if (R_FAILED((rc = ProxyStorage::Write(this->sector_buf, ofs, this->cur_seek)))) { - return rc; - } + R_TRY(ProxyStorage::Write(this->sector_buf, ofs, this->cur_seek)); size -= ofs; - + /* We're guaranteed alignment, here. */ const size_t aligned_remaining_size = size - (size % SectorSize); if (aligned_remaining_size) { - if (R_FAILED((rc = ProxyStorage::Write(buffer + ofs, aligned_remaining_size, offset + ofs)))) { - return rc; - } + R_TRY(ProxyStorage::Write(buffer + ofs, aligned_remaining_size, offset + ofs)); ofs += aligned_remaining_size; size -= aligned_remaining_size; } - + /* Write any leftover data. */ if (size) { - if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)))) { - return rc; - } + R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)); memcpy(this->sector_buf, buffer + ofs, size); - rc = ProxyStorage::Write(this->sector_buf, SectorSize, this->cur_seek); + R_TRY(ProxyStorage::Write(this->sector_buf, SectorSize, this->cur_seek)); } - } - - return rc; - }; + } + + return ResultSuccess; + } }; /* Represents an RCM-preserving BOOT0 partition. */ class Boot0Storage : public SectoredProxyStorage<0x200> { using Base = SectoredProxyStorage<0x200>; - + public: static constexpr u64 BctEndOffset = 0xFC000; static constexpr u64 BctSize = 0x4000; static constexpr u64 BctPubkStart = 0x210; static constexpr u64 BctPubkSize = 0x100; static constexpr u64 BctPubkEnd = BctPubkStart + BctPubkSize; - + static constexpr u64 EksStart = 0x180000; static constexpr u64 EksSize = 0x4000; static constexpr u64 EksEnd = EksStart + EksSize; @@ -154,6 +138,6 @@ class Boot0Storage : public SectoredProxyStorage<0x200> { Boot0Storage(FsStorage *s, u64 t) : Base(s), title_id(t) { } Boot0Storage(FsStorage s, u64 t) : Base(s), title_id(t) { } public: - virtual Result Read(void *_buffer, size_t size, u64 offset) override; + virtual Result Read(void *_buffer, size_t size, u64 offset) override; virtual Result Write(void *_buffer, size_t size, u64 offset) override; }; \ No newline at end of file diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_layeredrom.cpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_layeredrom.cpp index c57738971..4558a8ccd 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_layeredrom.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_layeredrom.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include @@ -50,7 +50,7 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { if (size == 0) { return ResultSuccess; } - + /* Validate size. */ u64 virt_size = (*this->p_source_infos)[this->p_source_infos->size() - 1].virtual_offset + (*this->p_source_infos)[this->p_source_infos->size() - 1].size; if (offset >= virt_size) { @@ -77,8 +77,7 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { low = mid + 1; } } - - Result rc; + size_t read_so_far = 0; while (read_so_far < size) { RomFSSourceInfo *cur_source = &((*this->p_source_infos)[cur_source_ind]); @@ -91,15 +90,11 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { case RomFSDataSource::MetaData: { FsFile file; - if (R_FAILED((rc = Utils::OpenSdFileForAtmosphere(this->title_id, ROMFS_METADATA_FILE_PATH, FS_OPEN_READ, &file)))) { - fatalSimple(rc); - } + R_ASSERT(Utils::OpenSdFileForAtmosphere(this->title_id, ROMFS_METADATA_FILE_PATH, FS_OPEN_READ, &file)); size_t out_read; - if (R_FAILED((rc = fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read)))) { - fatalSimple(rc); - } + R_ASSERT(fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read)); if (out_read != cur_read_size) { - Reboot(); + std::abort(); } fsFileClose(&file); } @@ -107,15 +102,11 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { case RomFSDataSource::LooseFile: { FsFile file; - if (R_FAILED((rc = Utils::OpenRomFSSdFile(this->title_id, cur_source->loose_source_info.path, FS_OPEN_READ, &file)))) { - fatalSimple(rc); - } + R_ASSERT(Utils::OpenRomFSSdFile(this->title_id, cur_source->loose_source_info.path, FS_OPEN_READ, &file)); size_t out_read; - if (R_FAILED((rc = fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read)))) { - fatalSimple(rc); - } + R_ASSERT(fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read)); if (out_read != cur_read_size) { - Reboot(); + std::abort(); } fsFileClose(&file); } @@ -127,23 +118,16 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { break; case RomFSDataSource::BaseRomFS: { - if (R_FAILED((rc = this->storage_romfs->Read((void *)((uintptr_t)buffer + read_so_far), cur_read_size, cur_source->base_source_info.offset + (offset - cur_source->virtual_offset))))) { - /* TODO: Can this ever happen? */ - /* fatalSimple(rc); */ - return rc; - } + R_ASSERT(this->storage_romfs->Read((void *)((uintptr_t)buffer + read_so_far), cur_read_size, cur_source->base_source_info.offset + (offset - cur_source->virtual_offset))); } break; case RomFSDataSource::FileRomFS: { - if (R_FAILED((rc = this->file_romfs->Read((void *)((uintptr_t)buffer + read_so_far), cur_read_size, cur_source->base_source_info.offset + (offset - cur_source->virtual_offset))))) { - fatalSimple(rc); - } + R_ASSERT(this->file_romfs->Read((void *)((uintptr_t)buffer + read_so_far), cur_read_size, cur_source->base_source_info.offset + (offset - cur_source->virtual_offset))); } break; default: - /* TODO: Better error. */ - fatalSimple(ResultKernelConnectionClosed); + std::abort(); break; } read_so_far += cur_read_size; @@ -157,7 +141,7 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) { offset = ((*this->p_source_infos)[cur_source_ind]).virtual_offset; } } - + return ResultSuccess; } Result LayeredRomFS::GetSize(u64 *out_size) { diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romfsbuild.cpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romfsbuild.cpp index a58753049..a7de93965 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romfsbuild.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romfsbuild.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include #include @@ -24,63 +24,67 @@ void RomFSBuildContext::VisitDirectory(FsFileSystem *filesys, RomFSBuildDirectoryContext *parent) { FsDir dir; - Result rc; - + std::vector child_dirs; - + /* Open the current parent directory. */ - if (R_FAILED((rc = Utils::OpenRomFSDir(filesys, this->title_id, parent->path, &dir)))) { - fatalSimple(rc); - } - - u64 read_entries; - while (R_SUCCEEDED((rc = fsDirRead(&dir, 0, &read_entries, 1, &this->dir_entry))) && read_entries == 1) { - if (this->dir_entry.type == ENTRYTYPE_DIR) { - RomFSBuildDirectoryContext *child = new RomFSBuildDirectoryContext({0}); - /* Set child's path. */ - child->cur_path_ofs = parent->path_len + 1; - child->path_len = child->cur_path_ofs + strlen(this->dir_entry.name); - child->path = new char[child->path_len + 1]; - strcpy(child->path, parent->path); - if (child->path_len > FS_MAX_PATH - 1) { - fatalSimple(ResultFsTooLongPath); + R_ASSERT(Utils::OpenRomFSDir(filesys, this->title_id, parent->path, &dir)); + { + ON_SCOPE_EXIT { fsDirClose(&dir); }; + + u64 read_entries; + while (true) { + R_ASSERT(fsDirRead(&dir, 0, &read_entries, 1, &this->dir_entry)); + if (read_entries != 1) { + break; } - strcat(child->path + parent->path_len, "/"); - strcat(child->path + parent->path_len, this->dir_entry.name); - - if (!this->AddDirectory(parent, child, NULL)) { - delete[] child->path; - delete child; + + if (this->dir_entry.type == ENTRYTYPE_DIR) { + RomFSBuildDirectoryContext *child = new RomFSBuildDirectoryContext({0}); + /* Set child's path. */ + child->cur_path_ofs = parent->path_len + 1; + child->path_len = child->cur_path_ofs + strlen(this->dir_entry.name); + child->path = new char[child->path_len + 1]; + strcpy(child->path, parent->path); + if (child->path_len > FS_MAX_PATH - 1) { + fatalSimple(ResultFsTooLongPath); + } + strcat(child->path + parent->path_len, "/"); + strcat(child->path + parent->path_len, this->dir_entry.name); + + if (!this->AddDirectory(parent, child, NULL)) { + delete[] child->path; + delete child; + } else { + child_dirs.push_back(child); + } + } else if (this->dir_entry.type == ENTRYTYPE_FILE) { + RomFSBuildFileContext *child = new RomFSBuildFileContext({0}); + /* Set child's path. */ + child->cur_path_ofs = parent->path_len + 1; + child->path_len = child->cur_path_ofs + strlen(this->dir_entry.name); + child->path = new char[child->path_len + 1]; + strcpy(child->path, parent->path); + if (child->path_len > FS_MAX_PATH - 1) { + fatalSimple(ResultFsTooLongPath); + } + strcat(child->path + parent->path_len, "/"); + strcat(child->path + parent->path_len, this->dir_entry.name); + + child->source = this->cur_source_type; + + child->size = this->dir_entry.fileSize; + + if (!this->AddFile(parent, child)) { + delete[] child->path; + delete child; + } } else { - child_dirs.push_back(child); + std::abort(); } - } else if (this->dir_entry.type == ENTRYTYPE_FILE) { - RomFSBuildFileContext *child = new RomFSBuildFileContext({0}); - /* Set child's path. */ - child->cur_path_ofs = parent->path_len + 1; - child->path_len = child->cur_path_ofs + strlen(this->dir_entry.name); - child->path = new char[child->path_len + 1]; - strcpy(child->path, parent->path); - if (child->path_len > FS_MAX_PATH - 1) { - fatalSimple(ResultFsTooLongPath); - } - strcat(child->path + parent->path_len, "/"); - strcat(child->path + parent->path_len, this->dir_entry.name); - - child->source = this->cur_source_type; - - child->size = this->dir_entry.fileSize; - - if (!this->AddFile(parent, child)) { - delete[] child->path; - delete child; - } - } else { - fatalSimple(rc); } } - fsDirClose(&dir); - + for (auto &child : child_dirs) { this->VisitDirectory(filesys, child); } @@ -121,7 +125,7 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p strcat(child->path + parent->path_len, "/"); strncat(child->path + parent->path_len, cur_file->name, cur_file->name_size); child->size = cur_file->size; - + child->source = this->cur_source_type; child->orig_offset = cur_file->offset; if (!this->AddFile(parent, child)) { @@ -150,7 +154,7 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p } strcat(child->path + parent->path_len, "/"); strncat(child->path + parent->path_len, cur_child->name, cur_child->name_size); - + RomFSBuildDirectoryContext *real = NULL; if (!this->AddDirectory(parent, child, &real)) { delete[] child->path; @@ -160,9 +164,9 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p /* TODO: Better error. */ fatalSimple(ResultKernelConnectionClosed); } - + this->VisitDirectory(real, cur_child_offset, dir_table, dir_table_size, file_table, file_table_size); - + if (cur_child->sibling == ROMFS_ENTRY_EMPTY) { cur_child = NULL; } else { @@ -174,26 +178,19 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p } void RomFSBuildContext::MergeRomStorage(IROStorage *storage, RomFSDataSource source) { - Result rc; RomFSHeader header; - if (R_FAILED((rc = storage->Read(&header, sizeof(header), 0)))) { - fatalSimple(rc); - } + R_ASSERT(storage->Read(&header, sizeof(header), 0)); if (header.header_size != sizeof(header)) { /* what */ - return; + std::abort(); } - + /* Read tables. */ auto dir_table = std::make_unique(header.dir_table_size); auto file_table = std::make_unique(header.file_table_size); - if (R_FAILED((rc = storage->Read(dir_table.get(), header.dir_table_size, header.dir_table_ofs)))) { - fatalSimple(rc); - } - if (R_FAILED((rc = storage->Read(file_table.get(), header.file_table_size, header.file_table_ofs)))) { - fatalSimple(rc); - } - + R_ASSERT(storage->Read(dir_table.get(), header.dir_table_size, header.dir_table_ofs)); + R_ASSERT(storage->Read(file_table.get(), header.file_table_size, header.file_table_ofs)); + this->cur_source_type = source; this->VisitDirectory(this->root, 0x0, dir_table.get(), (size_t)header.dir_table_size, file_table.get(), (size_t)header.file_table_size); } @@ -207,13 +204,13 @@ bool RomFSBuildContext::AddDirectory(RomFSBuildDirectoryContext *parent_dir_ctx, } return false; } - + /* Add a new directory. */ this->num_dirs++; this->dir_table_size += sizeof(RomFSDirectoryEntry) + ((dir_ctx->path_len - dir_ctx->cur_path_ofs + 3) & ~3); dir_ctx->parent = parent_dir_ctx; this->directories.insert({dir_ctx->path, dir_ctx}); - + if (out_dir_ctx) { *out_dir_ctx = dir_ctx; } @@ -226,13 +223,13 @@ bool RomFSBuildContext::AddFile(RomFSBuildDirectoryContext *parent_dir_ctx, RomF if (existing != this->files.end()) { return false; } - + /* Add a new file. */ this->num_files++; this->file_table_size += sizeof(RomFSFileEntry) + ((file_ctx->path_len - file_ctx->cur_path_ofs + 3) & ~3); file_ctx->parent = parent_dir_ctx; this->files.insert({file_ctx->path, file_ctx}); - + return true; } @@ -240,12 +237,12 @@ void RomFSBuildContext::Build(std::vector *out_infos) { RomFSBuildFileContext *cur_file; RomFSBuildDirectoryContext *cur_dir; u32 entry_offset; - + u32 dir_hash_table_entry_count = romfs_get_hash_table_count(this->num_dirs); u32 file_hash_table_entry_count = romfs_get_hash_table_count(this->num_files); this->dir_hash_table_size = 4 * dir_hash_table_entry_count; this->file_hash_table_size = 4 * file_hash_table_entry_count; - + /* Assign metadata pointers */ auto *header = reinterpret_cast(std::malloc(sizeof(RomFSHeader))); *header = {}; @@ -255,7 +252,7 @@ void RomFSBuildContext::Build(std::vector *out_infos) { RomFSDirectoryEntry *dir_table = (RomFSDirectoryEntry *)((uintptr_t)dir_hash_table + this->dir_hash_table_size); u32 *file_hash_table = (u32 *)((uintptr_t)dir_table + this->dir_table_size); RomFSFileEntry *file_table = (RomFSFileEntry *)((uintptr_t)file_hash_table + this->file_hash_table_size); - + /* Clear out hash tables. */ for (u32 i = 0; i < dir_hash_table_entry_count; i++) { dir_hash_table[i] = ROMFS_ENTRY_EMPTY; @@ -263,10 +260,10 @@ void RomFSBuildContext::Build(std::vector *out_infos) { for (u32 i = 0; i < file_hash_table_entry_count; i++) { file_hash_table[i] = ROMFS_ENTRY_EMPTY; } - + out_infos->clear(); out_infos->emplace_back(0, sizeof(*header), header, RomFSDataSource::Memory); - + /* Determine file offsets. */ entry_offset = 0; RomFSBuildFileContext *prev_file = NULL; @@ -297,7 +294,7 @@ void RomFSBuildContext::Build(std::vector *out_infos) { cur_file->sibling = cur_file->parent->file; cur_file->parent->file = cur_file; } - + /* Determine directory offsets. */ entry_offset = 0; for (const auto &it : this->directories) { @@ -311,8 +308,8 @@ void RomFSBuildContext::Build(std::vector *out_infos) { cur_dir->sibling = cur_dir->parent->child; cur_dir->parent->child = cur_dir; } - - + + /* Populate file tables. */ for (const auto &it : this->files) { cur_file = it.second; @@ -322,16 +319,16 @@ void RomFSBuildContext::Build(std::vector *out_infos) { cur_entry->sibling = (cur_file->sibling == NULL) ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset; cur_entry->offset = cur_file->offset; cur_entry->size = cur_file->size; - + u32 name_size = cur_file->path_len - cur_file->cur_path_ofs; u32 hash = romfs_calc_path_hash(cur_file->parent->entry_offset, (unsigned char *)cur_file->path + cur_file->cur_path_ofs, 0, name_size); cur_entry->hash = file_hash_table[hash % file_hash_table_entry_count]; file_hash_table[hash % file_hash_table_entry_count] = cur_file->entry_offset; - + cur_entry->name_size = name_size; memset(cur_entry->name, 0, (cur_entry->name_size + 3) & ~3); memcpy(cur_entry->name, cur_file->path + cur_file->cur_path_ofs, name_size); - + switch (cur_file->source) { case RomFSDataSource::BaseRomFS: case RomFSDataSource::FileRomFS: @@ -355,7 +352,7 @@ void RomFSBuildContext::Build(std::vector *out_infos) { break; } } - + /* Populate dir tables. */ for (const auto &it : this->directories) { cur_dir = it.second; @@ -364,17 +361,17 @@ void RomFSBuildContext::Build(std::vector *out_infos) { cur_entry->sibling = (cur_dir->sibling == NULL) ? ROMFS_ENTRY_EMPTY : cur_dir->sibling->entry_offset; cur_entry->child = (cur_dir->child == NULL) ? ROMFS_ENTRY_EMPTY : cur_dir->child->entry_offset; cur_entry->file = (cur_dir->file == NULL) ? ROMFS_ENTRY_EMPTY : cur_dir->file->entry_offset; - + u32 name_size = cur_dir->path_len - cur_dir->cur_path_ofs; u32 hash = romfs_calc_path_hash(cur_dir == this->root ? 0 : cur_dir->parent->entry_offset, (unsigned char *)cur_dir->path + cur_dir->cur_path_ofs, 0, name_size); cur_entry->hash = dir_hash_table[hash % dir_hash_table_entry_count]; dir_hash_table[hash % dir_hash_table_entry_count] = cur_dir->entry_offset; - + cur_entry->name_size = name_size; memset(cur_entry->name, 0, (cur_entry->name_size + 3) & ~3); memcpy(cur_entry->name, cur_dir->path + cur_dir->cur_path_ofs, name_size); } - + /* Delete directories. */ for (const auto &it : this->directories) { cur_dir = it.second; @@ -383,7 +380,7 @@ void RomFSBuildContext::Build(std::vector *out_infos) { } this->root = NULL; this->directories.clear(); - + /* Delete files. */ for (const auto &it : this->files) { cur_file = it.second; @@ -391,7 +388,7 @@ void RomFSBuildContext::Build(std::vector *out_infos) { delete cur_file; } this->files.clear(); - + /* Set header fields. */ header->header_size = sizeof(*header); header->file_hash_table_size = this->file_hash_table_size; @@ -411,5 +408,5 @@ void RomFSBuildContext::Build(std::vector *out_infos) { } else { out_infos->emplace_back(header->dir_hash_table_ofs, metadata_size, metadata, RomFSDataSource::Memory); } - + } diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romstorage.hpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romstorage.hpp index b3c531d64..a9dc70e24 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romstorage.hpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_romstorage.hpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #pragma once #include #include @@ -38,11 +38,11 @@ class RomFileStorage : public IROStorage { public: Result Read(void *buffer, size_t size, u64 offset) override { size_t out_sz = 0; - Result rc = fsFileRead(this->base_file, offset, buffer, size, FS_READOPTION_NONE, &out_sz); - if (R_SUCCEEDED(rc) && out_sz != size && out_sz) { - return this->Read((void *)((uintptr_t)buffer + out_sz), size - out_sz, offset + out_sz); + R_TRY(fsFileRead(this->base_file, offset, buffer, size, FS_READOPTION_NONE, &out_sz)); + if (out_sz != size && out_sz) { + R_TRY(this->Read((void *)((uintptr_t)buffer + out_sz), size - out_sz, offset + out_sz)); } - return rc; + return ResultSuccess; }; Result GetSize(u64 *out_size) override { return fsFileGetSize(this->base_file, out_size); diff --git a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_service.cpp b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_service.cpp index 0cbcb97f8..e5d53458c 100644 --- a/stratosphere/ams_mitm/source/fs_mitm/fsmitm_service.cpp +++ b/stratosphere/ams_mitm/source/fs_mitm/fsmitm_service.cpp @@ -87,31 +87,18 @@ void FsMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *ctx } Result FsMitmService::OpenHblWebContentFileSystem(Out> &out_fs) { - std::shared_ptr fs = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; - - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - out_fs.SetValue(std::move(fs)); - if (out_fs.IsDomain()) { - out_fs.ChangeObjectId(out_domain_id); - } - } - }; - /* Mount the SD card using fs.mitm's session. */ FsFileSystem sd_fs; - rc = fsMountSdcard(&sd_fs); - if (R_SUCCEEDED(rc)) { - std::unique_ptr web_ifs = std::make_unique(std::make_shared(sd_fs), AtmosphereHblWebContentDir); - fs = std::make_shared(std::move(web_ifs)); - if (out_fs.IsDomain()) { - out_domain_id = sd_fs.s.object_id; - } + R_TRY(fsMountSdcard(&sd_fs)); + + /* Set output filesystem. */ + std::unique_ptr web_ifs = std::make_unique(std::make_shared(sd_fs), AtmosphereHblWebContentDir); + out_fs.SetValue(std::make_shared(std::move(web_ifs))); + if (out_fs.IsDomain()) { + out_fs.ChangeObjectId(sd_fs.s.object_id); } - return rc; + return ResultSuccess; } Result FsMitmService::OpenFileSystemWithPatch(Out> out_fs, u64 title_id, u32 filesystem_type) { @@ -171,32 +158,18 @@ Result FsMitmService::OpenSdCardFileSystem(Out fs = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; - - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - out_fs.SetValue(std::move(fs)); - if (out_fs.IsDomain()) { - out_fs.ChangeObjectId(out_domain_id); - } - } - }; - /* Mount the SD card. */ FsFileSystem sd_fs; - if (R_FAILED((rc = fsMountSdcard(&sd_fs)))) { - return rc; - } + R_TRY(fsMountSdcard(&sd_fs)); - std::shared_ptr redir_fs = std::make_shared(new ProxyFileSystem(sd_fs), "/Nintendo", GetEmummcNintendoDirPath()); - fs = std::make_shared(redir_fs); + /* Set output filesystem. */ + std::unique_ptr redir_fs = std::make_unique(new ProxyFileSystem(sd_fs), "/Nintendo", GetEmummcNintendoDirPath()); + out_fs.SetValue(std::make_shared(std::move(redir_fs))); if (out_fs.IsDomain()) { - out_domain_id = sd_fs.s.object_id; + out_fs.ChangeObjectId(sd_fs.s.object_id); } - return rc; + return ResultSuccess; } Result FsMitmService::OpenSaveDataFileSystem(Out> out_fs, u8 space_id, FsSave save_struct) { @@ -219,33 +192,16 @@ Result FsMitmService::OpenSaveDataFileSystem(Out save_ifs = std::make_unique(save_fs); { - std::shared_ptr fs = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; - - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - out_fs.SetValue(std::move(fs)); - if (out_fs.IsDomain()) { - out_fs.ChangeObjectId(out_domain_id); - } - } - }; - /* Mount the SD card using fs.mitm's session. */ FsFileSystem sd_fs; - if (R_FAILED((rc = fsMountSdcard(&sd_fs)))) { - return rc; - } + R_TRY(fsMountSdcard(&sd_fs)); std::shared_ptr sd_ifs = std::make_shared(sd_fs); /* Verify that we can open the save directory, and that it exists. */ const u64 target_tid = save_struct.titleID == 0 ? this->title_id : save_struct.titleID; FsPath save_dir_path; - if (R_FAILED((rc = FsSaveUtils::GetSaveDataDirectoryPath(save_dir_path, space_id, save_struct.SaveDataType, target_tid, save_struct.userID, save_struct.saveID)))) { - return rc; - } + R_TRY(FsSaveUtils::GetSaveDataDirectoryPath(save_dir_path, space_id, save_struct.SaveDataType, target_tid, save_struct.userID, save_struct.saveID)); /* Check if this is the first time we're making the save. */ bool is_new_save = false; @@ -257,9 +213,7 @@ Result FsMitmService::OpenSaveDataFileSystem(Out dirsave_ifs = std::make_shared(new SubDirectoryFileSystem(sd_ifs, save_dir_path.str), std::move(save_ifs)); @@ -269,206 +223,170 @@ Result FsMitmService::OpenSaveDataFileSystem(OutCopySaveFromProxy(); } - fs = std::make_shared(static_cast>(dirsave_ifs)); + out_fs.SetValue(std::make_shared(static_cast>(dirsave_ifs))); if (out_fs.IsDomain()) { - out_domain_id = sd_fs.s.object_id; + out_fs.ChangeObjectId(sd_fs.s.object_id); } - return rc; + return ResultSuccess; } } /* Gate access to the BIS partitions. */ Result FsMitmService::OpenBisStorage(Out> out_storage, u32 _bis_partition_id) { - std::shared_ptr storage = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; const FsBisStorageId bis_partition_id = static_cast(_bis_partition_id); - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - out_storage.SetValue(std::move(storage)); - if (out_storage.IsDomain()) { - out_storage.ChangeObjectId(out_domain_id); - } - } - }; + /* Try to open a storage for the partition. */ + FsStorage bis_storage; + R_TRY(fsOpenBisStorageFwd(this->forward_service.get(), &bis_storage, bis_partition_id)); - { - FsStorage bis_storage; - rc = fsOpenBisStorageFwd(this->forward_service.get(), &bis_storage, bis_partition_id); - if (R_SUCCEEDED(rc)) { - const bool is_sysmodule = TitleIdIsSystem(this->title_id); - const bool has_bis_write_flag = Utils::HasFlag(this->title_id, "bis_write"); - const bool has_cal0_read_flag = Utils::HasFlag(this->title_id, "cal_read"); - if (bis_partition_id == FsBisStorageId_Boot0) { - storage = std::make_shared(new Boot0Storage(bis_storage, this->title_id)); - } else if (bis_partition_id == FsBisStorageId_CalibrationBinary) { - /* PRODINFO should *never* be writable. */ - if (is_sysmodule || has_cal0_read_flag) { - storage = std::make_shared(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage))); - } else { - /* Do not allow non-sysmodules to read *or* write CAL0. */ - fsStorageClose(&bis_storage); - rc = ResultFsPermissionDenied; - return rc; - } - } else { - if (is_sysmodule || has_bis_write_flag) { - /* Sysmodules should still be allowed to read and write. */ - storage = std::make_shared(new ProxyStorage(bis_storage)); - } else if (Utils::IsHblTid(this->title_id) && - ((FsBisStorageId_BootConfigAndPackage2NormalMain <= bis_partition_id && bis_partition_id <= FsBisStorageId_BootConfigAndPackage2RepairSub) || - bis_partition_id == FsBisStorageId_Boot1)) { - /* Allow HBL to write to boot1 (safe firm) + package2. */ - /* This is needed to not break compatibility with ChoiDujourNX, which does not check for write access before beginning an update. */ - /* TODO: get fixed so that this can be turned off without causing bricks :/ */ - storage = std::make_shared(new ProxyStorage(bis_storage)); - } else { - /* Non-sysmodules should be allowed to read. */ - storage = std::make_shared(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage))); - } - } - if (out_storage.IsDomain()) { - out_domain_id = bis_storage.s.object_id; - } + const bool is_sysmodule = TitleIdIsSystem(this->title_id); + const bool has_bis_write_flag = Utils::HasFlag(this->title_id, "bis_write"); + const bool has_cal0_read_flag = Utils::HasFlag(this->title_id, "cal_read"); + + /* Set output storage. */ + if (bis_partition_id == FsBisStorageId_Boot0) { + out_storage.SetValue(std::make_shared(new Boot0Storage(bis_storage, this->title_id))); + } else if (bis_partition_id == FsBisStorageId_CalibrationBinary) { + /* PRODINFO should *never* be writable. */ + if (is_sysmodule || has_cal0_read_flag) { + out_storage.SetValue(std::make_shared(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage)))); + } else { + /* Do not allow non-sysmodules to read *or* write CAL0. */ + fsStorageClose(&bis_storage); + return ResultFsPermissionDenied; + } + } else { + if (is_sysmodule || has_bis_write_flag) { + /* Sysmodules should still be allowed to read and write. */ + out_storage.SetValue(std::make_shared(new ProxyStorage(bis_storage))); + } else if (Utils::IsHblTid(this->title_id) && + ((FsBisStorageId_BootConfigAndPackage2NormalMain <= bis_partition_id && bis_partition_id <= FsBisStorageId_BootConfigAndPackage2RepairSub) || + bis_partition_id == FsBisStorageId_Boot1)) { + /* Allow HBL to write to boot1 (safe firm) + package2. */ + /* This is needed to not break compatibility with ChoiDujourNX, which does not check for write access before beginning an update. */ + /* TODO: get fixed so that this can be turned off without causing bricks :/ */ + out_storage.SetValue(std::make_shared(new ProxyStorage(bis_storage))); + } else { + /* Non-sysmodules should be allowed to read. */ + out_storage.SetValue(std::make_shared(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage)))); } } - return rc; + /* Copy domain id. */ + if (out_storage.IsDomain()) { + out_storage.ChangeObjectId(bis_storage.s.object_id); + } + + return ResultSuccess; } /* Add redirection for RomFS to the SD card. */ Result FsMitmService::OpenDataStorageByCurrentProcess(Out> out_storage) { - std::shared_ptr storage = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; - if (!this->should_override_contents) { return ResultAtmosphereMitmShouldForwardToSession; } - bool has_cache = StorageCacheGetEntry(this->title_id, &storage); + /* If we don't have anything to modify, there's no sense in maintaining a copy of the metadata tables. */ + if (!Utils::HasSdRomfsContent(this->title_id)) { + return ResultAtmosphereMitmShouldForwardToSession; + } - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - if (!has_cache) { - StorageCacheSetEntry(this->title_id, &storage); - } + /* Try to get from the cache. */ + { + std::shared_ptr cached_storage = nullptr; + bool has_cache = StorageCacheGetEntry(this->title_id, &cached_storage); - out_storage.SetValue(std::move(storage)); + if (has_cache) { if (out_storage.IsDomain()) { - out_storage.ChangeObjectId(out_domain_id); - } - } - }; - - - if (has_cache) { - if (out_storage.IsDomain()) { - FsStorage s = {0}; - rc = fsOpenDataStorageByCurrentProcessFwd(this->forward_service.get(), &s); - if (R_SUCCEEDED(rc)) { - out_domain_id = s.s.object_id; - } - } else { - rc = ResultSuccess; - } - if (R_FAILED(rc)) { - storage.reset(); - } - } else { - FsStorage data_storage; - FsFile data_file; - - rc = fsOpenDataStorageByCurrentProcessFwd(this->forward_service.get(), &data_storage); - - Log(armGetTls(), 0x100); - if (R_SUCCEEDED(rc)) { - if (Utils::HasSdRomfsContent(this->title_id)) { - /* TODO: Is there a sensible path that ends in ".romfs" we can use?" */ - if (R_SUCCEEDED(Utils::OpenSdFileForAtmosphere(this->title_id, "romfs.bin", FS_OPEN_READ, &data_file))) { - storage = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), std::make_shared(new FileStorage(new ProxyFile(data_file))), this->title_id)); - } else { - storage = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), nullptr, this->title_id)); - } - if (out_storage.IsDomain()) { - out_domain_id = data_storage.s.object_id; - } - } else { - /* If we don't have anything to modify, there's no sense in maintaining a copy of the metadata tables. */ - fsStorageClose(&data_storage); - rc = ResultAtmosphereMitmShouldForwardToSession; + /* TODO: Don't leak object id? */ + FsStorage s = {0}; + R_TRY(fsOpenDataStorageByCurrentProcessFwd(this->forward_service.get(), &s)); + out_storage.ChangeObjectId(s.s.object_id); } + out_storage.SetValue(std::move(cached_storage)); + return ResultSuccess; } } - return rc; + /* Try to open process romfs. */ + FsStorage data_storage; + R_TRY(fsOpenDataStorageByCurrentProcessFwd(this->forward_service.get(), &data_storage)); + + /* Make new layered romfs, cacheing to storage. */ + { + std::shared_ptr storage_to_cache = nullptr; + /* TODO: Is there a sensible path that ends in ".romfs" we can use?" */ + FsFile data_file; + if (R_SUCCEEDED(Utils::OpenSdFileForAtmosphere(this->title_id, "romfs.bin", FS_OPEN_READ, &data_file))) { + storage_to_cache = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), std::make_shared(new FileStorage(new ProxyFile(data_file))), this->title_id)); + } else { + storage_to_cache = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), nullptr, this->title_id)); + } + + StorageCacheSetEntry(this->title_id, &storage_to_cache); + + out_storage.SetValue(std::move(storage_to_cache)); + if (out_storage.IsDomain()) { + out_storage.ChangeObjectId(data_storage.s.object_id); + } + } + + return ResultSuccess; } /* Add redirection for System Data Archives to the SD card. */ Result FsMitmService::OpenDataStorageByDataId(Out> out_storage, u64 data_id, u8 sid) { - FsStorageId storage_id = (FsStorageId)sid; - FsStorage data_storage; - FsFile data_file; - if (!this->should_override_contents) { return ResultAtmosphereMitmShouldForwardToSession; } - std::shared_ptr storage = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; + /* If we don't have anything to modify, there's no sense in maintaining a copy of the metadata tables. */ + if (!Utils::HasSdRomfsContent(data_id)) { + return ResultAtmosphereMitmShouldForwardToSession; + } - bool has_cache = StorageCacheGetEntry(data_id, &storage); + FsStorageId storage_id = static_cast(sid); - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - if (!has_cache) { - StorageCacheSetEntry(data_id, &storage); - } + /* Try to get from the cache. */ + { + std::shared_ptr cached_storage = nullptr; + bool has_cache = StorageCacheGetEntry(data_id, &cached_storage); - out_storage.SetValue(std::move(storage)); + if (has_cache) { if (out_storage.IsDomain()) { - out_storage.ChangeObjectId(out_domain_id); - } - } - }; - - if (has_cache) { - if (out_storage.IsDomain()) { - FsStorage s = {0}; - rc = fsOpenDataStorageByDataIdFwd(this->forward_service.get(), storage_id, data_id, &s); - if (R_SUCCEEDED(rc)) { - out_domain_id = s.s.object_id; - } - } else { - rc = ResultSuccess; - } - if (R_FAILED(rc)) { - storage.reset(); - } - } else { - rc = fsOpenDataStorageByDataIdFwd(this->forward_service.get(), storage_id, data_id, &data_storage); - - if (R_SUCCEEDED(rc)) { - if (Utils::HasSdRomfsContent(data_id)) { - /* TODO: Is there a sensible path that ends in ".romfs" we can use?" */ - if (R_SUCCEEDED(Utils::OpenSdFileForAtmosphere(data_id, "romfs.bin", FS_OPEN_READ, &data_file))) { - storage = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), std::make_shared(new FileStorage(new ProxyFile(data_file))), data_id)); - } else { - storage = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), nullptr, data_id)); - } - if (out_storage.IsDomain()) { - out_domain_id = data_storage.s.object_id; - } - } else { - /* If we don't have anything to modify, there's no sense in maintaining a copy of the metadata tables. */ - fsStorageClose(&data_storage); - rc = ResultAtmosphereMitmShouldForwardToSession; + /* TODO: Don't leak object id? */ + FsStorage s = {0}; + R_TRY(fsOpenDataStorageByDataIdFwd(this->forward_service.get(), storage_id, data_id, &s)); + out_storage.ChangeObjectId(s.s.object_id); } + out_storage.SetValue(std::move(cached_storage)); + return ResultSuccess; } } - return rc; + /* Try to open data storage. */ + FsStorage data_storage; + R_TRY(fsOpenDataStorageByDataIdFwd(this->forward_service.get(), storage_id, data_id, &data_storage)); + + /* Make new layered romfs, cacheing to storage. */ + { + std::shared_ptr storage_to_cache = nullptr; + /* TODO: Is there a sensible path that ends in ".romfs" we can use?" */ + FsFile data_file; + if (R_SUCCEEDED(Utils::OpenSdFileForAtmosphere(data_id, "romfs.bin", FS_OPEN_READ, &data_file))) { + storage_to_cache = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), std::make_shared(new FileStorage(new ProxyFile(data_file))), data_id)); + } else { + storage_to_cache = std::make_shared(new LayeredRomFS(std::make_shared(new ProxyStorage(data_storage)), nullptr, data_id)); + } + + StorageCacheSetEntry(data_id, &storage_to_cache); + + out_storage.SetValue(std::move(storage_to_cache)); + if (out_storage.IsDomain()) { + out_storage.ChangeObjectId(data_storage.s.object_id); + } + } + + return ResultSuccess; } diff --git a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_am_service.cpp b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_am_service.cpp index 225912810..00d7a06d5 100644 --- a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_am_service.cpp +++ b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_am_service.cpp @@ -29,10 +29,13 @@ Result NsAmMitmService::GetApplicationContentPath(OutBuffer out_path, u64 ap } Result NsAmMitmService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) { - Result rc = nsamResolveApplicationContentPathFwd(this->forward_service.get(), title_id, static_cast(storage_type)); - /* Always succeed for web applet asking about HBL. */ - return (Utils::IsWebAppletTid(this->title_id) && Utils::IsHblTid(title_id)) ? 0 : rc; + if (Utils::IsWebAppletTid(this->title_id) && Utils::IsHblTid(title_id)) { + nsamResolveApplicationContentPathFwd(this->forward_service.get(), title_id, static_cast(storage_type)); + return ResultSuccess; + } + + return nsamResolveApplicationContentPathFwd(this->forward_service.get(), title_id, static_cast(storage_type)); } Result NsAmMitmService::GetRunningApplicationProgramId(Out out_tid, u64 app_id) { diff --git a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_main.cpp b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_main.cpp index 256ca76e1..136665673 100644 --- a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_main.cpp +++ b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_main.cpp @@ -13,7 +13,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - + #include #include #include @@ -36,15 +36,13 @@ void NsMitmMain(void *arg) { /* Ensure we can talk to NS. */ DoWithSmSession([&]() { - if (R_FAILED(nsInitialize())) { - std::abort(); - } - nsExit(); + R_ASSERT(nsInitialize()); }); + nsExit(); /* Create server manager */ auto server_manager = new WaitableManager(1); - + /* Create ns mitm. */ if (GetRuntimeFirmwareVersion() < FirmwareVersion_300) { AddMitmServerToManager(server_manager, "ns:am", 5); @@ -54,8 +52,8 @@ void NsMitmMain(void *arg) { /* Loop forever, servicing our services. */ server_manager->Process(); - + delete server_manager; - + } diff --git a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_web_service.cpp b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_web_service.cpp index 59561abdc..b970837fc 100644 --- a/stratosphere/ams_mitm/source/ns_mitm/nsmitm_web_service.cpp +++ b/stratosphere/ams_mitm/source/ns_mitm/nsmitm_web_service.cpp @@ -24,30 +24,17 @@ void NsWebMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext * } Result NsWebMitmService::GetDocumentInterface(Out> out_intf) { - std::shared_ptr intf = nullptr; - u32 out_domain_id = 0; - Result rc = ResultSuccess; - - ON_SCOPE_EXIT { - if (R_SUCCEEDED(rc)) { - out_intf.SetValue(std::move(intf)); - if (out_intf.IsDomain()) { - out_intf.ChangeObjectId(out_domain_id); - } - } - }; - /* Open a document interface. */ NsDocumentInterface doc; - rc = nsGetDocumentInterfaceFwd(this->forward_service.get(), &doc); - if (R_SUCCEEDED(rc)) { - intf = std::make_shared(this->title_id, doc); - if (out_intf.IsDomain()) { - out_domain_id = doc.s.object_id; - } + R_TRY(nsGetDocumentInterfaceFwd(this->forward_service.get(), &doc)); + + /* Set output interface. */ + out_intf.SetValue(std::move(std::make_shared(this->title_id, doc))); + if (out_intf.IsDomain()) { + out_intf.ChangeObjectId(doc.s.object_id); } - return rc; + return ResultSuccess; } Result NsDocumentService::GetApplicationContentPath(OutBuffer out_path, u64 app_id, u8 storage_type) { @@ -55,10 +42,13 @@ Result NsDocumentService::GetApplicationContentPath(OutBuffer out_path, u64 } Result NsDocumentService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) { - Result rc = nswebResolveApplicationContentPath(this->srv.get(), title_id, static_cast(storage_type)); - /* Always succeed for web applet asking about HBL. */ - return (Utils::IsWebAppletTid(this->title_id) && Utils::IsHblTid(title_id)) ? 0 : rc; + if (Utils::IsWebAppletTid(this->title_id) && Utils::IsHblTid(title_id)) { + nswebResolveApplicationContentPath(this->srv.get(), title_id, static_cast(storage_type)); + return ResultSuccess; + } + + return nswebResolveApplicationContentPath(this->srv.get(), title_id, static_cast(storage_type)); } Result NsDocumentService::GetRunningApplicationProgramId(Out out_tid, u64 app_id) { diff --git a/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.cpp b/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.cpp index 535d13ffe..88274477d 100644 --- a/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.cpp +++ b/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.cpp @@ -63,7 +63,7 @@ bool SetMitmService::IsValidRegionCode(u32 region_code) { return region_code < RegionCode_Max; } -void SetMitmService::EnsureLocale() { +Result SetMitmService::EnsureLocale() { std::scoped_lock lk(this->lock); if (!this->got_locale) { @@ -71,19 +71,16 @@ void SetMitmService::EnsureLocale() { if (this->title_id == TitleId_Ns) { u64 app_pid = 0; u64 app_tid = 0; - Result rc; - if (R_FAILED((rc = pmdmntGetApplicationPid(&app_pid)))) { - return; - } - if (R_FAILED((rc = pminfoGetTitleId(&app_tid, app_pid)))) { - return; - } + R_TRY(pmdmntGetApplicationPid(&app_pid)); + R_TRY(pminfoGetTitleId(&app_tid, app_pid)); this->locale = Utils::GetTitleOverrideLocale(app_tid); } else { this->locale = Utils::GetTitleOverrideLocale(this->title_id); this->got_locale = true; } } + + return ResultSuccess; } Result SetMitmService::GetLanguageCode(Out out_lang_code) { diff --git a/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.hpp b/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.hpp index b7e0341ed..59a46b88e 100644 --- a/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.hpp +++ b/stratosphere/ams_mitm/source/set_mitm/set_mitm_service.hpp @@ -50,7 +50,7 @@ class SetMitmService : public IMitmServiceObject { static bool IsValidLanguageCode(u64 lang_code); static bool IsValidRegionCode(u32 region_code); - void EnsureLocale(); + Result EnsureLocale(); protected: /* Overridden commands. */ Result GetLanguageCode(Out out_lang_code); diff --git a/stratosphere/ams_mitm/source/set_mitm/setsys_firmware_version.cpp b/stratosphere/ams_mitm/source/set_mitm/setsys_firmware_version.cpp index f0ccf6cb7..33305b2e4 100644 --- a/stratosphere/ams_mitm/source/set_mitm/setsys_firmware_version.cpp +++ b/stratosphere/ams_mitm/source/set_mitm/setsys_firmware_version.cpp @@ -32,7 +32,8 @@ void VersionManager::Initialize() { } /* Mount firmware version data archive. */ - if (R_SUCCEEDED(romfsMountFromDataArchive(TitleId_ArchiveSystemVersion, FsStorageId_NandSystem, "sysver"))) { + R_ASSERT(romfsMountFromDataArchive(TitleId_ArchiveSystemVersion, FsStorageId_NandSystem, "sysver")); + { ON_SCOPE_EXIT { romfsUnmount("sysver"); }; SetSysFirmwareVersion fw_ver; @@ -52,16 +53,13 @@ void VersionManager::Initialize() { g_fw_version = fw_ver; g_ams_fw_version = fw_ver; - } else { - /* Failure to open data archive is an abort. */ - std::abort(); } /* Modify the output firmware version. */ { u32 major, minor, micro; char display_version[sizeof(g_ams_fw_version.display_version)] = {0}; - + GetAtmosphereApiVersion(&major, &minor, µ, nullptr, nullptr); snprintf(display_version, sizeof(display_version), "%s (AMS %u.%u.%u)", g_ams_fw_version.display_version, major, minor, micro); @@ -73,7 +71,7 @@ void VersionManager::Initialize() { Result VersionManager::GetFirmwareVersion(u64 title_id, SetSysFirmwareVersion *out) { VersionManager::Initialize(); - + /* Report atmosphere string to qlaunch, maintenance and nothing else. */ if (title_id == TitleId_AppletQlaunch || title_id == TitleId_AppletMaintenanceMenu) { *out = g_ams_fw_version; diff --git a/stratosphere/ams_mitm/source/set_mitm/setsys_mitm_service.cpp b/stratosphere/ams_mitm/source/set_mitm/setsys_mitm_service.cpp index 7c91e894b..a9d98c501 100644 --- a/stratosphere/ams_mitm/source/set_mitm/setsys_mitm_service.cpp +++ b/stratosphere/ams_mitm/source/set_mitm/setsys_mitm_service.cpp @@ -22,19 +22,17 @@ #include "setsys_settings_items.hpp" void SetSysMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *ctx) { - /* No commands need postprocessing. */ + /* No commands need postprocessing. */ } Result SetSysMitmService::GetFirmwareVersion(OutPointerWithServerSize out) { - Result rc = VersionManager::GetFirmwareVersion(this->title_id, out.pointer); - + /* Get firmware version from manager. */ + R_TRY(VersionManager::GetFirmwareVersion(this->title_id, out.pointer)); + /* GetFirmwareVersion sanitizes these fields. */ - if (R_SUCCEEDED(rc)) { - out.pointer->revision_major = 0; - out.pointer->revision_minor = 0; - } - - return rc; + out.pointer->revision_major = 0; + out.pointer->revision_minor = 0; + return ResultSuccess; } Result SetSysMitmService::GetFirmwareVersion2(OutPointerWithServerSize out) { @@ -44,76 +42,63 @@ Result SetSysMitmService::GetFirmwareVersion2(OutPointerWithServerSize out_size, InPointer in_name, InPointer in_key) { char name[SET_MAX_NAME_SIZE] = {0}; char key[SET_MAX_NAME_SIZE] = {0}; - - Result rc = SettingsItemManager::ValidateName(in_name.pointer); - if (R_FAILED(rc)) { - return rc; - } - - rc = SettingsItemManager::ValidateKey(in_key.pointer); - if (R_FAILED(rc)) { - return rc; - } - + + /* Validate name and key. */ + R_TRY(SettingsItemManager::ValidateName(in_name.pointer)); + R_TRY(SettingsItemManager::ValidateKey(in_key.pointer)); + if (in_name.num_elements < SET_MAX_NAME_SIZE) { strncpy(name, in_name.pointer, in_name.num_elements); } else { strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1); } - + if (in_key.num_elements < SET_MAX_NAME_SIZE) { strncpy(key, in_key.pointer, in_key.num_elements); } else { strncpy(key, in_key.pointer, SET_MAX_NAME_SIZE-1); } - - rc = SettingsItemManager::GetValueSize(name, key, out_size.GetPointer()); - if (R_FAILED(rc)) { - rc = setsysGetSettingsItemValueSize(name, key, out_size.GetPointer()); + + /* Try to get override setting, fall back to real setting. */ + if (R_FAILED(SettingsItemManager::GetValueSize(name, key, out_size.GetPointer()))) { + R_TRY(setsysGetSettingsItemValueSize(name, key, out_size.GetPointer())); } - return rc; + return ResultSuccess; } Result SetSysMitmService::GetSettingsItemValue(Out out_size, OutBuffer out_value, InPointer in_name, InPointer in_key) { char name[SET_MAX_NAME_SIZE] = {0}; char key[SET_MAX_NAME_SIZE] = {0}; - - Result rc = SettingsItemManager::ValidateName(in_name.pointer); - if (R_FAILED(rc)) { - return rc; - } - - rc = SettingsItemManager::ValidateKey(in_key.pointer); - if (R_FAILED(rc)) { - return rc; - } - + + /* Validate name and key. */ + R_TRY(SettingsItemManager::ValidateName(in_name.pointer)); + R_TRY(SettingsItemManager::ValidateKey(in_key.pointer)); + if (out_value.buffer == nullptr) { return ResultSettingsItemValueBufferNull; } - + if (in_name.num_elements < SET_MAX_NAME_SIZE) { strncpy(name, in_name.pointer, in_name.num_elements); } else { strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1); } - + if (in_key.num_elements < SET_MAX_NAME_SIZE) { strncpy(key, in_key.pointer, in_key.num_elements); } else { strncpy(key, in_key.pointer, SET_MAX_NAME_SIZE-1); } - - rc = SettingsItemManager::GetValue(name, key, out_value.buffer, out_value.num_elements, out_size.GetPointer()); - - if (R_FAILED(rc)) { - rc = setsysGetSettingsItemValueFwd(this->forward_service.get(), name, key, out_value.buffer, out_value.num_elements, out_size.GetPointer()); + + /* Try to get override setting, fall back to real setting. */ + if (R_FAILED(SettingsItemManager::GetValue(name, key, out_value.buffer, out_value.num_elements, out_size.GetPointer()))) { + R_TRY(setsysGetSettingsItemValueFwd(this->forward_service.get(), name, key, out_value.buffer, out_value.num_elements, out_size.GetPointer())); } - return rc; + return ResultSuccess; } Result SetSysMitmService::GetEdid(OutPointerWithServerSize out) { return setsysGetEdidFwd(this->forward_service.get(), out.pointer); -} \ No newline at end of file +} diff --git a/stratosphere/ams_mitm/source/set_mitm/setsys_settings_items.cpp b/stratosphere/ams_mitm/source/set_mitm/setsys_settings_items.cpp index 0f795e84c..561cc32dc 100644 --- a/stratosphere/ams_mitm/source/set_mitm/setsys_settings_items.cpp +++ b/stratosphere/ams_mitm/source/set_mitm/setsys_settings_items.cpp @@ -38,11 +38,8 @@ static bool g_threw_fatal = false; static HosThread g_fatal_thread; static void FatalThreadFunc(void *arg) { - Result rc = (Result)((uintptr_t)arg); - svcSleepThread(5000000000ULL); - - fatalSimple(rc); + fatalSimple(static_cast(reinterpret_cast(arg))); } static bool IsCorrectFormat(const char *str, size_t len) { @@ -75,18 +72,18 @@ Result SettingsItemManager::ValidateName(const char *name, size_t max_size) { if (name == nullptr) { return ResultSettingsItemNameNull; } - + const size_t name_len = strnlen(name, std::min(max_size, MaxNameLength + 1)); if (name_len == 0) { return ResultSettingsItemNameEmpty; } else if (name_len > MaxNameLength) { return ResultSettingsItemNameTooLong; } - + if (!IsCorrectFormat(name, name_len)) { return ResultSettingsItemNameInvalidFormat; } - + return ResultSuccess; } @@ -98,18 +95,18 @@ Result SettingsItemManager::ValidateKey(const char *key, size_t max_size) { if (key == nullptr) { return ResultSettingsItemKeyNull; } - + const size_t key_len = strnlen(key, std::min(max_size, MaxKeyLength + 1)); if (key_len == 0) { return ResultSettingsItemKeyEmpty; } else if (key_len > MaxKeyLength) { return ResultSettingsItemKeyTooLong; } - + if (!IsCorrectFormat(key, key_len)) { return ResultSettingsItemKeyInvalidFormat; } - + return ResultSuccess; } @@ -139,15 +136,15 @@ static Result ParseValue(const char *name, const char *key, const char *val_tup) const char *delimiter = strchr(val_tup, '!'); const char *value_str = delimiter + 1; const char *type = val_tup; - + if (delimiter == NULL) { return ResultSettingsItemValueInvalidFormat; } - + while (isspace(*type) && type != delimiter) { type++; } - + size_t type_len = delimiter - type; size_t value_len = strlen(value_str); if (delimiter == NULL || value_len == 0 || type_len == 0) { @@ -156,7 +153,7 @@ static Result ParseValue(const char *name, const char *key, const char *val_tup) std::string kv = std::string(name).append("!").append(key); SettingsItemValue value; - + if (strncasecmp(type, "str", type_len) == 0 || strncasecmp(type, "string", type_len) == 0) { /* String */ value.size = value_len + 1; @@ -174,12 +171,12 @@ static Result ParseValue(const char *name, const char *key, const char *val_tup) if (data == nullptr) { return ResultSettingsItemValueAllocationFailed; } - + memset(data, 0, value.size); for (size_t i = 0; i < value_len; i++) { - data[i >> 1] |= hextoi(value_str[i]) << (4 * (i & 1)); + data[i >> 1] |= hextoi(value_str[i]) << (4 * (i & 1)); } - + value.data = data; } else if (strncasecmp(type, "u8", type_len) == 0) { /* u8 */ @@ -220,35 +217,35 @@ static Result ParseValue(const char *name, const char *key, const char *val_tup) } else { return ResultSettingsItemValueInvalidFormat; } - + g_settings_items[kv] = value; return ResultSuccess; } -static int SettingsItemIniHandler(void *user, const char *name, const char *key, const char *value) { - Result rc = *(reinterpret_cast(user)); - ON_SCOPE_EXIT { *(reinterpret_cast(user)) = rc; }; - - if (R_SUCCEEDED(rc)) { - rc = SettingsItemManager::ValidateName(name); - } - if (R_SUCCEEDED(rc)) { - rc = SettingsItemManager::ValidateKey(name); - } - if (R_SUCCEEDED(rc)) { - rc = ParseValue(name, key, value); - } - - return R_SUCCEEDED(rc) ? 1 : 0; +static Result ParseSettingsItemValue(const char *name, const char *key, const char *value) { + /* Validate name and key, then parse value. */ + R_TRY(SettingsItemManager::ValidateName(name)); + R_TRY(SettingsItemManager::ValidateKey(name)); + R_TRY(ParseValue(name, key, value)); + return ResultSuccess; } -void SettingsItemManager::LoadConfiguration() { +static int SettingsItemIniHandler(void *user, const char *name, const char *key, const char *value) { + Result *user_res = reinterpret_cast(user); + + /* Stop parsing after we fail to parse a value. */ + if (R_FAILED(*user_res)) { + return 0; + } + + *user_res = ParseSettingsItemValue(name, key, value); + return R_SUCCEEDED(*user_res) ? 1 : 0; +} + +static Result LoadConfigurationImpl() { /* Open file. */ FsFile config_file; - Result rc = Utils::OpenSdFile("/atmosphere/system_settings.ini", FS_OPEN_READ, &config_file); - if (R_FAILED(rc)) { - return; - } + R_TRY(Utils::OpenSdFile("/atmosphere/system_settings.ini", FS_OPEN_READ, &config_file)); ON_SCOPE_EXIT { fsFileClose(&config_file); }; @@ -257,19 +254,21 @@ void SettingsItemManager::LoadConfiguration() { std::string config_buf(0xFFFF, '\0'); /* Read from file. */ - if (R_SUCCEEDED(rc)) { - size_t actual_size; - rc = fsFileRead(&config_file, 0, config_buf.data(), config_buf.size(), FS_READOPTION_NONE, &actual_size); - } + size_t actual_size; + R_TRY(fsFileRead(&config_file, 0, config_buf.data(), config_buf.size(), FS_READOPTION_NONE, &actual_size)); - if (R_SUCCEEDED(rc)) { - ini_parse_string(config_buf.c_str(), SettingsItemIniHandler, &rc); - } + /* Parse. */ + Result parse_res = ResultSuccess; + ini_parse_string(config_buf.c_str(), SettingsItemIniHandler, &parse_res); + return parse_res; +} - /* Report error if we encountered one. */ - if (R_FAILED(rc) && !g_threw_fatal) { +void SettingsItemManager::LoadConfiguration() { + const Result load_res = LoadConfigurationImpl(); + if (R_FAILED(load_res) && !g_threw_fatal) { + /* Report error if we encountered one. */ g_threw_fatal = true; - g_fatal_thread.Initialize(&FatalThreadFunc, reinterpret_cast(rc), 0x1000, 49); + g_fatal_thread.Initialize(&FatalThreadFunc, reinterpret_cast(load_res), 0x1000, 49); g_fatal_thread.Start(); } } diff --git a/stratosphere/ams_mitm/source/utils.cpp b/stratosphere/ams_mitm/source/utils.cpp index ab30b8682..990b88c50 100644 --- a/stratosphere/ams_mitm/source/utils.cpp +++ b/stratosphere/ams_mitm/source/utils.cpp @@ -85,11 +85,8 @@ void Utils::InitializeThreadFunc(void *args) { Handle tmp_hnd = 0; static const char * const required_active_services[] = {"pcv", "gpio", "pinmux", "psc:c"}; for (unsigned int i = 0; i < sizeof(required_active_services) / sizeof(required_active_services[0]); i++) { - if (R_FAILED(smGetServiceOriginal(&tmp_hnd, smEncodeName(required_active_services[i])))) { - std::abort(); - } else { - svcCloseHandle(tmp_hnd); - } + R_ASSERT(smGetServiceOriginal(&tmp_hnd, smEncodeName(required_active_services[i]))); + svcCloseHandle(tmp_hnd); } }); @@ -102,9 +99,8 @@ void Utils::InitializeThreadFunc(void *args) { fsFsCreateDirectory(&g_sd_filesystem, "/atmosphere/automatic_backups"); { FsStorage cal0_storage; - if (R_FAILED(fsOpenBisStorage(&cal0_storage, FsBisStorageId_CalibrationBinary)) || R_FAILED(fsStorageRead(&cal0_storage, 0, g_cal0_storage_backup, ProdinfoSize))) { - std::abort(); - } + R_ASSERT(fsOpenBisStorage(&cal0_storage, FsBisStorageId_CalibrationBinary)); + R_ASSERT(fsStorageRead(&cal0_storage, 0, g_cal0_storage_backup, ProdinfoSize)); fsStorageClose(&cal0_storage); char serial_number[0x40] = {0}; @@ -199,7 +195,7 @@ void Utils::InitializeThreadFunc(void *args) { } Utils::RefreshConfiguration(); - + /* If we're emummc, persist a write handle to prevent other processes from touching the image. */ if (IsEmummc()) { const char *emummc_file_path = GetEmummcFilePath(); @@ -213,9 +209,7 @@ void Utils::InitializeThreadFunc(void *args) { /* Initialize set:sys. */ DoWithSmSession([&]() { - if (R_FAILED(setsysInitialize())) { - std::abort(); - } + R_ASSERT(setsysInitialize()); }); /* Signal SD is initialized. */ @@ -360,8 +354,6 @@ Result Utils::SaveSdFileForAtmosphere(u64 title_id, const char *fn, void *data, return ResultFsSdCardNotPresent; } - Result rc = ResultSuccess; - char path[FS_MAX_PATH]; if (*fn == '/') { snprintf(path, sizeof(path), "/atmosphere/titles/%016lx%s", title_id, fn); @@ -374,26 +366,16 @@ Result Utils::SaveSdFileForAtmosphere(u64 title_id, const char *fn, void *data, fsFsCreateFile(&g_sd_filesystem, path, size, 0); /* Try to open. */ - rc = fsFsOpenFile(&g_sd_filesystem, path, FS_OPEN_READ | FS_OPEN_WRITE, &f); - if (R_FAILED(rc)) { - return rc; - } - - /* Always close, if we opened. */ - ON_SCOPE_EXIT { - fsFileClose(&f); - }; + R_TRY(fsFsOpenFile(&g_sd_filesystem, path, FS_OPEN_READ | FS_OPEN_WRITE, &f)); + ON_SCOPE_EXIT { fsFileClose(&f); }; /* Try to make it big enough. */ - rc = fsFileSetSize(&f, size); - if (R_FAILED(rc)) { - return rc; - } + R_TRY(fsFileSetSize(&f, size)); /* Try to write the data. */ - rc = fsFileWrite(&f, 0, data, size, FS_WRITEOPTION_FLUSH); + R_TRY(fsFileWrite(&f, 0, data, size, FS_WRITEOPTION_FLUSH)); - return rc; + return ResultSuccess; } bool Utils::IsHblTid(u64 tid) { @@ -728,13 +710,12 @@ Result Utils::GetSettingsItemValue(const char *name, const char *key, void *out, Result Utils::GetSettingsItemBooleanValue(const char *name, const char *key, bool *out) { u8 val = 0; u64 out_size; - Result rc = Utils::GetSettingsItemValue(name, key, &val, sizeof(val), &out_size); - if (R_SUCCEEDED(rc)) { - if (out) { - *out = val != 0; - } + R_TRY(Utils::GetSettingsItemValue(name, key, &val, sizeof(val), &out_size)); + + if (out) { + *out = val != 0; } - return rc; + return ResultSuccess; } void Utils::RebootToFatalError(AtmosphereFatalErrorContext *ctx) {