ams_mitm: refactor for R_TRY

This commit is contained in:
Michael Scire 2019-06-20 04:04:33 -07:00
parent 4191dcee75
commit 60b831f369
32 changed files with 662 additions and 1246 deletions

View File

@ -31,7 +31,7 @@ DATA := data
INCLUDES := include ../../common/include INCLUDES := include ../../common/include
EXEFS_SRC := exefs_src 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 # options for code generation

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <cstdlib> #include <cstdlib>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
@ -34,7 +34,7 @@ extern "C" {
#define INNER_HEAP_SIZE 0x1000000 #define INNER_HEAP_SIZE 0x1000000
size_t nx_inner_heap_size = INNER_HEAP_SIZE; size_t nx_inner_heap_size = INNER_HEAP_SIZE;
char nx_inner_heap[INNER_HEAP_SIZE]; char nx_inner_heap[INNER_HEAP_SIZE];
void __libnx_initheap(void); void __libnx_initheap(void);
void __appInit(void); void __appInit(void);
void __appExit(void); void __appExit(void);
@ -69,27 +69,14 @@ void __libnx_initheap(void) {
} }
void __appInit(void) { void __appInit(void) {
Result rc;
SetFirmwareVersionForLibnx(); SetFirmwareVersionForLibnx();
DoWithSmSession([&]() { DoWithSmSession([&]() {
rc = fsInitialize(); R_ASSERT(fsInitialize());
if (R_FAILED(rc)) { R_ASSERT(pmdmntInitialize());
std::abort(); R_ASSERT(pminfoInitialize());
}
rc = pmdmntInitialize();
if (R_FAILED(rc)) {
std::abort();
}
rc = pminfoInitialize();
if (R_FAILED(rc)) {
std::abort();
}
}); });
CheckAtmosphereVersion(CURRENT_ATMOSPHERE_VERSION); CheckAtmosphereVersion(CURRENT_ATMOSPHERE_VERSION);
} }
@ -102,19 +89,15 @@ int main(int argc, char **argv)
{ {
consoleDebugInit(debugDevice_SVC); consoleDebugInit(debugDevice_SVC);
HosThread initializer_thread; HosThread initializer_thread;
LaunchAllMitmModules(); LaunchAllMitmModules();
if (R_FAILED(initializer_thread.Initialize(&Utils::InitializeThreadFunc, NULL, 0x4000, 0x15))) { R_ASSERT(initializer_thread.Initialize(&Utils::InitializeThreadFunc, NULL, 0x4000, 0x15));
std::abort(); R_ASSERT(initializer_thread.Start());
}
if (R_FAILED(initializer_thread.Start())) {
std::abort();
}
/* Wait for all mitm modules to end. */ /* Wait for all mitm modules to end. */
WaitAllMitmModules(); WaitAllMitmModules();
return 0; return 0;
} }

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <switch.h> #include <switch.h>
#include <stratosphere.hpp> #include <stratosphere.hpp>
#include <cstring> #include <cstring>
@ -43,16 +43,12 @@ void LaunchAllMitmModules() {
/* Create thread for each module. */ /* Create thread for each module. */
for (u32 i = 0; i < static_cast<u32>(MitmModuleId_Count); i++) { for (u32 i = 0; i < static_cast<u32>(MitmModuleId_Count); i++) {
const auto cur_module = &g_module_definitions[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))) { R_ASSERT(g_module_threads[i].Initialize(cur_module->main, nullptr, cur_module->stack_size, cur_module->priority));
std::abort();
}
} }
/* Start thread for each module. */ /* Start thread for each module. */
for (u32 i = 0; i < static_cast<u32>(MitmModuleId_Count); i++) { for (u32 i = 0; i < static_cast<u32>(MitmModuleId_Count); i++) {
if (R_FAILED(g_module_threads[i].Start())) { R_ASSERT(g_module_threads[i].Start());
std::abort();
}
} }
} }

View File

@ -21,15 +21,12 @@
#include "fs_ifile.hpp" #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 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<IFile> src_file; std::unique_ptr<IFile> src_file;
std::unique_ptr<IFile> dst_file; std::unique_ptr<IFile> dst_file;
const u64 file_size = dir_ent->fileSize; const u64 file_size = dir_ent->fileSize;
/* Open source file for reading. */ /* Open source file for reading. */
if (R_FAILED((rc = src_fs->OpenFile(src_file, src_path, OpenMode_Read)))) { R_TRY(src_fs->OpenFile(src_file, src_path, OpenMode_Read));
return rc;
}
/* Create and open destination file. */ /* Create and open destination file. */
{ {
@ -39,24 +36,16 @@ Result FsDirUtils::CopyFile(IFileSystem *dst_fs, IFileSystem *src_fs, const FsPa
std::abort(); std::abort();
} }
if (R_FAILED((rc = dst_fs->CreateFile(dst_path, file_size)))) { R_TRY(dst_fs->CreateFile(dst_path, file_size));
return rc; R_TRY(dst_fs->OpenFile(dst_file, dst_path, OpenMode_Write));
}
if (R_FAILED((rc = dst_fs->OpenFile(dst_file, dst_path, OpenMode_Write)))) {
return rc;
}
} }
/* Read/Write work_buf_size chunks. */ /* Read/Write work_buf_size chunks. */
u64 offset = 0; u64 offset = 0;
while (offset < file_size) { while (offset < file_size) {
u64 read_size; u64 read_size;
if (R_FAILED((rc = src_file->Read(&read_size, offset, work_buf, work_buf_size)))) { R_TRY(src_file->Read(&read_size, offset, work_buf, work_buf_size));
return rc; R_TRY(dst_file->Write(offset, work_buf, read_size));
}
if (R_FAILED((rc = dst_file->Write(offset, work_buf, read_size)))) {
return rc;
}
offset += 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) { Result FsDirUtils::EnsureDirectoryExists(IFileSystem *fs, const FsPath &path) {
FsPath normal_path; FsPath normal_path;
size_t normal_path_len; size_t normal_path_len;
Result rc;
/* Normalize the path. */ /* Normalize the path. */
if (R_FAILED((rc = FsPathUtils::Normalize(normal_path.str, sizeof(normal_path.str) - 1, path.str, &normal_path_len)))) { R_TRY(FsPathUtils::Normalize(normal_path.str, sizeof(normal_path.str) - 1, path.str, &normal_path_len));
return rc;
}
/* Repeatedly call CreateDirectory on each directory leading to the target. */ /* Repeatedly call CreateDirectory on each directory leading to the target. */
for (size_t i = 1; i < normal_path_len; i++) { 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] == '/') { if (normal_path.str[i] == '/') {
normal_path.str[i] = 0; normal_path.str[i] = 0;
{ {
rc = fs->CreateDirectory(normal_path); R_TRY_CATCH(fs->CreateDirectory(normal_path)) {
if (rc == ResultFsPathAlreadyExists) { R_CATCH(ResultFsPathAlreadyExists) {
rc = ResultSuccess; /* If path already exists, there's no problem. */
} }
if (R_FAILED(rc)) { } R_END_TRY_CATCH;
return rc;
}
} }
normal_path.str[i] = '/'; normal_path.str[i] = '/';
} }
} }
/* Call CreateDirectory on the final path. */ /* Call CreateDirectory on the final path. */
rc = fs->CreateDirectory(normal_path); R_TRY_CATCH(fs->CreateDirectory(normal_path)) {
if (rc == ResultFsPathAlreadyExists) { R_CATCH(ResultFsPathAlreadyExists) {
rc = ResultSuccess; /* If path already exists, there's no problem. */
} }
return rc; } R_END_TRY_CATCH;
return ResultSuccess;
} }

View File

@ -24,13 +24,10 @@ class FsDirUtils {
private: private:
template<typename OnEnterDir, typename OnExitDir, typename OnFile> template<typename OnEnterDir, typename OnExitDir, typename OnFile>
static Result IterateDirectoryRecursivelyInternal(IFileSystem *fs, FsPath &work_path, FsDirectoryEntry *ent_buf, OnEnterDir on_enter_dir, OnExitDir on_exit_dir, OnFile on_file) { 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<IDirectory> dir; std::unique_ptr<IDirectory> dir;
/* Open the directory. */ /* Open the directory. */
if (R_FAILED((rc = fs->OpenDirectory(dir, work_path, DirectoryOpenMode_All)))) { R_TRY(fs->OpenDirectory(dir, work_path, DirectoryOpenMode_All));
return rc;
}
const size_t parent_len = strnlen(work_path.str, sizeof(work_path.str) - 1); const size_t parent_len = strnlen(work_path.str, sizeof(work_path.str) - 1);
@ -38,9 +35,7 @@ class FsDirUtils {
while (true) { while (true) {
/* Read a single entry. */ /* Read a single entry. */
u64 read_count; u64 read_count;
if (R_FAILED((rc = dir->Read(&read_count, ent_buf, 1)))) { R_TRY(dir->Read(&read_count, ent_buf, 1));
return rc;
}
/* If we're out of entries, we're done. */ /* If we're out of entries, we're done. */
if (read_count == 0) { if (read_count == 0) {
@ -59,25 +54,17 @@ class FsDirUtils {
strncat(work_path.str, ent_buf->name, sizeof(work_path.str) - 1 - parent_len); strncat(work_path.str, ent_buf->name, sizeof(work_path.str) - 1 - parent_len);
if (is_dir) { if (is_dir) {
/* Enter directory. */ /* Enter directory. */
if (R_FAILED((rc = on_enter_dir(work_path, ent_buf)))) { R_TRY(on_enter_dir(work_path, ent_buf));
return rc;
}
/* Append separator, recurse. */ /* Append separator, recurse. */
strncat(work_path.str, "/", sizeof(work_path.str) - 1 - parent_len - child_name_len); 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)))) { R_TRY(IterateDirectoryRecursivelyInternal(fs, work_path, ent_buf, on_enter_dir, on_exit_dir, on_file));
return rc;
}
/* Exit directory. */ /* Exit directory. */
if (R_FAILED((rc = on_exit_dir(work_path, ent_buf)))) { R_TRY(on_exit_dir(work_path, ent_buf));
return rc;
}
} else { } else {
/* Call file handler. */ /* Call file handler. */
if (R_FAILED((rc = on_file(work_path, ent_buf)))) { R_TRY(on_file(work_path, ent_buf));
return rc;
}
} }
/* Restore parent path. */ /* 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) { 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); return CopyDirectoryRecursively(fs, fs, dst_path, src_path, work_buf, work_buf_size);
} }
/* Ensure directory existence. */ /* Ensure directory existence. */
static Result EnsureDirectoryExists(IFileSystem *fs, const FsPath &path); static Result EnsureDirectoryExists(IFileSystem *fs, const FsPath &path);
@ -140,19 +127,16 @@ class FsDirUtils {
template<typename F> template<typename F>
static Result RetryUntilTargetNotLocked(F f) { static Result RetryUntilTargetNotLocked(F f) {
const size_t MaxRetries = 10; const size_t MaxRetries = 10;
Result rc = ResultSuccess;
for (size_t i = 0; i < MaxRetries; i++) { for (size_t i = 0; i < MaxRetries; i++) {
rc = f(); R_TRY_CATCH(f()) {
R_CATCH(ResultFsTargetLocked) {
if (rc != ResultFsTargetLocked) { /* If target is locked, wait 100ms and try again. */
break; svcSleepThread(100'000'000ul);
} }
} R_END_TRY_CATCH;
/* If target is locked, wait 100ms and try again. */
svcSleepThread(100'000'000ul);
} }
return rc; return ResultSuccess;
} }
}; };

View File

@ -26,11 +26,7 @@ static char *GetNormalizedDirectory(const char *dir_prefix) {
/* Normalize the path. */ /* Normalize the path. */
char normal_path[FS_MAX_PATH + 1]; char normal_path[FS_MAX_PATH + 1];
size_t normal_path_len; size_t normal_path_len;
Result rc = FsPathUtils::Normalize(normal_path, sizeof(normal_path), dir_prefix, &normal_path_len); R_ASSERT(FsPathUtils::Normalize(normal_path, sizeof(normal_path), dir_prefix, &normal_path_len));
if (R_FAILED(rc)) {
/* N calls svcBreak here. */
std::abort();
}
/* Ensure terminating '/' */ /* Ensure terminating '/' */
if (normal_path[normal_path_len-1] != '/') { 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) { Result DirectoryRedirectionFileSystem::GetFullPath(char *out, size_t out_size, const char *relative_path) {
FsPath tmp_rel_path; FsPath tmp_rel_path;
Result rc = FsPathUtils::Normalize(tmp_rel_path.str, sizeof(tmp_rel_path), relative_path, nullptr); R_TRY(FsPathUtils::Normalize(tmp_rel_path.str, sizeof(tmp_rel_path), relative_path, nullptr));
if (R_FAILED(rc)) {
return rc;
}
if (std::strncmp(tmp_rel_path.str, this->before_dir, this->before_dir_len) == 0) { 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) { 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 DirectoryRedirectionFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CreateFile(full_path, size, flags); return this->base_fs->CreateFile(full_path, size, flags);
} }
Result DirectoryRedirectionFileSystem::DeleteFileImpl(const FsPath &path) { Result DirectoryRedirectionFileSystem::DeleteFileImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteFile(full_path); return this->base_fs->DeleteFile(full_path);
} }
Result DirectoryRedirectionFileSystem::CreateDirectoryImpl(const FsPath &path) { Result DirectoryRedirectionFileSystem::CreateDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CreateDirectory(full_path); return this->base_fs->CreateDirectory(full_path);
} }
Result DirectoryRedirectionFileSystem::DeleteDirectoryImpl(const FsPath &path) { Result DirectoryRedirectionFileSystem::DeleteDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteDirectory(full_path); return this->base_fs->DeleteDirectory(full_path);
} }
Result DirectoryRedirectionFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { Result DirectoryRedirectionFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteDirectoryRecursively(full_path); return this->base_fs->DeleteDirectoryRecursively(full_path);
} }
Result DirectoryRedirectionFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { Result DirectoryRedirectionFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
return this->base_fs->RenameFile(full_old_path, full_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 DirectoryRedirectionFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
return this->base_fs->RenameDirectory(full_old_path, full_new_path); return this->base_fs->RenameDirectory(full_old_path, full_new_path);
} }
Result DirectoryRedirectionFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { Result DirectoryRedirectionFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetEntryType(out, full_path); return this->base_fs->GetEntryType(out, full_path);
} }
Result DirectoryRedirectionFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) { Result DirectoryRedirectionFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->OpenFile(out_file, full_path, mode); return this->base_fs->OpenFile(out_file, full_path, mode);
} }
Result DirectoryRedirectionFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) { Result DirectoryRedirectionFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->OpenDirectory(out_dir, full_path, mode); 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 DirectoryRedirectionFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetFreeSpaceSize(out, full_path); return this->base_fs->GetFreeSpaceSize(out, full_path);
} }
Result DirectoryRedirectionFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) { Result DirectoryRedirectionFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetTotalSpaceSize(out, full_path); return this->base_fs->GetTotalSpaceSize(out, full_path);
} }
Result DirectoryRedirectionFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) { Result DirectoryRedirectionFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CleanDirectoryRecursively(full_path); return this->base_fs->CleanDirectoryRecursively(full_path);
} }
Result DirectoryRedirectionFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) { Result DirectoryRedirectionFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetFileTimeStampRaw(out, full_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 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; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path); return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path);
} }

