├── src ├── version.h ├── FileInfo.h ├── DirInfo.h ├── FSReplacements.h ├── FSAReplacements.h ├── utils │ ├── StringTools.cpp │ ├── logger.c │ ├── StringTools.h │ ├── utils.h │ ├── utils.cpp │ └── logger.h ├── DirInfoEx.h ├── FSWrapperMergeDirsWithParent.h ├── FSWrapperReplaceSingleFile.h ├── main.cpp ├── FSWrapper.h ├── FileUtils.h ├── IFSWrapper.h ├── export.cpp ├── FSWrapperReplaceSingleFile.cpp ├── FSWrapperMergeDirsWithParent.cpp ├── FileUtils.cpp ├── FSWrapper.cpp └── FSAReplacements.cpp ├── .gitignore ├── .github ├── dependabot.yml └── workflows │ ├── pr.yml │ └── ci.yml ├── Dockerfile ├── README.md ├── .clang-format ├── Makefile └── LICENSE /src/version.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #define VERSION_EXTRA "" -------------------------------------------------------------------------------- /src/FileInfo.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | struct FileInfo { 5 | public: 6 | FSFileHandle handle; 7 | int fd; 8 | }; 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.cbp 2 | *.elf 3 | *.layout 4 | *.rpx 5 | build/ 6 | *.save-failed 7 | .idea/ 8 | cmake-build-debug/ 9 | CMakeLists.txt 10 | *.wms 11 | *.zip 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "docker" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "daily" -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ghcr.io/wiiu-env/devkitppc:20241128 2 | 3 | COPY --from=ghcr.io/wiiu-env/libfunctionpatcher:20230621 /artifacts $DEVKITPRO 4 | COPY --from=ghcr.io/wiiu-env/wiiumodulesystem:20250208 /artifacts $DEVKITPRO 5 | COPY --from=ghcr.io/wiiu-env/libcontentredirection:20250208 /artifacts $DEVKITPRO 6 | 7 | WORKDIR project 8 | -------------------------------------------------------------------------------- /src/DirInfo.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | struct DirInfoBase { 6 | virtual ~DirInfoBase() = default; 7 | FSDirectoryHandle handle{}; 8 | }; 9 | 10 | struct DirInfo : DirInfoBase { 11 | ~DirInfo() override = default; 12 | DIR *dir{}; 13 | char path[0x280]{}; 14 | }; 15 | -------------------------------------------------------------------------------- /src/FSReplacements.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | extern function_replacement_data_t fs_file_function_replacements[]; 11 | extern uint32_t fs_file_function_replacements_size; 12 | 13 | #ifdef __cplusplus 14 | } 15 | #endif 16 | -------------------------------------------------------------------------------- /src/FSAReplacements.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | extern function_replacement_data_t fsa_file_function_replacements[]; 11 | extern uint32_t fsa_file_function_replacements_size; 12 | 13 | #ifdef __cplusplus 14 | } 15 | #endif 16 | -------------------------------------------------------------------------------- /src/utils/StringTools.cpp: -------------------------------------------------------------------------------- 1 | #include "StringTools.h" 2 | #include 3 | 4 | void SafeReplaceInString(std::string &subject, std::string search, const std::string &replace) { 5 | if (search.empty() || search == replace) { 6 | return; // Avoid infinite loops and invalid input 7 | } 8 | std::string lowerSubject = subject; 9 | 10 | std::ranges::transform(subject, lowerSubject.begin(), ::tolower); 11 | std::ranges::transform(search, search.begin(), ::tolower); 12 | 13 | if (const size_t pos = lowerSubject.find(search); pos != std::string::npos) { 14 | subject.replace(pos, search.length(), replace); 15 | } 16 | } -------------------------------------------------------------------------------- /src/DirInfoEx.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "DirInfo.h" 3 | #include 4 | 5 | typedef struct FSDirectoryEntryEx { 6 | FSADirectoryEntry realEntry = {}; 7 | bool isMarkedAsDeleted = false; 8 | } FSDirectoryEntryEx; 9 | 10 | struct DirInfoEx final : DirInfo { 11 | FSDirectoryEntryEx *readResult = nullptr; 12 | int readResultCapacity = 0; 13 | int readResultNumberOfEntries = 0; 14 | FSDirectoryHandle realDirHandle = 0; 15 | }; 16 | 17 | struct DirInfoExSingleFile final : DirInfoBase { 18 | FSADirectoryEntry directoryEntry = {}; 19 | bool entryRead = false; 20 | bool entryReadSuccess = false; 21 | FSDirectoryHandle realDirHandle = 0; 22 | }; 23 | -------------------------------------------------------------------------------- /src/utils/logger.c: -------------------------------------------------------------------------------- 1 | #ifdef DEBUG 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | uint32_t moduleLogInit = false; 8 | uint32_t cafeLogInit = false; 9 | uint32_t udpLogInit = false; 10 | #endif // DEBUG 11 | 12 | void initLogging() { 13 | #ifdef DEBUG 14 | if (!(moduleLogInit = WHBLogModuleInit())) { 15 | cafeLogInit = WHBLogCafeInit(); 16 | udpLogInit = WHBLogUdpInit(); 17 | } 18 | #endif // DEBUG 19 | } 20 | 21 | void deinitLogging() { 22 | #ifdef DEBUG 23 | if (moduleLogInit) { 24 | WHBLogModuleDeinit(); 25 | moduleLogInit = false; 26 | } 27 | if (cafeLogInit) { 28 | WHBLogCafeDeinit(); 29 | cafeLogInit = false; 30 | } 31 | if (udpLogInit) { 32 | WHBLogUdpDeinit(); 33 | udpLogInit = false; 34 | } 35 | #endif // DEBUG 36 | } -------------------------------------------------------------------------------- /src/utils/StringTools.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | template 7 | std::string string_format(const std::string &format, Args... args) { 8 | int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' 9 | auto size = static_cast(size_s); 10 | auto buf = std::make_unique(size); 11 | std::snprintf(buf.get(), size, format.c_str(), args...); 12 | return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside 13 | } 14 | 15 | void SafeReplaceInString(std::string &subject, std::string search, const std::string &replace); 16 | 17 | static inline bool starts_with_case_insensitive(const std::string_view str, const std::string_view prefix) { 18 | if (str.size() < prefix.size()) 19 | return false; 20 | 21 | return std::equal(prefix.begin(), prefix.end(), str.begin(), 22 | [](const char a, const char b) { 23 | return std::tolower(a) == std::tolower(b); 24 | }); 25 | } 26 | -------------------------------------------------------------------------------- /src/utils/utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | template 8 | std::unique_ptr make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward(args)...))) { 9 | return std::unique_ptr(new (std::nothrow) T(std::forward(args)...)); 10 | } 11 | 12 | template 13 | std::shared_ptr make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward(args)...))) { 14 | return std::shared_ptr(new (std::nothrow) T(std::forward(args)...)); 15 | } 16 | 17 | template 18 | bool remove_locked_first_if(std::mutex &mutex, std::vector &list, Predicate pred) { 19 | std::lock_guard lock(mutex); 20 | auto it = list.begin(); 21 | while (it != list.end()) { 22 | if (pred(*it)) { 23 | list.erase(it); 24 | return true; 25 | } 26 | it++; 27 | } 28 | return false; 29 | } 30 | 31 | // those work only in powers of 2 32 | #define ROUNDDOWN(val, align) ((val) & ~(align - 1)) 33 | #define ROUNDUP(val, align) ROUNDDOWN(((val) + (align - 1)), align) 34 | 35 | void translate_stat(const struct stat *posStat, FSStat *fsStat); -------------------------------------------------------------------------------- /src/FSWrapperMergeDirsWithParent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "DirInfoEx.h" 3 | #include "FSWrapper.h" 4 | 5 | #include 6 | 7 | class FSWrapperMergeDirsWithParent final : public FSWrapper { 8 | public: 9 | FSWrapperMergeDirsWithParent(const std::string &name, 10 | const std::string &pathToReplace, 11 | const std::string &replaceWithPath, 12 | bool fallbackOnError); 13 | 14 | ~FSWrapperMergeDirsWithParent() override; 15 | 16 | FSError FSOpenDirWrapper(const char *path, 17 | FSDirectoryHandle *handle) override; 18 | 19 | FSError FSReadDirWrapper(FSDirectoryHandle handle, 20 | FSDirectoryEntry *entry) override; 21 | 22 | FSError FSCloseDirWrapper(FSDirectoryHandle handle) override; 23 | 24 | FSError FSRewindDirWrapper(FSDirectoryHandle handle) override; 25 | 26 | std::shared_ptr getNewDirInfoHandle() override; 27 | 28 | bool SkipDeletedFilesInReadDir() override; 29 | 30 | uint32_t getLayerId() override { 31 | return static_cast(mClientHandle); 32 | } 33 | 34 | private: 35 | FSAClientHandle mClientHandle; 36 | 37 | std::shared_ptr getDirInfoExFromHandle(FSDirectoryHandle handle); 38 | }; 39 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: CI-PR 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | clang-format: 7 | runs-on: ubuntu-22.04 8 | steps: 9 | - uses: actions/checkout@v4 10 | - name: clang-format 11 | run: | 12 | docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src 13 | check-build-with-logging: 14 | runs-on: ubuntu-22.04 15 | needs: clang-format 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: build binary with logging 19 | run: | 20 | docker build . -t builder 21 | docker run --rm -v ${PWD}:/project builder make DEBUG=VERBOSE 22 | docker run --rm -v ${PWD}:/project builder make clean 23 | docker run --rm -v ${PWD}:/project builder make DEBUG=1 24 | build-binary: 25 | runs-on: ubuntu-22.04 26 | needs: clang-format 27 | steps: 28 | - uses: actions/checkout@v4 29 | - name: create version.h 30 | run: | 31 | git_hash=$(git rev-parse --short "${{ github.event.pull_request.head.sha }}") 32 | cat < ./src/version.h 33 | #pragma once 34 | #define VERSION_EXTRA " (nightly-$git_hash)" 35 | EOF 36 | - name: build binary 37 | run: | 38 | docker build . -t builder 39 | docker run --rm -v ${PWD}:/project builder make 40 | - uses: actions/upload-artifact@master 41 | with: 42 | name: binary 43 | path: "*.wms" -------------------------------------------------------------------------------- /src/FSWrapperReplaceSingleFile.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "DirInfoEx.h" 3 | #include "FSWrapper.h" 4 | 5 | #include 6 | 7 | class FSWrapperReplaceSingleFile final : public FSWrapper { 8 | public: 9 | FSWrapperReplaceSingleFile(const std::string &name, 10 | const std::string &fileToReplace, 11 | const std::string &replaceWithPath, 12 | bool fallbackOnError); 13 | 14 | ~FSWrapperReplaceSingleFile() override; 15 | 16 | FSError FSOpenDirWrapper(const char *path, 17 | FSDirectoryHandle *handle) override; 18 | 19 | FSError FSReadDirWrapper(FSDirectoryHandle handle, 20 | FSDirectoryEntry *entry) override; 21 | 22 | FSError FSCloseDirWrapper(FSDirectoryHandle handle) override; 23 | 24 | FSError FSRewindDirWrapper(FSDirectoryHandle handle) override; 25 | 26 | bool SkipDeletedFilesInReadDir() override; 27 | 28 | uint32_t getLayerId() override { 29 | return static_cast(mClientHandle); 30 | } 31 | 32 | 33 | protected: 34 | [[nodiscard]] std::string GetNewPath(const std::string_view &path) const override; 35 | 36 | std::shared_ptr getNewDirInfoHandle() override { 37 | OSFatal("FSWrapperReplaceSingleFile::getNewDirInfoHandle. Not implemented"); 38 | return {}; 39 | } 40 | 41 | private: 42 | bool IsDirPathToReplace(const std::string_view &path) const; 43 | 44 | std::shared_ptr getDirExFromHandle(FSDirectoryHandle handle); 45 | 46 | FSAClientHandle mClientHandle; 47 | std::string mPathToReplace; 48 | std::string mFileNameToReplace; 49 | std::string mFullPathToReplace; 50 | std::string mReplacedWithPath; 51 | std::string mReplacedWithFileName; 52 | }; 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CI-Release](https://github.com/wiiu-env/ContentRedirectionModule/actions/workflows/ci.yml/badge.svg)](https://github.com/wiiu-env/ContentRedirectionModule/actions/workflows/ci.yml) 2 | 3 | ## Usage 4 | (`[ENVIRONMENT]` is a placeholder for the actual environment name.) 5 | 6 | 1. Copy the file `ContentRedirectionModule.wms` into `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 7 | 2. Requires the [WUMSLoader](https://github.com/wiiu-env/WUMSLoader) in `sd:/wiiu/environments/[ENVIRONMENT]/modules/setup`. 8 | 3. Use [libcontentredirection](https://github.com/wiiu-env/libcontentredirection). 9 | 10 | ## Buildflags 11 | 12 | ### Logging 13 | Building via `make` only logs errors (via OSReport). To enable logging via the [LoggingModule](https://github.com/wiiu-env/LoggingModule) set `DEBUG` to `1` or `VERBOSE`. 14 | 15 | `make` Logs errors only (via OSReport). 16 | `make DEBUG=1` Enables information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule). 17 | `make DEBUG=VERBOSE` Enables verbose information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule). 18 | 19 | If the [LoggingModule](https://github.com/wiiu-env/LoggingModule) is not present, it'll fallback to UDP (Port 4405) and [CafeOS](https://github.com/wiiu-env/USBSerialLoggingModule) logging. 20 | 21 | ## Building using the Dockerfile 22 | 23 | It's possible to use a docker image for building. This way you don't need anything installed on your host system. 24 | 25 | ``` 26 | # Build docker image (only needed once) 27 | docker build . -t contentredirectionmodule-builder 28 | 29 | # make 30 | docker run -it --rm -v ${PWD}:/project contentredirectionmodule-builder make 31 | 32 | # make clean 33 | docker run -it --rm -v ${PWD}:/project contentredirectionmodule-builder make clean 34 | ``` 35 | 36 | ## Format the code via docker 37 | 38 | `docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src -i` -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI-Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | clang-format: 10 | runs-on: ubuntu-22.04 11 | steps: 12 | - uses: actions/checkout@v4 13 | - name: clang-format 14 | run: | 15 | docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src 16 | build-binary: 17 | runs-on: ubuntu-22.04 18 | needs: clang-format 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: create version.h 22 | run: | 23 | git_hash=$(git rev-parse --short "$GITHUB_SHA") 24 | cat < ./src/version.h 25 | #pragma once 26 | #define VERSION_EXTRA " (nightly-$git_hash)" 27 | EOF 28 | - name: build binary 29 | run: | 30 | docker build . -t builder 31 | docker run --rm -v ${PWD}:/project builder make 32 | - uses: actions/upload-artifact@master 33 | with: 34 | name: binary 35 | path: "*.wms" 36 | deploy-binary: 37 | needs: build-binary 38 | runs-on: ubuntu-22.04 39 | steps: 40 | - name: Get environment variables 41 | id: get_repository_name 42 | run: | 43 | echo REPOSITORY_NAME=$(echo "$GITHUB_REPOSITORY" | awk -F / '{print $2}' | sed -e "s/:refs//") >> $GITHUB_ENV 44 | echo DATETIME=$(echo $(date '+%Y%m%d-%H%M%S')) >> $GITHUB_ENV 45 | - uses: actions/download-artifact@master 46 | with: 47 | name: binary 48 | - name: zip artifact 49 | run: zip -r ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip *.wms 50 | - name: Create Release 51 | uses: "softprops/action-gh-release@v2" 52 | with: 53 | tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }} 54 | draft: false 55 | prerelease: true 56 | generate_release_notes: true 57 | name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }} 58 | files: | 59 | ./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | # Generated from CLion C/C++ Code Style settings 2 | BasedOnStyle: LLVM 3 | AccessModifierOffset: -4 4 | AlignAfterOpenBracket: Align 5 | AlignConsecutiveAssignments: Consecutive 6 | AlignConsecutiveMacros: AcrossEmptyLinesAndComments 7 | AlignOperands: Align 8 | AllowAllArgumentsOnNextLine: false 9 | AllowAllConstructorInitializersOnNextLine: false 10 | AllowAllParametersOfDeclarationOnNextLine: false 11 | AllowShortBlocksOnASingleLine: Always 12 | AllowShortCaseLabelsOnASingleLine: false 13 | AllowShortFunctionsOnASingleLine: All 14 | AllowShortIfStatementsOnASingleLine: Always 15 | AllowShortLambdasOnASingleLine: All 16 | AllowShortLoopsOnASingleLine: true 17 | AlwaysBreakAfterReturnType: None 18 | AlwaysBreakTemplateDeclarations: Yes 19 | BreakBeforeBraces: Custom 20 | BraceWrapping: 21 | AfterCaseLabel: false 22 | AfterClass: false 23 | AfterControlStatement: Never 24 | AfterEnum: false 25 | AfterFunction: false 26 | AfterNamespace: false 27 | AfterUnion: false 28 | BeforeCatch: false 29 | BeforeElse: false 30 | IndentBraces: false 31 | SplitEmptyFunction: false 32 | SplitEmptyRecord: true 33 | BreakBeforeBinaryOperators: None 34 | BreakBeforeTernaryOperators: true 35 | BreakConstructorInitializers: BeforeColon 36 | BreakInheritanceList: BeforeColon 37 | ColumnLimit: 0 38 | CompactNamespaces: false 39 | ContinuationIndentWidth: 8 40 | IndentCaseLabels: true 41 | IndentPPDirectives: None 42 | IndentWidth: 4 43 | KeepEmptyLinesAtTheStartOfBlocks: true 44 | MaxEmptyLinesToKeep: 2 45 | NamespaceIndentation: All 46 | ObjCSpaceAfterProperty: false 47 | ObjCSpaceBeforeProtocolList: true 48 | PointerAlignment: Right 49 | ReflowComments: false 50 | SpaceAfterCStyleCast: true 51 | SpaceAfterLogicalNot: false 52 | SpaceAfterTemplateKeyword: false 53 | SpaceBeforeAssignmentOperators: true 54 | SpaceBeforeCpp11BracedList: false 55 | SpaceBeforeCtorInitializerColon: true 56 | SpaceBeforeInheritanceColon: true 57 | SpaceBeforeParens: ControlStatements 58 | SpaceBeforeRangeBasedForLoopColon: true 59 | SpaceInEmptyParentheses: false 60 | SpacesBeforeTrailingComments: 1 61 | SpacesInAngles: false 62 | SpacesInCStyleCastParentheses: false 63 | SpacesInContainerLiterals: false 64 | SpacesInParentheses: false 65 | SpacesInSquareBrackets: false 66 | TabWidth: 4 67 | UseTab: Never 68 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "FSAReplacements.h" 2 | #include "FSReplacements.h" 3 | #include "FileUtils.h" 4 | #include "utils/StringTools.h" 5 | #include "utils/logger.h" 6 | #include "version.h" 7 | #include 8 | 9 | WUMS_MODULE_EXPORT_NAME("homebrew_content_redirection"); 10 | WUMS_USE_WUT_DEVOPTAB(); 11 | WUMS_DEPENDS_ON(homebrew_functionpatcher); 12 | 13 | #define VERSION "v0.2.8" 14 | 15 | DECL_FUNCTION(void, OSCancelThread, OSThread *thread) { 16 | if (thread == gThreadData[0].thread || thread == gThreadData[1].thread || thread == gThreadData[2].thread) { 17 | DEBUG_FUNCTION_LINE_INFO("Prevent calling OSCancelThread for ContentRedirection IO Threads"); 18 | return; 19 | } 20 | real_OSCancelThread(thread); 21 | } 22 | 23 | function_replacement_data_t OSCancelThreadReplacement = REPLACE_FUNCTION(OSCancelThread, LIBRARY_COREINIT, OSCancelThread); 24 | 25 | WUMS_INITIALIZE() { 26 | initLogging(); 27 | DEBUG_FUNCTION_LINE("Patch functions"); 28 | if (FunctionPatcher_InitLibrary() != FUNCTION_PATCHER_RESULT_SUCCESS) { 29 | OSFatal("homebrew_content_redirection: FunctionPatcher_InitLibrary failed"); 30 | } 31 | 32 | bool wasPatched; 33 | for (uint32_t i = 0; i < fs_file_function_replacements_size; i++) { 34 | wasPatched = false; 35 | if (FunctionPatcher_AddFunctionPatch(&fs_file_function_replacements[i], nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) { 36 | OSFatal("homebrew_content_redirection: Failed to patch function"); 37 | } 38 | } 39 | for (uint32_t i = 0; i < fsa_file_function_replacements_size; i++) { 40 | wasPatched = false; 41 | if (FunctionPatcher_AddFunctionPatch(&fsa_file_function_replacements[i], nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) { 42 | OSFatal("homebrew_content_redirection: Failed to patch function"); 43 | } 44 | } 45 | wasPatched = false; 46 | if (FunctionPatcher_AddFunctionPatch(&OSCancelThreadReplacement, nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) { 47 | OSFatal("homebrew_content_redirection: Failed to patch OSCancelThreadReplacement"); 48 | } 49 | DEBUG_FUNCTION_LINE("Patch functions finished"); 50 | deinitLogging(); 51 | } 52 | 53 | WUMS_APPLICATION_STARTS() { 54 | OSReport("Running ContentRedirectionModule " VERSION VERSION_EXTRA "\n"); 55 | initLogging(); 56 | startFSIOThreads(); 57 | } 58 | 59 | WUMS_APPLICATION_ENDS() { 60 | clearFSLayer(); 61 | 62 | stopFSIOThreads(); 63 | 64 | deinitLogging(); 65 | } 66 | -------------------------------------------------------------------------------- /src/utils/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils/logger.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define PRINTF_BUFFER_LENGTH 2048 9 | 10 | // https://gist.github.com/ccbrown/9722406 11 | void dumpHex(const void *data, size_t size) { 12 | char ascii[17]; 13 | size_t i, j; 14 | ascii[16] = '\0'; 15 | DEBUG_FUNCTION_LINE("0x%08X (0x0000): ", data); 16 | for (i = 0; i < size; ++i) { 17 | WHBLogWritef("%02X ", ((unsigned char *) data)[i]); 18 | if (((unsigned char *) data)[i] >= ' ' && ((unsigned char *) data)[i] <= '~') { 19 | ascii[i % 16] = ((unsigned char *) data)[i]; 20 | } else { 21 | ascii[i % 16] = '.'; 22 | } 23 | if ((i + 1) % 8 == 0 || i + 1 == size) { 24 | WHBLogWritef(" "); 25 | if ((i + 1) % 16 == 0) { 26 | WHBLogPrintf("| %s ", ascii); 27 | if (i + 1 < size) { 28 | DEBUG_FUNCTION_LINE("0x%08X (0x%04X); ", ((uint32_t) data) + i + 1, i + 1); 29 | } 30 | } else if (i + 1 == size) { 31 | ascii[(i + 1) % 16] = '\0'; 32 | if ((i + 1) % 16 <= 8) { 33 | WHBLogWritef(" "); 34 | } 35 | for (j = (i + 1) % 16; j < 16; ++j) { 36 | WHBLogWritef(" "); 37 | } 38 | WHBLogPrintf("| %s ", ascii); 39 | } 40 | } 41 | } 42 | } 43 | 44 | FSMode translate_permission_mode(mode_t mode) { 45 | // Convert normal Unix octal permission bits into CafeOS hexadecimal permission bits 46 | return (FSMode) (((mode & S_IRWXU) << 2) | ((mode & S_IRWXG) << 1) | (mode & S_IRWXO)); 47 | } 48 | 49 | FSTime translate_time(time_t timeValue) { 50 | // FSTime stats at 1980-01-01, time_t starts at 1970-01-01 51 | auto EPOCH_DIFF_SECS_WII_U_FS_TIME = 315532800; //EPOCH_DIFF_SECS(WIIU_FSTIME_EPOCH_YEAR) 52 | auto adjustedTimeValue = timeValue - EPOCH_DIFF_SECS_WII_U_FS_TIME; 53 | // FSTime is in microseconds, time_t is in seconds 54 | return adjustedTimeValue * 1000000; 55 | } 56 | 57 | void translate_stat(const struct stat *posStat, FSStat *fsStat) { 58 | memset(fsStat, 0, sizeof(FSStat)); 59 | fsStat->size = posStat->st_size; 60 | 61 | fsStat->mode = translate_permission_mode(posStat->st_mode); 62 | 63 | fsStat->flags = static_cast(0x1C000000); // These bits are always set 64 | if (S_ISDIR(posStat->st_mode)) { 65 | fsStat->flags = static_cast(fsStat->flags | FS_STAT_DIRECTORY); 66 | } else if (S_ISREG(posStat->st_mode)) { 67 | fsStat->flags = static_cast(fsStat->flags | FS_STAT_FILE); 68 | fsStat->allocSize = posStat->st_size; 69 | fsStat->quotaSize = posStat->st_size; 70 | } 71 | fsStat->modified = translate_time(posStat->st_atime); 72 | fsStat->created = translate_time(posStat->st_ctime); 73 | fsStat->entryId = posStat->st_ino; 74 | 75 | fsStat->owner = posStat->st_uid; 76 | fsStat->group = posStat->st_gid; 77 | } 78 | -------------------------------------------------------------------------------- /src/utils/logger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #define LOG_APP_TYPE "M" 12 | #define LOG_APP_NAME "content_redirect" 13 | 14 | #define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__) 15 | #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__) 16 | 17 | #define LOG(LOG_FUNC, FMT, ARGS...) LOG_EX_DEFAULT(LOG_FUNC, "", "", FMT, ##ARGS) 18 | 19 | #define LOG_EX_DEFAULT(LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) LOG_EX(__FILENAME__, __FUNCTION__, __LINE__, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ##ARGS) 20 | 21 | #define LOG_EX(FILENAME, FUNCTION, LINE, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) \ 22 | do { \ 23 | LOG_FUNC("[(%s)%18s][%23s]%30s@L%04d: " LOG_LEVEL "" FMT "" LINE_END, LOG_APP_TYPE, LOG_APP_NAME, FILENAME, FUNCTION, LINE, ##ARGS); \ 24 | } while (0) 25 | 26 | #ifdef DEBUG 27 | 28 | #ifdef VERBOSE_DEBUG 29 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) 30 | #define DEBUG_FUNCTION_LINE_VERBOSE_EX(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "", "", FMT, ##ARGS); 31 | #else 32 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) 33 | #define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0) 34 | #endif 35 | 36 | #define DEBUG_FUNCTION_LINE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) 37 | 38 | #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS) 39 | 40 | #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS) 41 | #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##WARN ## ", "", FMT, ##ARGS) 42 | #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##INFO ## ", "", FMT, ##ARGS) 43 | 44 | #define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS); 45 | 46 | #else 47 | 48 | #define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0) 49 | 50 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) 51 | 52 | #define DEBUG_FUNCTION_LINE(FMT, ARGS...) while (0) 53 | 54 | #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0) 55 | 56 | #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##ERROR## ", "\n", FMT, ##ARGS) 57 | #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##WARN ## ", "\n", FMT, ##ARGS) 58 | #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##INFO ## ", "\n", FMT, ##ARGS) 59 | 60 | #define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, OSReport, "##ERROR## ", "\n", FMT, ##ARGS); 61 | 62 | #endif 63 | 64 | void initLogging(); 65 | 66 | void deinitLogging(); 67 | 68 | #ifdef __cplusplus 69 | } 70 | #endif 71 | -------------------------------------------------------------------------------- /src/FSWrapper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "DirInfo.h" 4 | #include "FileInfo.h" 5 | #include "IFSWrapper.h" 6 | #include "utils/logger.h" 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | class FSWrapper : public IFSWrapper { 15 | public: 16 | FSWrapper(const std::string &name, const std::string &pathToReplace, const std::string &replacePathWith, const bool fallbackOnError, const bool isWriteable) { 17 | this->pName = name; 18 | this->pPathToReplace = pathToReplace; 19 | this->pReplacePathWith = replacePathWith; 20 | this->pFallbackOnError = fallbackOnError; 21 | this->pIsWriteable = isWriteable; 22 | this->pCheckIfDeleted = fallbackOnError; 23 | 24 | std::ranges::replace(pPathToReplace, '\\', '/'); 25 | std::ranges::replace(pReplacePathWith, '\\', '/'); 26 | } 27 | ~FSWrapper() override { 28 | { 29 | std::lock_guard lockFiles(openFilesMutex); 30 | openFiles.clear(); 31 | } 32 | { 33 | std::lock_guard lockDirs(openDirsMutex); 34 | openDirs.clear(); 35 | } 36 | } 37 | 38 | FSError FSOpenDirWrapper(const char *path, 39 | FSDirectoryHandle *handle) override; 40 | 41 | FSError FSReadDirWrapper(FSDirectoryHandle handle, 42 | FSDirectoryEntry *entry) override; 43 | 44 | FSError FSCloseDirWrapper(FSDirectoryHandle handle) override; 45 | 46 | 47 | FSError FSMakeDirWrapper(const char *path) override; 48 | 49 | 50 | FSError FSRewindDirWrapper(FSDirectoryHandle handle) override; 51 | 52 | 53 | FSError FSOpenFileWrapper(const char *path, 54 | const char *mode, 55 | FSFileHandle *handle) override; 56 | 57 | FSError FSCloseFileWrapper(FSFileHandle handle) override; 58 | 59 | FSError FSGetStatWrapper(const char *path, FSStat *stats) override; 60 | 61 | FSError FSGetStatFileWrapper(FSFileHandle handle, 62 | FSStat *stats) override; 63 | 64 | FSError FSReadFileWrapper(void *buffer, 65 | uint32_t size, 66 | uint32_t count, 67 | FSFileHandle handle, 68 | uint32_t unk1) override; 69 | 70 | FSError FSReadFileWithPosWrapper(void *buffer, 71 | uint32_t size, 72 | uint32_t count, 73 | uint32_t pos, 74 | FSFileHandle handle, 75 | int32_t unk1) override; 76 | 77 | FSError FSSetPosFileWrapper(FSFileHandle handle, 78 | uint32_t pos) override; 79 | 80 | FSError FSGetPosFileWrapper(FSFileHandle handle, 81 | uint32_t *pos) override; 82 | 83 | FSError FSIsEofWrapper(FSFileHandle handle) override; 84 | 85 | FSError FSTruncateFileWrapper(FSFileHandle handle) override; 86 | 87 | FSError FSWriteFileWrapper(const uint8_t *buffer, 88 | uint32_t size, 89 | uint32_t count, 90 | FSFileHandle handle, 91 | uint32_t unk1) override; 92 | 93 | FSError FSRemoveWrapper(const char *path) override; 94 | 95 | FSError FSRenameWrapper(const char *oldPath, 96 | const char *newPath) override; 97 | 98 | FSError FSFlushFileWrapper(FSFileHandle handle) override; 99 | 100 | uint32_t getLayerId() override { 101 | return getHandle(); 102 | } 103 | 104 | protected: 105 | virtual bool IsFileModeAllowed(const char *mode); 106 | 107 | virtual bool IsPathToReplace(const std::string_view &path); 108 | 109 | [[nodiscard]] virtual std::string GetNewPath(const std::string_view &path) const; 110 | 111 | std::shared_ptr getDirFromHandle(FSDirectoryHandle handle); 112 | std::shared_ptr getFileFromHandle(FSFileHandle handle); 113 | 114 | bool isValidDirHandle(FSDirectoryHandle handle) override; 115 | bool isValidFileHandle(FSFileHandle handle) override; 116 | 117 | void addDirHandle(const std::shared_ptr &dirHandle); 118 | void deleteDirHandle(FSDirectoryHandle handle) override; 119 | void deleteFileHandle(FSFileHandle handle) override; 120 | 121 | virtual bool CheckFileShouldBeIgnored(std::string &path); 122 | 123 | virtual std::shared_ptr getNewFileHandle(); 124 | virtual std::shared_ptr getNewDirInfoHandle(); 125 | 126 | virtual bool SkipDeletedFilesInReadDir(); 127 | 128 | bool pCheckIfDeleted = false; 129 | 130 | std::string deletePrefix = ".deleted_"; 131 | 132 | private: 133 | std::shared_ptr getDirInfoFromHandle(FSDirectoryHandle handle); 134 | std::string pPathToReplace; 135 | std::string pReplacePathWith; 136 | bool pIsWriteable = false; 137 | std::mutex openFilesMutex; 138 | std::mutex openDirsMutex; 139 | std::vector> openFiles; 140 | std::vector> openDirs; 141 | }; 142 | -------------------------------------------------------------------------------- /src/FileUtils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "IFSWrapper.h" 4 | #include "utils/logger.h" 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | struct FSIOThreadData { 13 | OSThread *thread; 14 | void *stack; 15 | OSMessageQueue queue; 16 | OSMessage messages[0x10]; 17 | bool setup; 18 | char threadName[0x50]; 19 | }; 20 | 21 | struct AsyncParamFS { 22 | FSClient *client; 23 | FSCmdBlock *block; 24 | FSErrorFlag errorMask; 25 | FSAsyncData asyncData; 26 | IOSAsyncCallbackFn callback; 27 | }; 28 | 29 | typedef enum FSShimSyncType { 30 | FS_SHIM_TYPE_SYNC = 1, 31 | FS_SHIM_TYPE_ASYNC = 2 32 | } FSShimSyncType; 33 | 34 | typedef enum FSShimApiType { 35 | FS_SHIM_API_FS = 1, 36 | FS_SHIM_API_FSA = 2 37 | } FSShimApiType; 38 | 39 | struct FSShimWrapper { 40 | FSAShimBuffer *shim; 41 | AsyncParamFS asyncFS; 42 | FSShimSyncType sync; 43 | FSShimApiType api; 44 | }; 45 | 46 | struct FSShimWrapperMessage { 47 | FSShimWrapper *param; 48 | OSMessageQueue messageQueue; 49 | OSMessage messages[0x1]; 50 | }; 51 | 52 | #define FS_IO_QUEUE_COMMAND_STOP 0x13371337 53 | #define FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND 0x42424242 54 | #define FS_IO_QUEUE_SYNC_RESULT 0x43434343 55 | 56 | extern bool gThreadsRunning; 57 | extern FSIOThreadData gThreadData[3]; 58 | extern std::mutex gFSLayerMutex; 59 | extern std::vector> gFSLayers; 60 | 61 | #define fsaShimPrepareRequestReadFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, uint8_t * buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAReadFlag readFlags))(0x101C400 + 0x436cc)) 62 | #define fsaShimPrepareRequestWriteFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const uint8_t *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAWriteFlag writeFlags))(0x101C400 + 0x437f4)) 63 | #define fsaShimPrepareRequestOpenFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, const char *mode, FSMode createMode, FSOpenFileFlags openFlag, uint32_t preallocSize))(0x101C400 + 0x43588)) 64 | #define fsaShimPrepareRequestCloseFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43a00)) 65 | #define fsaShimPrepareRequestStatFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43998)) 66 | #define fsaShimPrepareRequestQueryInfo ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSAQueryInfoType type))(0x101C400 + 0x44118)) 67 | #define fsaShimPrepareRequestSetPos ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle, FSAFilePosition position))(0x101C400 + 0x43930)) 68 | #define fsaShimPrepareRequestGetPos ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x438fc)) 69 | #define fsaShimPrepareRequestIsEof ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43964)) 70 | #define fsaShimPrepareRequestTruncate ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43a34)) 71 | #define fsaShimPrepareRequestRemove ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *))(0x101C400 + 0x43aa8)) 72 | #define fsaShimPrepareRequestRename ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *, const char *))(0x101C400 + 0x43bc0)) 73 | #define fsaShimPrepareRequestFlushFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x439cc)) 74 | #define fsaShimPrepareRequestChangeMode ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSMode mode, FSMode modeMask))(0x101C400 + 0x43ff4)) 75 | 76 | #define fsaShimPrepareRequestOpenDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path))(0x101C400 + 0x43458)) 77 | #define fsaShimPrepareRequestReadDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x434ec)) 78 | #define fsaShimPrepareRequestCloseDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x43554)) 79 | #define fsaShimPrepareRequestRewindDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x43520)) 80 | #define fsaShimPrepareRequestMakeDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSMode mode))(0x101C400 + 0x43314)) 81 | #define fsaShimPrepareRequestChangeDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path))(0x101C400 + 0x43258)) 82 | 83 | #define fsaDecodeFsaStatusToFsStatus ((FSStatus(*)(FSError))(0x101C400 + 0x4b148)) 84 | #define fsClientHandleFatalError ((void (*)(FSClientBody *, uint32_t))(0x101C400 + 0x4b34c)) 85 | #define fsClientHandleFatalErrorAndBlock ((void (*)(FSClientBody *, uint32_t))(0x101C400 + 0x4cc20)) 86 | 87 | extern "C" FSError __FSAShimDecodeIosErrorToFsaStatus(IOSHandle handle, IOSError err); 88 | 89 | bool sendMessageToThread(FSShimWrapperMessage *param); 90 | 91 | void clearFSLayer(); 92 | 93 | FSError doForLayer(FSShimWrapper *param); 94 | 95 | FSError processShimBufferForFS(FSShimWrapper *param); 96 | 97 | FSError processShimBufferForFSA(FSShimWrapper *param); 98 | 99 | FSCmdBlockBody *fsCmdBlockGetBody(FSCmdBlock *cmdBlock); 100 | 101 | FSClientBody *fsClientGetBody(FSClient *client); 102 | 103 | FSStatus handleAsyncResult(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus status); 104 | 105 | int64_t readIntoBuffer(int32_t handle, void *buffer, size_t size, size_t count); 106 | 107 | int64_t writeFromBuffer(int32_t handle, const void *buffer, size_t size, size_t count); 108 | 109 | void startFSIOThreads(); 110 | void stopFSIOThreads(); -------------------------------------------------------------------------------- /src/IFSWrapper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #define FS_ERROR_EXTRA_MASK 0xFFF00000 8 | #define FS_ERROR_REAL_MASK 0x000FFFFF 9 | #define FS_ERROR_FORCE_PARENT_LAYER (FSError) 0xFFE00000 10 | #define FS_ERROR_FORCE_NO_FALLBACK (FSError) 0xFFD00000 11 | #define FS_ERROR_FORCE_REAL_FUNCTION (FSError) 0xFFC00000 12 | 13 | #pragma GCC diagnostic push 14 | #pragma GCC diagnostic ignored "-Wunused-parameter" 15 | 16 | class IFSWrapper { 17 | public: 18 | virtual ~IFSWrapper() = default; 19 | virtual FSError FSOpenDirWrapper(const char *path, 20 | FSADirectoryHandle *handle) { 21 | return FS_ERROR_FORCE_PARENT_LAYER; 22 | } 23 | 24 | virtual FSError FSReadDirWrapper(FSADirectoryHandle handle, 25 | FSADirectoryEntry *entry) { 26 | return FS_ERROR_FORCE_PARENT_LAYER; 27 | } 28 | 29 | virtual FSError FSCloseDirWrapper(FSADirectoryHandle handle) { 30 | return FS_ERROR_FORCE_PARENT_LAYER; 31 | } 32 | 33 | 34 | virtual FSError FSRewindDirWrapper(FSADirectoryHandle handle) { 35 | return FS_ERROR_FORCE_PARENT_LAYER; 36 | } 37 | 38 | virtual FSError FSMakeDirWrapper(const char *path) { 39 | return FS_ERROR_FORCE_PARENT_LAYER; 40 | } 41 | 42 | virtual FSError FSOpenFileWrapper(const char *path, 43 | const char *mode, 44 | FSAFileHandle *handle) { 45 | return FS_ERROR_FORCE_PARENT_LAYER; 46 | } 47 | 48 | virtual FSError FSCloseFileWrapper(FSAFileHandle handle) { 49 | return FS_ERROR_FORCE_PARENT_LAYER; 50 | } 51 | 52 | virtual FSError FSGetStatWrapper(const char *path, 53 | FSAStat *stats) { 54 | return FS_ERROR_FORCE_PARENT_LAYER; 55 | } 56 | 57 | virtual FSError FSGetStatFileWrapper(FSAFileHandle handle, 58 | FSAStat *stats) { 59 | return FS_ERROR_FORCE_PARENT_LAYER; 60 | } 61 | 62 | virtual FSError FSReadFileWrapper(void *buffer, 63 | uint32_t size, 64 | uint32_t count, 65 | FSAFileHandle handle, 66 | uint32_t unk1) { 67 | return FS_ERROR_FORCE_PARENT_LAYER; 68 | } 69 | 70 | virtual FSError FSReadFileWithPosWrapper(void *buffer, 71 | uint32_t size, 72 | uint32_t count, 73 | uint32_t pos, 74 | FSAFileHandle handle, 75 | int32_t unk1) { 76 | return FS_ERROR_FORCE_PARENT_LAYER; 77 | } 78 | 79 | virtual FSError FSSetPosFileWrapper(FSAFileHandle handle, 80 | uint32_t pos) { 81 | return FS_ERROR_FORCE_PARENT_LAYER; 82 | } 83 | 84 | virtual FSError FSGetPosFileWrapper(FSAFileHandle handle, 85 | uint32_t *pos) { 86 | return FS_ERROR_FORCE_PARENT_LAYER; 87 | } 88 | 89 | virtual FSError FSIsEofWrapper(FSAFileHandle handle) { 90 | return FS_ERROR_FORCE_PARENT_LAYER; 91 | } 92 | 93 | virtual FSError FSTruncateFileWrapper(FSAFileHandle handle) { 94 | return FS_ERROR_FORCE_PARENT_LAYER; 95 | } 96 | 97 | virtual FSError FSWriteFileWrapper(const uint8_t *buffer, 98 | uint32_t size, 99 | uint32_t count, 100 | FSAFileHandle handle, 101 | uint32_t unk1) { 102 | return FS_ERROR_FORCE_PARENT_LAYER; 103 | } 104 | 105 | virtual FSError FSWriteFileWithPosWrapper(const uint8_t *buffer, 106 | uint32_t size, 107 | uint32_t count, 108 | FSAFilePosition pos, 109 | FSAFileHandle handle, 110 | uint32_t unk1) { 111 | return FS_ERROR_FORCE_PARENT_LAYER; 112 | } 113 | 114 | virtual FSError FSRemoveWrapper(const char *path) { 115 | return FS_ERROR_FORCE_PARENT_LAYER; 116 | } 117 | 118 | virtual FSError FSRenameWrapper(const char *oldPath, 119 | const char *newPath) { 120 | return FS_ERROR_FORCE_PARENT_LAYER; 121 | } 122 | 123 | virtual FSError FSFlushFileWrapper(FSAFileHandle handle) { 124 | return FS_ERROR_FORCE_PARENT_LAYER; 125 | } 126 | 127 | virtual bool fallbackOnError() { 128 | return pFallbackOnError; 129 | } 130 | 131 | virtual bool isActive() { 132 | return pIsActive; 133 | } 134 | 135 | virtual void setActive(bool newValue) { 136 | pIsActive = newValue; 137 | } 138 | 139 | [[nodiscard]] virtual std::string getName() const { 140 | return pName; 141 | } 142 | 143 | virtual bool isValidDirHandle(FSADirectoryHandle handle) = 0; 144 | 145 | virtual bool isValidFileHandle(FSAFileHandle handle) = 0; 146 | 147 | virtual void deleteDirHandle(FSADirectoryHandle handle) = 0; 148 | 149 | virtual void deleteFileHandle(FSAFileHandle handle) = 0; 150 | 151 | virtual uint32_t getLayerId() = 0; 152 | 153 | virtual uint32_t getHandle() { 154 | return reinterpret_cast(this); 155 | } 156 | 157 | IFSWrapper() { 158 | // Abuse this as a stable handle that references itself and survives std::move 159 | *mHandle = reinterpret_cast(mHandle.get()); 160 | } 161 | 162 | private: 163 | bool pIsActive = true; 164 | std::unique_ptr mHandle = std::make_unique(); 165 | 166 | protected: 167 | bool pFallbackOnError = false; 168 | std::string pName; 169 | }; 170 | #pragma GCC diagnostic pop 171 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | .SUFFIXES: 3 | #------------------------------------------------------------------------------- 4 | 5 | ifeq ($(strip $(DEVKITPRO)),) 6 | $(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") 7 | endif 8 | 9 | TOPDIR ?= $(CURDIR) 10 | 11 | include $(DEVKITPRO)/wums/share/wums_rules 12 | 13 | WUMS_ROOT := $(DEVKITPRO)/wums 14 | WUT_ROOT := $(DEVKITPRO)/wut 15 | #------------------------------------------------------------------------------- 16 | # TARGET is the name of the output 17 | # BUILD is the directory where object files & intermediate files will be placed 18 | # SOURCES is a list of directories containing source code 19 | # DATA is a list of directories containing data files 20 | # INCLUDES is a list of directories containing header files 21 | #------------------------------------------------------------------------------- 22 | TARGET := ContentRedirectionModule 23 | BUILD := build 24 | SOURCES := src \ 25 | src/utils 26 | DATA := data 27 | INCLUDES := src 28 | 29 | #------------------------------------------------------------------------------- 30 | # options for code generation 31 | #------------------------------------------------------------------------------- 32 | CFLAGS := -Wall -Wextra -Os -ffunction-sections\ 33 | $(MACHDEP) 34 | 35 | CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__ 36 | 37 | CXXFLAGS := $(CFLAGS) -std=c++20 38 | 39 | ASFLAGS := -g $(ARCH) 40 | LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) $(WUMSSPECS) 41 | 42 | ifeq ($(DEBUG),1) 43 | CXXFLAGS += -DDEBUG -g 44 | CFLAGS += -DDEBUG -g 45 | endif 46 | 47 | ifeq ($(DEBUG),VERBOSE) 48 | CXXFLAGS += -DDEBUG -DVERBOSE_DEBUG -g 49 | CFLAGS += -DDEBUG -DVERBOSE_DEBUG -g 50 | endif 51 | 52 | LIBS := -lwums -lwut -lfunctionpatcher 53 | 54 | #------------------------------------------------------------------------------- 55 | # list of directories containing libraries, this must be the top level 56 | # containing include and lib 57 | #------------------------------------------------------------------------------- 58 | LIBDIRS := $(PORTLIBS) $(WUT_ROOT) $(WUT_ROOT)/usr $(WUMS_ROOT) 59 | 60 | #------------------------------------------------------------------------------- 61 | # no real need to edit anything past this point unless you need to add additional 62 | # rules for different file extensions 63 | #------------------------------------------------------------------------------- 64 | ifneq ($(BUILD),$(notdir $(CURDIR))) 65 | #------------------------------------------------------------------------------- 66 | 67 | export OUTPUT := $(CURDIR)/$(TARGET) 68 | export TOPDIR := $(CURDIR) 69 | 70 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 71 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 72 | 73 | export DEPSDIR := $(CURDIR)/$(BUILD) 74 | 75 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) 76 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) 77 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) 78 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 79 | 80 | #------------------------------------------------------------------------------- 81 | # use CXX for linking C++ projects, CC for standard C 82 | #------------------------------------------------------------------------------- 83 | ifeq ($(strip $(CPPFILES)),) 84 | #------------------------------------------------------------------------------- 85 | export LD := $(CC) 86 | #------------------------------------------------------------------------------- 87 | else 88 | #------------------------------------------------------------------------------- 89 | export LD := $(CXX) 90 | #------------------------------------------------------------------------------- 91 | endif 92 | #------------------------------------------------------------------------------- 93 | 94 | export OFILES_BIN := $(addsuffix .o,$(BINFILES)) 95 | export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) 96 | export OFILES := $(OFILES_BIN) $(OFILES_SRC) 97 | export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) 98 | 99 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ 100 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 101 | -I$(CURDIR)/$(BUILD) 102 | 103 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) 104 | 105 | .PHONY: $(BUILD) clean all 106 | 107 | #------------------------------------------------------------------------------- 108 | all: $(BUILD) 109 | 110 | $(BUILD): 111 | @$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD)) 112 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 113 | 114 | #------------------------------------------------------------------------------- 115 | clean: 116 | @echo clean ... 117 | @rm -fr $(BUILD) $(TARGET).wms $(TARGET).elf 118 | 119 | #------------------------------------------------------------------------------- 120 | else 121 | .PHONY: all 122 | 123 | DEPENDS := $(OFILES:.o=.d) 124 | 125 | #------------------------------------------------------------------------------- 126 | # main targets 127 | #------------------------------------------------------------------------------- 128 | all : $(OUTPUT).wms 129 | 130 | $(OUTPUT).wms : $(OUTPUT).elf 131 | $(OUTPUT).elf : $(OFILES) 132 | 133 | $(OFILES_SRC) : $(HFILES_BIN) 134 | 135 | #------------------------------------------------------------------------------- 136 | # you need a rule like this for each extension you use as binary data 137 | #------------------------------------------------------------------------------- 138 | %.bin.o %_bin.h : %.bin 139 | #------------------------------------------------------------------------------- 140 | @echo $(notdir $<) 141 | @$(bin2o) 142 | 143 | #--------------------------------------------------------------------------------- 144 | %.o: %.s 145 | @echo $(notdir $<) 146 | @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) 147 | 148 | -include $(DEPENDS) 149 | 150 | #------------------------------------------------------------------------------- 151 | endif 152 | #------------------------------------------------------------------------------- 153 | -------------------------------------------------------------------------------- /src/export.cpp: -------------------------------------------------------------------------------- 1 | #include "FSWrapper.h" 2 | #include "FSWrapperMergeDirsWithParent.h" 3 | #include "FileUtils.h" 4 | #include "IFSWrapper.h" 5 | #include "malloc.h" 6 | #include "utils/StringTools.h" 7 | #include "utils/logger.h" 8 | #include "utils/utils.h" 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | struct AOCTitle { 18 | WUT_UNKNOWN_BYTES(0x68); 19 | }; 20 | 21 | WUT_CHECK_SIZE(AOCTitle, 0x68); 22 | 23 | bool getAOCPath(std::string &outStr) { 24 | int32_t (*AOC_Initialize)() = nullptr; 25 | int32_t (*AOC_Finalize)() = nullptr; 26 | int32_t (*AOC_ListTitle)(uint32_t * titleCountOut, AOCTitle * titleList, uint32_t maxCount, void *workBuffer, uint32_t workBufferSize) = nullptr; 27 | int32_t (*AOC_OpenTitle)(char *pathOut, AOCTitle *aocTitleInfo, void *workBuffer, uint32_t workBufferSize) = nullptr; 28 | int32_t (*AOC_CalculateWorkBufferSize)(uint32_t count) = nullptr; 29 | int32_t (*AOC_CloseTitle)(AOCTitle * aocTitleInfo) = nullptr; 30 | 31 | AOCTitle title{}; 32 | char aocPath[256]; 33 | aocPath[0] = '\0'; 34 | uint32_t outCount = 0; 35 | uint32_t workBufferSize = 0; 36 | void *workBuffer = nullptr; 37 | bool result = false; 38 | 39 | OSDynLoad_Module aoc_handle; 40 | if (OSDynLoad_Acquire("nn_aoc.rpl", &aoc_handle) != OS_DYNLOAD_OK) { 41 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_Acquire failed"); 42 | return false; 43 | } 44 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_Initialize", reinterpret_cast(&AOC_Initialize)) != OS_DYNLOAD_OK) { 45 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 46 | goto end; 47 | } 48 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_Finalize", reinterpret_cast(&AOC_Finalize)) != OS_DYNLOAD_OK) { 49 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 50 | goto end; 51 | } 52 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_OpenTitle", reinterpret_cast(&AOC_OpenTitle)) != OS_DYNLOAD_OK) { 53 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 54 | goto end; 55 | } 56 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_ListTitle", reinterpret_cast(&AOC_ListTitle)) != OS_DYNLOAD_OK) { 57 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 58 | goto end; 59 | } 60 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_CalculateWorkBufferSize", reinterpret_cast(&AOC_CalculateWorkBufferSize)) != OS_DYNLOAD_OK) { 61 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 62 | goto end; 63 | } 64 | if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_CloseTitle", reinterpret_cast(&AOC_CloseTitle)) != OS_DYNLOAD_OK) { 65 | DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed"); 66 | goto end; 67 | } 68 | 69 | AOC_Initialize(); 70 | 71 | workBufferSize = AOC_CalculateWorkBufferSize(1); 72 | workBuffer = memalign(0x40, workBufferSize); 73 | if (!workBuffer) { 74 | DEBUG_FUNCTION_LINE_WARN("Failed to alloc workBuffer"); 75 | goto end; 76 | } 77 | if (AOC_ListTitle(&outCount, &title, 1, workBuffer, workBufferSize) < 0) { 78 | DEBUG_FUNCTION_LINE_WARN("AOC_ListTitle failed"); 79 | goto end; 80 | } 81 | if (AOC_OpenTitle(aocPath, &title, workBuffer, workBufferSize) < 0) { 82 | DEBUG_FUNCTION_LINE_WARN("AOC_OpenTitle failed"); 83 | goto end; 84 | } 85 | 86 | result = true; 87 | outStr = aocPath; 88 | AOC_CloseTitle(&title); 89 | end: 90 | free(workBuffer); 91 | AOC_Finalize(); 92 | OSDynLoad_Release(aoc_handle); 93 | return result; 94 | } 95 | 96 | ContentRedirectionApiErrorType CRAddFSLayer(CRLayerHandle *handle, const char *layerName, const char *replacementDir, const FSLayerType layerType) { 97 | if (!handle || layerName == nullptr || replacementDir == nullptr) { 98 | DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_INVALID_ARG"); 99 | return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG; 100 | } 101 | std::unique_ptr ptr; 102 | if (layerType == FS_LAYER_TYPE_CONTENT_REPLACE) { 103 | DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/content\" to \"%s\", mode: \"replace\"", replacementDir); 104 | ptr = make_unique_nothrow(layerName, "/vol/content", replacementDir, false, false); 105 | } else if (layerType == FS_LAYER_TYPE_CONTENT_MERGE) { 106 | DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/content\" to \"%s\", mode: \"merge\"", replacementDir); 107 | ptr = make_unique_nothrow(layerName, "/vol/content", replacementDir, true); 108 | } else if (layerType == FS_LAYER_TYPE_AOC_MERGE || layerType == FS_LAYER_TYPE_AOC_REPLACE) { 109 | std::string targetPath; 110 | if (!getAOCPath(targetPath)) { 111 | DEBUG_FUNCTION_LINE_ERR("(%s) Failed to get the AOC path. Not redirecting /vol/aoc", layerName); 112 | return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG; 113 | } 114 | DEBUG_FUNCTION_LINE_INFO("Redirecting \"%s\" to \"%s\", mode: \"%s\"", targetPath.c_str(), replacementDir, layerType == FS_LAYER_TYPE_AOC_MERGE ? "merge" : "replace"); 115 | if (layerType == FS_LAYER_TYPE_AOC_MERGE) { 116 | ptr = make_unique_nothrow(layerName, targetPath.c_str(), replacementDir, true); 117 | } else { 118 | ptr = make_unique_nothrow(layerName, targetPath.c_str(), replacementDir, false, false); 119 | } 120 | } else if (layerType == FS_LAYER_TYPE_SAVE_REPLACE) { 121 | DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/save\" to \"%s\", mode: \"replace\"", replacementDir); 122 | ptr = make_unique_nothrow(layerName, "/vol/save", replacementDir, false, true); 123 | } else if (layerType == FS_LAYER_TYPE_SAVE_REPLACE_FOR_CURRENT_USER) { 124 | nn::act::Initialize(); 125 | nn::act::PersistentId persistentId = nn::act::GetPersistentId(); 126 | nn::act::Finalize(); 127 | 128 | std::string user = string_format("/vol/save/%08X", 0x80000000 | persistentId); 129 | 130 | DEBUG_FUNCTION_LINE_INFO("Redirecting \"%s\" to \"%s\", mode: \"replace\"", user.c_str(), replacementDir); 131 | ptr = make_unique_nothrow(layerName, user, replacementDir, false, true); 132 | } else { 133 | DEBUG_FUNCTION_LINE_ERR("CONTENT_REDIRECTION_API_ERROR_UNKNOWN_LAYER_DIR_TYPE: %s %s %d", layerName, replacementDir, layerType); 134 | return CONTENT_REDIRECTION_API_ERROR_UNKNOWN_FS_LAYER_TYPE; 135 | } 136 | if (ptr) { 137 | DEBUG_FUNCTION_LINE_VERBOSE("Added new layer (%s). Replacement dir: %s Type:%d", layerName, replacementDir, layerType); 138 | std::lock_guard lock(gFSLayerMutex); 139 | *handle = (CRLayerHandle) ptr->getHandle(); 140 | gFSLayers.push_back(std::move(ptr)); 141 | return CONTENT_REDIRECTION_API_ERROR_NONE; 142 | } 143 | DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory"); 144 | return CONTENT_REDIRECTION_API_ERROR_NO_MEMORY; 145 | } 146 | 147 | ContentRedirectionApiErrorType CRAddFSLayerEx(CRLayerHandle *handle, const char *layerName, const char *targetPath, const char *replacementPath, const FSLayerTypeEx layerType) { 148 | if (!handle || layerName == nullptr || replacementPath == nullptr || targetPath == nullptr) { 149 | DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_INVALID_ARG"); 150 | return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG; 151 | } 152 | std::unique_ptr ptr; 153 | switch (layerType) { 154 | case FS_LAYER_TYPE_EX_REPLACE_DIRECTORY: { 155 | DEBUG_FUNCTION_LINE_INFO("[AddFSLayerEx] Redirecting \"%s\" to \"%s\", mode: \"replace\"", targetPath, replacementPath); 156 | ptr = make_unique_nothrow(layerName, targetPath, replacementPath, false, false); 157 | break; 158 | } 159 | case FS_LAYER_TYPE_EX_MERGE_DIRECTORY: { 160 | DEBUG_FUNCTION_LINE_INFO("[AddFSLayerEx] Redirecting \"%s\" to \"%s\", mode: \"merge\"", targetPath, replacementPath); 161 | ptr = make_unique_nothrow(layerName, targetPath, replacementPath, true); 162 | break; 163 | } 164 | case FS_LAYER_TYPE_EX_REPLACE_FILE: { 165 | DEBUG_FUNCTION_LINE_INFO("[AddFSLayerEx] Redirecting file \"%s\" to \"%s\"", targetPath, replacementPath); 166 | ptr = make_unique_nothrow(layerName, targetPath, replacementPath, true); 167 | break; 168 | } 169 | default: { 170 | DEBUG_FUNCTION_LINE_ERR("[AddFSLayerEx] CONTENT_REDIRECTION_API_ERROR_UNKNOWN_LAYER_DIR_TYPE: %s %s %d", layerName, replacementPath, layerType); 171 | return CONTENT_REDIRECTION_API_ERROR_UNKNOWN_FS_LAYER_TYPE; 172 | } 173 | } 174 | 175 | if (ptr) { 176 | DEBUG_FUNCTION_LINE_VERBOSE("[AddFSLayerEx] Added new layer (%s). Target path: %s Replacement dir: %s Type:%d", layerName, targetPath, replacementPath, layerType); 177 | std::lock_guard lock(gFSLayerMutex); 178 | *handle = ptr->getHandle(); 179 | gFSLayers.emplace_back(std::move(ptr)); 180 | return CONTENT_REDIRECTION_API_ERROR_NONE; 181 | } 182 | DEBUG_FUNCTION_LINE_ERR("[AddFSLayerEx] Failed to allocate memory"); 183 | return CONTENT_REDIRECTION_API_ERROR_NO_MEMORY; 184 | } 185 | 186 | 187 | ContentRedirectionApiErrorType CRRemoveFSLayer(CRLayerHandle handle) { 188 | if (!remove_locked_first_if(gFSLayerMutex, gFSLayers, [handle](auto &cur) { return (CRLayerHandle) cur->getHandle() == handle; })) { 189 | DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle); 190 | return CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND; 191 | } 192 | return CONTENT_REDIRECTION_API_ERROR_NONE; 193 | } 194 | 195 | ContentRedirectionApiErrorType CRSetActive(CRLayerHandle handle, bool active) { 196 | std::lock_guard lock(gFSLayerMutex); 197 | for (auto &cur : gFSLayers) { 198 | if ((CRLayerHandle) cur->getHandle() == handle) { 199 | cur->setActive(active); 200 | return CONTENT_REDIRECTION_API_ERROR_NONE; 201 | } 202 | } 203 | 204 | DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle); 205 | return CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND; 206 | } 207 | 208 | ContentRedirectionApiErrorType CRGetVersion(ContentRedirectionVersion *outVersion) { 209 | if (outVersion == nullptr) { 210 | return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG; 211 | } 212 | *outVersion = 2; 213 | return CONTENT_REDIRECTION_API_ERROR_NONE; 214 | } 215 | 216 | int CRAddDevice(const devoptab_t *device) { 217 | return AddDevice(device); 218 | } 219 | 220 | int CRRemoveDevice(const char *name) { 221 | return RemoveDevice(name); 222 | } 223 | 224 | WUMS_EXPORT_FUNCTION(CRGetVersion); 225 | WUMS_EXPORT_FUNCTION(CRAddFSLayerEx); 226 | WUMS_EXPORT_FUNCTION(CRAddFSLayer); 227 | WUMS_EXPORT_FUNCTION(CRRemoveFSLayer); 228 | WUMS_EXPORT_FUNCTION(CRSetActive); 229 | WUMS_EXPORT_FUNCTION(CRAddDevice); 230 | WUMS_EXPORT_FUNCTION(CRRemoveDevice); -------------------------------------------------------------------------------- /src/FSWrapperReplaceSingleFile.cpp: -------------------------------------------------------------------------------- 1 | #include "FSWrapperReplaceSingleFile.h" 2 | #include "utils/StringTools.h" 3 | #include "utils/logger.h" 4 | #include "utils/utils.h" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | FSWrapperReplaceSingleFile::FSWrapperReplaceSingleFile(const std::string &name, 13 | const std::string &fileToReplace, 14 | const std::string &replaceWithPath, 15 | const bool fallbackOnError) : FSWrapper(name, 16 | fileToReplace, 17 | replaceWithPath, 18 | fallbackOnError, 19 | false) { 20 | auto strCpy = fileToReplace; 21 | std::ranges::replace(strCpy, '\\', '/'); 22 | auto asPath = std::filesystem::path(strCpy); 23 | mPathToReplace = asPath.parent_path(); 24 | mFileNameToReplace = asPath.filename(); 25 | mFullPathToReplace = fileToReplace; 26 | 27 | strCpy = replaceWithPath; 28 | std::ranges::replace(strCpy, '\\', '/'); 29 | asPath = std::filesystem::path(strCpy); 30 | mReplacedWithPath = asPath.parent_path(); 31 | mReplacedWithFileName = asPath.filename(); 32 | 33 | FSAInit(); 34 | this->mClientHandle = FSAAddClient(nullptr); 35 | if (mClientHandle < 0) { 36 | DEBUG_FUNCTION_LINE_ERR("[%s] FSAClientHandle failed: %s (%d)", name.c_str(), FSAGetStatusStr(static_cast(mClientHandle)), mClientHandle); 37 | mClientHandle = 0; 38 | } 39 | } 40 | 41 | FSWrapperReplaceSingleFile::~FSWrapperReplaceSingleFile() { 42 | if (mClientHandle) { 43 | if (const FSError res = FSADelClient(mClientHandle); res != FS_ERROR_OK) { 44 | DEBUG_FUNCTION_LINE_ERR("[%s] FSADelClient failed: %s (%d)", FSAGetStatusStr(res), res); 45 | } 46 | mClientHandle = 0; 47 | } 48 | } 49 | 50 | FSError FSWrapperReplaceSingleFile::FSOpenDirWrapper(const char *path, 51 | FSADirectoryHandle *handle) { 52 | if (!IsDirPathToReplace(path)) { 53 | return FS_ERROR_FORCE_PARENT_LAYER; 54 | } 55 | if (handle == nullptr) { 56 | DEBUG_FUNCTION_LINE_ERR("[%s] handle was NULL", getName().c_str()); 57 | return FS_ERROR_INVALID_PARAM; 58 | } 59 | if (const auto dirInfo = make_shared_nothrow()) { 60 | dirInfo->handle = (reinterpret_cast(dirInfo.get()) & 0x0FFFFFFF) | 0x30000000; 61 | *handle = dirInfo->handle; 62 | addDirHandle(dirInfo); 63 | if (!isValidDirHandle(*handle)) { 64 | FSWrapper::FSCloseDirWrapper(*handle); 65 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), *handle); 66 | return FS_ERROR_INVALID_DIRHANDLE; 67 | } 68 | if (const auto dirHandle = getDirExFromHandle(*handle); dirHandle != nullptr) { 69 | dirHandle->entryRead = false; 70 | dirHandle->entryReadSuccess = false; 71 | dirHandle->directoryEntry = {}; 72 | dirHandle->realDirHandle = 0; 73 | 74 | if (mClientHandle) { 75 | FSADirectoryHandle realHandle = 0; 76 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSAOpenDir with %s for parent layer", getName().c_str(), path); 77 | if (const FSError err = FSAOpenDir(mClientHandle, path, &realHandle); err == FS_ERROR_OK) { 78 | dirHandle->realDirHandle = realHandle; 79 | } else { 80 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to open real dir %s. %s (%d)", getName().c_str(), path, FSAGetStatusStr(err), err); 81 | } 82 | } else { 83 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 84 | } 85 | OSMemoryBarrier(); 86 | } 87 | } else { 88 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc dir handle", getName().c_str()); 89 | return FS_ERROR_MAX_DIRS; 90 | } 91 | return FS_ERROR_OK; 92 | } 93 | 94 | FSError FSWrapperReplaceSingleFile::FSReadDirWrapper(const FSADirectoryHandle handle, FSADirectoryEntry *entry) { 95 | if (!isValidDirHandle(handle)) { 96 | return FS_ERROR_FORCE_PARENT_LAYER; 97 | } 98 | const auto dirHandle = getDirExFromHandle(handle); 99 | if (!dirHandle) { 100 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle); 101 | return FS_ERROR_INVALID_DIRHANDLE; 102 | } 103 | FSError res = FS_ERROR_OK; 104 | do { 105 | if (!dirHandle->entryRead) { 106 | dirHandle->entryRead = true; 107 | const auto newPath = GetNewPath(mFullPathToReplace); 108 | 109 | struct stat path_stat {}; 110 | 111 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] dir read of %s (%s)", getName().c_str(), mFullPathToReplace.c_str(), newPath.c_str()); 112 | if (stat(newPath.c_str(), &path_stat) < 0) { 113 | DEBUG_FUNCTION_LINE_WARN("[%s] Path %s (%s) for dir read not found ", getName().c_str(), mFullPathToReplace.c_str(), newPath.c_str()); 114 | dirHandle->entryReadSuccess = false; 115 | continue; 116 | } 117 | translate_stat(&path_stat, &dirHandle->directoryEntry.info); 118 | strncpy(dirHandle->directoryEntry.name, mFileNameToReplace.c_str(), sizeof(dirHandle->directoryEntry.name)); 119 | memcpy(entry, &dirHandle->directoryEntry, sizeof(FSADirectoryEntry)); 120 | 121 | dirHandle->entryReadSuccess = true; 122 | OSMemoryBarrier(); 123 | } else { 124 | // Read the real directory. 125 | if (dirHandle->realDirHandle != 0) { 126 | if (mClientHandle) { 127 | FSADirectoryEntry realDirEntry; 128 | while (true) { 129 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSReadDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 130 | if (const FSError readDirResult = FSAReadDir(mClientHandle, dirHandle->realDirHandle, &realDirEntry); readDirResult == FS_ERROR_OK) { 131 | // Skip already read new files 132 | if (dirHandle->entryRead && dirHandle->entryReadSuccess && strcmp(dirHandle->directoryEntry.name, realDirEntry.name) == 0) { 133 | continue; 134 | } 135 | 136 | // But use new entries! 137 | memcpy(entry, &realDirEntry, sizeof(FSADirectoryEntry)); 138 | res = FS_ERROR_OK; 139 | break; 140 | } else if (readDirResult == FS_ERROR_END_OF_DIR) { 141 | res = FS_ERROR_END_OF_DIR; 142 | break; 143 | } else { 144 | DEBUG_FUNCTION_LINE_ERR("[%s] real_FSReadDir returned an unexpected error: %s (%d)", getName().c_str(), FSAGetStatusStr(readDirResult), readDirResult); 145 | res = FS_ERROR_END_OF_DIR; 146 | break; 147 | } 148 | } 149 | } else { 150 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 151 | } 152 | } 153 | } 154 | return res; 155 | } while (true); 156 | } 157 | 158 | FSError FSWrapperReplaceSingleFile::FSCloseDirWrapper(const FSADirectoryHandle handle) { 159 | if (!isValidDirHandle(handle)) { 160 | return FS_ERROR_FORCE_PARENT_LAYER; 161 | } 162 | const auto dirHandle = getDirExFromHandle(handle); 163 | if (dirHandle->realDirHandle != 0) { 164 | if (mClientHandle) { 165 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSCloseDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 166 | auto realResult = FSACloseDir(mClientHandle, dirHandle->realDirHandle); 167 | if (realResult == FS_ERROR_OK) { 168 | dirHandle->realDirHandle = 0; 169 | } else { 170 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close realDirHandle %d: res %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(realResult), realResult); 171 | return realResult == FS_ERROR_CANCELLED ? FS_ERROR_CANCELLED : FS_ERROR_MEDIA_ERROR; 172 | } 173 | } else { 174 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 175 | } 176 | } else { 177 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str()); 178 | } 179 | dirHandle->entryRead = false; 180 | dirHandle->entryReadSuccess = false; 181 | 182 | OSMemoryBarrier(); 183 | return FS_ERROR_OK; 184 | } 185 | 186 | FSError FSWrapperReplaceSingleFile::FSRewindDirWrapper(const FSADirectoryHandle handle) { 187 | if (!isValidDirHandle(handle)) { 188 | return FS_ERROR_FORCE_PARENT_LAYER; 189 | } 190 | const auto dirHandle = getDirExFromHandle(handle); 191 | dirHandle->entryRead = false; 192 | dirHandle->entryReadSuccess = false; 193 | if (dirHandle->realDirHandle != 0) { 194 | if (mClientHandle) { 195 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSARewindDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 196 | if (const FSError err = FSARewindDir(mClientHandle, dirHandle->realDirHandle); err != FS_ERROR_OK) { 197 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to rewind dir for realDirHandle %08X. %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(err), err); 198 | } 199 | } else { 200 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 201 | } 202 | } else { 203 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str()); 204 | } 205 | OSMemoryBarrier(); 206 | 207 | return FS_ERROR_OK; 208 | } 209 | 210 | bool FSWrapperReplaceSingleFile::SkipDeletedFilesInReadDir() { 211 | return false; 212 | } 213 | 214 | bool FSWrapperReplaceSingleFile::IsDirPathToReplace(const std::string_view &path) const { 215 | return starts_with_case_insensitive(path, mPathToReplace); 216 | } 217 | 218 | std::string FSWrapperReplaceSingleFile::GetNewPath(const std::string_view &path) const { 219 | auto pathCpy = std::string(path); 220 | SafeReplaceInString(pathCpy, this->mPathToReplace, this->mReplacedWithPath); 221 | SafeReplaceInString(pathCpy, this->mFileNameToReplace, this->mReplacedWithFileName); 222 | std::ranges::replace(pathCpy, '\\', '/'); 223 | 224 | uint32_t length = pathCpy.size(); 225 | 226 | //! clear path of double slashes 227 | for (uint32_t i = 1; i < length; ++i) { 228 | if (pathCpy[i - 1] == '/' && pathCpy[i] == '/') { 229 | pathCpy.erase(i, 1); 230 | i--; 231 | length--; 232 | } 233 | } 234 | 235 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Redirect %.*s -> %s", getName().c_str(), int(path.length()), path.data(), pathCpy.c_str()); 236 | return pathCpy; 237 | } 238 | 239 | std::shared_ptr FSWrapperReplaceSingleFile::getDirExFromHandle(FSADirectoryHandle handle) { 240 | auto dir = std::dynamic_pointer_cast(getDirFromHandle(handle)); 241 | 242 | if (!dir) { 243 | DEBUG_FUNCTION_LINE_ERR("[%s] dynamic_pointer_cast(%08X) failed", getName().c_str(), handle); 244 | OSFatal("ContentRedirectionModule: dynamic_pointer_cast failed"); 245 | } 246 | return dir; 247 | } -------------------------------------------------------------------------------- /src/FSWrapperMergeDirsWithParent.cpp: -------------------------------------------------------------------------------- 1 | #include "FSWrapperMergeDirsWithParent.h" 2 | #include "utils/StringTools.h" 3 | #include "utils/logger.h" 4 | #include "utils/utils.h" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | FSError FSWrapperMergeDirsWithParent::FSOpenDirWrapper(const char *path, 13 | FSADirectoryHandle *handle) { 14 | if (handle == nullptr) { 15 | DEBUG_FUNCTION_LINE_ERR("[%s] handle was NULL", getName().c_str()); 16 | return FS_ERROR_INVALID_PARAM; 17 | } 18 | 19 | auto res = FSWrapper::FSOpenDirWrapper(path, handle); 20 | if (res == FS_ERROR_OK) { 21 | if (!isValidDirHandle(*handle)) { 22 | FSWrapper::FSCloseDirWrapper(*handle); 23 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), *handle); 24 | return FS_ERROR_INVALID_DIRHANDLE; 25 | } 26 | auto dirHandle = getDirInfoExFromHandle(*handle); 27 | if (dirHandle != nullptr) { 28 | dirHandle->readResultCapacity = 0; 29 | dirHandle->readResultNumberOfEntries = 0; 30 | dirHandle->realDirHandle = 0; 31 | 32 | if (mClientHandle) { 33 | FSADirectoryHandle realHandle = 0; 34 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSAOpenDir with %s for parent layer", getName().c_str(), path); 35 | FSError err; 36 | if ((err = FSAOpenDir(mClientHandle, path, &realHandle)) == FS_ERROR_OK) { 37 | dirHandle->realDirHandle = realHandle; 38 | } else { 39 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to open real dir %s. %s (%d)", getName().c_str(), path, FSAGetStatusStr(err), err); 40 | } 41 | } else { 42 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 43 | } 44 | OSMemoryBarrier(); 45 | } 46 | } 47 | return res; 48 | } 49 | 50 | bool FSWrapperMergeDirsWithParent::SkipDeletedFilesInReadDir() { 51 | return false; 52 | } 53 | 54 | FSError FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSADirectoryHandle handle, FSADirectoryEntry *entry) { 55 | do { 56 | auto res = FSWrapper::FSReadDirWrapper(handle, entry); 57 | if (res == FS_ERROR_OK || res == FS_ERROR_END_OF_DIR) { 58 | if (!isValidDirHandle(handle)) { 59 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle); 60 | return FS_ERROR_INVALID_DIRHANDLE; 61 | } 62 | auto dirHandle = getDirInfoExFromHandle(handle); 63 | if (!dirHandle) { 64 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle); 65 | return FS_ERROR_INVALID_DIRHANDLE; 66 | } 67 | if (res == FS_ERROR_OK) { 68 | if (dirHandle->readResultCapacity == 0) { 69 | dirHandle->readResult = (FSDirectoryEntryEx *) malloc(sizeof(FSDirectoryEntryEx)); 70 | if (dirHandle->readResult == nullptr) { 71 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc memory for %08X (handle %08X)", getName().c_str(), dirHandle.get(), handle); 72 | OSFatal("ContentRedirectionModule: Failed to alloc memory for read result"); 73 | } 74 | dirHandle->readResultCapacity = 1; 75 | } 76 | 77 | if (dirHandle->readResultNumberOfEntries >= dirHandle->readResultCapacity) { 78 | auto newCapacity = dirHandle->readResultCapacity * 2; 79 | dirHandle->readResult = (FSDirectoryEntryEx *) realloc(dirHandle->readResult, newCapacity * sizeof(FSDirectoryEntryEx)); 80 | dirHandle->readResultCapacity = newCapacity; 81 | if (dirHandle->readResult == nullptr) { 82 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to realloc memory for %08X (handle %08X)", getName().c_str(), dirHandle.get(), handle); 83 | OSFatal("ContentRedirectionModule: Failed to alloc memory for read result"); 84 | } 85 | } 86 | 87 | memcpy(&dirHandle->readResult[dirHandle->readResultNumberOfEntries].realEntry, entry, sizeof(FSADirectoryEntry)); 88 | dirHandle->readResultNumberOfEntries++; 89 | 90 | /** 91 | * Read the next entry if this entry starts with deletePrefix. We keep the entry but mark it as deleted. 92 | */ 93 | if (starts_with_case_insensitive(entry->name, deletePrefix)) { 94 | dirHandle->readResult[dirHandle->readResultNumberOfEntries].isMarkedAsDeleted = true; 95 | 96 | OSMemoryBarrier(); 97 | continue; 98 | } 99 | 100 | OSMemoryBarrier(); 101 | } else if (res == FS_ERROR_END_OF_DIR) { 102 | // Read the real directory. 103 | if (dirHandle->realDirHandle != 0) { 104 | if (mClientHandle) { 105 | FSADirectoryEntry realDirEntry; 106 | FSError readDirResult; 107 | while (true) { 108 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSReadDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 109 | readDirResult = FSAReadDir(mClientHandle, dirHandle->realDirHandle, &realDirEntry); 110 | if (readDirResult == FS_ERROR_OK) { 111 | bool found = false; 112 | auto nameDeleted = deletePrefix + realDirEntry.name; 113 | for (int i = 0; i < dirHandle->readResultNumberOfEntries; i++) { 114 | auto curResult = &dirHandle->readResult[i]; 115 | 116 | // Don't return files that are "deleted" 117 | if (strcmp(curResult->realEntry.name, nameDeleted.c_str()) == 0) { 118 | found = true; 119 | break; 120 | } 121 | // Check if this is a new result 122 | if (strcmp(curResult->realEntry.name, realDirEntry.name) == 0 && !curResult->isMarkedAsDeleted) { 123 | found = true; 124 | break; 125 | } 126 | } 127 | // If it's new we can use it :) 128 | if (!found) { 129 | memcpy(entry, &realDirEntry, sizeof(FSADirectoryEntry)); 130 | res = FS_ERROR_OK; 131 | break; 132 | } 133 | } else if (readDirResult == FS_ERROR_END_OF_DIR) { 134 | res = FS_ERROR_END_OF_DIR; 135 | break; 136 | } else { 137 | DEBUG_FUNCTION_LINE_ERR("[%s] real_FSReadDir returned an unexpected error: %s (%d)", getName().c_str(), FSAGetStatusStr(readDirResult), readDirResult); 138 | res = FS_ERROR_END_OF_DIR; 139 | break; 140 | } 141 | } 142 | } else { 143 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 144 | } 145 | } 146 | } else { 147 | DEBUG_FUNCTION_LINE_ERR("[%s] Unexpected result %d", getName().c_str(), res); 148 | } 149 | } 150 | return res; 151 | } while (true); 152 | } 153 | 154 | FSError FSWrapperMergeDirsWithParent::FSCloseDirWrapper(FSADirectoryHandle handle) { 155 | auto res = FSWrapper::FSCloseDirWrapper(handle); 156 | 157 | if (res == FS_ERROR_OK) { 158 | if (!isValidDirHandle(handle)) { 159 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle); 160 | return FS_ERROR_INVALID_DIRHANDLE; 161 | } 162 | auto dirHandle = getDirInfoExFromHandle(handle); 163 | if (dirHandle->realDirHandle != 0) { 164 | if (mClientHandle) { 165 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSCloseDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 166 | auto realResult = FSACloseDir(mClientHandle, dirHandle->realDirHandle); 167 | if (realResult == FS_ERROR_OK) { 168 | dirHandle->realDirHandle = 0; 169 | } else { 170 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close realDirHandle %d: res %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(realResult), realResult); 171 | return realResult == FS_ERROR_CANCELLED ? FS_ERROR_CANCELLED : FS_ERROR_MEDIA_ERROR; 172 | } 173 | } else { 174 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 175 | } 176 | } else { 177 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str()); 178 | } 179 | 180 | if (dirHandle->readResult != nullptr) { 181 | free(dirHandle->readResult); 182 | dirHandle->readResult = nullptr; 183 | dirHandle->readResultCapacity = 0; 184 | dirHandle->readResultNumberOfEntries = 0; 185 | } 186 | 187 | OSMemoryBarrier(); 188 | } 189 | return res; 190 | } 191 | 192 | FSError FSWrapperMergeDirsWithParent::FSRewindDirWrapper(FSADirectoryHandle handle) { 193 | auto res = FSWrapper::FSRewindDirWrapper(handle); 194 | if (res == FS_ERROR_OK) { 195 | if (!isValidDirHandle(handle)) { 196 | DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle); 197 | return FS_ERROR_INVALID_DIRHANDLE; 198 | } 199 | auto dirHandle = getDirInfoExFromHandle(handle); 200 | if (dirHandle->readResult != nullptr) { 201 | dirHandle->readResultNumberOfEntries = 0; 202 | #pragma GCC diagnostic push 203 | #pragma GCC diagnostic ignored "-Wclass-memaccess" 204 | memset(dirHandle->readResult, 0, sizeof(FSDirectoryEntryEx) * dirHandle->readResultCapacity); 205 | #pragma GCC diagnostic pop 206 | } 207 | 208 | if (dirHandle->realDirHandle != 0) { 209 | if (mClientHandle) { 210 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSARewindDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle); 211 | if (FSError err = FSARewindDir(mClientHandle, dirHandle->realDirHandle); err != FS_ERROR_OK) { 212 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to rewind dir for realDirHandle %08X. %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(err), err); 213 | } 214 | } else { 215 | DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str()); 216 | } 217 | } else { 218 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str()); 219 | } 220 | OSMemoryBarrier(); 221 | } 222 | return res; 223 | } 224 | 225 | FSWrapperMergeDirsWithParent::FSWrapperMergeDirsWithParent(const std::string &name, 226 | const std::string &pathToReplace, 227 | const std::string &replaceWithPath, 228 | bool fallbackOnError) : FSWrapper(name, 229 | pathToReplace, 230 | replaceWithPath, 231 | fallbackOnError, 232 | false) { 233 | FSAInit(); 234 | this->mClientHandle = FSAAddClient(nullptr); 235 | if (mClientHandle < 0) { 236 | DEBUG_FUNCTION_LINE_ERR("[%s] FSAClientHandle failed: %s (%d)", name.c_str(), FSAGetStatusStr(static_cast(mClientHandle)), mClientHandle); 237 | mClientHandle = 0; 238 | } 239 | } 240 | 241 | FSWrapperMergeDirsWithParent::~FSWrapperMergeDirsWithParent() { 242 | if (mClientHandle) { 243 | FSError res; 244 | if ((res = FSADelClient(mClientHandle)) != FS_ERROR_OK) { 245 | DEBUG_FUNCTION_LINE_ERR("[%s] FSADelClient failed: %s (%d)", FSAGetStatusStr(res), res); 246 | } 247 | mClientHandle = 0; 248 | } 249 | } 250 | 251 | std::shared_ptr FSWrapperMergeDirsWithParent::getDirInfoExFromHandle(FSADirectoryHandle handle) { 252 | auto dir = std::dynamic_pointer_cast(getDirFromHandle(handle)); 253 | 254 | if (!dir) { 255 | DEBUG_FUNCTION_LINE_ERR("[%s] dynamic_pointer_cast(%08X) failed", getName().c_str(), handle); 256 | OSFatal("ContentRedirectionModule: dynamic_pointer_cast failed"); 257 | } 258 | return dir; 259 | } 260 | 261 | std::shared_ptr FSWrapperMergeDirsWithParent::getNewDirInfoHandle() { 262 | return make_shared_nothrow(); 263 | } 264 | -------------------------------------------------------------------------------- /src/FileUtils.cpp: -------------------------------------------------------------------------------- 1 | #include "FileUtils.h" 2 | #include "FSWrapper.h" 3 | #include "IFSWrapper.h" 4 | #include "utils/StringTools.h" 5 | #include "utils/logger.h" 6 | #include "utils/utils.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | namespace { 15 | std::mutex sWorkingDirMutex; 16 | std::map sWorkingDirs; 17 | } // namespace 18 | 19 | std::mutex gFSLayerMutex; 20 | std::vector> gFSLayers; 21 | 22 | std::string getFullPathGeneric(const FSAClientHandle client, const char *path, std::mutex &mutex, const std::map &map) { 23 | std::lock_guard workingDirLock(mutex); 24 | 25 | std::string res; 26 | 27 | if (path[0] != '/' && path[0] != '\\') { 28 | if (map.count(client) == 0) { 29 | DEBUG_FUNCTION_LINE_WARN("No working dir found for client %08X, fallback to \"/\"", client); 30 | sWorkingDirs[client] = "/"; 31 | } 32 | res = string_format("%s%s", map.at(client).c_str(), path); 33 | } else { 34 | res = path; 35 | } 36 | 37 | std::ranges::replace(res, '\\', '/'); 38 | 39 | return res; 40 | } 41 | 42 | void setWorkingDirGeneric(const FSAClientHandle client, const char *path, std::mutex &mutex, std::map &map) { 43 | if (!path) { 44 | DEBUG_FUNCTION_LINE_WARN("Path was NULL"); 45 | return; 46 | } 47 | 48 | std::lock_guard workingDirLock(mutex); 49 | 50 | std::string cwd(path); 51 | if (cwd.empty() || cwd.back() != '/') { 52 | cwd.push_back('/'); 53 | } 54 | map[client] = cwd; 55 | OSMemoryBarrier(); 56 | } 57 | 58 | 59 | std::string getFullPath(const FSAClientHandle pClient, const char *path) { 60 | return getFullPathGeneric(pClient, path, sWorkingDirMutex, sWorkingDirs); 61 | } 62 | 63 | void setWorkingDir(const FSAClientHandle client, const char *path) { 64 | setWorkingDirGeneric(client, path, sWorkingDirMutex, sWorkingDirs); 65 | } 66 | 67 | void clearFSLayer() { 68 | { 69 | std::lock_guard workingDirLock(sWorkingDirMutex); 70 | sWorkingDirs.clear(); 71 | } 72 | { 73 | std::lock_guard layerLock(gFSLayerMutex); 74 | gFSLayers.clear(); 75 | } 76 | } 77 | 78 | bool sendMessageToThread(FSShimWrapperMessage *param) { 79 | auto *curThread = &gThreadData[OSGetCoreId()]; 80 | if (curThread->setup) { 81 | OSMessage send; 82 | send.message = param; 83 | send.args[0] = FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND; 84 | auto res = OSSendMessage(&curThread->queue, &send, OS_MESSAGE_FLAGS_NONE); 85 | if (!res) { 86 | DEBUG_FUNCTION_LINE_ERR("Message Queue for ContentRedirection IO Thread is full"); 87 | OSFatal("ContentRedirectionModule: Message Queue for ContentRedirection IO Thread is full"); 88 | } 89 | return res; 90 | } else { 91 | DEBUG_FUNCTION_LINE_ERR("Thread not setup"); 92 | OSFatal("ContentRedirectionModule: Thread not setup"); 93 | } 94 | return false; 95 | } 96 | 97 | FSError doForLayer(FSShimWrapper *param) { 98 | std::lock_guard lock(gFSLayerMutex); 99 | if (!gFSLayers.empty()) { 100 | uint32_t startIndex = gFSLayers.size(); 101 | for (uint32_t i = gFSLayers.size(); i > 0; i--) { 102 | if (gFSLayers[i - 1]->getLayerId() == param->shim->clientHandle) { 103 | startIndex = i - 1; 104 | break; 105 | } 106 | } 107 | 108 | if (startIndex > 0) { 109 | for (uint32_t i = startIndex; i > 0; i--) { 110 | auto &layer = gFSLayers[i - 1]; 111 | if (!layer->isActive()) { 112 | continue; 113 | } 114 | auto layerResult = FS_ERROR_FORCE_PARENT_LAYER; 115 | auto command = (FSACommandEnum) param->shim->command; 116 | #pragma GCC diagnostic push 117 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 118 | switch (command) { 119 | case FSA_COMMAND_OPEN_DIR: { 120 | auto *request = ¶m->shim->request.openDir; 121 | auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path); 122 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] OpenDir: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str()); 123 | // Hacky solution: 124 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 125 | auto *handlePtr = (FSDirectoryHandle *) hackyBuffer[1]; 126 | layerResult = layer->FSOpenDirWrapper(fullPath.c_str(), handlePtr); 127 | break; 128 | } 129 | case FSA_COMMAND_READ_DIR: { 130 | auto *request = ¶m->shim->request.readDir; 131 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadDir: %08X", layer->getName().c_str(), request->handle); 132 | // Hacky solution: 133 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 134 | auto *dirEntryPtr = (FSADirectoryEntry *) hackyBuffer[1]; 135 | layerResult = layer->FSReadDirWrapper(request->handle, dirEntryPtr); 136 | break; 137 | } 138 | case FSA_COMMAND_CLOSE_DIR: { 139 | auto *request = ¶m->shim->request.closeDir; 140 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] CloseDir: %08X", layer->getName().c_str(), request->handle); 141 | layerResult = layer->FSCloseDirWrapper(request->handle); 142 | if (layerResult != FS_ERROR_FORCE_REAL_FUNCTION && layerResult != FS_ERROR_FORCE_PARENT_LAYER) { 143 | if (layer->isValidDirHandle(request->handle)) { 144 | layer->deleteDirHandle(request->handle); 145 | } else { 146 | DEBUG_FUNCTION_LINE_ERR("[%s] Expected to delete dirHandle by %08X but it was not found", layer->getName().c_str(), request->handle); 147 | } 148 | } 149 | break; 150 | } 151 | case FSA_COMMAND_REWIND_DIR: { 152 | auto *request = ¶m->shim->request.rewindDir; 153 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] RewindDir: %08X", layer->getName().c_str(), request->handle); 154 | layerResult = layer->FSRewindDirWrapper(request->handle); 155 | break; 156 | } 157 | case FSA_COMMAND_MAKE_DIR: { 158 | auto *request = ¶m->shim->request.makeDir; 159 | auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path); 160 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] MakeDir: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str()); 161 | layerResult = layer->FSMakeDirWrapper(fullPath.c_str()); 162 | break; 163 | } 164 | case FSA_COMMAND_OPEN_FILE: { 165 | auto *request = ¶m->shim->request.openFile; 166 | auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path); 167 | // Hacky solution: 168 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 169 | auto *handlePtr = (FSFileHandle *) hackyBuffer[1]; 170 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] OpenFile: path %s (full path: %s) mode %s", layer->getName().c_str(), request->path, fullPath.c_str(), request->mode); 171 | layerResult = layer->FSOpenFileWrapper(fullPath.c_str(), request->mode, handlePtr); 172 | break; 173 | } 174 | case FSA_COMMAND_CLOSE_FILE: { 175 | auto *request = ¶m->shim->request.closeFile; 176 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] CloseFile: %08X", layer->getName().c_str(), request->handle); 177 | layerResult = layer->FSCloseFileWrapper(request->handle); 178 | if (layerResult != FS_ERROR_FORCE_REAL_FUNCTION && layerResult != FS_ERROR_FORCE_PARENT_LAYER) { 179 | if (layer->isValidFileHandle(request->handle)) { 180 | layer->deleteFileHandle(request->handle); 181 | } else { 182 | DEBUG_FUNCTION_LINE_ERR("[%s] Expected to delete fileHandle by handle %08X but it was not found", layer->getName().c_str(), request->handle); 183 | } 184 | } 185 | break; 186 | } 187 | case FSA_COMMAND_GET_INFO_BY_QUERY: { 188 | auto *request = ¶m->shim->request.getInfoByQuery; 189 | if (request->type == FSA_QUERY_INFO_STAT) { 190 | auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path); 191 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetStat: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str()); 192 | // Hacky solution: 193 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 194 | auto *statPtr = (FSStat *) hackyBuffer[1]; 195 | layerResult = layer->FSGetStatWrapper(fullPath.c_str(), statPtr); 196 | } 197 | break; 198 | } 199 | case FSA_COMMAND_STAT_FILE: { 200 | auto *request = ¶m->shim->request.statFile; 201 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetStatFile: %08X", layer->getName().c_str(), request->handle); 202 | // Hacky solution: 203 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 204 | auto *statPtr = (FSStat *) hackyBuffer[1]; 205 | layerResult = layer->FSGetStatFileWrapper(request->handle, statPtr); 206 | break; 207 | } 208 | case FSA_COMMAND_READ_FILE: { 209 | 210 | auto *request = ¶m->shim->request.readFile; 211 | if (request->readFlags == FSA_READ_FLAG_NONE) { 212 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadFile: buffer %08X size %08X count %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->handle); 213 | layerResult = layer->FSReadFileWrapper(request->buffer, request->size, request->count, request->handle, 0); 214 | } else if (request->readFlags == FSA_READ_FLAG_READ_WITH_POS) { 215 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadFileWithPos: buffer %08X size %08X count %08X pos %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->pos, request->handle); 216 | layerResult = layer->FSReadFileWithPosWrapper(request->buffer, request->size, request->count, request->pos, request->handle, 0); 217 | } 218 | break; 219 | } 220 | case FSA_COMMAND_SET_POS_FILE: { 221 | 222 | auto *request = ¶m->shim->request.setPosFile; 223 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] SetPosFile: %08X %08X", layer->getName().c_str(), request->handle, request->pos); 224 | layerResult = layer->FSSetPosFileWrapper(request->handle, request->pos); 225 | break; 226 | } 227 | case FSA_COMMAND_GET_POS_FILE: { 228 | auto *request = ¶m->shim->request.getPosFile; 229 | // Hacky solution: 230 | auto *hackyBuffer = (uint32_t *) ¶m->shim->response; 231 | auto *posPtr = (FSAFilePosition *) hackyBuffer[1]; 232 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetPosFile: %08X", layer->getName().c_str(), request->handle); 233 | layerResult = layer->FSGetPosFileWrapper(request->handle, posPtr); 234 | break; 235 | } 236 | case FSA_COMMAND_IS_EOF: { 237 | auto *request = ¶m->shim->request.isEof; 238 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] IsEof: %08X", layer->getName().c_str(), request->handle); 239 | layerResult = layer->FSIsEofWrapper(request->handle); 240 | break; 241 | } 242 | case FSA_COMMAND_TRUNCATE_FILE: { 243 | 244 | auto *request = ¶m->shim->request.truncateFile; 245 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] TruncateFile: %08X", layer->getName().c_str(), request->handle); 246 | layerResult = layer->FSTruncateFileWrapper(request->handle); 247 | break; 248 | } 249 | case FSA_COMMAND_WRITE_FILE: { 250 | 251 | auto *request = ¶m->shim->request.writeFile; 252 | if (request->writeFlags == FSA_WRITE_FLAG_NONE) { 253 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] WriteFile: buffer %08X size %08X count %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->handle); 254 | layerResult = layer->FSWriteFileWrapper(request->buffer, request->size, request->count, request->handle, 0); 255 | } else if (request->writeFlags == FSA_WRITE_FLAG_READ_WITH_POS) { 256 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] WriteFileWithPos: buffer %08X size %08X count %08X pos %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->pos, request->handle); 257 | layerResult = layer->FSWriteFileWithPosWrapper(request->buffer, request->size, request->count, request->pos, request->handle, 0); 258 | } 259 | break; 260 | } 261 | case FSA_COMMAND_REMOVE: { 262 | auto *request = ¶m->shim->request.remove; 263 | auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path); 264 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Remove: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str()); 265 | layerResult = layer->FSRemoveWrapper(fullPath.c_str()); 266 | break; 267 | } 268 | case FSA_COMMAND_RENAME: { 269 | auto *request = ¶m->shim->request.rename; 270 | auto fullOldPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->oldPath); 271 | auto fullNewPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->newPath); 272 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Rename: %s -> %s (full path: %s -> %s)", layer->getName().c_str(), request->oldPath, request->newPath, fullOldPath.c_str(), fullNewPath.c_str()); 273 | layerResult = layer->FSRenameWrapper(fullOldPath.c_str(), fullNewPath.c_str()); 274 | break; 275 | } 276 | case FSA_COMMAND_FLUSH_FILE: { 277 | auto *request = ¶m->shim->request.flushFile; 278 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] FlushFile: %08X", layer->getName().c_str(), request->handle); 279 | layerResult = layer->FSFlushFileWrapper(request->handle); 280 | break; 281 | } 282 | case FSA_COMMAND_CHANGE_DIR: { 283 | auto *request = ¶m->shim->request.changeDir; 284 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] ChangeDir: %s", layer->getName().c_str(), request->path); 285 | setWorkingDir((FSAClientHandle) param->shim->clientHandle, request->path); 286 | // We still want to call the original function. 287 | layerResult = FS_ERROR_FORCE_PARENT_LAYER; 288 | break; 289 | } 290 | case FSA_COMMAND_GET_CWD: { 291 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_GET_CWD hook not implemented"); 292 | break; 293 | } 294 | case FSA_COMMAND_APPEND_FILE: { 295 | auto *request = ¶m->shim->request.appendFile; 296 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_APPEND_FILE hook not implemented for handle %08X", request->handle); 297 | break; 298 | } 299 | case FSA_COMMAND_FLUSH_MULTI_QUOTA: { 300 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_FLUSH_MULTI_QUOTA hook not implemented"); 301 | break; 302 | } 303 | case FSA_COMMAND_OPEN_FILE_BY_STAT: { 304 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_OPEN_FILE_BY_STAT hook not implemented"); 305 | break; 306 | } 307 | case FSA_COMMAND_CHANGE_OWNER: { 308 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_CHANGE_OWNER hook not implemented"); 309 | break; 310 | } 311 | case FSA_COMMAND_CHANGE_MODE: { 312 | DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_CHANGE_OWNER hook not implemented"); 313 | break; 314 | } 315 | default: { 316 | break; 317 | } 318 | } 319 | #pragma GCC diagnostic pop 320 | if (layerResult != FS_ERROR_FORCE_PARENT_LAYER) { 321 | auto maskedResult = (FSError) ((layerResult & FS_ERROR_REAL_MASK) | FS_ERROR_EXTRA_MASK); 322 | auto result = layerResult >= 0 ? layerResult : maskedResult; 323 | 324 | if (result < FS_ERROR_OK && result != FS_ERROR_END_OF_FILE && result != FS_ERROR_END_OF_DIR && result != FS_ERROR_CANCELLED) { 325 | if (layer->fallbackOnError()) { 326 | // Only fallback if FS_ERROR_FORCE_NO_FALLBACK flag is not set. 327 | if (static_cast(layerResult & FS_ERROR_EXTRA_MASK) != FS_ERROR_FORCE_NO_FALLBACK) { 328 | continue; 329 | } 330 | } 331 | } 332 | if (param->sync == FS_SHIM_TYPE_SYNC) { 333 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Return with result %08X %s", layer->getName().c_str(), result, result <= 0 ? FSAGetStatusStr(result) : ""); 334 | return result; 335 | } else if (param->sync == FS_SHIM_TYPE_ASYNC) { 336 | // convert to IOSError 337 | auto err = (IOSError) result; 338 | if (result == FS_ERROR_INVALID_BUFFER) { 339 | err = IOS_ERROR_ACCESS; 340 | } else if (result == FS_ERROR_INVALID_CLIENTHANDLE) { 341 | err = IOS_ERROR_INVALID; 342 | } else if (result == FS_ERROR_BUSY) { 343 | err = IOS_ERROR_QFULL; 344 | } 345 | 346 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call async callback :) with result %08X %s", layer->getName().c_str(), err, result <= 0 ? FSAGetStatusStr(result) : ""); 347 | param->asyncFS.callback(err, ¶m->asyncFS); 348 | 349 | return FS_ERROR_OK; 350 | } else { 351 | // This should never happen. 352 | DEBUG_FUNCTION_LINE_ERR("Unknown sync type."); 353 | OSFatal("ContentRedirectionModule: Unknown sync type."); 354 | } 355 | } else { 356 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call parent layer / real function", layer->getName().c_str()); 357 | } 358 | } 359 | } 360 | } 361 | return FS_ERROR_FORCE_REAL_FUNCTION; 362 | } 363 | 364 | FSCmdBlockBody *fsCmdBlockGetBody(FSCmdBlock *cmdBlock) { 365 | if (!cmdBlock) { 366 | return nullptr; 367 | } 368 | 369 | auto body = (FSCmdBlockBody *) (ROUNDUP((uint32_t) cmdBlock, 0x40)); 370 | return body; 371 | } 372 | 373 | FSClientBody *fsClientGetBody(FSClient *client) { 374 | if (!client) { 375 | return nullptr; 376 | } 377 | 378 | auto body = (FSClientBody *) (ROUNDUP((uint32_t) client, 0x40)); 379 | body->client = client; 380 | return body; 381 | } 382 | 383 | FSStatus handleAsyncResult(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus status) { 384 | if (asyncData->callback != nullptr) { 385 | if (asyncData->ioMsgQueue != nullptr) { 386 | DEBUG_FUNCTION_LINE_ERR("callback and ioMsgQueue both set."); 387 | OSFatal("ContentRedirectionModule: callback and ioMsgQueue both set."); 388 | } 389 | // userCallbacks are called in the DefaultAppIOQueue. 390 | asyncData->ioMsgQueue = OSGetDefaultAppIOQueue(); 391 | } 392 | 393 | if (asyncData->ioMsgQueue != nullptr) { 394 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 395 | FSAsyncResult *result = &(fsCmdBlockGetBody(block)->asyncResult); 396 | //DEBUG_FUNCTION_LINE("Send result %d to ioMsgQueue (%08X)", status, asyncData->ioMsgQueue); 397 | result->asyncData.callback = asyncData->callback; 398 | result->asyncData.param = asyncData->param; 399 | result->asyncData.ioMsgQueue = asyncData->ioMsgQueue; 400 | memset(&result->ioMsg, 0, sizeof(result->ioMsg)); 401 | result->ioMsg.data = result; 402 | result->ioMsg.type = OS_FUNCTION_TYPE_FS_CMD_ASYNC; 403 | result->client = client; 404 | result->block = block; 405 | result->status = status; 406 | 407 | OSMemoryBarrier(); 408 | while (!OSSendMessage(asyncData->ioMsgQueue, (OSMessage *) &(result->ioMsg), OS_MESSAGE_FLAGS_NONE)) { 409 | DEBUG_FUNCTION_LINE_ERR("Failed to send message"); 410 | } 411 | } 412 | return FS_STATUS_OK; 413 | } 414 | 415 | int64_t readIntoBuffer(int32_t handle, void *buffer, size_t size, size_t count) { 416 | auto sizeToRead = size * count; 417 | /* 418 | // https://github.com/decaf-emu/decaf-emu/blob/131aeb14fccff8461a5fd9f2aa5c040ba3880ef5/src/libdecaf/src/cafe/libraries/coreinit/coreinit_fs_cmd.cpp#L2346 419 | if (sizeToRead > 0x100000) { 420 | sizeToRead = 0x100000; 421 | }*/ 422 | void *newBuffer = buffer; 423 | int32_t curResult; 424 | int64_t totalSize = 0; 425 | while (sizeToRead > 0) { 426 | 427 | curResult = read(handle, newBuffer, sizeToRead); 428 | if (curResult < 0) { 429 | DEBUG_FUNCTION_LINE_ERR("Reading %08X bytes from handle %08X failed. result %08X errno: %d ", size * count, handle, curResult, errno); 430 | return -1; 431 | } 432 | if (curResult == 0) { 433 | break; 434 | } 435 | newBuffer = (void *) (((uint32_t) newBuffer) + curResult); 436 | totalSize += curResult; 437 | sizeToRead -= curResult; 438 | } 439 | return totalSize; 440 | } 441 | 442 | int64_t writeFromBuffer(int32_t handle, const void *buffer, size_t size, size_t count) { 443 | auto sizeToWrite = size * count; 444 | auto *ptr = buffer; 445 | int32_t curResult; 446 | int64_t totalSize = 0; 447 | while (sizeToWrite > 0) { 448 | curResult = write(handle, ptr, sizeToWrite); 449 | if (curResult < 0) { 450 | DEBUG_FUNCTION_LINE_ERR("Writing %08X bytes from handle %08X failed. result %08X errno: %d ", size * count, handle, curResult, errno); 451 | return -1; 452 | } 453 | if (curResult == 0) { 454 | break; 455 | } 456 | ptr = (void *) (((uint32_t) ptr) + curResult); 457 | totalSize += curResult; 458 | sizeToWrite -= curResult; 459 | } 460 | return totalSize; 461 | } 462 | 463 | FSIOThreadData gThreadData[3]; 464 | bool gThreadsRunning = false; 465 | 466 | static int32_t fsIOthreadCallback([[maybe_unused]] int argc, const char **argv) { 467 | auto *magic = ((FSIOThreadData *) argv); 468 | 469 | DEBUG_FUNCTION_LINE_VERBOSE("Hello from IO Thread for core: %d", OSGetCoreId()); 470 | constexpr int32_t messageSize = sizeof(magic->messages) / sizeof(magic->messages[0]); 471 | OSInitMessageQueue(&magic->queue, magic->messages, messageSize); 472 | 473 | OSMessage recv; 474 | while (OSReceiveMessage(&magic->queue, &recv, OS_MESSAGE_FLAGS_BLOCKING)) { 475 | if (recv.args[0] == FS_IO_QUEUE_COMMAND_STOP) { 476 | DEBUG_FUNCTION_LINE_VERBOSE("Received break command! Stop thread"); 477 | break; 478 | } else if (recv.args[0] == FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND) { 479 | auto *message = (FSShimWrapperMessage *) recv.message; 480 | auto *param = (FSShimWrapper *) message->param; 481 | FSError res = FS_ERROR_MEDIA_ERROR; 482 | auto syncType = param->sync; 483 | 484 | if (param->api == FS_SHIM_API_FS) { 485 | res = processShimBufferForFS(param); 486 | } else if (param->api == FS_SHIM_API_FSA) { 487 | res = processShimBufferForFSA(param); 488 | } else { 489 | DEBUG_FUNCTION_LINE_ERR("Incompatible API type %d", param->api); 490 | OSFatal("ContentRedirectionModule: Incompatible API type"); 491 | } 492 | // param is free'd at this point!!! 493 | if (syncType == FS_SHIM_TYPE_SYNC) { 494 | // For sync messages we can't (and don't need to) free "message", because it contains the queue we're about to use. 495 | // But this is not a problem because it's sync anyway. 496 | OSMessage send; 497 | send.args[0] = FS_IO_QUEUE_SYNC_RESULT; 498 | send.args[1] = (uint32_t) res; 499 | if (!OSSendMessage(&message->messageQueue, &send, OS_MESSAGE_FLAGS_NONE)) { 500 | DEBUG_FUNCTION_LINE_ERR("Failed to send message"); 501 | OSFatal("ContentRedirectionModule: Failed to send message"); 502 | } 503 | 504 | } else if (syncType == FS_SHIM_TYPE_ASYNC) { 505 | // If it's async we need to clean up "message" :) 506 | free(message); 507 | } 508 | } 509 | } 510 | 511 | return 0; 512 | } 513 | 514 | void startFSIOThreads() { 515 | int32_t threadAttributes[] = {OS_THREAD_ATTRIB_AFFINITY_CPU0, OS_THREAD_ATTRIB_AFFINITY_CPU1, OS_THREAD_ATTRIB_AFFINITY_CPU2}; 516 | auto stackSize = 16 * 1024; 517 | 518 | int coreId = 0; 519 | for (int core : threadAttributes) { 520 | auto *threadData = &gThreadData[coreId]; 521 | memset(threadData, 0, sizeof(*threadData)); 522 | threadData->setup = false; 523 | threadData->thread = (OSThread *) memalign(8, sizeof(OSThread)); 524 | if (!threadData->thread) { 525 | DEBUG_FUNCTION_LINE_ERR("Failed to allocate threadData"); 526 | OSFatal("ContentRedirectionModule: Failed to allocate IO Thread"); 527 | continue; 528 | } 529 | threadData->stack = (uint8_t *) memalign(0x20, stackSize); 530 | if (!threadData->thread) { 531 | free(threadData->thread); 532 | DEBUG_FUNCTION_LINE_ERR("Failed to allocate threadData stack"); 533 | OSFatal("ContentRedirectionModule: Failed to allocate IO Thread stack"); 534 | continue; 535 | } 536 | 537 | OSMemoryBarrier(); 538 | 539 | if (!OSCreateThread(threadData->thread, &fsIOthreadCallback, 1, (char *) threadData, reinterpret_cast((uint32_t) threadData->stack + stackSize), stackSize, 0, core)) { 540 | free(threadData->thread); 541 | free(threadData->stack); 542 | threadData->setup = false; 543 | DEBUG_FUNCTION_LINE_ERR("failed to create threadData"); 544 | OSFatal("ContentRedirectionModule: Failed to create threadData"); 545 | } 546 | 547 | strncpy(threadData->threadName, string_format("ContentRedirection IO Thread %d", coreId).c_str(), sizeof(threadData->threadName) - 1); 548 | OSSetThreadName(threadData->thread, threadData->threadName); 549 | OSResumeThread(threadData->thread); 550 | threadData->setup = true; 551 | coreId++; 552 | } 553 | 554 | gThreadsRunning = true; 555 | OSMemoryBarrier(); 556 | } 557 | 558 | void stopFSIOThreads() { 559 | if (!gThreadsRunning) { 560 | return; 561 | } 562 | for (auto &gThread : gThreadData) { 563 | auto *thread = &gThread; 564 | if (!thread->setup) { 565 | continue; 566 | } 567 | OSMessage message; 568 | message.args[0] = FS_IO_QUEUE_COMMAND_STOP; 569 | OSSendMessage(&thread->queue, &message, OS_MESSAGE_FLAGS_NONE); 570 | 571 | if (OSIsThreadSuspended(thread->thread)) { 572 | OSResumeThread(thread->thread); 573 | } 574 | 575 | OSJoinThread(thread->thread, nullptr); 576 | if (thread->stack) { 577 | free(thread->stack); 578 | thread->stack = nullptr; 579 | } 580 | if (thread->thread) { 581 | free(thread->thread); 582 | thread->thread = nullptr; 583 | } 584 | } 585 | 586 | gThreadsRunning = false; 587 | } -------------------------------------------------------------------------------- /src/FSWrapper.cpp: -------------------------------------------------------------------------------- 1 | #include "FSWrapper.h" 2 | #include "FileUtils.h" 3 | #include "utils/StringTools.h" 4 | #include "utils/logger.h" 5 | #include "utils/utils.h" 6 | 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | FSError FSWrapper::FSOpenDirWrapper(const char *path, FSDirectoryHandle *handle) { 19 | if (path == nullptr) { 20 | return FS_ERROR_INVALID_PARAM; 21 | } 22 | if (!IsPathToReplace(path)) { 23 | return FS_ERROR_FORCE_PARENT_LAYER; 24 | } 25 | 26 | if (handle == nullptr) { 27 | DEBUG_FUNCTION_LINE_ERR("[%s] handle was nullptr", getName().c_str()); 28 | return FS_ERROR_INVALID_PARAM; 29 | } 30 | 31 | FSError result = FS_ERROR_OK; 32 | 33 | const auto dirHandle = getNewDirInfoHandle(); 34 | if (dirHandle) { 35 | DIR *dir; 36 | auto newPath = GetNewPath(path); 37 | 38 | if ((dir = opendir(newPath.c_str()))) { 39 | dirHandle->dir = dir; 40 | dirHandle->handle = (((uint32_t) dirHandle.get()) & 0x0FFFFFFF) | 0x30000000; 41 | *handle = dirHandle->handle; 42 | 43 | dirHandle->path[0] = '\0'; 44 | strncat(dirHandle->path, newPath.c_str(), sizeof(dirHandle->path) - 1); 45 | addDirHandle(dirHandle); 46 | } else { 47 | auto err = errno; 48 | if (err == ENOENT) { 49 | DEBUG_FUNCTION_LINE("[%s] Open dir %s (%s) failed. FS_ERROR_NOT_FOUND", getName().c_str(), path, newPath.c_str()); 50 | return FS_ERROR_NOT_FOUND; 51 | } 52 | DEBUG_FUNCTION_LINE_ERR("[%s] Open dir %s (%s) failed. errno %d", getName().c_str(), path, newPath.c_str(), err); 53 | if (err == EACCES) { 54 | return FS_ERROR_PERMISSION_ERROR; 55 | } else if (err == ENOTDIR) { 56 | return FS_ERROR_NOT_DIR; 57 | } else if (err == ENFILE || err == EMFILE) { 58 | return FS_ERROR_MAX_DIRS; 59 | } 60 | return FS_ERROR_MEDIA_ERROR; 61 | } 62 | } else { 63 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc dir handle", getName().c_str()); 64 | result = FS_ERROR_MAX_DIRS; 65 | } 66 | return result; 67 | } 68 | 69 | FSError FSWrapper::FSReadDirWrapper(const FSDirectoryHandle handle, FSDirectoryEntry *entry) { 70 | if (!isValidDirHandle(handle)) { 71 | return FS_ERROR_FORCE_PARENT_LAYER; 72 | } 73 | const auto dirHandle = getDirInfoFromHandle(handle); 74 | 75 | DIR *dir = dirHandle->dir; 76 | 77 | FSError result = FS_ERROR_END_OF_DIR; 78 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] readdir %08X (handle %08X)", getName().c_str(), dir, handle); 79 | do { 80 | errno = 0; 81 | struct dirent *entry_ = readdir(dir); 82 | 83 | if (entry_) { 84 | if (SkipDeletedFilesInReadDir() && starts_with_case_insensitive(entry_->d_name, deletePrefix)) { 85 | DEBUG_FUNCTION_LINE_ERR("Skip file file name %s because of the prefix", entry_->d_name); 86 | continue; 87 | } 88 | entry->name[0] = '\0'; 89 | strncat(entry->name, entry_->d_name, sizeof(entry->name) - 1); 90 | entry->info.mode = (FSMode) FS_MODE_READ_OWNER; 91 | if (entry_->d_type == DT_DIR) { 92 | entry->info.flags = (FSStatFlags) ((uint32_t) FS_STAT_DIRECTORY); 93 | entry->info.size = 0; 94 | } else { 95 | entry->info.flags = (FSStatFlags) 0; 96 | if (strcmp(entry_->d_name, ".") == 0 || strcmp(entry_->d_name, "..") == 0) { 97 | entry->info.size = 0; 98 | } else { 99 | #ifdef _DIRENT_HAVE_D_STAT 100 | translate_stat(&entry_->d_stat, &entry->info); 101 | #else 102 | struct stat sb {}; 103 | auto path = string_format("%s/%s", dirHandle->path, entry_->d_name); 104 | std::replace(path.begin(), path.end(), '\\', '/'); 105 | 106 | uint32_t length = path.size(); 107 | 108 | //! clear path of double slashes 109 | for (uint32_t i = 1; i < length; ++i) { 110 | if (path[i - 1] == '/' && path[i] == '/') { 111 | path.erase(i, 1); 112 | i--; 113 | length--; 114 | } 115 | } 116 | 117 | if (stat(path.c_str(), &sb) >= 0) { 118 | translate_stat(&sb, &entry->info); 119 | } else { 120 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to stat file (%s) in read dir %08X (dir handle %08X)", getName().c_str(), path.c_str(), dir, handle); 121 | result = FS_ERROR_MEDIA_ERROR; 122 | break; 123 | } 124 | #endif 125 | } 126 | } 127 | result = FS_ERROR_OK; 128 | } else { 129 | auto err = errno; 130 | if (err != 0) { 131 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to read dir %08X (handle %08X). errno %d (%s)", getName().c_str(), dir, handle, err, strerror(err)); 132 | result = FS_ERROR_MEDIA_ERROR; 133 | } 134 | } 135 | break; 136 | } while (true); 137 | return result; 138 | } 139 | 140 | FSError FSWrapper::FSCloseDirWrapper(const FSDirectoryHandle handle) { 141 | if (!isValidDirHandle(handle)) { 142 | return FS_ERROR_FORCE_PARENT_LAYER; 143 | } 144 | const auto dirHandle = getDirInfoFromHandle(handle); 145 | 146 | DIR *dir = dirHandle->dir; 147 | 148 | FSError result = FS_ERROR_OK; 149 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] closedir %08X (handle %08X)", getName().c_str(), dir, handle); 150 | if (closedir(dir) < 0) { 151 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close dir %08X (handle %08X)", getName().c_str(), dir, handle); 152 | result = FS_ERROR_MEDIA_ERROR; 153 | } 154 | dirHandle->dir = nullptr; 155 | 156 | return result; 157 | } 158 | 159 | FSError FSWrapper::FSRewindDirWrapper(const FSDirectoryHandle handle) { 160 | if (!isValidDirHandle(handle)) { 161 | return FS_ERROR_FORCE_PARENT_LAYER; 162 | } 163 | const auto dirHandle = getDirInfoFromHandle(handle); 164 | 165 | DIR *dir = dirHandle->dir; 166 | 167 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] rewinddir %08X (handle %08X)", getName().c_str(), dir, handle); 168 | rewinddir(dir); 169 | 170 | return FS_ERROR_OK; 171 | } 172 | 173 | FSError FSWrapper::FSMakeDirWrapper(const char *path) { 174 | if (!IsPathToReplace(path)) { 175 | return FS_ERROR_FORCE_PARENT_LAYER; 176 | } 177 | if (!pIsWriteable) { 178 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to create dir %s but layer is not writeable", getName().c_str(), path); 179 | return FS_ERROR_PERMISSION_ERROR; 180 | } 181 | auto newPath = GetNewPath(path); 182 | 183 | auto res = mkdir(newPath.c_str(), 0000660); 184 | if (res < 0) { 185 | auto err = errno; 186 | if (err == EACCES) { 187 | return FS_ERROR_PERMISSION_ERROR; 188 | } else if (err == EEXIST) { 189 | return FS_ERROR_ALREADY_EXISTS; 190 | } else if (err == ENOTDIR) { 191 | return FS_ERROR_NOT_DIR; 192 | } else if (err == ENOENT) { 193 | return FS_ERROR_NOT_FOUND; 194 | } 195 | return FS_ERROR_MEDIA_ERROR; 196 | } 197 | return FS_ERROR_OK; 198 | } 199 | 200 | FSError FSWrapper::FSOpenFileWrapper(const char *path, const char *mode, FSFileHandle *handle) { 201 | if (!IsPathToReplace(path)) { 202 | return FS_ERROR_FORCE_PARENT_LAYER; 203 | } 204 | 205 | if (path == nullptr) { 206 | DEBUG_FUNCTION_LINE_ERR("[%s] path was nullptr", getName().c_str()); 207 | return FS_ERROR_INVALID_PARAM; 208 | } 209 | 210 | if (mode == nullptr || handle == nullptr) { 211 | DEBUG_FUNCTION_LINE_ERR("[%s] mode or handle was nullptr", getName().c_str()); 212 | return FS_ERROR_INVALID_PARAM; 213 | } 214 | 215 | auto newPath = GetNewPath(path); 216 | 217 | if (pCheckIfDeleted && CheckFileShouldBeIgnored(newPath)) { 218 | return static_cast((FS_ERROR_NOT_FOUND & FS_ERROR_REAL_MASK) | FS_ERROR_FORCE_NO_FALLBACK); 219 | } 220 | 221 | auto result = FS_ERROR_OK; 222 | int _mode; 223 | // Map flags to open modes 224 | if (!IsFileModeAllowed(mode)) { 225 | OSReport("## WARN ## [%s] Given mode is not allowed %s", getName().c_str(), mode); 226 | DEBUG_FUNCTION_LINE("[%s] Given mode is not allowed %s", getName().c_str(), mode); 227 | return FS_ERROR_ACCESS_ERROR; 228 | } 229 | 230 | if (strcmp(mode, "r") == 0 || strcmp(mode, "rb") == 0) { 231 | _mode = O_RDONLY; 232 | } else if (strcmp(mode, "r+") == 0) { 233 | _mode = O_RDWR; 234 | } else if (strcmp(mode, "w") == 0 || strcmp(mode, "wb") == 0) { 235 | _mode = O_WRONLY | O_CREAT | O_TRUNC; 236 | } else if (strcmp(mode, "w+") == 0) { 237 | _mode = O_RDWR | O_CREAT | O_TRUNC; 238 | } else if (strcmp(mode, "a") == 0) { 239 | _mode = O_WRONLY | O_CREAT | O_APPEND; 240 | } else if (strcmp(mode, "a+") == 0) { 241 | _mode = O_RDWR | O_CREAT | O_APPEND; 242 | } else { 243 | DEBUG_FUNCTION_LINE_ERR("[%s] mode \"%s\" was allowed but is unsupported", getName().c_str(), mode); 244 | return FS_ERROR_ACCESS_ERROR; 245 | } 246 | 247 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Open %s (as %s) mode %s,", getName().c_str(), path, newPath.c_str(), mode); 248 | int32_t fd = open(newPath.c_str(), _mode); 249 | if (fd >= 0) { 250 | auto fileHandle = getNewFileHandle(); 251 | if (fileHandle) { 252 | std::lock_guard lock(openFilesMutex); 253 | 254 | fileHandle->handle = (((uint32_t) fileHandle.get()) & 0x0FFFFFFF) | 0x30000000; 255 | *handle = fileHandle->handle; 256 | fileHandle->fd = fd; 257 | 258 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Opened %s (as %s) mode %s (%08X), fd %d (%08X)", getName().c_str(), path, newPath.c_str(), mode, _mode, fd, fileHandle->handle); 259 | 260 | openFiles.push_back(fileHandle); 261 | 262 | OSMemoryBarrier(); 263 | } else { 264 | close(fd); 265 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc new fileHandle", getName().c_str()); 266 | result = FS_ERROR_MAX_FILES; 267 | } 268 | } else { 269 | auto err = errno; 270 | if (err == ENOENT) { 271 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] File not found %s (%s)", getName().c_str(), path, newPath.c_str()); 272 | result = FS_ERROR_NOT_FOUND; 273 | } else { 274 | DEBUG_FUNCTION_LINE("[%s] Open file %s (%s) failed. errno %d ", getName().c_str(), path, newPath.c_str(), err); 275 | if (err == EACCES) { 276 | return FS_ERROR_PERMISSION_ERROR; 277 | } else if (err == ENOENT) { 278 | result = FS_ERROR_NOT_FOUND; 279 | } else if (err == EEXIST) { 280 | result = FS_ERROR_ALREADY_EXISTS; 281 | } else if (err == EISDIR) { 282 | result = FS_ERROR_NOT_FILE; 283 | } else if (err == ENOTDIR) { 284 | result = FS_ERROR_NOT_DIR; 285 | } else if (err == ENFILE || err == EMFILE) { 286 | result = FS_ERROR_MAX_FILES; 287 | } else { 288 | result = FS_ERROR_MEDIA_ERROR; 289 | } 290 | } 291 | } 292 | 293 | return result; 294 | } 295 | 296 | FSError FSWrapper::FSCloseFileWrapper(const FSFileHandle handle) { 297 | if (!isValidFileHandle(handle)) { 298 | return FS_ERROR_FORCE_PARENT_LAYER; 299 | } 300 | 301 | auto fileHandle = getFileFromHandle(handle); 302 | 303 | int real_fd = fileHandle->fd; 304 | 305 | FSError result = FS_ERROR_OK; 306 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Close %d (handle %08X)", getName().c_str(), real_fd, handle); 307 | if (close(real_fd) != 0) { 308 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close %d (handle %08X) ", getName().c_str(), real_fd, handle); 309 | result = FS_ERROR_MEDIA_ERROR; 310 | } 311 | fileHandle->fd = -1; 312 | return result; 313 | } 314 | 315 | bool FSWrapper::CheckFileShouldBeIgnored(std::string &path) { 316 | auto asPath = std::filesystem::path(path); 317 | 318 | if (starts_with_case_insensitive(asPath.filename().c_str(), deletePrefix)) { 319 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Ignore %s, filename starts with %s", getName().c_str(), path.c_str(), deletePrefix.c_str()); 320 | return true; 321 | } 322 | 323 | auto newDelPath = asPath.replace_filename(deletePrefix + asPath.filename().c_str()); 324 | struct stat buf {}; 325 | if (stat(newDelPath.c_str(), &buf) == 0) { 326 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Ignore %s, file %s exists", getName().c_str(), path.c_str(), newDelPath.c_str()); 327 | return true; 328 | } 329 | return false; 330 | } 331 | 332 | FSError FSWrapper::FSGetStatWrapper(const char *path, FSStat *stats) { 333 | if (path == nullptr || stats == nullptr) { 334 | DEBUG_FUNCTION_LINE_ERR("[%s] path was or stats nullptr", getName().c_str()); 335 | return FS_ERROR_INVALID_PARAM; 336 | } 337 | 338 | if (!IsPathToReplace(path)) { 339 | return FS_ERROR_FORCE_PARENT_LAYER; 340 | } 341 | auto newPath = GetNewPath(path); 342 | 343 | struct stat path_stat {}; 344 | 345 | if (pCheckIfDeleted && CheckFileShouldBeIgnored(newPath)) { 346 | return static_cast((FS_ERROR_NOT_FOUND & FS_ERROR_REAL_MASK) | FS_ERROR_FORCE_NO_FALLBACK); 347 | } 348 | 349 | FSError result = FS_ERROR_OK; 350 | 351 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] stat of %s (%s)", getName().c_str(), path, newPath.c_str()); 352 | if (stat(newPath.c_str(), &path_stat) < 0) { 353 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Path %s (%s) not found ", getName().c_str(), path, newPath.c_str()); 354 | result = FS_ERROR_NOT_FOUND; 355 | } else { 356 | translate_stat(&path_stat, stats); 357 | } 358 | return result; 359 | } 360 | 361 | FSError FSWrapper::FSGetStatFileWrapper(const FSFileHandle handle, FSStat *stats) { 362 | if (!isValidFileHandle(handle)) { 363 | return FS_ERROR_FORCE_PARENT_LAYER; 364 | } 365 | auto fileHandle = getFileFromHandle(handle); 366 | 367 | int real_fd = fileHandle->fd; 368 | 369 | struct stat path_stat {}; 370 | 371 | FSError result = FS_ERROR_OK; 372 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] fstat of fd %d (FSFileHandle %08X)", getName().c_str(), real_fd, handle); 373 | if (fstat(real_fd, &path_stat) < 0) { 374 | DEBUG_FUNCTION_LINE_ERR("[%s] fstat of fd %d (FSFileHandle %08X) failed", getName().c_str(), real_fd, handle); 375 | result = FS_ERROR_MEDIA_ERROR; 376 | } else { 377 | translate_stat(&path_stat, stats); 378 | } 379 | 380 | return result; 381 | } 382 | 383 | FSError FSWrapper::FSReadFileWrapper(void *buffer, const uint32_t size, const uint32_t count, const FSFileHandle handle, [[maybe_unused]] uint32_t unk1) { 384 | if (!isValidFileHandle(handle)) { 385 | return FS_ERROR_FORCE_PARENT_LAYER; 386 | } 387 | 388 | if (size * count == 0) { 389 | return FS_ERROR_OK; 390 | } 391 | 392 | if (buffer == nullptr) { 393 | DEBUG_FUNCTION_LINE_ERR("[%s] buffer is null but size * count is not 0 (It's: %d)", getName().c_str(), size * count); 394 | return FS_ERROR_INVALID_BUFFER; 395 | } 396 | 397 | auto fileHandle = getFileFromHandle(handle); 398 | int real_fd = fileHandle->fd; 399 | 400 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Read %u bytes of fd %08X (FSFileHandle %08X) to buffer %08X", getName().c_str(), size * count, real_fd, handle, buffer); 401 | int64_t read = readIntoBuffer(real_fd, buffer, size, count); 402 | 403 | FSError result; 404 | if (read < 0) { 405 | DEBUG_FUNCTION_LINE_ERR("[%s] Read %u bytes of fd %d (FSFileHandle %08X) failed", getName().c_str(), size * count, real_fd, handle); 406 | auto err = errno; 407 | if (err == EBADF || err == EROFS) { 408 | return FS_ERROR_ACCESS_ERROR; 409 | } 410 | result = FS_ERROR_MEDIA_ERROR; 411 | } else { 412 | result = static_cast(((uint32_t) read) / size); 413 | } 414 | 415 | return result; 416 | } 417 | 418 | FSError FSWrapper::FSReadFileWithPosWrapper(void *buffer, const uint32_t size, const uint32_t count, const uint32_t pos, const FSFileHandle handle, const int32_t unk1) { 419 | if (!isValidFileHandle(handle)) { 420 | return FS_ERROR_FORCE_PARENT_LAYER; 421 | } 422 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Read from with position.", getName().c_str()); 423 | FSError result; 424 | if ((result = this->FSSetPosFileWrapper(handle, pos)) != FS_ERROR_OK) { 425 | return result; 426 | } 427 | 428 | result = this->FSReadFileWrapper(buffer, size, count, handle, unk1); 429 | 430 | return result; 431 | } 432 | 433 | FSError FSWrapper::FSSetPosFileWrapper(const FSFileHandle handle, const uint32_t pos) { 434 | if (!isValidFileHandle(handle)) { 435 | return FS_ERROR_FORCE_PARENT_LAYER; 436 | } 437 | auto fileHandle = getFileFromHandle(handle); 438 | 439 | FSError result = FS_ERROR_OK; 440 | 441 | int real_fd = fileHandle->fd; 442 | 443 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %d (FSFileHandle %08X) SEEK_SET to position %08X", getName().c_str(), real_fd, handle, pos); 444 | off_t newPos; 445 | if ((newPos = lseek(real_fd, (off_t) pos, SEEK_SET)) != pos) { 446 | DEBUG_FUNCTION_LINE_ERR("[%s] lseek fd %d (FSFileHandle %08X) to position %08X failed", getName().c_str(), real_fd, handle, pos); 447 | if (newPos < 0) { 448 | // TODO: read errno 449 | } 450 | result = FS_ERROR_MEDIA_ERROR; 451 | } else { 452 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] pos set to %u for fd %d (FSFileHandle %08X)", getName().c_str(), pos, real_fd, handle); 453 | } 454 | 455 | return result; 456 | } 457 | 458 | FSError FSWrapper::FSGetPosFileWrapper(const FSFileHandle handle, uint32_t *pos) { 459 | if (!isValidFileHandle(handle)) { 460 | return FS_ERROR_FORCE_PARENT_LAYER; 461 | } 462 | auto fileHandle = getFileFromHandle(handle); 463 | 464 | FSError result = FS_ERROR_OK; 465 | 466 | int real_fd = fileHandle->fd; 467 | 468 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for truncation", getName().c_str(), real_fd, handle); 469 | off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR); 470 | if (currentPos == -1) { 471 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position (res: %lld) of fd (handle %08X) to check EoF", getName().c_str(), currentPos, real_fd, handle); 472 | result = FS_ERROR_MEDIA_ERROR; 473 | } else { 474 | *pos = currentPos; 475 | } 476 | return result; 477 | } 478 | 479 | FSError FSWrapper::FSIsEofWrapper(const FSFileHandle handle) { 480 | if (!isValidFileHandle(handle)) { 481 | return FS_ERROR_FORCE_PARENT_LAYER; 482 | } 483 | auto fileHandle = getFileFromHandle(handle); 484 | 485 | FSError result; 486 | 487 | int real_fd = fileHandle->fd; 488 | 489 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for EOF detection", getName().c_str(), real_fd, handle); 490 | off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR); 491 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get end position for EOF detection", getName().c_str(), real_fd, handle); 492 | off_t endPos = lseek(real_fd, (off_t) 0, SEEK_END); 493 | 494 | if (currentPos == -1 || endPos == -1) { 495 | // TODO: check errno 496 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position (res: %lld) or endPos (res: %lld) of fd (handle %08X) to check EoF", getName().c_str(), currentPos, endPos, real_fd, handle); 497 | result = FS_ERROR_MEDIA_ERROR; 498 | } else if (currentPos == endPos) { 499 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] FSIsEof END for %d\n", getName().c_str(), real_fd); 500 | result = FS_ERROR_END_OF_FILE; 501 | } else { 502 | lseek(real_fd, currentPos, SEEK_CUR); 503 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] FSIsEof OK for %d\n", getName().c_str(), real_fd); 504 | result = FS_ERROR_OK; 505 | } 506 | 507 | return result; 508 | } 509 | 510 | FSError FSWrapper::FSTruncateFileWrapper(const FSFileHandle handle) { 511 | if (!isValidFileHandle(handle)) { 512 | return FS_ERROR_FORCE_PARENT_LAYER; 513 | } 514 | 515 | if (!pIsWriteable) { 516 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to truncate fd %d (handle %08X) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle); 517 | return FS_ERROR_ACCESS_ERROR; 518 | } 519 | 520 | auto fileHandle = getFileFromHandle(handle); 521 | 522 | FSError result = FS_ERROR_OK; 523 | 524 | int real_fd = fileHandle->fd; 525 | 526 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for truncation", getName().c_str(), real_fd, handle); 527 | off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR); 528 | if (currentPos == -1) { 529 | // TODO check errno 530 | DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position of fd (handle %08X) to truncate file", getName().c_str(), real_fd, handle); 531 | result = FS_ERROR_MEDIA_ERROR; 532 | } else { 533 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Truncate fd %08X (FSFileHandle %08X) to %lld bytes ", getName().c_str(), real_fd, handle, currentPos); 534 | if (ftruncate(real_fd, currentPos) < 0) { 535 | DEBUG_FUNCTION_LINE_ERR("[%s] ftruncate failed for fd %08X (FSFileHandle %08X) errno %d", getName().c_str(), real_fd, handle, errno); 536 | result = FS_ERROR_MEDIA_ERROR; 537 | } 538 | } 539 | 540 | return result; 541 | } 542 | 543 | FSError FSWrapper::FSWriteFileWrapper(const uint8_t *buffer, const uint32_t size, const uint32_t count, const FSFileHandle handle, [[maybe_unused]] uint32_t unk1) { 544 | if (!isValidFileHandle(handle)) { 545 | return FS_ERROR_FORCE_PARENT_LAYER; 546 | } 547 | if (!pIsWriteable) { 548 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to write to fd %d (handle %08X) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle); 549 | return FS_ERROR_ACCESS_ERROR; 550 | } 551 | auto fileHandle = getFileFromHandle(handle); 552 | 553 | FSError result; 554 | 555 | int real_fd = fileHandle->fd; 556 | 557 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Write %u bytes to fd %08X (FSFileHandle %08X) from buffer %08X", getName().c_str(), count * size, real_fd, handle, buffer); 558 | auto writeRes = writeFromBuffer(real_fd, buffer, size, count); 559 | if (writeRes < 0) { 560 | auto err = errno; 561 | DEBUG_FUNCTION_LINE_ERR("[%s] Write failed %u bytes to fd %08X (FSFileHandle %08X) from buffer %08X errno %d", getName().c_str(), count * size, real_fd, handle, buffer, err); 562 | if (err == EFBIG) { 563 | result = FS_ERROR_FILE_TOO_BIG; 564 | } else if (err == EACCES) { 565 | result = FS_ERROR_ACCESS_ERROR; 566 | } else { 567 | result = FS_ERROR_MEDIA_ERROR; 568 | } 569 | } else { 570 | result = static_cast(static_cast(writeRes) / size); 571 | } 572 | 573 | return result; 574 | } 575 | 576 | FSError FSWrapper::FSRemoveWrapper(const char *path) { 577 | if (!IsPathToReplace(path)) { 578 | return FS_ERROR_FORCE_PARENT_LAYER; 579 | } 580 | if (!pIsWriteable) { 581 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to remove %s but layer is not writeable", getName().c_str(), path); 582 | return FS_ERROR_PERMISSION_ERROR; 583 | } 584 | auto newPath = GetNewPath(path); 585 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Remove %s (%s)", getName().c_str(), path, newPath.c_str()); 586 | if (remove(newPath.c_str()) < 0) { 587 | auto err = errno; 588 | DEBUG_FUNCTION_LINE_ERR("[%s] Rename failed %s (%s) errno %d", getName().c_str(), path, newPath.c_str(), err); 589 | if (err == ENOTDIR) { 590 | return FS_ERROR_NOT_DIR; 591 | } else if (err == EACCES) { 592 | return FS_ERROR_ACCESS_ERROR; 593 | } else if (err == EISDIR) { 594 | return FS_ERROR_NOT_FILE; 595 | } else if (err == EPERM) { 596 | return FS_ERROR_PERMISSION_ERROR; 597 | } 598 | return FS_ERROR_MEDIA_ERROR; 599 | } 600 | return FS_ERROR_OK; 601 | } 602 | 603 | FSError FSWrapper::FSRenameWrapper(const char *oldPath, const char *newPath) { 604 | if (!IsPathToReplace(oldPath) || !IsPathToReplace(newPath)) { 605 | return FS_ERROR_FORCE_PARENT_LAYER; 606 | } 607 | if (!pIsWriteable) { 608 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to rename %s to %s but layer is not writeable", getName().c_str(), oldPath, newPath); 609 | return FS_ERROR_PERMISSION_ERROR; 610 | } 611 | auto oldPathRedirect = GetNewPath(oldPath); 612 | auto newPathRedirect = GetNewPath(newPath); 613 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Rename %s (%s) -> %s (%s)", getName().c_str(), oldPath, oldPathRedirect.c_str(), newPath, newPathRedirect.c_str()); 614 | if (rename(oldPathRedirect.c_str(), newPathRedirect.c_str()) < 0) { 615 | auto err = errno; 616 | DEBUG_FUNCTION_LINE_ERR("[%s] Rename failed %s (%s) -> %s (%s). errno %d", getName().c_str(), oldPath, oldPathRedirect.c_str(), newPath, newPathRedirect.c_str(), err); 617 | if (err == ENOTDIR) { 618 | return FS_ERROR_NOT_DIR; 619 | } else if (err == EACCES) { 620 | return FS_ERROR_ACCESS_ERROR; 621 | } else if (err == EISDIR) { 622 | return FS_ERROR_NOT_FILE; 623 | } else if (err == EPERM) { 624 | return FS_ERROR_PERMISSION_ERROR; 625 | } 626 | return FS_ERROR_MEDIA_ERROR; 627 | } 628 | return FS_ERROR_OK; 629 | } 630 | 631 | FSError FSWrapper::FSFlushFileWrapper(const FSFileHandle handle) { 632 | if (!isValidFileHandle(handle)) { 633 | return FS_ERROR_FORCE_PARENT_LAYER; 634 | } 635 | if (!pIsWriteable) { 636 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to fsync fd %d (handle %08X)) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle); 637 | return FS_ERROR_ACCESS_ERROR; 638 | } 639 | 640 | const auto fileHandle = getFileFromHandle(handle); 641 | const int real_fd = fileHandle->fd; 642 | 643 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] fsync fd %08X (FSFileHandle %08X)", real_fd, handle); 644 | FSError result = FS_ERROR_OK; 645 | if (fsync(real_fd) < 0) { 646 | DEBUG_FUNCTION_LINE_ERR("[%s] fsync failed for fd %08X (FSFileHandle %08X)", getName().c_str(), real_fd, handle); 647 | auto err = errno; 648 | if (err == EBADF) { 649 | result = FS_ERROR_INVALID_FILEHANDLE; 650 | } else { 651 | result = FS_ERROR_MEDIA_ERROR; 652 | } 653 | } 654 | return result; 655 | } 656 | 657 | bool FSWrapper::IsFileModeAllowed(const char *mode) { 658 | if (strcmp(mode, "r") == 0 || strcmp(mode, "rb") == 0) { 659 | return true; 660 | } 661 | 662 | if (pIsWriteable && (strcmp(mode, "r+") == 0 || 663 | strcmp(mode, "w") == 0 || 664 | strcmp(mode, "wb") == 0 || 665 | strcmp(mode, "w+") == 0 || 666 | strcmp(mode, "a") == 0 || 667 | strcmp(mode, "a+") == 0)) { 668 | return true; 669 | } 670 | 671 | return false; 672 | } 673 | 674 | bool FSWrapper::IsPathToReplace(const std::string_view &path) { 675 | return starts_with_case_insensitive(path, pPathToReplace); 676 | } 677 | 678 | std::string FSWrapper::GetNewPath(const std::string_view &path) const { 679 | auto res = std::string(path); 680 | SafeReplaceInString(res, this->pPathToReplace, this->pReplacePathWith); 681 | 682 | std::ranges::replace(res, '\\', '/'); 683 | 684 | uint32_t length = res.size(); 685 | 686 | //! clear path of double slashes 687 | for (uint32_t i = 1; i < length; ++i) { 688 | if (res[i - 1] == '/' && res[i] == '/') { 689 | res.erase(i, 1); 690 | i--; 691 | length--; 692 | } 693 | } 694 | 695 | DEBUG_FUNCTION_LINE_VERBOSE("[%s] Redirect %.*s -> %s", getName().c_str(), int(path.length()), path.data(), res.c_str()); 696 | return res; 697 | } 698 | 699 | bool FSWrapper::isValidFileHandle(FSFileHandle handle) { 700 | std::lock_guard lock(openFilesMutex); 701 | return std::ranges::any_of(openFiles, [handle](auto &cur) { return cur->handle == handle; }); 702 | } 703 | 704 | bool FSWrapper::isValidDirHandle(FSDirectoryHandle handle) { 705 | std::lock_guard lock(openDirsMutex); 706 | return std::ranges::any_of(openDirs, [handle](auto &cur) { return cur->handle == handle; }); 707 | } 708 | 709 | 710 | std::shared_ptr FSWrapper::getNewFileHandle() { 711 | return make_shared_nothrow(); 712 | } 713 | 714 | std::shared_ptr FSWrapper::getNewDirInfoHandle() { 715 | return make_shared_nothrow(); 716 | } 717 | 718 | std::shared_ptr FSWrapper::getFileFromHandle(const FSFileHandle handle) { 719 | std::lock_guard lock(openFilesMutex); 720 | for (auto &file : openFiles) { 721 | if (file->handle == handle) { 722 | return file; 723 | } 724 | } 725 | DEBUG_FUNCTION_LINE_ERR("[%s] FileInfo for handle %08X was not found. isValidFileHandle check missing?", getName().c_str(), handle); 726 | OSFatal("ContentRedirectionModule: Failed to find file handle"); 727 | return nullptr; 728 | } 729 | 730 | std::shared_ptr FSWrapper::getDirFromHandle(const FSDirectoryHandle handle) { 731 | std::lock_guard lock(openDirsMutex); 732 | for (auto &dir : openDirs) { 733 | if (dir->handle == handle) { 734 | return dir; 735 | } 736 | } 737 | DEBUG_FUNCTION_LINE_ERR("[%s] DirInfo for handle %08X was not found. isValidDirHandle check missing?", getName().c_str(), handle); 738 | OSFatal("ContentRedirectionModule: Failed to find dir handle"); 739 | return nullptr; 740 | } 741 | 742 | void FSWrapper::addDirHandle(const std::shared_ptr &dirHandle) { 743 | std::lock_guard lock(openDirsMutex); 744 | openDirs.push_back(dirHandle); 745 | OSMemoryBarrier(); 746 | } 747 | 748 | void FSWrapper::deleteDirHandle(FSDirectoryHandle handle) { 749 | if (!remove_locked_first_if(openDirsMutex, openDirs, [handle](auto &cur) { return static_cast(cur->handle) == handle; })) { 750 | DEBUG_FUNCTION_LINE_ERR("[%s] Delete failed because the handle %08X was not found", getName().c_str(), handle); 751 | } 752 | } 753 | 754 | void FSWrapper::deleteFileHandle(FSFileHandle handle) { 755 | if (!remove_locked_first_if(openFilesMutex, openFiles, [handle](auto &cur) { return static_cast(cur->handle) == handle; })) { 756 | DEBUG_FUNCTION_LINE_ERR("[%s] Delete failed because the handle %08X was not found", getName().c_str(), handle); 757 | } 758 | } 759 | 760 | bool FSWrapper::SkipDeletedFilesInReadDir() { 761 | return true; 762 | } 763 | 764 | std::shared_ptr FSWrapper::getDirInfoFromHandle(const FSDirectoryHandle handle) { 765 | auto dir = std::dynamic_pointer_cast(getDirFromHandle(handle)); 766 | 767 | if (!dir) { 768 | DEBUG_FUNCTION_LINE_ERR("[%s] dynamic_pointer_cast(%08X) failed", getName().c_str(), handle); 769 | OSFatal("ContentRedirectionModule: dynamic_pointer_cast failed"); 770 | } 771 | return dir; 772 | } 773 | -------------------------------------------------------------------------------- /src/FSAReplacements.cpp: -------------------------------------------------------------------------------- 1 | #include "FSAReplacements.h" 2 | #include "FileUtils.h" 3 | #include "utils/logger.h" 4 | #include 5 | #include 6 | #include 7 | 8 | static FSError processFSAShimInThread(FSAShimBuffer *shimBuffer) { 9 | FSError res; 10 | if (gThreadsRunning) { 11 | auto param = (FSShimWrapper *) malloc(sizeof(FSShimWrapper)); 12 | if (param == nullptr) { 13 | DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapper"); 14 | OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapper"); 15 | } 16 | 17 | param->api = FS_SHIM_API_FSA; 18 | param->sync = FS_SHIM_TYPE_SYNC; 19 | param->shim = shimBuffer; 20 | 21 | if (OSGetCurrentThread() == gThreadData[OSGetCoreId()].thread) { 22 | res = processShimBufferForFSA(param); 23 | //No need to clean "param", it has been already free'd in processFSAShimBuffer. 24 | } else { 25 | auto message = (FSShimWrapperMessage *) malloc(sizeof(FSShimWrapperMessage)); 26 | if (message == nullptr) { 27 | DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapperMessage"); 28 | OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapperMessage"); 29 | } 30 | message->param = param; 31 | 32 | constexpr int32_t messageSize = sizeof(message->messages) / sizeof(message->messages[0]); 33 | OSInitMessageQueue(&message->messageQueue, message->messages, messageSize); 34 | if (!sendMessageToThread(message)) { 35 | DEBUG_FUNCTION_LINE_ERR("Failed to send message to thread"); 36 | OSFatal("ContentRedirectionModule: Failed send message to thread"); 37 | } 38 | OSMessage recv; 39 | if (!OSReceiveMessage(&message->messageQueue, &recv, OS_MESSAGE_FLAGS_BLOCKING)) { 40 | DEBUG_FUNCTION_LINE_ERR("Failed to receive message"); 41 | OSFatal("ContentRedirectionModule: Failed to receive message"); 42 | } 43 | if (recv.args[0] != FS_IO_QUEUE_SYNC_RESULT) { 44 | DEBUG_FUNCTION_LINE_ERR("ContentRedirection: Unexpected message in message queue."); 45 | OSFatal("ContentRedirection: Unexpected message in message queue."); 46 | } 47 | res = (FSError) recv.args[1]; 48 | // We only need to clean up "message". "param" has already been free'd by the other thread. 49 | free(message); 50 | } 51 | } else { 52 | res = FS_ERROR_FORCE_REAL_FUNCTION; 53 | DEBUG_FUNCTION_LINE_WARN("Threads are not running yet, skip replacement"); 54 | } 55 | return res; 56 | } 57 | 58 | DECL_FUNCTION(FSError, FSAOpenFileEx, FSAClientHandle client, const char *path, const char *mode, FSMode createMode, FSOpenFileFlags openFlag, uint32_t preallocSize, FSAFileHandle *handle) { 59 | if (handle == nullptr) { 60 | DEBUG_FUNCTION_LINE_WARN("handle is null."); 61 | return FS_ERROR_INVALID_BUFFER; 62 | } 63 | *handle = -1; 64 | 65 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 66 | if (!shimBuffer) { 67 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 68 | return FS_ERROR_OUT_OF_RESOURCES; 69 | } 70 | 71 | auto res = fsaShimPrepareRequestOpenFile(shimBuffer, client, path, mode, createMode, openFlag, preallocSize); 72 | if (res != FS_ERROR_OK) { 73 | free(shimBuffer); 74 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestOpenFile failed"); 75 | return res; 76 | } 77 | // Hacky solution to pass the pointer into the other thread. 78 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 79 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 80 | hackyBuffer[1] = (uint32_t) handle; 81 | res = processFSAShimInThread(shimBuffer); 82 | free(shimBuffer); 83 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 84 | return res; 85 | } 86 | 87 | // Other plugins/modules may override this function as well, so we need to call "real_FSAOpenFileEx" instead of using 88 | // the existing shimBuffer (which would be more efficient). 89 | return real_FSAOpenFileEx(client, path, mode, createMode, openFlag, preallocSize, handle); 90 | } 91 | 92 | DECL_FUNCTION(FSError, FSAOpenFile, FSAClientHandle client, const char *path, const char *mode, FSAFileHandle *handle) { 93 | if (handle == nullptr) { 94 | DEBUG_FUNCTION_LINE_WARN("handle is null."); 95 | return FS_ERROR_INVALID_BUFFER; 96 | } 97 | *handle = -1; 98 | 99 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 100 | if (!shimBuffer) { 101 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 102 | return FS_ERROR_OUT_OF_RESOURCES; 103 | } 104 | 105 | auto res = fsaShimPrepareRequestOpenFile(shimBuffer, client, path, mode, static_cast(0x660), static_cast(0), 0); 106 | if (res != FS_ERROR_OK) { 107 | free(shimBuffer); 108 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestOpenFile failed"); 109 | return res; 110 | } 111 | // Hacky solution to pass the pointer into the other thread. 112 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 113 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 114 | hackyBuffer[1] = (uint32_t) handle; 115 | res = processFSAShimInThread(shimBuffer); 116 | free(shimBuffer); 117 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 118 | return res; 119 | } 120 | 121 | // Other plugins/modules may override this function as well, so we need to call "real_FSAOpenFile" instead of using 122 | // the existing shimBuffer (which would be more efficient). 123 | return real_FSAOpenFile(client, path, mode, handle); 124 | } 125 | 126 | DECL_FUNCTION(FSError, FSACloseFile, FSAClientHandle client, FSAFileHandle handle) { 127 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 128 | if (!shimBuffer) { 129 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 130 | return FS_ERROR_OUT_OF_RESOURCES; 131 | } 132 | 133 | auto res = fsaShimPrepareRequestCloseFile(shimBuffer, client, handle); 134 | if (res != FS_ERROR_OK) { 135 | free(shimBuffer); 136 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestCloseFile failed"); 137 | return res; 138 | } 139 | res = processFSAShimInThread(shimBuffer); 140 | free(shimBuffer); 141 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 142 | return res; 143 | } 144 | 145 | // Other plugins/modules may override this function as well, so we need to call "real_FSACloseFile" instead of using 146 | // the existing shimBuffer (which would be more efficient). 147 | return real_FSACloseFile(client, handle); 148 | } 149 | 150 | DECL_FUNCTION(FSError, FSAFlushFile, FSAClientHandle client, FSAFileHandle handle) { 151 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 152 | if (!shimBuffer) { 153 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 154 | return FS_ERROR_OUT_OF_RESOURCES; 155 | } 156 | 157 | auto res = fsaShimPrepareRequestFlushFile(shimBuffer, client, handle); 158 | if (res != FS_ERROR_OK) { 159 | free(shimBuffer); 160 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestFlushFile failed"); 161 | return res; 162 | } 163 | res = processFSAShimInThread(shimBuffer); 164 | free(shimBuffer); 165 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 166 | return res; 167 | } 168 | 169 | // Other plugins/modules may override this function as well, so we need to call "real_FSAFlushFile" instead of using 170 | // the existing shimBuffer (which would be more efficient). 171 | return real_FSAFlushFile(client, handle); 172 | } 173 | 174 | DECL_FUNCTION(FSError, FSAGetStat, FSAClientHandle client, const char *path, FSAStat *stat) { 175 | if (stat == nullptr) { 176 | DEBUG_FUNCTION_LINE_WARN("stat is null."); 177 | return FS_ERROR_INVALID_BUFFER; 178 | } 179 | 180 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 181 | if (!shimBuffer) { 182 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 183 | return FS_ERROR_OUT_OF_RESOURCES; 184 | } 185 | 186 | auto res = fsaShimPrepareRequestQueryInfo(shimBuffer, client, path, FSA_QUERY_INFO_STAT); 187 | if (res != FS_ERROR_OK) { 188 | free(shimBuffer); 189 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 190 | return res; 191 | } 192 | // Hacky solution to pass the pointer into the other thread. 193 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 194 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 195 | hackyBuffer[1] = (uint32_t) stat; 196 | res = processFSAShimInThread(shimBuffer); 197 | free(shimBuffer); 198 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 199 | return res; 200 | } 201 | 202 | // Other plugins/modules may override this function as well, so we need to call "real_FSAGetStat" instead of using 203 | // the existing shimBuffer (which would be more efficient). 204 | return real_FSAGetStat(client, path, stat); 205 | } 206 | 207 | DECL_FUNCTION(FSError, FSAGetStatFile, FSAClientHandle client, FSAFileHandle handle, FSAStat *stat) { 208 | if (stat == nullptr) { 209 | DEBUG_FUNCTION_LINE_WARN("stat is null."); 210 | return FS_ERROR_INVALID_BUFFER; 211 | } 212 | 213 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 214 | if (!shimBuffer) { 215 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 216 | return FS_ERROR_OUT_OF_RESOURCES; 217 | } 218 | 219 | auto res = fsaShimPrepareRequestStatFile(shimBuffer, client, handle); 220 | if (res != FS_ERROR_OK) { 221 | free(shimBuffer); 222 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 223 | return res; 224 | } 225 | // Hacky solution to pass the pointer into the other thread. 226 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 227 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 228 | hackyBuffer[1] = (uint32_t) stat; 229 | res = processFSAShimInThread(shimBuffer); 230 | free(shimBuffer); 231 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 232 | return res; 233 | } 234 | 235 | // Other plugins/modules may override this function as well, so we need to call "real_FSAGetStatFile" instead of using 236 | // the existing shimBuffer (which would be more efficient). 237 | return real_FSAGetStatFile(client, handle, stat); 238 | } 239 | 240 | DECL_FUNCTION(FSError, FSARemove, FSAClientHandle client, const char *path) { 241 | if (path == nullptr) { 242 | DEBUG_FUNCTION_LINE_WARN("path is null."); 243 | return FS_ERROR_INVALID_PARAM; 244 | } 245 | 246 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 247 | if (!shimBuffer) { 248 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 249 | return FS_ERROR_OUT_OF_RESOURCES; 250 | } 251 | 252 | auto res = fsaShimPrepareRequestRemove(shimBuffer, client, path); 253 | if (res != FS_ERROR_OK) { 254 | free(shimBuffer); 255 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 256 | return res; 257 | } 258 | res = processFSAShimInThread(shimBuffer); 259 | free(shimBuffer); 260 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 261 | return res; 262 | } 263 | 264 | // Other plugins/modules may override this function as well, so we need to call "real_FSARemove" instead of using 265 | // the existing shimBuffer (which would be more efficient). 266 | return real_FSARemove(client, path); 267 | } 268 | 269 | DECL_FUNCTION(FSError, FSARename, FSAClientHandle client, const char *oldPath, const char *newPath) { 270 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 271 | if (!shimBuffer) { 272 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 273 | return FS_ERROR_OUT_OF_RESOURCES; 274 | } 275 | 276 | auto res = fsaShimPrepareRequestRename(shimBuffer, client, oldPath, newPath); 277 | if (res != FS_ERROR_OK) { 278 | free(shimBuffer); 279 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 280 | return res; 281 | } 282 | res = processFSAShimInThread(shimBuffer); 283 | free(shimBuffer); 284 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 285 | return res; 286 | } 287 | 288 | // Other plugins/modules may override this function as well, so we need to call "real_FSARename" instead of using 289 | // the existing shimBuffer (which would be more efficient). 290 | return real_FSARename(client, oldPath, newPath); 291 | } 292 | 293 | DECL_FUNCTION(FSError, FSASetPosFile, FSAClientHandle client, FSAFileHandle handle, FSAFilePosition pos) { 294 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 295 | if (!shimBuffer) { 296 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 297 | return FS_ERROR_OUT_OF_RESOURCES; 298 | } 299 | 300 | auto res = fsaShimPrepareRequestSetPos(shimBuffer, client, handle, pos); 301 | if (res != FS_ERROR_OK) { 302 | free(shimBuffer); 303 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 304 | return res; 305 | } 306 | res = processFSAShimInThread(shimBuffer); 307 | free(shimBuffer); 308 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 309 | return res; 310 | } 311 | 312 | // Other plugins/modules may override this function as well, so we need to call "real_FSASetPosFile" instead of using 313 | // the existing shimBuffer (which would be more efficient). 314 | return real_FSASetPosFile(client, handle, pos); 315 | } 316 | 317 | DECL_FUNCTION(FSError, FSATruncateFile, FSAClientHandle client, FSAFileHandle handle) { 318 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 319 | if (!shimBuffer) { 320 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 321 | return FS_ERROR_OUT_OF_RESOURCES; 322 | } 323 | 324 | auto res = fsaShimPrepareRequestTruncate(shimBuffer, client, handle); 325 | if (res != FS_ERROR_OK) { 326 | free(shimBuffer); 327 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 328 | return res; 329 | } 330 | res = processFSAShimInThread(shimBuffer); 331 | free(shimBuffer); 332 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 333 | return res; 334 | } 335 | 336 | // Other plugins/modules may override this function as well, so we need to call "real_FSATruncateFile" instead of using 337 | // the existing shimBuffer (which would be more efficient). 338 | return real_FSATruncateFile(client, handle); 339 | } 340 | 341 | DECL_FUNCTION(FSError, FSAReadFile, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFileHandle handle, uint32_t flags) { 342 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 343 | if (!shimBuffer) { 344 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 345 | return FS_ERROR_OUT_OF_RESOURCES; 346 | } 347 | 348 | auto res = fsaShimPrepareRequestReadFile(shimBuffer, client, buffer, size, count, 0, handle, static_cast(flags & 0xfffffffe)); 349 | if (res != FS_ERROR_OK) { 350 | free(shimBuffer); 351 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 352 | return res; 353 | } 354 | res = processFSAShimInThread(shimBuffer); 355 | free(shimBuffer); 356 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 357 | return res; 358 | } 359 | 360 | // Other plugins/modules may override this function as well, so we need to call "real_FSAReadFile" instead of using 361 | // the existing shimBuffer (which would be more efficient). 362 | return real_FSAReadFile(client, buffer, size, count, handle, flags); 363 | } 364 | 365 | DECL_FUNCTION(FSError, FSAReadFileWithPos, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFilePosition pos, FSAFileHandle handle, uint32_t flags) { 366 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 367 | if (!shimBuffer) { 368 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 369 | return FS_ERROR_OUT_OF_RESOURCES; 370 | } 371 | 372 | auto res = fsaShimPrepareRequestReadFile(shimBuffer, client, buffer, size, count, pos, handle, static_cast(flags | FSA_READ_FLAG_READ_WITH_POS)); 373 | if (res != FS_ERROR_OK) { 374 | free(shimBuffer); 375 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 376 | return res; 377 | } 378 | res = processFSAShimInThread(shimBuffer); 379 | free(shimBuffer); 380 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 381 | return res; 382 | } 383 | 384 | // Other plugins/modules may override this function as well, so we need to call "real_FSAReadFileWithPos" instead of using 385 | // the existing shimBuffer (which would be more efficient). 386 | return real_FSAReadFileWithPos(client, buffer, size, count, pos, handle, flags); 387 | } 388 | 389 | DECL_FUNCTION(FSError, FSAWriteFile, FSAClientHandle client, const uint8_t *buffer, uint32_t size, uint32_t count, FSAFileHandle handle, uint32_t flags) { 390 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 391 | if (!shimBuffer) { 392 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 393 | return FS_ERROR_OUT_OF_RESOURCES; 394 | } 395 | 396 | auto res = fsaShimPrepareRequestWriteFile(shimBuffer, client, buffer, size, count, 0, handle, static_cast(flags & 0xfffffffe)); 397 | if (res != FS_ERROR_OK) { 398 | free(shimBuffer); 399 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 400 | return res; 401 | } 402 | res = processFSAShimInThread(shimBuffer); 403 | free(shimBuffer); 404 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 405 | return res; 406 | } 407 | 408 | // Other plugins/modules may override this function as well, so we need to call "real_FSAWriteFile" instead of using 409 | // the existing shimBuffer (which would be more efficient). 410 | return real_FSAWriteFile(client, buffer, size, count, handle, flags); 411 | } 412 | 413 | DECL_FUNCTION(FSError, FSAWriteFileWithPos, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFilePosition pos, FSAFileHandle handle, uint32_t flags) { 414 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 415 | if (!shimBuffer) { 416 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 417 | return FS_ERROR_OUT_OF_RESOURCES; 418 | } 419 | 420 | auto res = fsaShimPrepareRequestWriteFile(shimBuffer, client, buffer, size, count, pos, handle, static_cast(flags | FSA_WRITE_FLAG_READ_WITH_POS)); 421 | if (res != FS_ERROR_OK) { 422 | free(shimBuffer); 423 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 424 | return res; 425 | } 426 | res = processFSAShimInThread(shimBuffer); 427 | free(shimBuffer); 428 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 429 | return res; 430 | } 431 | 432 | // Other plugins/modules may override this function as well, so we need to call "real_FSAWriteFileWithPos" instead of using 433 | // the existing shimBuffer (which would be more efficient). 434 | return real_FSAWriteFileWithPos(client, buffer, size, count, pos, handle, flags); 435 | } 436 | 437 | DECL_FUNCTION(FSError, FSAGetPosFile, FSAClientHandle client, FSAFileHandle handle, FSAFilePosition *outPos) { 438 | if (outPos == nullptr) { 439 | DEBUG_FUNCTION_LINE_WARN("outPos is null."); 440 | return FS_ERROR_INVALID_BUFFER; 441 | } 442 | 443 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 444 | if (!shimBuffer) { 445 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 446 | return FS_ERROR_OUT_OF_RESOURCES; 447 | } 448 | 449 | auto res = fsaShimPrepareRequestGetPos(shimBuffer, client, handle); 450 | if (res != FS_ERROR_OK) { 451 | free(shimBuffer); 452 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 453 | return res; 454 | } 455 | // Hacky solution to pass the pointer into the other thread. 456 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 457 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 458 | hackyBuffer[1] = (uint32_t) outPos; 459 | res = processFSAShimInThread(shimBuffer); 460 | free(shimBuffer); 461 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 462 | return res; 463 | } 464 | 465 | // Other plugins/modules may override this function as well, so we need to call "real_FSAGetPosFile" instead of using 466 | // the existing shimBuffer (which would be more efficient). 467 | return real_FSAGetPosFile(client, handle, outPos); 468 | } 469 | 470 | DECL_FUNCTION(FSError, FSAIsEof, FSAClientHandle client, FSAFileHandle handle) { 471 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 472 | if (!shimBuffer) { 473 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 474 | return FS_ERROR_OUT_OF_RESOURCES; 475 | } 476 | 477 | auto res = fsaShimPrepareRequestIsEof(shimBuffer, client, handle); 478 | if (res != FS_ERROR_OK) { 479 | free(shimBuffer); 480 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 481 | return res; 482 | } 483 | res = processFSAShimInThread(shimBuffer); 484 | free(shimBuffer); 485 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 486 | return res; 487 | } 488 | 489 | // Other plugins/modules may override this function as well, so we need to call "real_FSAIsEof" instead of using 490 | // the existing shimBuffer (which would be more efficient). 491 | return real_FSAIsEof(client, handle); 492 | } 493 | 494 | DECL_FUNCTION(FSError, FSAFlushMultiQuota, FSAClientHandle client, const char *path) { 495 | DEBUG_FUNCTION_LINE("NOT IMPLEMENTED. path %s", path); 496 | return real_FSAFlushMultiQuota(client, path); 497 | } 498 | 499 | DECL_FUNCTION(FSError, FSAFlushQuota, FSAClientHandle client, const char *path) { 500 | DEBUG_FUNCTION_LINE("NOT IMPLEMENTED. path %s", path); 501 | return real_FSAFlushQuota(client, path); 502 | } 503 | 504 | DECL_FUNCTION(FSError, FSAChangeMode, FSAClientHandle client, const char *path, FSMode permission) { 505 | DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED path %s permission: %08X", path, permission); 506 | return real_FSAChangeMode(client, path, permission); 507 | } 508 | 509 | DECL_FUNCTION(FSError, FSAOpenFileByStat, FSAClientHandle client, FSAStat *stat, const char *mode, const char *path, FSAFileHandle *outFileHandle) { 510 | DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED"); 511 | return real_FSAOpenFileByStat(client, stat, mode, path, outFileHandle); 512 | } 513 | 514 | DECL_FUNCTION(FSError, FSAAppendFile, FSAClientHandle client, FSAFileHandle fileHandle, uint32_t size, uint32_t count) { 515 | DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED"); 516 | return real_FSAAppendFile(client, fileHandle, size, count); 517 | } 518 | 519 | DECL_FUNCTION(FSError, FSAAppendFileEx, FSAClientHandle client, FSAFileHandle fileHandle, uint32_t size, uint32_t count, uint32_t flags) { 520 | DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED"); 521 | return real_FSAAppendFileEx(client, fileHandle, size, count, flags); 522 | } 523 | 524 | DECL_FUNCTION(FSError, FSAOpenDir, FSAClientHandle client, const char *path, FSADirectoryHandle *dirHandle) { 525 | if (dirHandle == nullptr) { 526 | DEBUG_FUNCTION_LINE_WARN("handle is null."); 527 | return FS_ERROR_INVALID_BUFFER; 528 | } 529 | *dirHandle = -1; 530 | 531 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 532 | if (!shimBuffer) { 533 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 534 | return FS_ERROR_OUT_OF_RESOURCES; 535 | } 536 | 537 | auto res = fsaShimPrepareRequestOpenDir(shimBuffer, client, path); 538 | if (res != FS_ERROR_OK) { 539 | free(shimBuffer); 540 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 541 | return res; 542 | } 543 | // Hacky solution to pass the pointer into the other thread. 544 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 545 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 546 | hackyBuffer[1] = (uint32_t) dirHandle; 547 | res = processFSAShimInThread(shimBuffer); 548 | free(shimBuffer); 549 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 550 | return res; 551 | } 552 | 553 | // Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using 554 | // the existing shimBuffer (which would be more efficient). 555 | return real_FSAOpenDir(client, path, dirHandle); 556 | } 557 | 558 | DECL_FUNCTION(FSError, FSAReadDir, FSAClientHandle client, FSADirectoryHandle dirHandle, FSADirectoryEntry *directoryEntry) { 559 | if (directoryEntry == nullptr) { 560 | DEBUG_FUNCTION_LINE_WARN("handle is null."); 561 | return FS_ERROR_INVALID_BUFFER; 562 | } 563 | 564 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 565 | if (!shimBuffer) { 566 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 567 | return FS_ERROR_OUT_OF_RESOURCES; 568 | } 569 | 570 | auto res = fsaShimPrepareRequestReadDir(shimBuffer, client, dirHandle); 571 | if (res != FS_ERROR_OK) { 572 | free(shimBuffer); 573 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 574 | return res; 575 | } 576 | // Hacky solution to pass the pointer into the other thread. 577 | #pragma GCC diagnostic ignored "-Waddress-of-packed-member" 578 | auto *hackyBuffer = (uint32_t *) &shimBuffer->response; 579 | hackyBuffer[1] = (uint32_t) directoryEntry; 580 | res = processFSAShimInThread(shimBuffer); 581 | free(shimBuffer); 582 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 583 | return res; 584 | } 585 | 586 | // Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using 587 | // the existing shimBuffer (which would be more efficient). 588 | return real_FSAReadDir(client, dirHandle, directoryEntry); 589 | } 590 | 591 | DECL_FUNCTION(FSError, FSARewindDir, FSAClientHandle client, FSADirectoryHandle dirHandle) { 592 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 593 | if (!shimBuffer) { 594 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 595 | return FS_ERROR_OUT_OF_RESOURCES; 596 | } 597 | 598 | auto res = fsaShimPrepareRequestRewindDir(shimBuffer, client, dirHandle); 599 | if (res != FS_ERROR_OK) { 600 | free(shimBuffer); 601 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 602 | return res; 603 | } 604 | res = processFSAShimInThread(shimBuffer); 605 | free(shimBuffer); 606 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 607 | return res; 608 | } 609 | 610 | // Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using 611 | // the existing shimBuffer (which would be more efficient). 612 | return real_FSARewindDir(client, dirHandle); 613 | } 614 | 615 | DECL_FUNCTION(FSError, FSACloseDir, FSAClientHandle client, FSADirectoryHandle dirHandle) { 616 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 617 | if (!shimBuffer) { 618 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 619 | return FS_ERROR_OUT_OF_RESOURCES; 620 | } 621 | 622 | auto res = fsaShimPrepareRequestCloseDir(shimBuffer, client, dirHandle); 623 | if (res != FS_ERROR_OK) { 624 | free(shimBuffer); 625 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 626 | return res; 627 | } 628 | res = processFSAShimInThread(shimBuffer); 629 | free(shimBuffer); 630 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 631 | return res; 632 | } 633 | 634 | // Other plugins/modules may override this function as well, so we need to call "real_FSACloseDir" instead of using 635 | // the existing shimBuffer (which would be more efficient). 636 | return real_FSACloseDir(client, dirHandle); 637 | } 638 | 639 | DECL_FUNCTION(FSError, FSAMakeDir, FSAClientHandle client, const char *path, FSMode mode) { 640 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 641 | if (!shimBuffer) { 642 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 643 | return FS_ERROR_OUT_OF_RESOURCES; 644 | } 645 | 646 | auto res = fsaShimPrepareRequestMakeDir(shimBuffer, client, path, mode); 647 | if (res != FS_ERROR_OK) { 648 | free(shimBuffer); 649 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 650 | return res; 651 | } 652 | res = processFSAShimInThread(shimBuffer); 653 | free(shimBuffer); 654 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 655 | return res; 656 | } 657 | 658 | // Other plugins/modules may override this function as well, so we need to call "real_FSAMakeDir" instead of using 659 | // the existing shimBuffer (which would be more efficient). 660 | return real_FSAMakeDir(client, path, mode); 661 | } 662 | 663 | DECL_FUNCTION(FSError, FSAChangeDir, FSAClientHandle client, const char *path) { 664 | auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer)); 665 | if (!shimBuffer) { 666 | DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES"); 667 | return FS_ERROR_OUT_OF_RESOURCES; 668 | } 669 | 670 | auto res = fsaShimPrepareRequestChangeDir(shimBuffer, client, path); 671 | if (res != FS_ERROR_OK) { 672 | free(shimBuffer); 673 | DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed"); 674 | return res; 675 | } 676 | res = processFSAShimInThread(shimBuffer); 677 | free(shimBuffer); 678 | if (res != FS_ERROR_FORCE_REAL_FUNCTION) { 679 | return res; 680 | } 681 | 682 | // Other plugins/modules may override this function as well, so we need to call "real_FSAChangeDir" instead of using 683 | // the existing shimBuffer (which would be more efficient). 684 | return real_FSAChangeDir(client, path); 685 | } 686 | 687 | function_replacement_data_t fsa_file_function_replacements[] = { 688 | REPLACE_FUNCTION(FSAOpenFile, LIBRARY_COREINIT, FSAOpenFile), 689 | REPLACE_FUNCTION(FSAOpenFileEx, LIBRARY_COREINIT, FSAOpenFileEx), 690 | REPLACE_FUNCTION(FSACloseFile, LIBRARY_COREINIT, FSACloseFile), 691 | REPLACE_FUNCTION(FSAFlushFile, LIBRARY_COREINIT, FSAFlushFile), 692 | REPLACE_FUNCTION(FSAGetStat, LIBRARY_COREINIT, FSAGetStat), 693 | REPLACE_FUNCTION(FSAGetStatFile, LIBRARY_COREINIT, FSAGetStatFile), 694 | REPLACE_FUNCTION(FSARemove, LIBRARY_COREINIT, FSARemove), 695 | REPLACE_FUNCTION(FSARename, LIBRARY_COREINIT, FSARename), 696 | REPLACE_FUNCTION(FSASetPosFile, LIBRARY_COREINIT, FSASetPosFile), 697 | REPLACE_FUNCTION(FSATruncateFile, LIBRARY_COREINIT, FSATruncateFile), 698 | REPLACE_FUNCTION(FSAReadFile, LIBRARY_COREINIT, FSAReadFile), 699 | REPLACE_FUNCTION(FSAReadFileWithPos, LIBRARY_COREINIT, FSAReadFileWithPos), 700 | REPLACE_FUNCTION(FSAWriteFile, LIBRARY_COREINIT, FSAWriteFile), 701 | REPLACE_FUNCTION(FSAWriteFileWithPos, LIBRARY_COREINIT, FSAWriteFileWithPos), 702 | REPLACE_FUNCTION(FSAGetPosFile, LIBRARY_COREINIT, FSAGetPosFile), 703 | REPLACE_FUNCTION(FSAIsEof, LIBRARY_COREINIT, FSAIsEof), 704 | 705 | REPLACE_FUNCTION(FSAFlushMultiQuota, LIBRARY_COREINIT, FSAFlushMultiQuota), 706 | REPLACE_FUNCTION(FSAFlushQuota, LIBRARY_COREINIT, FSAFlushQuota), 707 | REPLACE_FUNCTION(FSAChangeMode, LIBRARY_COREINIT, FSAChangeMode), 708 | REPLACE_FUNCTION(FSAOpenFileByStat, LIBRARY_COREINIT, FSAOpenFileByStat), 709 | REPLACE_FUNCTION(FSAAppendFile, LIBRARY_COREINIT, FSAAppendFile), 710 | REPLACE_FUNCTION(FSAAppendFileEx, LIBRARY_COREINIT, FSAAppendFileEx), 711 | 712 | REPLACE_FUNCTION(FSAOpenDir, LIBRARY_COREINIT, FSAOpenDir), 713 | REPLACE_FUNCTION(FSAReadDir, LIBRARY_COREINIT, FSAReadDir), 714 | REPLACE_FUNCTION(FSARewindDir, LIBRARY_COREINIT, FSARewindDir), 715 | REPLACE_FUNCTION(FSACloseDir, LIBRARY_COREINIT, FSACloseDir), 716 | REPLACE_FUNCTION(FSAMakeDir, LIBRARY_COREINIT, FSAMakeDir), 717 | REPLACE_FUNCTION(FSAChangeDir, LIBRARY_COREINIT, FSAChangeDir), 718 | }; 719 | 720 | uint32_t fsa_file_function_replacements_size = sizeof(fsa_file_function_replacements) / sizeof(function_replacement_data_t); 721 | 722 | FSError processShimBufferForFSA(FSShimWrapper *param) { 723 | auto res = doForLayer(param); 724 | if (res == FS_ERROR_FORCE_REAL_FUNCTION) { 725 | if (param->sync == FS_SHIM_TYPE_ASYNC) { 726 | DEBUG_FUNCTION_LINE_ERR("ASYNC FSA API is not supported"); 727 | OSFatal("ContentRedirectionModule: ASYNC FSA API is not supported"); 728 | } 729 | } 730 | free(param); 731 | return res; 732 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------