View File

@ -31,17 +31,11 @@ class DirectoryRedirectionFileSystem : public IFileSystem {
public: public:
DirectoryRedirectionFileSystem(IFileSystem *fs, const char *before, const char *after) : base_fs(fs) { DirectoryRedirectionFileSystem(IFileSystem *fs, const char *before, const char *after) : base_fs(fs) {
Result rc = this->Initialize(before, after); R_ASSERT(this->Initialize(before, after));
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
DirectoryRedirectionFileSystem(std::shared_ptr<IFileSystem> fs, const char *before, const char *after) : base_fs(fs) { DirectoryRedirectionFileSystem(std::shared_ptr<IFileSystem> fs, const char *before, const char *after) : base_fs(fs) {
Result rc = this->Initialize(before, after); R_ASSERT(this->Initialize(before, after));
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }

View File

@ -62,59 +62,44 @@ class DirectorySaveDataFile : public IFile {
/* ================================================================================================ */ /* ================================================================================================ */
Result DirectorySaveDataFileSystem::Initialize() { Result DirectorySaveDataFileSystem::Initialize() {
Result rc;
DirectoryEntryType ent_type; DirectoryEntryType ent_type;
/* Check that the working directory exists. */ /* 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 path isn't found, create working directory and committed directory. */
if (rc == ResultFsPathNotFound) { R_CATCH(ResultFsPathNotFound) {
if (R_FAILED((rc = this->fs->CreateDirectory(WorkingDirectoryPath)))) { R_TRY(this->fs->CreateDirectory(WorkingDirectoryPath));
return rc; R_TRY(this->fs->CreateDirectory(CommittedDirectoryPath));
}
if (R_FAILED((rc = this->fs->CreateDirectory(CommittedDirectoryPath)))) {
return rc;
}
} else {
return rc;
} }
} } R_END_TRY_CATCH;
/* Now check for the committed directory. */ /* Now check for the committed directory. */
rc = this->fs->GetEntryType(&ent_type, CommittedDirectoryPath); R_TRY_CATCH(this->fs->GetEntryType(&ent_type, CommittedDirectoryPath)) {
if (R_SUCCEEDED(rc)) { /* Committed doesn't exist, so synchronize and rename. */
/* If committed exists, synchronize it to the working directory. */ R_CATCH(ResultFsPathNotFound) {
return this->SynchronizeDirectory(WorkingDirectoryPath, CommittedDirectoryPath); R_TRY(this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath));
} else if (rc == ResultFsPathNotFound) { return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath);
if (R_FAILED((rc = this->SynchronizeDirectory(SynchronizingDirectoryPath, WorkingDirectoryPath)))) {
return rc;
} }
return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); } R_END_TRY_CATCH;
} else {
return rc; /* 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 DirectorySaveDataFileSystem::SynchronizeDirectory(const FsPath &dst_dir, const FsPath &src_dir) {
Result rc;
/* Delete destination dir and recreate it. */ /* Delete destination dir and recreate it. */
if (R_FAILED((rc = this->fs->DeleteDirectoryRecursively(dst_dir)))) { R_TRY_CATCH(this->fs->DeleteDirectoryRecursively(dst_dir)) {
/* Nintendo returns error unconditionally, but I think that's a bug in their code. */ R_CATCH(ResultFsPathNotFound) {
if (rc != ResultFsPathNotFound) { /* Nintendo returns error unconditionally, but I think that's a bug in their code. */
return rc;
} }
} } R_END_TRY_CATCH;
if (R_FAILED((rc = this->fs->CreateDirectory(dst_dir)))) {
return rc; R_TRY(this->fs->CreateDirectory(dst_dir));
}
/* Get a buffer to work with. */ /* Get a buffer to work with. */
void *work_buf = nullptr; void *work_buf = nullptr;
size_t work_buf_size = 0; size_t work_buf_size = 0;
if (R_FAILED((rc = this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)))) { R_TRY(this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize));
return rc;
}
ON_SCOPE_EXIT { free(work_buf); }; ON_SCOPE_EXIT { free(work_buf); };
return FsDirUtils::CopyDirectoryRecursively(this->fs, dst_dir, src_dir, work_buf, work_buf_size); 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] != '/') { if (relative_path[0] != '/') {
return ResultFsInvalidPath; return ResultFsInvalidPath;
} }
/* Copy working directory path. */ /* Copy working directory path. */
std::strncpy(out, WorkingDirectoryPath.str, out_size); std::strncpy(out, WorkingDirectoryPath.str, out_size);
out[out_size-1] = 0; out[out_size-1] = 0;
/* Normalize it. */ /* Normalize it. */
constexpr size_t working_len = WorkingDirectoryPathLen - 1; constexpr size_t working_len = WorkingDirectoryPathLen - 1;
return FsPathUtils::Normalize(out + working_len, out_size - working_len, relative_path, nullptr); return FsPathUtils::Normalize(out + working_len, out_size - working_len, relative_path, nullptr);
@ -168,20 +153,13 @@ void DirectorySaveDataFileSystem::OnWritableFileClose() {
Result DirectorySaveDataFileSystem::CopySaveFromProxy() { Result DirectorySaveDataFileSystem::CopySaveFromProxy() {
if (this->proxy_save_fs != nullptr) { if (this->proxy_save_fs != nullptr) {
Result rc;
/* Get a buffer to work with. */ /* Get a buffer to work with. */
void *work_buf = nullptr; void *work_buf = nullptr;
size_t work_buf_size = 0; size_t work_buf_size = 0;
if (R_FAILED((rc = this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)))) { R_TRY(this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize));
return rc;
}
ON_SCOPE_EXIT { free(work_buf); }; ON_SCOPE_EXIT { free(work_buf); };
rc = FsDirUtils::CopyDirectoryRecursively(this, this->proxy_save_fs.get(), FsPathUtils::RootPath, FsPathUtils::RootPath, work_buf, work_buf_size); R_TRY(FsDirUtils::CopyDirectoryRecursively(this, this->proxy_save_fs.get(), FsPathUtils::RootPath, FsPathUtils::RootPath, work_buf, work_buf_size));
if (R_FAILED(rc)) {
return rc;
}
return this->Commit(); return this->Commit();
} }
return ResultSuccess; return ResultSuccess;
@ -190,125 +168,81 @@ Result DirectorySaveDataFileSystem::CopySaveFromProxy() {
/* ================================================================================================ */ /* ================================================================================================ */
Result DirectorySaveDataFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) { Result DirectorySaveDataFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->CreateFile(full_path, size, flags); return this->fs->CreateFile(full_path, size, flags);
} }
Result DirectorySaveDataFileSystem::DeleteFileImpl(const FsPath &path) { Result DirectorySaveDataFileSystem::DeleteFileImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->DeleteFile(full_path); return this->fs->DeleteFile(full_path);
} }
Result DirectorySaveDataFileSystem::CreateDirectoryImpl(const FsPath &path) { Result DirectorySaveDataFileSystem::CreateDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->CreateDirectory(full_path); return this->fs->CreateDirectory(full_path);
} }
Result DirectorySaveDataFileSystem::DeleteDirectoryImpl(const FsPath &path) { Result DirectorySaveDataFileSystem::DeleteDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->DeleteDirectory(full_path); return this->fs->DeleteDirectory(full_path);
} }
Result DirectorySaveDataFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { Result DirectorySaveDataFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->DeleteDirectoryRecursively(full_path); return this->fs->DeleteDirectoryRecursively(full_path);
} }
Result DirectorySaveDataFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { Result DirectorySaveDataFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->RenameFile(full_old_path, full_new_path); return this->fs->RenameFile(full_old_path, full_new_path);
} }
Result DirectorySaveDataFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) { Result DirectorySaveDataFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->RenameDirectory(full_old_path, full_new_path); return this->fs->RenameDirectory(full_old_path, full_new_path);
} }
Result DirectorySaveDataFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { Result DirectorySaveDataFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->GetEntryType(out, full_path); return this->fs->GetEntryType(out, full_path);
} }
Result DirectorySaveDataFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) { Result DirectorySaveDataFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
{ {
/* Open the raw file. */ /* Open the raw file. */
std::unique_ptr<IFile> file; std::unique_ptr<IFile> file;
if (R_FAILED((rc = this->fs->OpenFile(file, full_path, mode)))) { R_TRY(this->fs->OpenFile(file, full_path, mode));
return rc;
}
/* Create DirectorySaveDataFile wrapper. */ /* Create DirectorySaveDataFile wrapper. */
out_file = std::make_unique<DirectorySaveDataFile>(std::move(file), this, mode); out_file = std::make_unique<DirectorySaveDataFile>(std::move(file), this, mode);
@ -328,13 +262,9 @@ Result DirectorySaveDataFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_fil
} }
Result DirectorySaveDataFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) { Result DirectorySaveDataFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->OpenDirectory(out_dir, full_path, mode); 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. */ /* Instead, we will synchronize first, then delete committed, then rename. */
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
Result rc;
/* Ensure we don't have any open writable files. */ /* Ensure we don't have any open writable files. */
if (this->open_writable_files != 0) { if (this->open_writable_files != 0) {
@ -361,25 +290,20 @@ Result DirectorySaveDataFileSystem::CommitImpl() {
const auto RenameSynchDir = [&]() { return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); }; const auto RenameSynchDir = [&]() { return this->fs->RenameDirectory(SynchronizingDirectoryPath, CommittedDirectoryPath); };
/* Synchronize working directory. */ /* Synchronize working directory. */
if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(SynchronizeWorkingDir))))) { R_TRY(FsDirUtils::RetryUntilTargetNotLocked(std::move(SynchronizeWorkingDir)));
return rc;
}
/* Delete committed directory. */ /* Delete committed directory. */
if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(DeleteCommittedDir))))) { R_TRY_CATCH(FsDirUtils::RetryUntilTargetNotLocked(std::move(DeleteCommittedDir))) {
/* It is okay for us to not have a committed directory here. */ R_CATCH(ResultFsPathNotFound) {
if (rc != ResultFsPathNotFound) { /* It is okay for us to not have a committed directory here. */
return rc;
} }
} } R_END_TRY_CATCH;
/* Rename synchronizing directory to committed directory. */ /* Rename synchronizing directory to committed directory. */
if (R_FAILED((rc = FsDirUtils::RetryUntilTargetNotLocked(std::move(RenameSynchDir))))) { R_TRY(FsDirUtils::RetryUntilTargetNotLocked(std::move(RenameSynchDir)));
return rc;
}
/* TODO: Should I call this->fs->Commit()? Nintendo does not. */ /* TODO: Should I call this->fs->Commit()? Nintendo does not. */
return rc; return ResultSuccess;
} }
Result DirectorySaveDataFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) { 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 DirectorySaveDataFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
return this->fs->CleanDirectoryRecursively(full_path); return this->fs->CleanDirectoryRecursively(full_path);
} }

View File

@ -43,26 +43,17 @@ class DirectorySaveDataFileSystem : public IFileSystem {
public: public:
DirectorySaveDataFileSystem(IFileSystem *fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(fs), proxy_save_fs(std::move(pfs)) { DirectorySaveDataFileSystem(IFileSystem *fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(fs), proxy_save_fs(std::move(pfs)) {
this->fs = this->unique_fs.get(); this->fs = this->unique_fs.get();
Result rc = this->Initialize(); R_ASSERT(this->Initialize());
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
DirectorySaveDataFileSystem(std::unique_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(std::move(fs)), proxy_save_fs(std::move(pfs)) { DirectorySaveDataFileSystem(std::unique_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(std::move(fs)), proxy_save_fs(std::move(pfs)) {
this->fs = this->unique_fs.get(); this->fs = this->unique_fs.get();
Result rc = this->Initialize(); R_ASSERT(this->Initialize());
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
DirectorySaveDataFileSystem(std::shared_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : shared_fs(fs), proxy_save_fs(std::move(pfs)) { DirectorySaveDataFileSystem(std::shared_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : shared_fs(fs), proxy_save_fs(std::move(pfs)) {
this->fs = this->shared_fs.get(); this->fs = this->shared_fs.get();
Result rc = this->Initialize(); R_ASSERT(this->Initialize());
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
virtual ~DirectorySaveDataFileSystem() { } virtual ~DirectorySaveDataFileSystem() { }

View File

@ -29,7 +29,6 @@ Result FileStorage::UpdateSize() {
} }
Result FileStorage::Read(void *buffer, size_t size, u64 offset) { Result FileStorage::Read(void *buffer, size_t size, u64 offset) {
Result rc;
u64 read_size; u64 read_size;
if (size == 0) { if (size == 0) {
@ -38,9 +37,7 @@ Result FileStorage::Read(void *buffer, size_t size, u64 offset) {
if (buffer == nullptr) { if (buffer == nullptr) {
return ResultFsNullptrArgument; return ResultFsNullptrArgument;
} }
if (R_FAILED((rc = this->UpdateSize()))) { R_TRY(this->UpdateSize());
return rc;
}
if (!IStorage::IsRangeValid(offset, size, this->size)) { if (!IStorage::IsRangeValid(offset, size, this->size)) {
return ResultFsOutOfRange; 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 FileStorage::Write(void *buffer, size_t size, u64 offset) {
Result rc;
if (size == 0) { if (size == 0) {
return ResultSuccess; return ResultSuccess;
} }
if (buffer == nullptr) { if (buffer == nullptr) {
return ResultFsNullptrArgument; return ResultFsNullptrArgument;
} }
if (R_FAILED((rc = this->UpdateSize()))) { R_TRY(this->UpdateSize());
return rc;
}
if (!IStorage::IsRangeValid(offset, size, this->size)) { if (!IStorage::IsRangeValid(offset, size, this->size)) {
return ResultFsOutOfRange; return ResultFsOutOfRange;
} }
@ -77,10 +70,7 @@ Result FileStorage::Flush() {
} }
Result FileStorage::GetSize(u64 *out_size) { Result FileStorage::GetSize(u64 *out_size) {
Result rc = this->UpdateSize(); R_TRY(this->UpdateSize());
if (R_FAILED(rc)) {
return rc;
}
*out_size = this->size; *out_size = this->size;
return ResultSuccess; 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 FileStorage::OperateRange(FsOperationId operation_type, u64 offset, u64 size, FsRangeInfo *out_range_info) {
Result rc;
switch (operation_type) { switch (operation_type) {
case FsOperationId_InvalidateCache: case FsOperationId_InvalidateCache:
case FsOperationId_QueryRange: case FsOperationId_QueryRange:
@ -106,9 +94,7 @@ Result FileStorage::OperateRange(FsOperationId operation_type, u64 offset, u64 s
} }
return ResultSuccess; return ResultSuccess;
} }
if (R_FAILED((rc = this->UpdateSize()))) { R_TRY(this->UpdateSize());
return rc;
}
/* N checks for positivity + signed overflow on offset/size here, but we're using unsigned types... */ /* 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); return this->file->OperateRange(operation_type, offset, size, out_range_info);
default: default:

View File

@ -104,13 +104,10 @@ class ProxyDirectory : public IDirectory {
public: public:
virtual Result ReadImpl(uint64_t *out_count, FsDirectoryEntry *out_entries, uint64_t max_entries) { virtual Result ReadImpl(uint64_t *out_count, FsDirectoryEntry *out_entries, uint64_t max_entries) {
size_t count; 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); *out_count = count;
if (R_SUCCEEDED(rc)) { return ResultSuccess;
*out_count = count;
}
return rc;
} }
virtual Result GetEntryCountImpl(uint64_t *count) { virtual Result GetEntryCountImpl(uint64_t *count) {
return fsDirGetEntryCount(this->base_dir.get(), count); return fsDirGetEntryCount(this->base_dir.get(), count);

View File

@ -172,13 +172,10 @@ class ProxyFile : public IFile {
public: public:
virtual Result ReadImpl(u64 *out, u64 offset, void *buffer, u64 size) override { virtual Result ReadImpl(u64 *out, u64 offset, void *buffer, u64 size) override {
size_t out_sz; 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); *out = out_sz;
if (R_SUCCEEDED(rc)) { return ResultSuccess;
*out = out_sz;
}
return rc;
} }
virtual Result GetSizeImpl(u64 *out) override { virtual Result GetSizeImpl(u64 *out) override {
return fsFileGetSize(this->base_file.get(), out); return fsFileGetSize(this->base_file.get(), out);

View File

@ -216,55 +216,35 @@ class IFileSystemInterface : public IServiceObject {
/* Actual command API. */ /* Actual command API. */
virtual Result CreateFile(InPointer<char> in_path, uint64_t size, int flags) final { virtual Result CreateFile(InPointer<char> in_path, uint64_t size, int flags) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->CreateFile(path, size, flags); return this->base_fs->CreateFile(path, size, flags);
} }
virtual Result DeleteFile(InPointer<char> in_path) final { virtual Result DeleteFile(InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->DeleteFile(path); return this->base_fs->DeleteFile(path);
} }
virtual Result CreateDirectory(InPointer<char> in_path) final { virtual Result CreateDirectory(InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->CreateDirectory(path); return this->base_fs->CreateDirectory(path);
} }
virtual Result DeleteDirectory(InPointer<char> in_path) final { virtual Result DeleteDirectory(InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->DeleteDirectory(path); return this->base_fs->DeleteDirectory(path);
} }
virtual Result DeleteDirectoryRecursively(InPointer<char> in_path) final { virtual Result DeleteDirectoryRecursively(InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->DeleteDirectoryRecursively(path); return this->base_fs->DeleteDirectoryRecursively(path);
} }
@ -272,14 +252,8 @@ class IFileSystemInterface : public IServiceObject {
virtual Result RenameFile(InPointer<char> in_old_path, InPointer<char> in_new_path) final { virtual Result RenameFile(InPointer<char> in_old_path, InPointer<char> in_new_path) final {
FsPath old_path; FsPath old_path;
FsPath new_path; FsPath new_path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer));
Result rc; R_TRY(FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer));
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;
}
return this->base_fs->RenameFile(old_path, new_path); return this->base_fs->RenameFile(old_path, new_path);
} }
@ -287,14 +261,8 @@ class IFileSystemInterface : public IServiceObject {
virtual Result RenameDirectory(InPointer<char> in_old_path, InPointer<char> in_new_path) final { virtual Result RenameDirectory(InPointer<char> in_old_path, InPointer<char> in_new_path) final {
FsPath old_path; FsPath old_path;
FsPath new_path; FsPath new_path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&old_path, in_old_path.pointer));
Result rc; R_TRY(FsPathUtils::ConvertPathForServiceObject(&new_path, in_new_path.pointer));
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;
}
return this->base_fs->RenameDirectory(old_path, new_path); return this->base_fs->RenameDirectory(old_path, new_path);
} }
@ -302,54 +270,35 @@ class IFileSystemInterface : public IServiceObject {
virtual Result GetEntryType(Out<u32> out_type, InPointer<char> in_path) final { virtual Result GetEntryType(Out<u32> out_type, InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
DirectoryEntryType type; DirectoryEntryType type;
rc = this->base_fs->GetEntryType(&type, path); R_TRY(this->base_fs->GetEntryType(&type, path));
if (R_SUCCEEDED(rc)) {
out_type.SetValue(type); out_type.SetValue(type);
} return ResultSuccess;
return rc;
} }
virtual Result OpenFile(Out<std::shared_ptr<IFileInterface>> out_intf, InPointer<char> in_path, uint32_t mode) final { virtual Result OpenFile(Out<std::shared_ptr<IFileInterface>> out_intf, InPointer<char> in_path, uint32_t mode) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
std::unique_ptr<IFile> out_file; std::unique_ptr<IFile> out_file;
R_TRY(this->base_fs->OpenFile(out_file, path, static_cast<OpenMode>(mode)));
Result rc; out_intf.SetValue(std::make_shared<IFileInterface>(std::move(out_file)));
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { return ResultSuccess;
return rc;
}
rc = this->base_fs->OpenFile(out_file, path, static_cast<OpenMode>(mode));
if (R_SUCCEEDED(rc)) {
out_intf.SetValue(std::make_shared<IFileInterface>(std::move(out_file)));
/* TODO: Nintendo checks allocation success here, should we?. */
}
return rc;
} }
virtual Result OpenDirectory(Out<std::shared_ptr<IDirectoryInterface>> out_intf, InPointer<char> in_path, uint32_t mode) final { virtual Result OpenDirectory(Out<std::shared_ptr<IDirectoryInterface>> out_intf, InPointer<char> in_path, uint32_t mode) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
std::unique_ptr<IDirectory> out_dir; std::unique_ptr<IDirectory> out_dir;
R_TRY(this->base_fs->OpenDirectory(out_dir, path, static_cast<DirectoryOpenMode>(mode)));
Result rc; out_intf.SetValue(std::make_shared<IDirectoryInterface>(std::move(out_dir)));
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) { return ResultSuccess;
return rc;
}
rc = this->base_fs->OpenDirectory(out_dir, path, static_cast<DirectoryOpenMode>(mode));
if (R_SUCCEEDED(rc)) {
out_intf.SetValue(std::make_shared<IDirectoryInterface>(std::move(out_dir)));
/* TODO: Nintendo checks allocation success here, should we?. */
}
return rc;
} }
virtual Result Commit() final { virtual Result Commit() final {
@ -358,55 +307,35 @@ class IFileSystemInterface : public IServiceObject {
virtual Result GetFreeSpaceSize(Out<uint64_t> out_size, InPointer<char> in_path) final { virtual Result GetFreeSpaceSize(Out<uint64_t> out_size, InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->GetFreeSpaceSize(out_size.GetPointer(), path); return this->base_fs->GetFreeSpaceSize(out_size.GetPointer(), path);
} }
virtual Result GetTotalSpaceSize(Out<uint64_t> out_size, InPointer<char> in_path) final { virtual Result GetTotalSpaceSize(Out<uint64_t> out_size, InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->GetTotalSpaceSize(out_size.GetPointer(), path); return this->base_fs->GetTotalSpaceSize(out_size.GetPointer(), path);
} }
virtual Result CleanDirectoryRecursively(InPointer<char> in_path) final { virtual Result CleanDirectoryRecursively(InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->CleanDirectoryRecursively(path); return this->base_fs->CleanDirectoryRecursively(path);
} }
virtual Result GetFileTimeStampRaw(Out<FsTimeStampRaw> out_timestamp, InPointer<char> in_path) final { virtual Result GetFileTimeStampRaw(Out<FsTimeStampRaw> out_timestamp, InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->GetFileTimeStampRaw(out_timestamp.GetPointer(), path); return this->base_fs->GetFileTimeStampRaw(out_timestamp.GetPointer(), path);
} }
virtual Result QueryEntry(OutBuffer<char, BufferType_Type1> out_buffer, InBuffer<char, BufferType_Type1> in_buffer, int query, InPointer<char> in_path) final { virtual Result QueryEntry(OutBuffer<char, BufferType_Type1> out_buffer, InBuffer<char, BufferType_Type1> in_buffer, int query, InPointer<char> in_path) final {
FsPath path; FsPath path;
R_TRY(FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer));
Result rc;
if (R_FAILED((rc = FsPathUtils::ConvertPathForServiceObject(&path, in_path.pointer)))) {
return rc;
}
return this->base_fs->QueryEntry(out_buffer.buffer, out_buffer.num_elements, in_buffer.buffer, in_buffer.num_elements, query, path); 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) { virtual Result GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) {
FsEntryType type; FsEntryType type;
R_TRY(fsFsGetEntryType(this->base_fs.get(), path.str, &type));
Result rc = fsFsGetEntryType(this->base_fs.get(), path.str, &type); *out = static_cast<DirectoryEntryType>(static_cast<u32>(type));
if (R_SUCCEEDED(rc)) { return ResultSuccess;
*out = static_cast<DirectoryEntryType>(static_cast<u32>(type));
}
return rc;
} }
virtual Result OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) { virtual Result OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) {
FsFile f; FsFile f;
R_TRY(fsFsOpenFile(this->base_fs.get(), path.str, static_cast<int>(mode), &f));
Result rc = fsFsOpenFile(this->base_fs.get(), path.str, static_cast<int>(mode), &f); out_file = std::make_unique<ProxyFile>(f);
if (R_SUCCEEDED(rc)) { return ResultSuccess;
out_file = std::make_unique<ProxyFile>(f);
}
return rc;
} }
virtual Result OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) { virtual Result OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) {
FsDir d; FsDir d;
R_TRY(fsFsOpenDirectory(this->base_fs.get(), path.str, static_cast<int>(mode), &d));
Result rc = fsFsOpenDirectory(this->base_fs.get(), path.str, static_cast<int>(mode), &d); out_dir = std::make_unique<ProxyDirectory>(d);
if (R_SUCCEEDED(rc)) { return ResultSuccess;
out_dir = std::make_unique<ProxyDirectory>(d);
}
return rc;
} }
virtual Result CommitImpl() { virtual Result CommitImpl() {

View File

@ -85,9 +85,9 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) {
ParentDir, ParentDir,
WindowsDriveLetter, WindowsDriveLetter,
}; };
PathState state = PathState::Start; PathState state = PathState::Start;
for (const char *cur = path; *cur != 0; cur++) { for (const char *cur = path; *cur != 0; cur++) {
const char c = *cur; const char c = *cur;
switch (state) { switch (state) {
@ -145,7 +145,7 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) {
break; break;
} }
} }
switch (state) { switch (state) {
case PathState::Start: case PathState::Start:
case PathState::WindowsDriveLetter: case PathState::WindowsDriveLetter:
@ -160,7 +160,7 @@ Result FsPathUtils::IsNormalized(bool *out, const char *path) {
*out = false; *out = false;
break; break;
} }
return ResultSuccess; return ResultSuccess;
} }
@ -169,11 +169,11 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s
if (src[0] != '/') { if (src[0] != '/') {
return ResultFsInvalidPathFormat; return ResultFsInvalidPathFormat;
} }
bool skip_next_sep = false; bool skip_next_sep = false;
size_t i = 0; size_t i = 0;
size_t len = 0; size_t len = 0;
while (src[i] != 0) { while (src[i] != 0) {
if (src[i] == '/') { if (src[i] == '/') {
/* Swallow separators. */ /* Swallow separators. */
@ -181,7 +181,7 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s
if (src[i] == 0) { if (src[i] == 0) {
break; break;
} }
/* Handle skip if needed */ /* Handle skip if needed */
if (!skip_next_sep) { if (!skip_next_sep) {
if (len + 1 == max_out_size) { 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; return ResultFsTooLongPath;
} }
out[len++] = '/'; out[len++] = '/';
/* TODO: N has some weird windows support stuff here under a bool. */ /* TODO: N has some weird windows support stuff here under a bool. */
/* Boolean is normally false though? */ /* Boolean is normally false though? */
} }
skip_next_sep = false; skip_next_sep = false;
} }
/* See length of current dir. */ /* See length of current dir. */
size_t dir_len = 0; size_t dir_len = 0;
while (src[i+dir_len] != '/' && src[i+dir_len] != 0) { while (src[i+dir_len] != '/' && src[i+dir_len] != 0) {
dir_len++; dir_len++;
} }
if (FsPathUtils::IsCurrentDirectory(&src[i])) { if (FsPathUtils::IsCurrentDirectory(&src[i])) {
skip_next_sep = true; skip_next_sep = true;
} else if (FsPathUtils::IsParentDirectory(&src[i])) { } else if (FsPathUtils::IsParentDirectory(&src[i])) {
if (len == 1) { if (len == 1) {
return ResultFsDirectoryUnobtainable; return ResultFsDirectoryUnobtainable;
} }
/* Walk up a directory. */ /* Walk up a directory. */
len -= 2; len -= 2;
while (out[len] != '/') { while (out[len] != '/') {
@ -236,33 +236,34 @@ Result FsPathUtils::Normalize(char *out, size_t max_out_size, const char *src, s
return ResultFsTooLongPath; return ResultFsTooLongPath;
} }
} }
i += dir_len; i += dir_len;
} }
if (skip_next_sep) { if (skip_next_sep) {
len--; len--;
} }
if (len == 0 && max_out_size) { if (len == 0 && max_out_size) {
out[len++] = '/'; out[len++] = '/';
} }
if (max_out_size < len - 1) { if (max_out_size < len - 1) {
return ResultFsTooLongPath; return ResultFsTooLongPath;
} }
/* NULL terminate. */ /* NULL terminate. */
out[len] = 0; out[len] = 0;
if (out_len != nullptr) { if (out_len != nullptr) {
*out_len = len; *out_len = len;
} }
/* Assert normalized. */ /* Assert normalized. */
bool normalized = false; bool normalized = false;
if (R_FAILED(FsPathUtils::IsNormalized(&normalized, out)) || !normalized) { R_ASSERT(FsPathUtils::IsNormalized(&normalized, out));
if (!normalized) {
std::abort(); std::abort();
} }
return ResultSuccess; return ResultSuccess;
} }

View File

@ -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) { 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; const char *space_id_str, *save_type_str;
Result rc;
/* Get space_id, save_data_type strings. */ /* 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)))) { R_TRY(GetSaveDataSpaceIdString(&space_id_str, space_id));
return rc; R_TRY(GetSaveDataTypeString(&save_type_str, save_data_type));
}
/* Clear and initialize the path. */ /* Clear and initialize the path. */
std::memset(&out_path, 0, sizeof(out_path)); std::memset(&out_path, 0, sizeof(out_path));

View File

@ -26,33 +26,29 @@ Result SubDirectoryFileSystem::Initialize(const char *bp) {
if (strnlen(bp, FS_MAX_PATH) >= FS_MAX_PATH) { if (strnlen(bp, FS_MAX_PATH) >= FS_MAX_PATH) {
return ResultFsTooLongPath; return ResultFsTooLongPath;
} }
/* Normalize the path. */ /* Normalize the path. */
char normal_path[FS_MAX_PATH + 1]; char normal_path[FS_MAX_PATH + 1];
size_t normal_path_len; size_t normal_path_len;
Result rc = FsPathUtils::Normalize(normal_path, sizeof(normal_path), bp, &normal_path_len); R_ASSERT(FsPathUtils::Normalize(normal_path, sizeof(normal_path), bp, &normal_path_len));
if (R_FAILED(rc)) {
/* N calls svcBreak here. */
std::abort();
}
/* Ensure terminating '/' */ /* Ensure terminating '/' */
if (normal_path[normal_path_len-1] != '/') { if (normal_path[normal_path_len-1] != '/') {
if (normal_path_len + 2 > sizeof(normal_path)) { if (normal_path_len + 2 > sizeof(normal_path)) {
std::abort(); std::abort();
} }
strncat(normal_path, "/", 2); strncat(normal_path, "/", 2);
normal_path[sizeof(normal_path)-1] = 0; normal_path[sizeof(normal_path)-1] = 0;
normal_path_len++; normal_path_len++;
} }
this->base_path_len = normal_path_len + 1; this->base_path_len = normal_path_len + 1;
this->base_path = reinterpret_cast<char *>(malloc(this->base_path_len)); this->base_path = reinterpret_cast<char *>(malloc(this->base_path_len));
if (this->base_path == nullptr) { if (this->base_path == nullptr) {
return ResultFsAllocationFailureInSubDirectoryFileSystem; return ResultFsAllocationFailureInSubDirectoryFileSystem;
} }
std::strncpy(this->base_path, normal_path, this->base_path_len); std::strncpy(this->base_path, normal_path, this->base_path_len);
this->base_path[this->base_path_len-1] = 0; this->base_path[this->base_path_len-1] = 0;
return ResultSuccess; 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) { if (this->base_path_len + strnlen(relative_path, FS_MAX_PATH) > out_size) {
return ResultFsTooLongPath; return ResultFsTooLongPath;
} }
/* Copy base path. */ /* Copy base path. */
std::strncpy(out, this->base_path, out_size); std::strncpy(out, this->base_path, out_size);
out[out_size-1] = 0; out[out_size-1] = 0;
/* Normalize it. */ /* Normalize it. */
return FsPathUtils::Normalize(out + this->base_path_len - 2, out_size - (this->base_path_len - 2), relative_path, nullptr); 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 SubDirectoryFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CreateFile(full_path, size, flags); return this->base_fs->CreateFile(full_path, size, flags);
} }
Result SubDirectoryFileSystem::DeleteFileImpl(const FsPath &path) { Result SubDirectoryFileSystem::DeleteFileImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteFile(full_path); return this->base_fs->DeleteFile(full_path);
} }
Result SubDirectoryFileSystem::CreateDirectoryImpl(const FsPath &path) { Result SubDirectoryFileSystem::CreateDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CreateDirectory(full_path); return this->base_fs->CreateDirectory(full_path);
} }
Result SubDirectoryFileSystem::DeleteDirectoryImpl(const FsPath &path) { Result SubDirectoryFileSystem::DeleteDirectoryImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteDirectory(full_path); return this->base_fs->DeleteDirectory(full_path);
} }
Result SubDirectoryFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) { Result SubDirectoryFileSystem::DeleteDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->DeleteDirectoryRecursively(full_path); return this->base_fs->DeleteDirectoryRecursively(full_path);
} }
Result SubDirectoryFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) { Result SubDirectoryFileSystem::RenameFileImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
return this->base_fs->RenameFile(full_old_path, full_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 SubDirectoryFileSystem::RenameDirectoryImpl(const FsPath &old_path, const FsPath &new_path) {
Result rc;
FsPath full_old_path, full_new_path; FsPath full_old_path, full_new_path;
R_TRY(GetFullPath(full_old_path, old_path));
if (R_FAILED((rc = GetFullPath(full_old_path, old_path)))) { R_TRY(GetFullPath(full_new_path, new_path));
return rc;
}
if (R_FAILED((rc = GetFullPath(full_new_path, new_path)))) {
return rc;
}
return this->base_fs->RenameDirectory(full_old_path, full_new_path); return this->base_fs->RenameDirectory(full_old_path, full_new_path);
} }
Result SubDirectoryFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) { Result SubDirectoryFileSystem::GetEntryTypeImpl(DirectoryEntryType *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetEntryType(out, full_path); return this->base_fs->GetEntryType(out, full_path);
} }
Result SubDirectoryFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) { Result SubDirectoryFileSystem::OpenFileImpl(std::unique_ptr<IFile> &out_file, const FsPath &path, OpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->OpenFile(out_file, full_path, mode); return this->base_fs->OpenFile(out_file, full_path, mode);
} }
Result SubDirectoryFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) { Result SubDirectoryFileSystem::OpenDirectoryImpl(std::unique_ptr<IDirectory> &out_dir, const FsPath &path, DirectoryOpenMode mode) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->OpenDirectory(out_dir, full_path, mode); 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 SubDirectoryFileSystem::GetFreeSpaceSizeImpl(uint64_t *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetFreeSpaceSize(out, full_path); return this->base_fs->GetFreeSpaceSize(out, full_path);
} }
Result SubDirectoryFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) { Result SubDirectoryFileSystem::GetTotalSpaceSizeImpl(uint64_t *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetTotalSpaceSize(out, full_path); return this->base_fs->GetTotalSpaceSize(out, full_path);
} }
Result SubDirectoryFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) { Result SubDirectoryFileSystem::CleanDirectoryRecursivelyImpl(const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->CleanDirectoryRecursively(full_path); return this->base_fs->CleanDirectoryRecursively(full_path);
} }
Result SubDirectoryFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) { Result SubDirectoryFileSystem::GetFileTimeStampRawImpl(FsTimeStampRaw *out, const FsPath &path) {
Result rc;
FsPath full_path; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->GetFileTimeStampRaw(out, full_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 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; FsPath full_path;
R_TRY(GetFullPath(full_path, path));
if (R_FAILED((rc = GetFullPath(full_path, path)))) {
return rc;
}
return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path); return this->base_fs->QueryEntry(out, out_size, in, in_size, query, full_path);
} }

View File

@ -26,20 +26,14 @@ class SubDirectoryFileSystem : public IFileSystem {
std::shared_ptr<IFileSystem> base_fs; std::shared_ptr<IFileSystem> base_fs;
char *base_path = nullptr; char *base_path = nullptr;
size_t base_path_len = 0; size_t base_path_len = 0;
public: public:
SubDirectoryFileSystem(IFileSystem *fs, const char *bp) : base_fs(fs) { SubDirectoryFileSystem(IFileSystem *fs, const char *bp) : base_fs(fs) {
Result rc = this->Initialize(bp); R_ASSERT(this->Initialize(bp));
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
SubDirectoryFileSystem(std::shared_ptr<IFileSystem> fs, const char *bp) : base_fs(fs) { SubDirectoryFileSystem(std::shared_ptr<IFileSystem> fs, const char *bp) : base_fs(fs) {
Result rc = this->Initialize(bp); R_ASSERT(this->Initialize(bp));
if (R_FAILED(rc)) {
fatalSimple(rc);
}
} }
@ -48,7 +42,7 @@ class SubDirectoryFileSystem : public IFileSystem {
free(this->base_path); free(this->base_path);
} }
} }
private: private:
Result Initialize(const char *bp); Result Initialize(const char *bp);
protected: protected:
@ -56,7 +50,7 @@ class SubDirectoryFileSystem : public IFileSystem {
Result GetFullPath(FsPath &full_path, const FsPath &relative_path) { Result GetFullPath(FsPath &full_path, const FsPath &relative_path) {
return GetFullPath(full_path.str, sizeof(full_path.str), relative_path.str); return GetFullPath(full_path.str, sizeof(full_path.str), relative_path.str);
} }
public: public:
virtual Result CreateFileImpl(const FsPath &path, uint64_t size, int flags) override; virtual Result CreateFileImpl(const FsPath &path, uint64_t size, int flags) override;
virtual Result DeleteFileImpl(const FsPath &path) override; virtual Result DeleteFileImpl(const FsPath &path) override;

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <switch.h> #include <switch.h>
#include <cstring> #include <cstring>
#include <stratosphere.hpp> #include <stratosphere.hpp>
@ -38,16 +38,15 @@ bool Boot0Storage::CanModifyBctPubks() {
Result Boot0Storage::Read(void *_buffer, size_t size, u64 offset) { Result Boot0Storage::Read(void *_buffer, size_t size, u64 offset) {
std::scoped_lock<HosMutex> lk{g_boot0_mutex}; std::scoped_lock<HosMutex> lk{g_boot0_mutex};
return Base::Read(_buffer, size, offset); return Base::Read(_buffer, size, offset);
} }
Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) { Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) {
std::scoped_lock<HosMutex> lk{g_boot0_mutex}; std::scoped_lock<HosMutex> lk{g_boot0_mutex};
Result rc = ResultSuccess;
u8 *buffer = static_cast<u8 *>(_buffer); u8 *buffer = static_cast<u8 *>(_buffer);
/* Protect the keyblob region from writes. */ /* Protect the keyblob region from writes. */
if (offset <= EksStart) { if (offset <= EksStart) {
if (offset + size < EksStart) { if (offset + size < EksStart) {
@ -59,9 +58,7 @@ Result Boot0Storage::Write(void *_buffer, size_t size, u64 offset) {
} else { } else {
/* Perform portion of write falling past end of keyblobs. */ /* Perform portion of write falling past end of keyblobs. */
const u64 diff = EksEnd - offset; const u64 diff = EksEnd - offset;
if (R_FAILED((rc = Base::Write(buffer + diff, size - diff, EksEnd)))) { R_TRY(Base::Write(buffer + diff, size - diff, EksEnd));
return rc;
}
/* Adjust size to avoid writing end of data. */ /* Adjust size to avoid writing end of data. */
size = EksStart - offset; 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. */ /* Fall through, no need to do anything here. */
} }
} }
if (size == 0) { if (size == 0) {
return ResultSuccess; return ResultSuccess;
} }
/* We care about protecting autorcm from NS. */ /* We care about protecting autorcm from NS. */
if (CanModifyBctPubks() || offset >= BctEndOffset || (offset + BctSize >= BctEndOffset && offset % BctSize >= BctPubkEnd)) { if (CanModifyBctPubks() || offset >= BctEndOffset || (offset + BctSize >= BctEndOffset && offset % BctSize >= BctPubkEnd)) {
return Base::Write(buffer, size, offset); return Base::Write(buffer, size, offset);
} }
/* First, let's deal with the data past the end. */ /* First, let's deal with the data past the end. */
if (offset + size >= BctEndOffset) { if (offset + size >= BctEndOffset) {
const u64 diff = BctEndOffset - offset; const u64 diff = BctEndOffset - offset;
if (R_FAILED((rc = ProxyStorage::Write(buffer + diff, size - diff, BctEndOffset)))) { R_TRY(ProxyStorage::Write(buffer + diff, size - diff, BctEndOffset));
return rc;
}
size = diff; size = diff;
} }
/* Read in the current BCT region. */ /* Read in the current BCT region. */
if (R_FAILED((rc = ProxyStorage::Read(g_boot0_bct_buffer, BctEndOffset, 0)))) { R_TRY(ProxyStorage::Read(g_boot0_bct_buffer, BctEndOffset, 0));
return rc;
}
/* Update the bct buffer. */ /* Update the bct buffer. */
for (u64 cur_ofs = offset; cur_ofs < BctEndOffset && cur_ofs < offset + size; cur_ofs++) { for (u64 cur_ofs = offset; cur_ofs < BctEndOffset && cur_ofs < offset + size; cur_ofs++) {
const u64 cur_bct_rel_ofs = cur_ofs % BctSize; 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]; g_boot0_bct_buffer[cur_ofs] = buffer[cur_ofs - offset];
} }
} }
return ProxyStorage::Write(g_boot0_bct_buffer, BctEndOffset, 0); return ProxyStorage::Write(g_boot0_bct_buffer, BctEndOffset, 0);
} }

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#pragma once #pragma once
#include <switch.h> #include <switch.h>
#include <cstring> #include <cstring>
@ -22,7 +22,7 @@
#include "fs_istorage.hpp" #include "fs_istorage.hpp"
/* Represents a sectored storage. */ /* Represents a sectored storage. */
template<u64 SectorSize> template<u64 SectorSize>
class SectoredProxyStorage : public ProxyStorage { class SectoredProxyStorage : public ProxyStorage {
private: private:
u64 cur_seek = 0; u64 cur_seek = 0;
@ -39,19 +39,16 @@ class SectoredProxyStorage : public ProxyStorage {
SectoredProxyStorage(FsStorage s) : ProxyStorage(s) { } SectoredProxyStorage(FsStorage s) : ProxyStorage(s) { }
public: public:
virtual Result Read(void *_buffer, size_t size, u64 offset) override { virtual Result Read(void *_buffer, size_t size, u64 offset) override {
Result rc = ResultSuccess;
u8 *buffer = static_cast<u8 *>(_buffer); u8 *buffer = static_cast<u8 *>(_buffer);
this->Seek(offset); this->Seek(offset);
if (this->cur_sector_ofs == 0 && size % SectorSize == 0) { if (this->cur_sector_ofs == 0 && size % SectorSize == 0) {
/* Fast case. */ /* Fast case. */
return ProxyStorage::Read(buffer, size, offset); return ProxyStorage::Read(buffer, size, offset);
} }
if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)))) { R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek));
return rc;
}
if (size + this->cur_sector_ofs <= SectorSize) { if (size + this->cur_sector_ofs <= SectorSize) {
memcpy(buffer, sector_buf + this->cur_sector_ofs, size); memcpy(buffer, sector_buf + this->cur_sector_ofs, size);
} else { } else {
@ -59,90 +56,77 @@ class SectoredProxyStorage : public ProxyStorage {
size_t ofs = SectorSize - this->cur_sector_ofs; size_t ofs = SectorSize - this->cur_sector_ofs;
memcpy(buffer, sector_buf + this->cur_sector_ofs, ofs); memcpy(buffer, sector_buf + this->cur_sector_ofs, ofs);
size -= ofs; size -= ofs;
/* We're guaranteed alignment, here. */ /* We're guaranteed alignment, here. */
const size_t aligned_remaining_size = size - (size % SectorSize); const size_t aligned_remaining_size = size - (size % SectorSize);
if (aligned_remaining_size) { if (aligned_remaining_size) {
if (R_FAILED((rc = ProxyStorage::Read(buffer + ofs, aligned_remaining_size, offset + ofs)))) { R_TRY(ProxyStorage::Read(buffer + ofs, aligned_remaining_size, offset + ofs));
return rc;
}
ofs += aligned_remaining_size; ofs += aligned_remaining_size;
size -= aligned_remaining_size; size -= aligned_remaining_size;
} }
/* Read any leftover data. */ /* Read any leftover data. */
if (size) { if (size) {
if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)))) { R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs));
return rc;
}
memcpy(buffer + ofs, sector_buf, size); memcpy(buffer + ofs, sector_buf, size);
} }
} }
return rc; return ResultSuccess;
}; }
virtual Result Write(void *_buffer, size_t size, u64 offset) override { virtual Result Write(void *_buffer, size_t size, u64 offset) override {
Result rc = ResultSuccess;
u8 *buffer = static_cast<u8 *>(_buffer); u8 *buffer = static_cast<u8 *>(_buffer);
this->Seek(offset); this->Seek(offset);
if (this->cur_sector_ofs == 0 && size % SectorSize == 0) { if (this->cur_sector_ofs == 0 && size % SectorSize == 0) {
/* Fast case. */ /* Fast case. */
return ProxyStorage::Write(buffer, size, offset); return ProxyStorage::Write(buffer, size, offset);
} }
if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek)))) { R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, this->cur_seek));
return rc;
}
if (size + this->cur_sector_ofs <= SectorSize) { if (size + this->cur_sector_ofs <= SectorSize) {
memcpy(this->sector_buf + this->cur_sector_ofs, buffer, size); 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 { } else {
/* Leaving the sector... */ /* Leaving the sector... */
size_t ofs = SectorSize - this->cur_sector_ofs; size_t ofs = SectorSize - this->cur_sector_ofs;
memcpy(this->sector_buf + this->cur_sector_ofs, buffer, ofs); memcpy(this->sector_buf + this->cur_sector_ofs, buffer, ofs);
if (R_FAILED((rc = ProxyStorage::Write(this->sector_buf, ofs, this->cur_seek)))) { R_TRY(ProxyStorage::Write(this->sector_buf, ofs, this->cur_seek));
return rc;
}
size -= ofs; size -= ofs;
/* We're guaranteed alignment, here. */ /* We're guaranteed alignment, here. */
const size_t aligned_remaining_size = size - (size % SectorSize); const size_t aligned_remaining_size = size - (size % SectorSize);
if (aligned_remaining_size) { if (aligned_remaining_size) {
if (R_FAILED((rc = ProxyStorage::Write(buffer + ofs, aligned_remaining_size, offset + ofs)))) { R_TRY(ProxyStorage::Write(buffer + ofs, aligned_remaining_size, offset + ofs));
return rc;
}
ofs += aligned_remaining_size; ofs += aligned_remaining_size;
size -= aligned_remaining_size; size -= aligned_remaining_size;
} }
/* Write any leftover data. */ /* Write any leftover data. */
if (size) { if (size) {
if (R_FAILED((rc = ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs)))) { R_TRY(ProxyStorage::Read(this->sector_buf, SectorSize, offset + ofs));
return rc;
}
memcpy(this->sector_buf, buffer + ofs, size); 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. */ /* Represents an RCM-preserving BOOT0 partition. */
class Boot0Storage : public SectoredProxyStorage<0x200> { class Boot0Storage : public SectoredProxyStorage<0x200> {
using Base = SectoredProxyStorage<0x200>; using Base = SectoredProxyStorage<0x200>;
public: public:
static constexpr u64 BctEndOffset = 0xFC000; static constexpr u64 BctEndOffset = 0xFC000;
static constexpr u64 BctSize = 0x4000; static constexpr u64 BctSize = 0x4000;
static constexpr u64 BctPubkStart = 0x210; static constexpr u64 BctPubkStart = 0x210;
static constexpr u64 BctPubkSize = 0x100; static constexpr u64 BctPubkSize = 0x100;
static constexpr u64 BctPubkEnd = BctPubkStart + BctPubkSize; static constexpr u64 BctPubkEnd = BctPubkStart + BctPubkSize;
static constexpr u64 EksStart = 0x180000; static constexpr u64 EksStart = 0x180000;
static constexpr u64 EksSize = 0x4000; static constexpr u64 EksSize = 0x4000;
static constexpr u64 EksEnd = EksStart + EksSize; 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) { }
Boot0Storage(FsStorage s, u64 t) : Base(s), title_id(t) { } Boot0Storage(FsStorage s, u64 t) : Base(s), title_id(t) { }
public: 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; virtual Result Write(void *_buffer, size_t size, u64 offset) override;
}; };

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <switch.h> #include <switch.h>
#include <stratosphere.hpp> #include <stratosphere.hpp>
@ -50,7 +50,7 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) {
if (size == 0) { if (size == 0) {
return ResultSuccess; return ResultSuccess;
} }
/* Validate size. */ /* 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; 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) { if (offset >= virt_size) {
@ -77,8 +77,7 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) {
low = mid + 1; low = mid + 1;
} }
} }
Result rc;
size_t read_so_far = 0; size_t read_so_far = 0;
while (read_so_far < size) { while (read_so_far < size) {
RomFSSourceInfo *cur_source = &((*this->p_source_infos)[cur_source_ind]); 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: case RomFSDataSource::MetaData:
{ {
FsFile file; FsFile file;
if (R_FAILED((rc = Utils::OpenSdFileForAtmosphere(this->title_id, ROMFS_METADATA_FILE_PATH, FS_OPEN_READ, &file)))) { R_ASSERT(Utils::OpenSdFileForAtmosphere(this->title_id, ROMFS_METADATA_FILE_PATH, FS_OPEN_READ, &file));
fatalSimple(rc);
}
size_t out_read; 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)))) { R_ASSERT(fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read));
fatalSimple(rc);
}
if (out_read != cur_read_size) { if (out_read != cur_read_size) {
Reboot(); std::abort();
} }
fsFileClose(&file); fsFileClose(&file);
} }
@ -107,15 +102,11 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) {
case RomFSDataSource::LooseFile: case RomFSDataSource::LooseFile:
{ {
FsFile file; FsFile file;
if (R_FAILED((rc = Utils::OpenRomFSSdFile(this->title_id, cur_source->loose_source_info.path, FS_OPEN_READ, &file)))) { R_ASSERT(Utils::OpenRomFSSdFile(this->title_id, cur_source->loose_source_info.path, FS_OPEN_READ, &file));
fatalSimple(rc);
}
size_t out_read; 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)))) { R_ASSERT(fsFileRead(&file, (offset - cur_source->virtual_offset), (void *)((uintptr_t)buffer + read_so_far), cur_read_size, FS_READOPTION_NONE, &out_read));
fatalSimple(rc);
}
if (out_read != cur_read_size) { if (out_read != cur_read_size) {
Reboot(); std::abort();
} }
fsFileClose(&file); fsFileClose(&file);
} }
@ -127,23 +118,16 @@ Result LayeredRomFS::Read(void *buffer, size_t size, u64 offset) {
break; break;
case RomFSDataSource::BaseRomFS: 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))))) { 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)));
/* TODO: Can this ever happen? */
/* fatalSimple(rc); */
return rc;
}
} }
break; break;
case RomFSDataSource::FileRomFS: 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))))) { 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)));
fatalSimple(rc);
}
} }
break; break;
default: default:
/* TODO: Better error. */ std::abort();
fatalSimple(ResultKernelConnectionClosed);
break; break;
} }
read_so_far += cur_read_size; 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; offset = ((*this->p_source_infos)[cur_source_ind]).virtual_offset;
} }
} }
return ResultSuccess; return ResultSuccess;
} }
Result LayeredRomFS::GetSize(u64 *out_size) { Result LayeredRomFS::GetSize(u64 *out_size) {

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <switch.h> #include <switch.h>
#include <string.h> #include <string.h>
#include <stratosphere.hpp> #include <stratosphere.hpp>
@ -24,63 +24,67 @@
void RomFSBuildContext::VisitDirectory(FsFileSystem *filesys, RomFSBuildDirectoryContext *parent) { void RomFSBuildContext::VisitDirectory(FsFileSystem *filesys, RomFSBuildDirectoryContext *parent) {
FsDir dir; FsDir dir;
Result rc;
std::vector<RomFSBuildDirectoryContext *> child_dirs; std::vector<RomFSBuildDirectoryContext *> child_dirs;
/* Open the current parent directory. */ /* Open the current parent directory. */
if (R_FAILED((rc = Utils::OpenRomFSDir(filesys, this->title_id, parent->path, &dir)))) { R_ASSERT(Utils::OpenRomFSDir(filesys, this->title_id, parent->path, &dir));
fatalSimple(rc); {
} ON_SCOPE_EXIT { fsDirClose(&dir); };
u64 read_entries; u64 read_entries;
while (R_SUCCEEDED((rc = fsDirRead(&dir, 0, &read_entries, 1, &this->dir_entry))) && read_entries == 1) { while (true) {
if (this->dir_entry.type == ENTRYTYPE_DIR) { R_ASSERT(fsDirRead(&dir, 0, &read_entries, 1, &this->dir_entry));
RomFSBuildDirectoryContext *child = new RomFSBuildDirectoryContext({0}); if (read_entries != 1) {
/* Set child's path. */ break;
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->dir_entry.type == ENTRYTYPE_DIR) {
RomFSBuildDirectoryContext *child = new RomFSBuildDirectoryContext({0});
if (!this->AddDirectory(parent, child, NULL)) { /* Set child's path. */
delete[] child->path; child->cur_path_ofs = parent->path_len + 1;
delete child; 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 { } 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) { for (auto &child : child_dirs) {
this->VisitDirectory(filesys, child); this->VisitDirectory(filesys, child);
} }
@ -121,7 +125,7 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p
strcat(child->path + parent->path_len, "/"); strcat(child->path + parent->path_len, "/");
strncat(child->path + parent->path_len, cur_file->name, cur_file->name_size); strncat(child->path + parent->path_len, cur_file->name, cur_file->name_size);
child->size = cur_file->size; child->size = cur_file->size;
child->source = this->cur_source_type; child->source = this->cur_source_type;
child->orig_offset = cur_file->offset; child->orig_offset = cur_file->offset;
if (!this->AddFile(parent, child)) { if (!this->AddFile(parent, child)) {
@ -150,7 +154,7 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p
} }
strcat(child->path + parent->path_len, "/"); strcat(child->path + parent->path_len, "/");
strncat(child->path + parent->path_len, cur_child->name, cur_child->name_size); strncat(child->path + parent->path_len, cur_child->name, cur_child->name_size);
RomFSBuildDirectoryContext *real = NULL; RomFSBuildDirectoryContext *real = NULL;
if (!this->AddDirectory(parent, child, &real)) { if (!this->AddDirectory(parent, child, &real)) {
delete[] child->path; delete[] child->path;
@ -160,9 +164,9 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p
/* TODO: Better error. */ /* TODO: Better error. */
fatalSimple(ResultKernelConnectionClosed); fatalSimple(ResultKernelConnectionClosed);
} }
this->VisitDirectory(real, cur_child_offset, dir_table, dir_table_size, file_table, file_table_size); this->VisitDirectory(real, cur_child_offset, dir_table, dir_table_size, file_table, file_table_size);
if (cur_child->sibling == ROMFS_ENTRY_EMPTY) { if (cur_child->sibling == ROMFS_ENTRY_EMPTY) {
cur_child = NULL; cur_child = NULL;
} else { } else {
@ -174,26 +178,19 @@ void RomFSBuildContext::VisitDirectory(RomFSBuildDirectoryContext *parent, u32 p
} }
void RomFSBuildContext::MergeRomStorage(IROStorage *storage, RomFSDataSource source) { void RomFSBuildContext::MergeRomStorage(IROStorage *storage, RomFSDataSource source) {
Result rc;
RomFSHeader header; RomFSHeader header;
if (R_FAILED((rc = storage->Read(&header, sizeof(header), 0)))) { R_ASSERT(storage->Read(&header, sizeof(header), 0));
fatalSimple(rc);
}
if (header.header_size != sizeof(header)) { if (header.header_size != sizeof(header)) {
/* what */ /* what */
return; std::abort();
} }
/* Read tables. */ /* Read tables. */
auto dir_table = std::make_unique<u8[]>(header.dir_table_size); auto dir_table = std::make_unique<u8[]>(header.dir_table_size);
auto file_table = std::make_unique<u8[]>(header.file_table_size); auto file_table = std::make_unique<u8[]>(header.file_table_size);
if (R_FAILED((rc = storage->Read(dir_table.get(), header.dir_table_size, header.dir_table_ofs)))) { R_ASSERT(storage->Read(dir_table.get(), header.dir_table_size, header.dir_table_ofs));
fatalSimple(rc); R_ASSERT(storage->Read(file_table.get(), header.file_table_size, header.file_table_ofs));
}
if (R_FAILED((rc = storage->Read(file_table.get(), header.file_table_size, header.file_table_ofs)))) {
fatalSimple(rc);
}
this->cur_source_type = source; 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); 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; return false;
} }
/* Add a new directory. */ /* Add a new directory. */
this->num_dirs++; this->num_dirs++;
this->dir_table_size += sizeof(RomFSDirectoryEntry) + ((dir_ctx->path_len - dir_ctx->cur_path_ofs + 3) & ~3); this->dir_table_size += sizeof(RomFSDirectoryEntry) + ((dir_ctx->path_len - dir_ctx->cur_path_ofs + 3) & ~3);
dir_ctx->parent = parent_dir_ctx; dir_ctx->parent = parent_dir_ctx;
this->directories.insert({dir_ctx->path, dir_ctx}); this->directories.insert({dir_ctx->path, dir_ctx});
if (out_dir_ctx) { if (out_dir_ctx) {
*out_dir_ctx = dir_ctx; *out_dir_ctx = dir_ctx;
} }
@ -226,13 +223,13 @@ bool RomFSBuildContext::AddFile(RomFSBuildDirectoryContext *parent_dir_ctx, RomF
if (existing != this->files.end()) { if (existing != this->files.end()) {
return false; return false;
} }
/* Add a new file. */ /* Add a new file. */
this->num_files++; this->num_files++;
this->file_table_size += sizeof(RomFSFileEntry) + ((file_ctx->path_len - file_ctx->cur_path_ofs + 3) & ~3); this->file_table_size += sizeof(RomFSFileEntry) + ((file_ctx->path_len - file_ctx->cur_path_ofs + 3) & ~3);
file_ctx->parent = parent_dir_ctx; file_ctx->parent = parent_dir_ctx;
this->files.insert({file_ctx->path, file_ctx}); this->files.insert({file_ctx->path, file_ctx});
return true; return true;
} }
@ -240,12 +237,12 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
RomFSBuildFileContext *cur_file; RomFSBuildFileContext *cur_file;
RomFSBuildDirectoryContext *cur_dir; RomFSBuildDirectoryContext *cur_dir;
u32 entry_offset; u32 entry_offset;
u32 dir_hash_table_entry_count = romfs_get_hash_table_count(this->num_dirs); 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); 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->dir_hash_table_size = 4 * dir_hash_table_entry_count;
this->file_hash_table_size = 4 * file_hash_table_entry_count; this->file_hash_table_size = 4 * file_hash_table_entry_count;
/* Assign metadata pointers */ /* Assign metadata pointers */
auto *header = reinterpret_cast<RomFSHeader*>(std::malloc(sizeof(RomFSHeader))); auto *header = reinterpret_cast<RomFSHeader*>(std::malloc(sizeof(RomFSHeader)));
*header = {}; *header = {};
@ -255,7 +252,7 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
RomFSDirectoryEntry *dir_table = (RomFSDirectoryEntry *)((uintptr_t)dir_hash_table + this->dir_hash_table_size); 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); 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); RomFSFileEntry *file_table = (RomFSFileEntry *)((uintptr_t)file_hash_table + this->file_hash_table_size);
/* Clear out hash tables. */ /* Clear out hash tables. */
for (u32 i = 0; i < dir_hash_table_entry_count; i++) { for (u32 i = 0; i < dir_hash_table_entry_count; i++) {
dir_hash_table[i] = ROMFS_ENTRY_EMPTY; dir_hash_table[i] = ROMFS_ENTRY_EMPTY;
@ -263,10 +260,10 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
for (u32 i = 0; i < file_hash_table_entry_count; i++) { for (u32 i = 0; i < file_hash_table_entry_count; i++) {
file_hash_table[i] = ROMFS_ENTRY_EMPTY; file_hash_table[i] = ROMFS_ENTRY_EMPTY;
} }
out_infos->clear(); out_infos->clear();
out_infos->emplace_back(0, sizeof(*header), header, RomFSDataSource::Memory); out_infos->emplace_back(0, sizeof(*header), header, RomFSDataSource::Memory);
/* Determine file offsets. */ /* Determine file offsets. */
entry_offset = 0; entry_offset = 0;
RomFSBuildFileContext *prev_file = NULL; RomFSBuildFileContext *prev_file = NULL;
@ -297,7 +294,7 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
cur_file->sibling = cur_file->parent->file; cur_file->sibling = cur_file->parent->file;
cur_file->parent->file = cur_file; cur_file->parent->file = cur_file;
} }
/* Determine directory offsets. */ /* Determine directory offsets. */
entry_offset = 0; entry_offset = 0;
for (const auto &it : this->directories) { for (const auto &it : this->directories) {
@ -311,8 +308,8 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
cur_dir->sibling = cur_dir->parent->child; cur_dir->sibling = cur_dir->parent->child;
cur_dir->parent->child = cur_dir; cur_dir->parent->child = cur_dir;
} }
/* Populate file tables. */ /* Populate file tables. */
for (const auto &it : this->files) { for (const auto &it : this->files) {
cur_file = it.second; cur_file = it.second;
@ -322,16 +319,16 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
cur_entry->sibling = (cur_file->sibling == NULL) ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset; cur_entry->sibling = (cur_file->sibling == NULL) ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset;
cur_entry->offset = cur_file->offset; cur_entry->offset = cur_file->offset;
cur_entry->size = cur_file->size; cur_entry->size = cur_file->size;
u32 name_size = cur_file->path_len - cur_file->cur_path_ofs; 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); 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]; 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; file_hash_table[hash % file_hash_table_entry_count] = cur_file->entry_offset;
cur_entry->name_size = name_size; cur_entry->name_size = name_size;
memset(cur_entry->name, 0, (cur_entry->name_size + 3) & ~3); 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); memcpy(cur_entry->name, cur_file->path + cur_file->cur_path_ofs, name_size);
switch (cur_file->source) { switch (cur_file->source) {
case RomFSDataSource::BaseRomFS: case RomFSDataSource::BaseRomFS:
case RomFSDataSource::FileRomFS: case RomFSDataSource::FileRomFS:
@ -355,7 +352,7 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
break; break;
} }
} }
/* Populate dir tables. */ /* Populate dir tables. */
for (const auto &it : this->directories) { for (const auto &it : this->directories) {
cur_dir = it.second; cur_dir = it.second;
@ -364,17 +361,17 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
cur_entry->sibling = (cur_dir->sibling == NULL) ? ROMFS_ENTRY_EMPTY : cur_dir->sibling->entry_offset; 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->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; 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 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); 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]; 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; dir_hash_table[hash % dir_hash_table_entry_count] = cur_dir->entry_offset;
cur_entry->name_size = name_size; cur_entry->name_size = name_size;
memset(cur_entry->name, 0, (cur_entry->name_size + 3) & ~3); 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); memcpy(cur_entry->name, cur_dir->path + cur_dir->cur_path_ofs, name_size);
} }
/* Delete directories. */ /* Delete directories. */
for (const auto &it : this->directories) { for (const auto &it : this->directories) {
cur_dir = it.second; cur_dir = it.second;
@ -383,7 +380,7 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
} }
this->root = NULL; this->root = NULL;
this->directories.clear(); this->directories.clear();
/* Delete files. */ /* Delete files. */
for (const auto &it : this->files) { for (const auto &it : this->files) {
cur_file = it.second; cur_file = it.second;
@ -391,7 +388,7 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
delete cur_file; delete cur_file;
} }
this->files.clear(); this->files.clear();
/* Set header fields. */ /* Set header fields. */
header->header_size = sizeof(*header); header->header_size = sizeof(*header);
header->file_hash_table_size = this->file_hash_table_size; header->file_hash_table_size = this->file_hash_table_size;
@ -411,5 +408,5 @@ void RomFSBuildContext::Build(std::vector<RomFSSourceInfo> *out_infos) {
} else { } else {
out_infos->emplace_back(header->dir_hash_table_ofs, metadata_size, metadata, RomFSDataSource::Memory); out_infos->emplace_back(header->dir_hash_table_ofs, metadata_size, metadata, RomFSDataSource::Memory);
} }
} }

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#pragma once #pragma once
#include <switch.h> #include <switch.h>
#include <stratosphere.hpp> #include <stratosphere.hpp>
@ -38,11 +38,11 @@ class RomFileStorage : public IROStorage {
public: public:
Result Read(void *buffer, size_t size, u64 offset) override { Result Read(void *buffer, size_t size, u64 offset) override {
size_t out_sz = 0; size_t out_sz = 0;
Result rc = fsFileRead(this->base_file, offset, buffer, size, FS_READOPTION_NONE, &out_sz); R_TRY(fsFileRead(this->base_file, offset, buffer, size, FS_READOPTION_NONE, &out_sz));
if (R_SUCCEEDED(rc) && out_sz != size && out_sz) { if (out_sz != size && out_sz) {
return this->Read((void *)((uintptr_t)buffer + out_sz), size - out_sz, offset + 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 { Result GetSize(u64 *out_size) override {
return fsFileGetSize(this->base_file, out_size); return fsFileGetSize(this->base_file, out_size);

View File

@ -87,31 +87,18 @@ void FsMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *ctx
} }
Result FsMitmService::OpenHblWebContentFileSystem(Out<std::shared_ptr<IFileSystemInterface>> &out_fs) { Result FsMitmService::OpenHblWebContentFileSystem(Out<std::shared_ptr<IFileSystemInterface>> &out_fs) {
std::shared_ptr<IFileSystemInterface> 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. */ /* Mount the SD card using fs.mitm's session. */
FsFileSystem sd_fs; FsFileSystem sd_fs;
rc = fsMountSdcard(&sd_fs); R_TRY(fsMountSdcard(&sd_fs));
if (R_SUCCEEDED(rc)) {
std::unique_ptr<IFileSystem> web_ifs = std::make_unique<SubDirectoryFileSystem>(std::make_shared<ProxyFileSystem>(sd_fs), AtmosphereHblWebContentDir); /* Set output filesystem. */
fs = std::make_shared<IFileSystemInterface>(std::move(web_ifs)); std::unique_ptr<IFileSystem> web_ifs = std::make_unique<SubDirectoryFileSystem>(std::make_shared<ProxyFileSystem>(sd_fs), AtmosphereHblWebContentDir);
if (out_fs.IsDomain()) { out_fs.SetValue(std::make_shared<IFileSystemInterface>(std::move(web_ifs)));
out_domain_id = sd_fs.s.object_id; if (out_fs.IsDomain()) {
} out_fs.ChangeObjectId(sd_fs.s.object_id);
} }
return rc; return ResultSuccess;
} }
Result FsMitmService::OpenFileSystemWithPatch(Out<std::shared_ptr<IFileSystemInterface>> out_fs, u64 title_id, u32 filesystem_type) { Result FsMitmService::OpenFileSystemWithPatch(Out<std::shared_ptr<IFileSystemInterface>> out_fs, u64 title_id, u32 filesystem_type) {
@ -171,32 +158,18 @@ Result FsMitmService::OpenSdCardFileSystem(Out<std::shared_ptr<IFileSystemInterf
return ResultAtmosphereMitmShouldForwardToSession; return ResultAtmosphereMitmShouldForwardToSession;
} }
std::shared_ptr<IFileSystemInterface> 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. */ /* Mount the SD card. */
FsFileSystem sd_fs; FsFileSystem sd_fs;
if (R_FAILED((rc = fsMountSdcard(&sd_fs)))) { R_TRY(fsMountSdcard(&sd_fs));
return rc;
}
std::shared_ptr<IFileSystem> redir_fs = std::make_shared<DirectoryRedirectionFileSystem>(new ProxyFileSystem(sd_fs), "/Nintendo", GetEmummcNintendoDirPath()); /* Set output filesystem. */
fs = std::make_shared<IFileSystemInterface>(redir_fs); std::unique_ptr<IFileSystem> redir_fs = std::make_unique<DirectoryRedirectionFileSystem>(new ProxyFileSystem(sd_fs), "/Nintendo", GetEmummcNintendoDirPath());
out_fs.SetValue(std::make_shared<IFileSystemInterface>(std::move(redir_fs)));
if (out_fs.IsDomain()) { 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<std::shared_ptr<IFileSystemInterface>> out_fs, u8 space_id, FsSave save_struct) { Result FsMitmService::OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInterface>> out_fs, u8 space_id, FsSave save_struct) {
@ -219,33 +192,16 @@ Result FsMitmService::OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInte
std::unique_ptr<IFileSystem> save_ifs = std::make_unique<ProxyFileSystem>(save_fs); std::unique_ptr<IFileSystem> save_ifs = std::make_unique<ProxyFileSystem>(save_fs);
{ {
std::shared_ptr<IFileSystemInterface> 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. */ /* Mount the SD card using fs.mitm's session. */
FsFileSystem sd_fs; FsFileSystem sd_fs;
if (R_FAILED((rc = fsMountSdcard(&sd_fs)))) { R_TRY(fsMountSdcard(&sd_fs));
return rc;
}
std::shared_ptr<IFileSystem> sd_ifs = std::make_shared<ProxyFileSystem>(sd_fs); std::shared_ptr<IFileSystem> sd_ifs = std::make_shared<ProxyFileSystem>(sd_fs);
/* Verify that we can open the save directory, and that it exists. */ /* 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; const u64 target_tid = save_struct.titleID == 0 ? this->title_id : save_struct.titleID;
FsPath save_dir_path; 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)))) { R_TRY(FsSaveUtils::GetSaveDataDirectoryPath(save_dir_path, space_id, save_struct.SaveDataType, target_tid, save_struct.userID, save_struct.saveID));
return rc;
}
/* Check if this is the first time we're making the save. */ /* Check if this is the first time we're making the save. */
bool is_new_save = false; bool is_new_save = false;
@ -257,9 +213,7 @@ Result FsMitmService::OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInte
} }
/* Ensure the directory exists. */ /* Ensure the directory exists. */
if (R_FAILED((rc = FsDirUtils::EnsureDirectoryExists(sd_ifs.get(), save_dir_path)))) { R_TRY(FsDirUtils::EnsureDirectoryExists(sd_ifs.get(), save_dir_path));
return rc;
}
std::shared_ptr<DirectorySaveDataFileSystem> dirsave_ifs = std::make_shared<DirectorySaveDataFileSystem>(new SubDirectoryFileSystem(sd_ifs, save_dir_path.str), std::move(save_ifs)); std::shared_ptr<DirectorySaveDataFileSystem> dirsave_ifs = std::make_shared<DirectorySaveDataFileSystem>(new SubDirectoryFileSystem(sd_ifs, save_dir_path.str), std::move(save_ifs));
@ -269,206 +223,170 @@ Result FsMitmService::OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInte
dirsave_ifs->CopySaveFromProxy(); dirsave_ifs->CopySaveFromProxy();
} }
fs = std::make_shared<IFileSystemInterface>(static_cast<std::shared_ptr<IFileSystem>>(dirsave_ifs)); out_fs.SetValue(std::make_shared<IFileSystemInterface>(static_cast<std::shared_ptr<IFileSystem>>(dirsave_ifs)));
if (out_fs.IsDomain()) { 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. */ /* Gate access to the BIS partitions. */
Result FsMitmService::OpenBisStorage(Out<std::shared_ptr<IStorageInterface>> out_storage, u32 _bis_partition_id) { Result FsMitmService::OpenBisStorage(Out<std::shared_ptr<IStorageInterface>> out_storage, u32 _bis_partition_id) {
std::shared_ptr<IStorageInterface> storage = nullptr;
u32 out_domain_id = 0;
Result rc = ResultSuccess;
const FsBisStorageId bis_partition_id = static_cast<FsBisStorageId>(_bis_partition_id); const FsBisStorageId bis_partition_id = static_cast<FsBisStorageId>(_bis_partition_id);
ON_SCOPE_EXIT { /* Try to open a storage for the partition. */
if (R_SUCCEEDED(rc)) { FsStorage bis_storage;
out_storage.SetValue(std::move(storage)); R_TRY(fsOpenBisStorageFwd(this->forward_service.get(), &bis_storage, bis_partition_id));
if (out_storage.IsDomain()) {
out_storage.ChangeObjectId(out_domain_id);
}
}
};
{ const bool is_sysmodule = TitleIdIsSystem(this->title_id);
FsStorage bis_storage; const bool has_bis_write_flag = Utils::HasFlag(this->title_id, "bis_write");
rc = fsOpenBisStorageFwd(this->forward_service.get(), &bis_storage, bis_partition_id); const bool has_cal0_read_flag = Utils::HasFlag(this->title_id, "cal_read");
if (R_SUCCEEDED(rc)) {
const bool is_sysmodule = TitleIdIsSystem(this->title_id); /* Set output storage. */
const bool has_bis_write_flag = Utils::HasFlag(this->title_id, "bis_write"); if (bis_partition_id == FsBisStorageId_Boot0) {
const bool has_cal0_read_flag = Utils::HasFlag(this->title_id, "cal_read"); out_storage.SetValue(std::make_shared<IStorageInterface>(new Boot0Storage(bis_storage, this->title_id)));
if (bis_partition_id == FsBisStorageId_Boot0) { } else if (bis_partition_id == FsBisStorageId_CalibrationBinary) {
storage = std::make_shared<IStorageInterface>(new Boot0Storage(bis_storage, this->title_id)); /* PRODINFO should *never* be writable. */
} else if (bis_partition_id == FsBisStorageId_CalibrationBinary) { if (is_sysmodule || has_cal0_read_flag) {
/* PRODINFO should *never* be writable. */ out_storage.SetValue(std::make_shared<IStorageInterface>(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage))));
if (is_sysmodule || has_cal0_read_flag) { } else {
storage = std::make_shared<IStorageInterface>(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage))); /* Do not allow non-sysmodules to read *or* write CAL0. */
} else { fsStorageClose(&bis_storage);
/* Do not allow non-sysmodules to read *or* write CAL0. */ return ResultFsPermissionDenied;
fsStorageClose(&bis_storage); }
rc = ResultFsPermissionDenied; } else {
return rc; if (is_sysmodule || has_bis_write_flag) {
} /* Sysmodules should still be allowed to read and write. */
} else { out_storage.SetValue(std::make_shared<IStorageInterface>(new ProxyStorage(bis_storage)));
if (is_sysmodule || has_bis_write_flag) { } else if (Utils::IsHblTid(this->title_id) &&
/* Sysmodules should still be allowed to read and write. */ ((FsBisStorageId_BootConfigAndPackage2NormalMain <= bis_partition_id && bis_partition_id <= FsBisStorageId_BootConfigAndPackage2RepairSub) ||
storage = std::make_shared<IStorageInterface>(new ProxyStorage(bis_storage)); bis_partition_id == FsBisStorageId_Boot1)) {
} else if (Utils::IsHblTid(this->title_id) && /* Allow HBL to write to boot1 (safe firm) + package2. */
((FsBisStorageId_BootConfigAndPackage2NormalMain <= bis_partition_id && bis_partition_id <= FsBisStorageId_BootConfigAndPackage2RepairSub) || /* This is needed to not break compatibility with ChoiDujourNX, which does not check for write access before beginning an update. */
bis_partition_id == FsBisStorageId_Boot1)) { /* TODO: get fixed so that this can be turned off without causing bricks :/ */
/* Allow HBL to write to boot1 (safe firm) + package2. */ out_storage.SetValue(std::make_shared<IStorageInterface>(new ProxyStorage(bis_storage)));
/* This is needed to not break compatibility with ChoiDujourNX, which does not check for write access before beginning an update. */ } else {
/* TODO: get fixed so that this can be turned off without causing bricks :/ */ /* Non-sysmodules should be allowed to read. */
storage = std::make_shared<IStorageInterface>(new ProxyStorage(bis_storage)); out_storage.SetValue(std::make_shared<IStorageInterface>(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage))));
} else {
/* Non-sysmodules should be allowed to read. */
storage = std::make_shared<IStorageInterface>(new ReadOnlyStorageAdapter(new ProxyStorage(bis_storage)));
}
}
if (out_storage.IsDomain()) {
out_domain_id = bis_storage.s.object_id;
}
} }
} }
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. */ /* Add redirection for RomFS to the SD card. */
Result FsMitmService::OpenDataStorageByCurrentProcess(Out<std::shared_ptr<IStorageInterface>> out_storage) { Result FsMitmService::OpenDataStorageByCurrentProcess(Out<std::shared_ptr<IStorageInterface>> out_storage) {
std::shared_ptr<IStorageInterface> storage = nullptr;
u32 out_domain_id = 0;
Result rc = ResultSuccess;
if (!this->should_override_contents) { if (!this->should_override_contents) {
return ResultAtmosphereMitmShouldForwardToSession; 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 { /* Try to get from the cache. */
if (R_SUCCEEDED(rc)) { {
if (!has_cache) { std::shared_ptr<IStorageInterface> cached_storage = nullptr;
StorageCacheSetEntry(this->title_id, &storage); bool has_cache = StorageCacheGetEntry(this->title_id, &cached_storage);
}
out_storage.SetValue(std::move(storage)); if (has_cache) {
if (out_storage.IsDomain()) { if (out_storage.IsDomain()) {
out_storage.ChangeObjectId(out_domain_id); /* TODO: Don't leak object id? */
} FsStorage s = {0};
} R_TRY(fsOpenDataStorageByCurrentProcessFwd(this->forward_service.get(), &s));
}; out_storage.ChangeObjectId(s.s.object_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<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(new ProxyStorage(data_storage)), std::make_shared<ReadOnlyStorageAdapter>(new FileStorage(new ProxyFile(data_file))), this->title_id));
} else {
storage = std::make_shared<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(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;
} }
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<IStorageInterface> 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<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(new ProxyStorage(data_storage)), std::make_shared<ReadOnlyStorageAdapter>(new FileStorage(new ProxyFile(data_file))), this->title_id));
} else {
storage_to_cache = std::make_shared<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(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. */ /* Add redirection for System Data Archives to the SD card. */
Result FsMitmService::OpenDataStorageByDataId(Out<std::shared_ptr<IStorageInterface>> out_storage, u64 data_id, u8 sid) { Result FsMitmService::OpenDataStorageByDataId(Out<std::shared_ptr<IStorageInterface>> out_storage, u64 data_id, u8 sid) {
FsStorageId storage_id = (FsStorageId)sid;
FsStorage data_storage;
FsFile data_file;
if (!this->should_override_contents) { if (!this->should_override_contents) {
return ResultAtmosphereMitmShouldForwardToSession; return ResultAtmosphereMitmShouldForwardToSession;
} }
std::shared_ptr<IStorageInterface> storage = nullptr; /* If we don't have anything to modify, there's no sense in maintaining a copy of the metadata tables. */
u32 out_domain_id = 0; if (!Utils::HasSdRomfsContent(data_id)) {
Result rc = ResultSuccess; return ResultAtmosphereMitmShouldForwardToSession;
}
bool has_cache = StorageCacheGetEntry(data_id, &storage); FsStorageId storage_id = static_cast<FsStorageId>(sid);
ON_SCOPE_EXIT { /* Try to get from the cache. */
if (R_SUCCEEDED(rc)) { {
if (!has_cache) { std::shared_ptr<IStorageInterface> cached_storage = nullptr;
StorageCacheSetEntry(data_id, &storage); bool has_cache = StorageCacheGetEntry(data_id, &cached_storage);
}
out_storage.SetValue(std::move(storage)); if (has_cache) {
if (out_storage.IsDomain()) { if (out_storage.IsDomain()) {
out_storage.ChangeObjectId(out_domain_id); /* 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);
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<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(new ProxyStorage(data_storage)), std::make_shared<ReadOnlyStorageAdapter>(new FileStorage(new ProxyFile(data_file))), data_id));
} else {
storage = std::make_shared<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(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;
} }
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<IStorageInterface> 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<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(new ProxyStorage(data_storage)), std::make_shared<ReadOnlyStorageAdapter>(new FileStorage(new ProxyFile(data_file))), data_id));
} else {
storage_to_cache = std::make_shared<IStorageInterface>(new LayeredRomFS(std::make_shared<ReadOnlyStorageAdapter>(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;
} }

View File

@ -29,10 +29,13 @@ Result NsAmMitmService::GetApplicationContentPath(OutBuffer<u8> out_path, u64 ap
} }
Result NsAmMitmService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) { Result NsAmMitmService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) {
Result rc = nsamResolveApplicationContentPathFwd(this->forward_service.get(), title_id, static_cast<FsStorageId>(storage_type));
/* Always succeed for web applet asking about HBL. */ /* 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<FsStorageId>(storage_type));
return ResultSuccess;
}
return nsamResolveApplicationContentPathFwd(this->forward_service.get(), title_id, static_cast<FsStorageId>(storage_type));
} }
Result NsAmMitmService::GetRunningApplicationProgramId(Out<u64> out_tid, u64 app_id) { Result NsAmMitmService::GetRunningApplicationProgramId(Out<u64> out_tid, u64 app_id) {

View File

@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <cstdlib> #include <cstdlib>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
@ -36,15 +36,13 @@ void NsMitmMain(void *arg) {
/* Ensure we can talk to NS. */ /* Ensure we can talk to NS. */
DoWithSmSession([&]() { DoWithSmSession([&]() {
if (R_FAILED(nsInitialize())) { R_ASSERT(nsInitialize());
std::abort();
}
nsExit();
}); });
nsExit();
/* Create server manager */ /* Create server manager */
auto server_manager = new WaitableManager(1); auto server_manager = new WaitableManager(1);
/* Create ns mitm. */ /* Create ns mitm. */
if (GetRuntimeFirmwareVersion() < FirmwareVersion_300) { if (GetRuntimeFirmwareVersion() < FirmwareVersion_300) {
AddMitmServerToManager<NsAmMitmService>(server_manager, "ns:am", 5); AddMitmServerToManager<NsAmMitmService>(server_manager, "ns:am", 5);
@ -54,8 +52,8 @@ void NsMitmMain(void *arg) {
/* Loop forever, servicing our services. */ /* Loop forever, servicing our services. */
server_manager->Process(); server_manager->Process();
delete server_manager; delete server_manager;
} }

View File

@ -24,30 +24,17 @@ void NsWebMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *
} }
Result NsWebMitmService::GetDocumentInterface(Out<std::shared_ptr<NsDocumentService>> out_intf) { Result NsWebMitmService::GetDocumentInterface(Out<std::shared_ptr<NsDocumentService>> out_intf) {
std::shared_ptr<NsDocumentService> 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. */ /* Open a document interface. */
NsDocumentInterface doc; NsDocumentInterface doc;
rc = nsGetDocumentInterfaceFwd(this->forward_service.get(), &doc); R_TRY(nsGetDocumentInterfaceFwd(this->forward_service.get(), &doc));
if (R_SUCCEEDED(rc)) {
intf = std::make_shared<NsDocumentService>(this->title_id, doc); /* Set output interface. */
if (out_intf.IsDomain()) { out_intf.SetValue(std::move(std::make_shared<NsDocumentService>(this->title_id, doc)));
out_domain_id = doc.s.object_id; if (out_intf.IsDomain()) {
} out_intf.ChangeObjectId(doc.s.object_id);
} }
return rc; return ResultSuccess;
} }
Result NsDocumentService::GetApplicationContentPath(OutBuffer<u8> out_path, u64 app_id, u8 storage_type) { Result NsDocumentService::GetApplicationContentPath(OutBuffer<u8> out_path, u64 app_id, u8 storage_type) {
@ -55,10 +42,13 @@ Result NsDocumentService::GetApplicationContentPath(OutBuffer<u8> out_path, u64
} }
Result NsDocumentService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) { Result NsDocumentService::ResolveApplicationContentPath(u64 title_id, u8 storage_type) {
Result rc = nswebResolveApplicationContentPath(this->srv.get(), title_id, static_cast<FsStorageId>(storage_type));
/* Always succeed for web applet asking about HBL. */ /* 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<FsStorageId>(storage_type));
return ResultSuccess;
}
return nswebResolveApplicationContentPath(this->srv.get(), title_id, static_cast<FsStorageId>(storage_type));
} }
Result NsDocumentService::GetRunningApplicationProgramId(Out<u64> out_tid, u64 app_id) { Result NsDocumentService::GetRunningApplicationProgramId(Out<u64> out_tid, u64 app_id) {

View File

@ -63,7 +63,7 @@ bool SetMitmService::IsValidRegionCode(u32 region_code) {
return region_code < RegionCode_Max; return region_code < RegionCode_Max;
} }
void SetMitmService::EnsureLocale() { Result SetMitmService::EnsureLocale() {
std::scoped_lock<HosMutex> lk(this->lock); std::scoped_lock<HosMutex> lk(this->lock);
if (!this->got_locale) { if (!this->got_locale) {
@ -71,19 +71,16 @@ void SetMitmService::EnsureLocale() {
if (this->title_id == TitleId_Ns) { if (this->title_id == TitleId_Ns) {
u64 app_pid = 0; u64 app_pid = 0;
u64 app_tid = 0; u64 app_tid = 0;
Result rc; R_TRY(pmdmntGetApplicationPid(&app_pid));
if (R_FAILED((rc = pmdmntGetApplicationPid(&app_pid)))) { R_TRY(pminfoGetTitleId(&app_tid, app_pid));
return;
}
if (R_FAILED((rc = pminfoGetTitleId(&app_tid, app_pid)))) {
return;
}
this->locale = Utils::GetTitleOverrideLocale(app_tid); this->locale = Utils::GetTitleOverrideLocale(app_tid);
} else { } else {
this->locale = Utils::GetTitleOverrideLocale(this->title_id); this->locale = Utils::GetTitleOverrideLocale(this->title_id);
this->got_locale = true; this->got_locale = true;
} }
} }
return ResultSuccess;
} }
Result SetMitmService::GetLanguageCode(Out<u64> out_lang_code) { Result SetMitmService::GetLanguageCode(Out<u64> out_lang_code) {

View File

@ -50,7 +50,7 @@ class SetMitmService : public IMitmServiceObject {
static bool IsValidLanguageCode(u64 lang_code); static bool IsValidLanguageCode(u64 lang_code);
static bool IsValidRegionCode(u32 region_code); static bool IsValidRegionCode(u32 region_code);
void EnsureLocale(); Result EnsureLocale();
protected: protected:
/* Overridden commands. */ /* Overridden commands. */
Result GetLanguageCode(Out<u64> out_lang_code); Result GetLanguageCode(Out<u64> out_lang_code);

View File

@ -32,7 +32,8 @@ void VersionManager::Initialize() {
} }
/* Mount firmware version data archive. */ /* 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"); }; ON_SCOPE_EXIT { romfsUnmount("sysver"); };
SetSysFirmwareVersion fw_ver; SetSysFirmwareVersion fw_ver;
@ -52,16 +53,13 @@ void VersionManager::Initialize() {
g_fw_version = fw_ver; g_fw_version = fw_ver;
g_ams_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. */ /* Modify the output firmware version. */
{ {
u32 major, minor, micro; u32 major, minor, micro;
char display_version[sizeof(g_ams_fw_version.display_version)] = {0}; char display_version[sizeof(g_ams_fw_version.display_version)] = {0};
GetAtmosphereApiVersion(&major, &minor, &micro, nullptr, nullptr); GetAtmosphereApiVersion(&major, &minor, &micro, nullptr, nullptr);
snprintf(display_version, sizeof(display_version), "%s (AMS %u.%u.%u)", g_ams_fw_version.display_version, major, minor, micro); 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) { Result VersionManager::GetFirmwareVersion(u64 title_id, SetSysFirmwareVersion *out) {
VersionManager::Initialize(); VersionManager::Initialize();
/* Report atmosphere string to qlaunch, maintenance and nothing else. */ /* Report atmosphere string to qlaunch, maintenance and nothing else. */
if (title_id == TitleId_AppletQlaunch || title_id == TitleId_AppletMaintenanceMenu) { if (title_id == TitleId_AppletQlaunch || title_id == TitleId_AppletMaintenanceMenu) {
*out = g_ams_fw_version; *out = g_ams_fw_version;

View File

@ -22,19 +22,17 @@
#include "setsys_settings_items.hpp" #include "setsys_settings_items.hpp"
void SetSysMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *ctx) { void SetSysMitmService::PostProcess(IMitmServiceObject *obj, IpcResponseContext *ctx) {
/* No commands need postprocessing. */ /* No commands need postprocessing. */
} }
Result SetSysMitmService::GetFirmwareVersion(OutPointerWithServerSize<SetSysFirmwareVersion, 0x1> out) { Result SetSysMitmService::GetFirmwareVersion(OutPointerWithServerSize<SetSysFirmwareVersion, 0x1> 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. */ /* GetFirmwareVersion sanitizes these fields. */
if (R_SUCCEEDED(rc)) { out.pointer->revision_major = 0;
out.pointer->revision_major = 0; out.pointer->revision_minor = 0;
out.pointer->revision_minor = 0; return ResultSuccess;
}
return rc;
} }
Result SetSysMitmService::GetFirmwareVersion2(OutPointerWithServerSize<SetSysFirmwareVersion, 0x1> out) { Result SetSysMitmService::GetFirmwareVersion2(OutPointerWithServerSize<SetSysFirmwareVersion, 0x1> out) {
@ -44,76 +42,63 @@ Result SetSysMitmService::GetFirmwareVersion2(OutPointerWithServerSize<SetSysFir
Result SetSysMitmService::GetSettingsItemValueSize(Out<u64> out_size, InPointer<char> in_name, InPointer<char> in_key) { Result SetSysMitmService::GetSettingsItemValueSize(Out<u64> out_size, InPointer<char> in_name, InPointer<char> in_key) {
char name[SET_MAX_NAME_SIZE] = {0}; char name[SET_MAX_NAME_SIZE] = {0};
char key[SET_MAX_NAME_SIZE] = {0}; char key[SET_MAX_NAME_SIZE] = {0};
Result rc = SettingsItemManager::ValidateName(in_name.pointer); /* Validate name and key. */
if (R_FAILED(rc)) { R_TRY(SettingsItemManager::ValidateName(in_name.pointer));
return rc; R_TRY(SettingsItemManager::ValidateKey(in_key.pointer));
}
rc = SettingsItemManager::ValidateKey(in_key.pointer);
if (R_FAILED(rc)) {
return rc;
}
if (in_name.num_elements < SET_MAX_NAME_SIZE) { if (in_name.num_elements < SET_MAX_NAME_SIZE) {
strncpy(name, in_name.pointer, in_name.num_elements); strncpy(name, in_name.pointer, in_name.num_elements);
} else { } else {
strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1); strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1);
} }
if (in_key.num_elements < SET_MAX_NAME_SIZE) { if (in_key.num_elements < SET_MAX_NAME_SIZE) {
strncpy(key, in_key.pointer, in_key.num_elements); strncpy(key, in_key.pointer, in_key.num_elements);
} else { } else {
strncpy(key, in_key.pointer, SET_MAX_NAME_SIZE-1); strncpy(key, in_key.pointer, SET_MAX_NAME_SIZE-1);
} }
rc = SettingsItemManager::GetValueSize(name, key, out_size.GetPointer()); /* Try to get override setting, fall back to real setting. */
if (R_FAILED(rc)) { if (R_FAILED(SettingsItemManager::GetValueSize(name, key, out_size.GetPointer()))) {
rc = setsysGetSettingsItemValueSize(name, key, out_size.GetPointer()); R_TRY(setsysGetSettingsItemValueSize(name, key, out_size.GetPointer()));
} }
return rc; return ResultSuccess;
} }
Result SetSysMitmService::GetSettingsItemValue(Out<u64> out_size, OutBuffer<u8> out_value, InPointer<char> in_name, InPointer<char> in_key) { Result SetSysMitmService::GetSettingsItemValue(Out<u64> out_size, OutBuffer<u8> out_value, InPointer<char> in_name, InPointer<char> in_key) {
char name[SET_MAX_NAME_SIZE] = {0}; char name[SET_MAX_NAME_SIZE] = {0};
char key[SET_MAX_NAME_SIZE] = {0}; char key[SET_MAX_NAME_SIZE] = {0};
Result rc = SettingsItemManager::ValidateName(in_name.pointer); /* Validate name and key. */
if (R_FAILED(rc)) { R_TRY(SettingsItemManager::ValidateName(in_name.pointer));
return rc; R_TRY(SettingsItemManager::ValidateKey(in_key.pointer));
}
rc = SettingsItemManager::ValidateKey(in_key.pointer);
if (R_FAILED(rc)) {
return rc;
}
if (out_value.buffer == nullptr) { if (out_value.buffer == nullptr) {
return ResultSettingsItemValueBufferNull; return ResultSettingsItemValueBufferNull;
} }
if (in_name.num_elements < SET_MAX_NAME_SIZE) { if (in_name.num_elements < SET_MAX_NAME_SIZE) {
strncpy(name, in_name.pointer, in_name.num_elements); strncpy(name, in_name.pointer, in_name.num_elements);
} else { } else {
strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1); strncpy(name, in_name.pointer, SET_MAX_NAME_SIZE-1);
} }
if (in_key.num_elements < SET_MAX_NAME_SIZE) { if (in_key.num_elements < SET_MAX_NAME_SIZE) {
strncpy(key, in_key.pointer, in_key.num_elements); strncpy(key, in_key.pointer, in_key.num_elements);
} else { } else {
strncpy(key, in_key.pointer, SET_MAX_NAME_SIZE-1); 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()); /* 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()))) {
if (R_FAILED(rc)) { R_TRY(setsysGetSettingsItemValueFwd(this->forward_service.get(), name, key, out_value.buffer, out_value.num_elements, out_size.GetPointer()));
rc = 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<SetSysEdid, 0x1> out) { Result SetSysMitmService::GetEdid(OutPointerWithServerSize<SetSysEdid, 0x1> out) {
return setsysGetEdidFwd(this->forward_service.get(), out.pointer); return setsysGetEdidFwd(this->forward_service.get(), out.pointer);
} }

View File

@ -38,11 +38,8 @@ static bool g_threw_fatal = false;
static HosThread g_fatal_thread; static HosThread g_fatal_thread;
static void FatalThreadFunc(void *arg) { static void FatalThreadFunc(void *arg) {
Result rc = (Result)((uintptr_t)arg);
svcSleepThread(5000000000ULL); svcSleepThread(5000000000ULL);
fatalSimple(static_cast<Result>(reinterpret_cast<uintptr_t>(arg)));
fatalSimple(rc);
} }
static bool IsCorrectFormat(const char *str, size_t len) { 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) { if (name == nullptr) {
return ResultSettingsItemNameNull; return ResultSettingsItemNameNull;
} }
const size_t name_len = strnlen(name, std::min(max_size, MaxNameLength + 1)); const size_t name_len = strnlen(name, std::min(max_size, MaxNameLength + 1));
if (name_len == 0) { if (name_len == 0) {
return ResultSettingsItemNameEmpty; return ResultSettingsItemNameEmpty;
} else if (name_len > MaxNameLength) { } else if (name_len > MaxNameLength) {
return ResultSettingsItemNameTooLong; return ResultSettingsItemNameTooLong;
} }
if (!IsCorrectFormat(name, name_len)) { if (!IsCorrectFormat(name, name_len)) {
return ResultSettingsItemNameInvalidFormat; return ResultSettingsItemNameInvalidFormat;
} }
return ResultSuccess; return ResultSuccess;
} }
@ -98,18 +95,18 @@ Result SettingsItemManager::ValidateKey(const char *key, size_t max_size) {
if (key == nullptr) { if (key == nullptr) {
return ResultSettingsItemKeyNull; return ResultSettingsItemKeyNull;
} }
const size_t key_len = strnlen(key, std::min(max_size, MaxKeyLength + 1)); const size_t key_len = strnlen(key, std::min(max_size, MaxKeyLength + 1));
if (key_len == 0) { if (key_len == 0) {
return ResultSettingsItemKeyEmpty; return ResultSettingsItemKeyEmpty;
} else if (key_len > MaxKeyLength) { } else if (key_len > MaxKeyLength) {
return ResultSettingsItemKeyTooLong; return ResultSettingsItemKeyTooLong;
} }
if (!IsCorrectFormat(key, key_len)) { if (!IsCorrectFormat(key, key_len)) {
return ResultSettingsItemKeyInvalidFormat; return ResultSettingsItemKeyInvalidFormat;
} }
return ResultSuccess; 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 *delimiter = strchr(val_tup, '!');
const char *value_str = delimiter + 1; const char *value_str = delimiter + 1;
const char *type = val_tup; const char *type = val_tup;
if (delimiter == NULL) { if (delimiter == NULL) {
return ResultSettingsItemValueInvalidFormat; return ResultSettingsItemValueInvalidFormat;
} }
while (isspace(*type) && type != delimiter) { while (isspace(*type) && type != delimiter) {
type++; type++;
} }
size_t type_len = delimiter - type; size_t type_len = delimiter - type;
size_t value_len = strlen(value_str); size_t value_len = strlen(value_str);
if (delimiter == NULL || value_len == 0 || type_len == 0) { 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); std::string kv = std::string(name).append("!").append(key);
SettingsItemValue value; SettingsItemValue value;
if (strncasecmp(type, "str", type_len) == 0 || strncasecmp(type, "string", type_len) == 0) { if (strncasecmp(type, "str", type_len) == 0 || strncasecmp(type, "string", type_len) == 0) {
/* String */ /* String */
value.size = value_len + 1; 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) { if (data == nullptr) {
return ResultSettingsItemValueAllocationFailed; return ResultSettingsItemValueAllocationFailed;
} }
memset(data, 0, value.size); memset(data, 0, value.size);
for (size_t i = 0; i < value_len; i++) { 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; value.data = data;
} else if (strncasecmp(type, "u8", type_len) == 0) { } else if (strncasecmp(type, "u8", type_len) == 0) {
/* u8 */ /* u8 */
@ -220,35 +217,35 @@ static Result ParseValue(const char *name, const char *key, const char *val_tup)
} else { } else {
return ResultSettingsItemValueInvalidFormat; return ResultSettingsItemValueInvalidFormat;
} }
g_settings_items[kv] = value; g_settings_items[kv] = value;
return ResultSuccess; return ResultSuccess;
} }
static int SettingsItemIniHandler(void *user, const char *name, const char *key, const char *value) { static Result ParseSettingsItemValue(const char *name, const char *key, const char *value) {
Result rc = *(reinterpret_cast<Result *>(user)); /* Validate name and key, then parse value. */
ON_SCOPE_EXIT { *(reinterpret_cast<Result *>(user)) = rc; }; R_TRY(SettingsItemManager::ValidateName(name));
R_TRY(SettingsItemManager::ValidateKey(name));
if (R_SUCCEEDED(rc)) { R_TRY(ParseValue(name, key, value));
rc = SettingsItemManager::ValidateName(name); return ResultSuccess;
}
if (R_SUCCEEDED(rc)) {
rc = SettingsItemManager::ValidateKey(name);
}
if (R_SUCCEEDED(rc)) {
rc = ParseValue(name, key, value);
}
return R_SUCCEEDED(rc) ? 1 : 0;
} }
void SettingsItemManager::LoadConfiguration() { static int SettingsItemIniHandler(void *user, const char *name, const char *key, const char *value) {
Result *user_res = reinterpret_cast<Result *>(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. */ /* Open file. */
FsFile config_file; FsFile config_file;
Result rc = Utils::OpenSdFile("/atmosphere/system_settings.ini", FS_OPEN_READ, &config_file); R_TRY(Utils::OpenSdFile("/atmosphere/system_settings.ini", FS_OPEN_READ, &config_file));
if (R_FAILED(rc)) {
return;
}
ON_SCOPE_EXIT { ON_SCOPE_EXIT {
fsFileClose(&config_file); fsFileClose(&config_file);
}; };
@ -257,19 +254,21 @@ void SettingsItemManager::LoadConfiguration() {
std::string config_buf(0xFFFF, '\0'); std::string config_buf(0xFFFF, '\0');
/* Read from file. */ /* Read from file. */
if (R_SUCCEEDED(rc)) { size_t actual_size;
size_t actual_size; R_TRY(fsFileRead(&config_file, 0, config_buf.data(), config_buf.size(), FS_READOPTION_NONE, &actual_size));
rc = fsFileRead(&config_file, 0, config_buf.data(), config_buf.size(), FS_READOPTION_NONE, &actual_size);
}
if (R_SUCCEEDED(rc)) { /* Parse. */
ini_parse_string(config_buf.c_str(), SettingsItemIniHandler, &rc); Result parse_res = ResultSuccess;
} ini_parse_string(config_buf.c_str(), SettingsItemIniHandler, &parse_res);
return parse_res;
}
/* Report error if we encountered one. */ void SettingsItemManager::LoadConfiguration() {
if (R_FAILED(rc) && !g_threw_fatal) { const Result load_res = LoadConfigurationImpl();
if (R_FAILED(load_res) && !g_threw_fatal) {
/* Report error if we encountered one. */
g_threw_fatal = true; g_threw_fatal = true;
g_fatal_thread.Initialize(&FatalThreadFunc, reinterpret_cast<void *>(rc), 0x1000, 49); g_fatal_thread.Initialize(&FatalThreadFunc, reinterpret_cast<void *>(load_res), 0x1000, 49);
g_fatal_thread.Start(); g_fatal_thread.Start();
} }
} }

View File

@ -85,11 +85,8 @@ void Utils::InitializeThreadFunc(void *args) {
Handle tmp_hnd = 0; Handle tmp_hnd = 0;
static const char * const required_active_services[] = {"pcv", "gpio", "pinmux", "psc:c"}; 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++) { 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])))) { R_ASSERT(smGetServiceOriginal(&tmp_hnd, smEncodeName(required_active_services[i])));
std::abort(); svcCloseHandle(tmp_hnd);
} else {
svcCloseHandle(tmp_hnd);
}
} }
}); });
@ -102,9 +99,8 @@ void Utils::InitializeThreadFunc(void *args) {
fsFsCreateDirectory(&g_sd_filesystem, "/atmosphere/automatic_backups"); fsFsCreateDirectory(&g_sd_filesystem, "/atmosphere/automatic_backups");
{ {
FsStorage cal0_storage; FsStorage cal0_storage;
if (R_FAILED(fsOpenBisStorage(&cal0_storage, FsBisStorageId_CalibrationBinary)) || R_FAILED(fsStorageRead(&cal0_storage, 0, g_cal0_storage_backup, ProdinfoSize))) { R_ASSERT(fsOpenBisStorage(&cal0_storage, FsBisStorageId_CalibrationBinary));
std::abort(); R_ASSERT(fsStorageRead(&cal0_storage, 0, g_cal0_storage_backup, ProdinfoSize));
}
fsStorageClose(&cal0_storage); fsStorageClose(&cal0_storage);
char serial_number[0x40] = {0}; char serial_number[0x40] = {0};
@ -199,7 +195,7 @@ void Utils::InitializeThreadFunc(void *args) {
} }
Utils::RefreshConfiguration(); Utils::RefreshConfiguration();
/* If we're emummc, persist a write handle to prevent other processes from touching the image. */ /* If we're emummc, persist a write handle to prevent other processes from touching the image. */
if (IsEmummc()) { if (IsEmummc()) {
const char *emummc_file_path = GetEmummcFilePath(); const char *emummc_file_path = GetEmummcFilePath();
@ -213,9 +209,7 @@ void Utils::InitializeThreadFunc(void *args) {
/* Initialize set:sys. */ /* Initialize set:sys. */
DoWithSmSession([&]() { DoWithSmSession([&]() {
if (R_FAILED(setsysInitialize())) { R_ASSERT(setsysInitialize());
std::abort();
}
}); });
/* Signal SD is initialized. */ /* Signal SD is initialized. */
@ -360,8 +354,6 @@ Result Utils::SaveSdFileForAtmosphere(u64 title_id, const char *fn, void *data,
return ResultFsSdCardNotPresent; return ResultFsSdCardNotPresent;
} }
Result rc = ResultSuccess;
char path[FS_MAX_PATH]; char path[FS_MAX_PATH];
if (*fn == '/') { if (*fn == '/') {
snprintf(path, sizeof(path), "/atmosphere/titles/%016lx%s", title_id, 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); fsFsCreateFile(&g_sd_filesystem, path, size, 0);
/* Try to open. */ /* Try to open. */
rc = fsFsOpenFile(&g_sd_filesystem, path, FS_OPEN_READ | FS_OPEN_WRITE, &f); R_TRY(fsFsOpenFile(&g_sd_filesystem, path, FS_OPEN_READ | FS_OPEN_WRITE, &f));
if (R_FAILED(rc)) { ON_SCOPE_EXIT { fsFileClose(&f); };
return rc;
}
/* Always close, if we opened. */
ON_SCOPE_EXIT {
fsFileClose(&f);
};
/* Try to make it big enough. */ /* Try to make it big enough. */
rc = fsFileSetSize(&f, size); R_TRY(fsFileSetSize(&f, size));
if (R_FAILED(rc)) {
return rc;
}
/* Try to write the data. */ /* 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) { 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) { Result Utils::GetSettingsItemBooleanValue(const char *name, const char *key, bool *out) {
u8 val = 0; u8 val = 0;
u64 out_size; u64 out_size;
Result rc = Utils::GetSettingsItemValue(name, key, &val, sizeof(val), &out_size); R_TRY(Utils::GetSettingsItemValue(name, key, &val, sizeof(val), &out_size));
if (R_SUCCEEDED(rc)) {
if (out) { if (out) {
*out = val != 0; *out = val != 0;
}
} }
return rc; return ResultSuccess;
} }
void Utils::RebootToFatalError(AtmosphereFatalErrorContext *ctx) { void Utils::RebootToFatalError(AtmosphereFatalErrorContext *ctx) {