├── src ├── version.h ├── globals.cpp ├── globals.h ├── main.h ├── SaveRedirection.h ├── fs │ ├── FSUtils.h │ ├── FileReaderWUHB.h │ ├── FileReader.h │ ├── CFile.hpp │ ├── FileReader.cpp │ ├── FileReaderWUHB.cpp │ ├── DirList.h │ ├── CFile.cpp │ ├── FSUtils.cpp │ └── DirList.cpp ├── utils │ ├── logger.c │ ├── utils.cpp │ ├── utils.h │ ├── StringTools.h │ ├── logger.h │ ├── StringTools.cpp │ ├── ini.h │ ├── fnmatch.c │ └── ini.c ├── FileInfos.h ├── SaveRedirection.cpp └── main.cpp ├── data ├── iconTex.tga ├── bootLogoTex.tga └── bootMovie.h264 ├── .gitignore ├── .github ├── dependabot.yml └── workflows │ ├── pr.yml │ └── ci.yml ├── Dockerfile ├── .clang-format ├── README.md ├── Makefile └── LICENSE /src/version.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #define VERSION_EXTRA "" -------------------------------------------------------------------------------- /src/globals.cpp: -------------------------------------------------------------------------------- 1 | #include "globals.h" 2 | 3 | std::string gSerialId; -------------------------------------------------------------------------------- /src/globals.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | extern std::string gSerialId; -------------------------------------------------------------------------------- /data/iconTex.tga: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiiu-env/homebrew_on_menu_plugin/HEAD/data/iconTex.tga -------------------------------------------------------------------------------- /data/bootLogoTex.tga: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiiu-env/homebrew_on_menu_plugin/HEAD/data/bootLogoTex.tga -------------------------------------------------------------------------------- /data/bootMovie.h264: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiiu-env/homebrew_on_menu_plugin/HEAD/data/bootMovie.h264 -------------------------------------------------------------------------------- /src/main.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "version.h" 4 | 5 | #define VERSION "v0.1.8" 6 | #define VERSION_FULL VERSION VERSION_EXTRA 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/* 2 | *.mod 3 | sysapp.layout 4 | sysapp.cbp 5 | src/filelist.h 6 | cmake-build-debug/CMakeCache.txt 7 | cmake-build-debug/ 8 | .idea/ 9 | *.wps 10 | *.elf 11 | CMakeLists.txt 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" 11 | -------------------------------------------------------------------------------- /src/SaveRedirection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | extern bool gInWiiUMenu; 4 | 5 | #define HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE "/wiiu/homebrew_on_menu_plugin" 6 | #define HOMEBREW_ON_MENU_PLUGIN_DATA_PATH "/vol/external01" HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE 7 | 8 | void SaveRedirectionCleanUp(); -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ghcr.io/wiiu-env/devkitppc:20240505 2 | 3 | COPY --from=ghcr.io/wiiu-env/wiiupluginsystem:20240505 /artifacts $DEVKITPRO 4 | COPY --from=ghcr.io/wiiu-env/librpxloader:20240425 /artifacts $DEVKITPRO 5 | COPY --from=ghcr.io/wiiu-env/libsdutils:20230621 /artifacts $DEVKITPRO 6 | COPY --from=ghcr.io/wiiu-env/libwuhbutils:20230621 /artifacts $DEVKITPRO 7 | COPY --from=ghcr.io/wiiu-env/libcontentredirection:20240428 /artifacts $DEVKITPRO 8 | COPY --from=ghcr.io/wiiu-env/libnotifications:20230621 /artifacts $DEVKITPRO 9 | 10 | WORKDIR project 11 | -------------------------------------------------------------------------------- /src/fs/FSUtils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | class FSUtils { 7 | public: 8 | static int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size); 9 | 10 | //! todo: C++ class 11 | static int32_t CreateSubfolder(const char *fullpath); 12 | 13 | static int32_t CheckFile(const char *filepath); 14 | 15 | static int32_t saveBufferToFile(const char *path, void *buffer, uint32_t size); 16 | 17 | static bool copyFile(const std::string &in, const std::string &out); 18 | }; 19 | -------------------------------------------------------------------------------- /src/fs/FileReaderWUHB.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FileInfos.h" 3 | #include "FileReader.h" 4 | #include 5 | 6 | 7 | class FileReaderWUHB : public FileReader { 8 | bool initDone = false; 9 | std::shared_ptr info; 10 | WUHBFileHandle fileHandle = 0; 11 | bool autoUnmount = false; 12 | 13 | public: 14 | explicit FileReaderWUHB(const std::shared_ptr &info, const std::string &relativeFilepath, bool autoUnmount); 15 | ~FileReaderWUHB() override; 16 | int64_t read(uint8_t *buffer, uint32_t size) override; 17 | bool isReady() override; 18 | void UnmountBundle(); 19 | }; 20 | -------------------------------------------------------------------------------- /src/fs/FileReader.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class FileReader { 10 | 11 | public: 12 | FileReader(uint8_t *buffer, uint32_t size); 13 | 14 | explicit FileReader(std::string &path); 15 | 16 | virtual ~FileReader(); 17 | 18 | virtual int64_t read(uint8_t *buffer, uint32_t size); 19 | 20 | virtual bool isReady(); 21 | 22 | virtual uint32_t getHandle() { 23 | return reinterpret_cast(this); 24 | } 25 | 26 | protected: 27 | FileReader() = default; 28 | 29 | private: 30 | bool isReadFromBuffer = false; 31 | uint8_t *input_buffer = nullptr; 32 | uint32_t input_size = 0; 33 | uint32_t input_pos = 0; 34 | 35 | bool isReadFromFile = false; 36 | int file_fd = 0; 37 | }; 38 | -------------------------------------------------------------------------------- /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/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include "logger.h" 3 | #include 4 | #include 5 | 6 | /* hash: compute hash value of string */ 7 | unsigned int hash_string(const char *str) { 8 | unsigned int h; 9 | unsigned char *p; 10 | 11 | h = 0; 12 | for (p = (unsigned char *) str; *p != '\0'; p++) { 13 | h = 37 * h + *p; 14 | } 15 | return h; // or, h % ARRAY_SIZE; 16 | } 17 | 18 | bool Utils::GetSerialId(std::string &serialID) { 19 | bool result = false; 20 | alignas(0x40) MCPSysProdSettings settings{}; 21 | auto handle = MCP_Open(); 22 | if (handle >= 0) { 23 | if (MCP_GetSysProdSettings(handle, &settings) == 0) { 24 | serialID = std::string(settings.code_id) + settings.serial_id; 25 | result = true; 26 | } else { 27 | DEBUG_FUNCTION_LINE_ERR("Failed to get SerialId"); 28 | } 29 | MCP_Close(handle); 30 | } else { 31 | DEBUG_FUNCTION_LINE_ERR("MCP_Open failed"); 32 | } 33 | return result; 34 | } -------------------------------------------------------------------------------- /src/utils/utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | uint32_t hash_string(const char *); 11 | 12 | template 13 | std::unique_ptr make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward(args)...))) { 14 | return std::unique_ptr(new (std::nothrow) T(std::forward(args)...)); 15 | } 16 | 17 | template 18 | std::shared_ptr make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward(args)...))) { 19 | return std::shared_ptr(new (std::nothrow) T(std::forward(args)...)); 20 | } 21 | 22 | template 23 | bool remove_locked_first_if(std::mutex &mutex, std::forward_list &list, Predicate pred) { 24 | std::lock_guard lock(mutex); 25 | auto oit = list.before_begin(), it = std::next(oit); 26 | while (it != list.end()) { 27 | if (pred(*it)) { 28 | list.erase_after(oit); 29 | return true; 30 | } 31 | oit = it++; 32 | } 33 | return false; 34 | } 35 | 36 | namespace Utils { 37 | bool GetSerialId(std::string &serialID); 38 | } -------------------------------------------------------------------------------- /.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: "*.wps" -------------------------------------------------------------------------------- /src/fs/CFile.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CFILE_HPP_ 2 | #define CFILE_HPP_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | class CFile { 12 | public: 13 | enum eOpenTypes { 14 | ReadOnly, 15 | WriteOnly, 16 | ReadWrite, 17 | Append 18 | }; 19 | 20 | CFile(); 21 | 22 | CFile(const std::string &filepath, eOpenTypes mode); 23 | 24 | CFile(const uint8_t *memory, int32_t memsize); 25 | 26 | virtual ~CFile(); 27 | 28 | int32_t open(const std::string &filepath, eOpenTypes mode); 29 | 30 | int32_t open(const uint8_t *memory, int32_t memsize); 31 | 32 | BOOL isOpen() const { 33 | if (iFd >= 0) 34 | return true; 35 | 36 | if (mem_file) 37 | return true; 38 | 39 | return false; 40 | } 41 | 42 | void close(); 43 | 44 | int32_t read(uint8_t *ptr, size_t size); 45 | 46 | int32_t write(const uint8_t *ptr, size_t size); 47 | 48 | int32_t fwrite(const char *format, ...); 49 | 50 | int32_t seek(long int offset, int32_t origin); 51 | 52 | uint64_t tell() { 53 | return pos; 54 | }; 55 | 56 | uint64_t size() { 57 | return filesize; 58 | }; 59 | 60 | void rewind() { 61 | this->seek(0, SEEK_SET); 62 | }; 63 | 64 | protected: 65 | int32_t iFd; 66 | const uint8_t *mem_file{}; 67 | uint64_t filesize{}; 68 | uint64_t pos{}; 69 | }; 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /src/fs/FileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReader.h" 2 | #include "../utils/logger.h" 3 | #include 4 | 5 | int64_t FileReader::read(uint8_t *buffer, uint32_t size) { 6 | if (isReadFromBuffer) { 7 | if (input_buffer == nullptr) { 8 | return -1; 9 | } 10 | uint32_t toRead = size; 11 | if (toRead > input_size - input_pos) { 12 | toRead = input_size - input_pos; 13 | } 14 | if (toRead == 0) { 15 | return 0; 16 | } 17 | memcpy(buffer, &input_buffer[input_pos], toRead); 18 | input_pos += toRead; 19 | return toRead; 20 | } else if (isReadFromFile) { 21 | int res = ::read(file_fd, buffer, size); 22 | return res; 23 | } 24 | return -2; 25 | } 26 | 27 | FileReader::FileReader(std::string &path) { 28 | int fd; 29 | if ((fd = open(path.c_str(), O_RDONLY)) >= 0) { 30 | this->isReadFromFile = true; 31 | this->isReadFromBuffer = false; 32 | this->file_fd = fd; 33 | } else { 34 | DEBUG_FUNCTION_LINE("## INFO ## Failed to open file %s", path.c_str()); 35 | } 36 | } 37 | 38 | FileReader::~FileReader() { 39 | if (isReadFromFile) { 40 | ::close(this->file_fd); 41 | } 42 | } 43 | 44 | FileReader::FileReader(uint8_t *buffer, uint32_t size) { 45 | this->input_buffer = buffer; 46 | this->input_size = size; 47 | this->input_pos = 0; 48 | this->isReadFromBuffer = true; 49 | this->isReadFromFile = false; 50 | } 51 | 52 | bool FileReader::isReady() { 53 | return this->isReadFromFile || this->isReadFromBuffer; 54 | } -------------------------------------------------------------------------------- /.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: "*.wps" 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 *.wps 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/utils/StringTools.h: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | * Copyright (C) 2010 3 | * by Dimok 4 | * 5 | * This software is provided 'as-is', without any express or implied 6 | * warranty. In no event will the authors be held liable for any 7 | * damages arising from the use of this software. 8 | * 9 | * Permission is granted to anyone to use this software for any 10 | * purpose, including commercial applications, and to alter it and 11 | * redistribute it freely, subject to the following restrictions: 12 | * 13 | * 1. The origin of this software must not be misrepresented; you 14 | * must not claim that you wrote the original software. If you use 15 | * this software in a product, an acknowledgment in the product 16 | * documentation would be appreciated but is not required. 17 | * 18 | * 2. Altered source versions must be plainly marked as such, and 19 | * must not be misrepresented as being the original software. 20 | * 21 | * 3. This notice may not be removed or altered from any source 22 | * distribution. 23 | * 24 | * for WiiXplorer 2010 25 | ***************************************************************************/ 26 | #pragma once 27 | 28 | #include 29 | #include 30 | #include 31 | 32 | template 33 | std::string string_format(const std::string &format, Args... args) { 34 | int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' 35 | auto size = static_cast(size_s); 36 | auto buf = std::make_unique(size); 37 | std::snprintf(buf.get(), size, format.c_str(), args...); 38 | return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside 39 | } 40 | 41 | class StringTools { 42 | public: 43 | static std::string remove_extension(const std::string &filename); 44 | 45 | static std::string get_extension(const std::string &filename); 46 | 47 | static int32_t strtokcmp(const char *string, const char *compare, const char *separator); 48 | 49 | static const char *FullpathToFilename(const char *path); 50 | 51 | static void RemoveDoubleSlashs(std::string &str); 52 | 53 | static std::vector StringSplit(const std::string &inValue, const std::string &splitter); 54 | }; 55 | -------------------------------------------------------------------------------- /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 "P" 12 | #define LOG_APP_NAME "homebrew_on_menu" 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(LOG_FUNC, "", "", FMT, ##ARGS) 18 | 19 | #define LOG_EX(LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) \ 20 | do { \ 21 | LOG_FUNC("[(%s)%18s][%23s]%30s@L%04d: " LOG_LEVEL "" FMT "" LINE_END, LOG_APP_TYPE, LOG_APP_NAME, __FILENAME__, __FUNCTION__, __LINE__, ##ARGS); \ 22 | } while (0) 23 | 24 | 25 | #ifdef DEBUG 26 | 27 | #ifdef VERBOSE_DEBUG 28 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) 29 | #else 30 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) 31 | #endif 32 | 33 | #define DEBUG_FUNCTION_LINE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) 34 | 35 | #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS) 36 | 37 | #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS) 38 | #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##WARN ## ", "", FMT, ##ARGS) 39 | #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##INFO ## ", "", FMT, ##ARGS) 40 | 41 | #else 42 | 43 | #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) 44 | 45 | #define DEBUG_FUNCTION_LINE(FMT, ARGS...) while (0) 46 | 47 | #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0) 48 | 49 | #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX(OSReport, "##ERROR## ", "\n", FMT, ##ARGS) 50 | #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX(OSReport, "##WARN ## ", "\n", FMT, ##ARGS) 51 | #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX(OSReport, "##INFO ## ", "\n", FMT, ##ARGS) 52 | 53 | #endif 54 | 55 | void initLogging(); 56 | 57 | void deinitLogging(); 58 | 59 | #ifdef __cplusplus 60 | } 61 | #endif 62 | -------------------------------------------------------------------------------- /src/fs/FileReaderWUHB.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReaderWUHB.h" 2 | #include "utils/StringTools.h" 3 | #include "utils/logger.h" 4 | #include 5 | #include 6 | 7 | FileReaderWUHB::FileReaderWUHB(const std::shared_ptr &info, const std::string &relativeFilepath, bool autoUnmount) { 8 | if (!info) { 9 | DEBUG_FUNCTION_LINE_ERR("Info was NULL"); 10 | return; 11 | } 12 | if (!info->isBundle) { 13 | DEBUG_FUNCTION_LINE("Failed to init file reader for %s, is not a bundle.", info->relativeFilepath.c_str()); 14 | return; 15 | } 16 | this->autoUnmount = autoUnmount; 17 | this->info = info; 18 | std::lock_guard lock(info->accessLock); 19 | 20 | auto romfsName = string_format("%08X", info->lowerTitleID); 21 | 22 | if (!info->MountBundle(romfsName)) { 23 | return; 24 | } 25 | 26 | auto filepath = romfsName.append(":/").append(relativeFilepath); 27 | 28 | WUHBUtilsStatus status; 29 | if ((status = WUHBUtils_FileOpen(filepath.c_str(), &this->fileHandle)) != WUHB_UTILS_RESULT_SUCCESS) { 30 | DEBUG_FUNCTION_LINE("Failed to open file in bundle: %s error: %d", filepath.c_str(), status); 31 | 32 | UnmountBundle(); 33 | 34 | return; 35 | } 36 | this->info->fileCount++; 37 | 38 | this->initDone = true; 39 | OSMemoryBarrier(); 40 | } 41 | 42 | FileReaderWUHB::~FileReaderWUHB() { 43 | if (!this->initDone) { 44 | return; 45 | } 46 | 47 | std::lock_guard lock(info->accessLock); 48 | 49 | if (this->fileHandle != 0) { 50 | if (WUHBUtils_FileClose(this->fileHandle) != WUHB_UTILS_RESULT_SUCCESS) { 51 | DEBUG_FUNCTION_LINE_ERR("WUHBUtils_FileClose failed for %08X", this->fileHandle); 52 | } 53 | this->fileHandle = 0; 54 | info->fileCount--; 55 | } 56 | 57 | UnmountBundle(); 58 | OSMemoryBarrier(); 59 | } 60 | 61 | int64_t FileReaderWUHB::read(uint8_t *buffer, uint32_t size) { 62 | if (!this->initDone) { 63 | DEBUG_FUNCTION_LINE_ERR("read file but init was not successful"); 64 | return -1; 65 | } 66 | int32_t outRes = -1; 67 | if (WUHBUtils_FileRead(this->fileHandle, buffer, size, &outRes) == WUHB_UTILS_RESULT_SUCCESS) { 68 | return outRes; 69 | } 70 | DEBUG_FUNCTION_LINE_ERR("WUHBUtils_FileRead failed"); 71 | return -1; 72 | } 73 | 74 | bool FileReaderWUHB::isReady() { 75 | return this->initDone; 76 | } 77 | void FileReaderWUHB::UnmountBundle() { 78 | if (autoUnmount && info->fileCount <= 0) { 79 | if (!info->UnmountBundle()) { 80 | DEBUG_FUNCTION_LINE_ERR("Failed to unmount"); 81 | } 82 | } else { 83 | DEBUG_FUNCTION_LINE_VERBOSE("Filecount is %d, we don't want to unmount yet", info->fileCount); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/FileInfos.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "utils/logger.h" 3 | #include "utils/utils.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class FileInfos { 10 | public: 11 | explicit FileInfos(const std::string &relativePath) : relativeFilepath(relativePath) { 12 | this->lowerTitleID = hash_string(relativePath.c_str()); 13 | } 14 | ~FileInfos() { 15 | std::lock_guard lock(mountLock); 16 | if (isMounted) { 17 | UnmountBundle(); 18 | } 19 | } 20 | bool MountBundle(const std::string &romfsName) { 21 | if (isMounted) { 22 | if (mountPath != romfsName) { 23 | DEBUG_FUNCTION_LINE_ERR("Can't mount as %s because it's already mounted with a different name (%s)", romfsName.c_str(), mountPath.c_str()); 24 | return false; 25 | } 26 | return true; 27 | } 28 | if (!isBundle) { 29 | DEBUG_FUNCTION_LINE_VERBOSE("Mounting not possible, is not a bundle"); 30 | return false; 31 | } 32 | auto fullMountPath = std::string("/vol/external01/").append(this->relativeFilepath); 33 | int32_t outRes = -1; 34 | if (WUHBUtils_MountBundle(romfsName.c_str(), fullMountPath.c_str(), BundleSource_FileDescriptor_CafeOS, &outRes) != WUHB_UTILS_RESULT_SUCCESS || outRes < 0) { 35 | DEBUG_FUNCTION_LINE_ERR("Failed to mount bundle: %s", romfsName.c_str()); 36 | return false; 37 | } 38 | DEBUG_FUNCTION_LINE_VERBOSE("Succesfully mounted %s", romfsName.c_str()); 39 | this->isMounted = true; 40 | mountPath = romfsName; 41 | return true; 42 | } 43 | 44 | bool UnmountBundle() { 45 | if (!isBundle) { 46 | DEBUG_FUNCTION_LINE_VERBOSE("Skip unmounting, is not a bundle"); 47 | return true; 48 | } 49 | if (!isMounted) { 50 | DEBUG_FUNCTION_LINE_VERBOSE("Skip unmounting, is not mounted"); 51 | return true; 52 | } 53 | int32_t outRes = -1; 54 | if (WUHBUtils_UnmountBundle(mountPath.c_str(), &outRes) != WUHB_UTILS_RESULT_SUCCESS || outRes < 0) { 55 | DEBUG_FUNCTION_LINE_ERR("Failed to unmount bundle: %s", mountPath.c_str()); 56 | return false; 57 | } else { 58 | DEBUG_FUNCTION_LINE_VERBOSE("Successfully unmounted bundle %s", this->mountPath.c_str()); 59 | } 60 | this->isMounted = false; 61 | this->mountPath.clear(); 62 | 63 | return true; 64 | } 65 | 66 | std::string relativeFilepath; 67 | std::string filename; 68 | 69 | std::string longname; 70 | std::string shortname; 71 | std::string author; 72 | 73 | uint32_t lowerTitleID; 74 | MCPTitleListType titleInfo{}; 75 | 76 | int32_t fileCount = 0; 77 | 78 | bool isBundle = false; 79 | 80 | std::mutex accessLock; 81 | 82 | private: 83 | std::mutex mountLock; 84 | std::string mountPath; 85 | bool isMounted = false; 86 | }; -------------------------------------------------------------------------------- /src/utils/StringTools.cpp: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | * Copyright (C) 2010 3 | * by Dimok 4 | * 5 | * This software is provided 'as-is', without any express or implied 6 | * warranty. In no event will the authors be held liable for any 7 | * damages arising from the use of this software. 8 | * 9 | * Permission is granted to anyone to use this software for any 10 | * purpose, including commercial applications, and to alter it and 11 | * redistribute it freely, subject to the following restrictions: 12 | * 13 | * 1. The origin of this software must not be misrepresented; you 14 | * must not claim that you wrote the original software. If you use 15 | * this software in a product, an acknowledgment in the product 16 | * documentation would be appreciated but is not required. 17 | * 18 | * 2. Altered source versions must be plainly marked as such, and 19 | * must not be misrepresented as being the original software. 20 | * 21 | * 3. This notice may not be removed or altered from any source 22 | * distribution. 23 | * 24 | * for WiiXplorer 2010 25 | ***************************************************************************/ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | std::string StringTools::remove_extension(const std::string &filename) { 34 | size_t lastdot = filename.find_last_of('.'); 35 | if (lastdot == std::string::npos) return filename; 36 | return filename.substr(0, lastdot); 37 | } 38 | 39 | std::string StringTools::get_extension(const std::string &filename) { 40 | size_t lastdot = filename.find_last_of('.'); 41 | if (lastdot == std::string::npos) return ""; 42 | return filename.substr(lastdot); 43 | } 44 | 45 | 46 | int32_t StringTools::strtokcmp(const char *string, const char *compare, const char *separator) { 47 | if (!string || !compare) 48 | return -1; 49 | 50 | char TokCopy[512]; 51 | strncpy(TokCopy, compare, sizeof(TokCopy)); 52 | TokCopy[511] = '\0'; 53 | 54 | char *strTok = strtok(TokCopy, separator); 55 | 56 | while (strTok != nullptr) { 57 | if (strcasecmp(string, strTok) == 0) { 58 | return 0; 59 | } 60 | strTok = strtok(nullptr, separator); 61 | } 62 | 63 | return -1; 64 | } 65 | const char *StringTools::FullpathToFilename(const char *path) { 66 | if (!path) 67 | return path; 68 | 69 | const char *ptr = path; 70 | const char *Filename = ptr; 71 | 72 | while (*ptr != '\0') { 73 | if (ptr[0] == '/' && ptr[1] != '\0') 74 | Filename = ptr + 1; 75 | 76 | ++ptr; 77 | } 78 | 79 | return Filename; 80 | } 81 | 82 | void StringTools::RemoveDoubleSlashs(std::string &str) { 83 | uint32_t length = str.size(); 84 | 85 | //! clear relativeFilepath of double slashes 86 | for (uint32_t i = 1; i < length; ++i) { 87 | if (str[i - 1] == '/' && str[i] == '/') { 88 | str.erase(i, 1); 89 | i--; 90 | length--; 91 | } 92 | } 93 | } 94 | 95 | std::vector StringTools::StringSplit(const std::string &inValue, const std::string &splitter) { 96 | std::string value = inValue; 97 | std::vector result; 98 | while (true) { 99 | unsigned int index = value.find(splitter); 100 | if (index == std::string::npos) { 101 | result.push_back(value); 102 | break; 103 | } 104 | std::string first = value.substr(0, index); 105 | result.push_back(first); 106 | if (index + splitter.size() == value.length()) { 107 | result.push_back(""); 108 | break; 109 | } 110 | if (index + splitter.size() > value.length()) { 111 | break; 112 | } 113 | value = value.substr(index + splitter.size(), value.length()); 114 | } 115 | return result; 116 | } 117 | -------------------------------------------------------------------------------- /src/fs/DirList.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * Copyright (C) 2010 3 | * by Dimok 4 | * 5 | * This software is provided 'as-is', without any express or implied 6 | * warranty. In no event will the authors be held liable for any 7 | * damages arising from the use of this software. 8 | * 9 | * Permission is granted to anyone to use this software for any 10 | * purpose, including commercial applications, and to alter it and 11 | * redistribute it freely, subject to the following restrictions: 12 | * 13 | * 1. The origin of this software must not be misrepresented; you 14 | * must not claim that you wrote the original software. If you use 15 | * this software in a product, an acknowledgment in the product 16 | * documentation would be appreciated but is not required. 17 | * 18 | * 2. Altered source versions must be plainly marked as such, and 19 | * must not be misrepresented as being the original software. 20 | * 21 | * 3. This notice may not be removed or altered from any source 22 | * distribution. 23 | * 24 | * DirList Class 25 | * for WiiXplorer 2010 26 | ***************************************************************************/ 27 | #ifndef ___DIRLIST_H_ 28 | #define ___DIRLIST_H_ 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | typedef struct { 35 | char *FilePath; 36 | BOOL isDir; 37 | } DirEntry; 38 | 39 | class DirList { 40 | public: 41 | //!Constructor 42 | DirList(void); 43 | 44 | //!\param path Path from where to load the filelist of all files 45 | //!\param filter A fileext that needs to be filtered 46 | //!\param flags search/filter flags from the enum 47 | DirList(const std::string &path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff); 48 | 49 | //!Destructor 50 | virtual ~DirList(); 51 | 52 | //! Load all the files from a directory 53 | BOOL LoadPath(const std::string &path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff); 54 | 55 | //! Get a filename of the list 56 | //!\param list index 57 | const char *GetFilename(int32_t index) const; 58 | 59 | //! Get the a filepath of the list 60 | //!\param list index 61 | const char *GetFilepath(int32_t index) const { 62 | if (!valid(index)) 63 | return ""; 64 | else 65 | return FileInfo[index].FilePath; 66 | } 67 | 68 | //! Get the a filesize of the list 69 | //!\param list index 70 | uint64_t GetFilesize(int32_t index) const; 71 | 72 | //! Is index a dir or a file 73 | //!\param list index 74 | BOOL IsDir(int32_t index) const { 75 | if (!valid(index)) 76 | return false; 77 | return FileInfo[index].isDir; 78 | }; 79 | 80 | //! Get the filecount of the whole list 81 | int32_t GetFilecount() const { 82 | return FileInfo.size(); 83 | }; 84 | 85 | //! Sort list by filepath 86 | void SortList(); 87 | 88 | //! Custom sort command for custom sort functions definitions 89 | void SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b)); 90 | 91 | //! Get the index of the specified filename 92 | int32_t GetFileIndex(const char *filename) const; 93 | 94 | //! Enum for search/filter flags 95 | enum { 96 | Files = 0x01, 97 | Dirs = 0x02, 98 | CheckSubfolders = 0x08, 99 | }; 100 | 101 | protected: 102 | // Internal parser 103 | BOOL InternalLoadPath(std::string &path); 104 | 105 | //!Add a list entrie 106 | void AddEntrie(const std::string &filepath, const char *filename, BOOL isDir); 107 | 108 | //! Clear the list 109 | void ClearList(); 110 | 111 | //! Check if valid pos is requested 112 | inline BOOL valid(uint32_t pos) const { 113 | return (pos < FileInfo.size()); 114 | }; 115 | 116 | uint32_t Flags; 117 | uint32_t Depth; 118 | const char *Filter; 119 | std::vector FileInfo; 120 | }; 121 | 122 | #endif 123 | -------------------------------------------------------------------------------- /src/fs/CFile.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | CFile::CFile() { 9 | iFd = -1; 10 | mem_file = nullptr; 11 | filesize = 0; 12 | pos = 0; 13 | } 14 | 15 | CFile::CFile(const std::string &filepath, eOpenTypes mode) { 16 | iFd = -1; 17 | this->open(filepath, mode); 18 | } 19 | 20 | CFile::CFile(const uint8_t *mem, int32_t size) { 21 | iFd = -1; 22 | this->open(mem, size); 23 | } 24 | 25 | CFile::~CFile() { 26 | this->close(); 27 | } 28 | 29 | int32_t CFile::open(const std::string &filepath, eOpenTypes mode) { 30 | this->close(); 31 | int32_t openMode = 0; 32 | 33 | // This depend on the devoptab implementation. 34 | // see https://github.com/devkitPro/wut/blob/master/libraries/wutdevoptab/devoptab_fs_open.c#L21 fpr reference 35 | 36 | switch (mode) { 37 | default: 38 | case ReadOnly: // file must exist 39 | openMode = O_RDONLY; 40 | break; 41 | case WriteOnly: // file will be created / zerod 42 | openMode = O_TRUNC | O_CREAT | O_WRONLY; 43 | break; 44 | case ReadWrite: // file must exist 45 | openMode = O_RDWR; 46 | break; 47 | case Append: // append to file, file will be created if missing. write only 48 | openMode = O_CREAT | O_APPEND | O_WRONLY; 49 | break; 50 | } 51 | 52 | //! Using fopen works only on the first launch as expected 53 | //! on the second launch it causes issues because we don't overwrite 54 | //! the .data sections which is needed for a normal application to re-init 55 | //! this will be added with launching as RPX 56 | iFd = ::open(filepath.c_str(), openMode); 57 | if (iFd < 0) 58 | return iFd; 59 | 60 | 61 | filesize = ::lseek(iFd, 0, SEEK_END); 62 | ::lseek(iFd, 0, SEEK_SET); 63 | 64 | return 0; 65 | } 66 | 67 | int32_t CFile::open(const uint8_t *mem, int32_t size) { 68 | this->close(); 69 | 70 | mem_file = mem; 71 | filesize = size; 72 | 73 | return 0; 74 | } 75 | 76 | void CFile::close() { 77 | if (iFd >= 0) 78 | ::close(iFd); 79 | 80 | iFd = -1; 81 | mem_file = NULL; 82 | filesize = 0; 83 | pos = 0; 84 | } 85 | 86 | int32_t CFile::read(uint8_t *ptr, size_t size) { 87 | if (iFd >= 0) { 88 | int32_t ret = ::read(iFd, ptr, size); 89 | if (ret > 0) 90 | pos += ret; 91 | return ret; 92 | } 93 | 94 | int32_t readsize = size; 95 | 96 | if (readsize > (int64_t) (filesize - pos)) 97 | readsize = filesize - pos; 98 | 99 | if (readsize <= 0) 100 | return readsize; 101 | 102 | if (mem_file != NULL) { 103 | memcpy(ptr, mem_file + pos, readsize); 104 | pos += readsize; 105 | return readsize; 106 | } 107 | 108 | return -1; 109 | } 110 | 111 | int32_t CFile::write(const uint8_t *ptr, size_t size) { 112 | if (iFd >= 0) { 113 | size_t done = 0; 114 | while (done < size) { 115 | int32_t ret = ::write(iFd, ptr, size - done); 116 | if (ret <= 0) 117 | return ret; 118 | 119 | ptr += ret; 120 | done += ret; 121 | pos += ret; 122 | } 123 | return done; 124 | } 125 | 126 | return -1; 127 | } 128 | 129 | int32_t CFile::seek(long int offset, int32_t origin) { 130 | int32_t ret = 0; 131 | int64_t newPos = pos; 132 | 133 | if (origin == SEEK_SET) { 134 | newPos = offset; 135 | } else if (origin == SEEK_CUR) { 136 | newPos += offset; 137 | } else if (origin == SEEK_END) { 138 | newPos = filesize + offset; 139 | } 140 | 141 | if (newPos < 0) { 142 | pos = 0; 143 | } else { 144 | pos = newPos; 145 | } 146 | 147 | if (iFd >= 0) 148 | ret = ::lseek(iFd, pos, SEEK_SET); 149 | 150 | if (mem_file != NULL) { 151 | if (pos > filesize) { 152 | pos = filesize; 153 | } 154 | } 155 | 156 | return ret; 157 | } 158 | 159 | int32_t CFile::fwrite(const char *format, ...) { 160 | char tmp[512]; 161 | tmp[0] = 0; 162 | int32_t result = -1; 163 | 164 | va_list va; 165 | va_start(va, format); 166 | if ((vsprintf(tmp, format, va) >= 0)) { 167 | result = this->write((uint8_t *) tmp, strlen(tmp)); 168 | } 169 | va_end(va); 170 | 171 | 172 | return result; 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CI-Release](https://github.com/wiiu-env/homebrew_on_menu_plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/wiiu-env/homebrew_on_menu_plugin/actions/workflows/ci.yml) 2 | 3 | # Homebrew on menu 4 | 5 | This plugin allows you to boot homebrew directly from your Wii U Menu. 6 | 7 | ## Installation 8 | (`[ENVIRONMENT]` is a placeholder for the actual environment name.) 9 | 10 | 1. Copy the file `homebrew_on_menu.wps` into `sd:/wiiu/environments/[ENVIRONMENT]/plugins`. 11 | 2. Requires the [WiiUPluginLoaderBackend](https://github.com/wiiu-env/WiiUPluginLoaderBackend) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 12 | 3. Requires the [RPXLoadingModule](https://github.com/wiiu-env/RPXLoadingModule) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 13 | 4. Requires the [WUHBUtilsModule](https://github.com/wiiu-env/WUHBUtilsModule) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 14 | 5. Requires the [ContentRedirectionModule](https://github.com/wiiu-env/ContentRedirectionModule) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 15 | 6. Requires the [SDHotSwapModule](https://github.com/wiiu-env/SDHotSwapModule) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 16 | 7. Requires the [NotificationModule](https://github.com/wiiu-env/NotificationModule) in `sd:/wiiu/environments/[ENVIRONMENT]/modules`. 17 | 18 | ## Usage 19 | 20 | Place your homebrew (`.rpx` or `.wuhb`) in `sd:/wiiu/apps` or any subdirectory inside `sd:/wiiu/apps`. 21 | 22 | Via the plugin config menu (press L, DPAD Down and Minus on the gamepad) you can configure the plugin. The available options are the following: 23 | - **Features**: 24 | - Hide all homebrew [except Homebrew Launcher]: (Default is false) 25 | - Hides all homebrew from the Wii U Menu except the `sd:/wiiu/apps/homebrew_launcher.wuhb` and `sd:/wiiu/apps/homebrew_launcher/homebrew_launcher.wuhb` 26 | - This config item is called "Hide all homebrew" when no `homebrew_launcher.wuhb` is present. 27 | - Prefer .wuhb over .rpx (Default is true) 28 | - Hides a `.rpx` from the Wii U Menu if a `.wuhb` with the same name exists in the same directory. 29 | - Hide all .rpx (Default is false) 30 | - Hides all `.rpx` from the Wii U Menu. 31 | 32 | ## Hide specific apps 33 | 34 | A list of executables to hide can be provided via `sd:/wiiu/apps/.ignore`. This file is a text file, each line contains a file/pattern to exclude. 35 | Every line is considered case-insensitive and relative to `sd:/wiiu/apps/`. Lines starting with "#" will be ignored and can be used for comments. `*` is supported as a wildcard. 36 | 37 | Example: 38 | ``` 39 | # Ignore any .rpx in the my_game sub directory 40 | my_game/*.rpx 41 | # Ignore any executable in the other_game sub directory 42 | other_game/* 43 | # Ignore any executable that starts with "retroarch" 44 | retroarch* 45 | */retroarch* 46 | # Ignore sd:/wiiu/apps/CoolGame.wuhb 47 | CoolGame.wuhb 48 | ``` 49 | 50 | ## Save data redirection 51 | In order to preserve the order of homebrew apps even when you run the Wii U Menu without this plugin, this plugin will redirect the Wii U Menu save data to 52 | `sd:/wiiu/homebrew_on_menu_plugin/[SerialNumberOfTheConsole]/save`. When no save data is found on the sd card, the current save data is copied from the console, 53 | but after that it's never updated. 54 | 55 | **If the plugin is configured to hide any homebrew except a Homebrew Launcher, the redirection is disabled.** 56 | 57 | ## Buildflags 58 | 59 | ### Logging 60 | 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`. 61 | 62 | `make` Logs errors only (via OSReport). 63 | `make DEBUG=1` Enables information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule). 64 | `make DEBUG=VERBOSE` Enables verbose information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule). 65 | 66 | 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. 67 | 68 | ## Building using the Dockerfile 69 | 70 | It's possible to use a docker image for building. This way you don't need anything installed on your host system. 71 | 72 | ``` 73 | # Build docker image (only needed once) 74 | docker build . -t homebrew_on_menu_plugin-builder 75 | 76 | # make 77 | docker run -it --rm -v ${PWD}:/project homebrew_on_menu_plugin-builder make 78 | 79 | # make clean 80 | docker run -it --rm -v ${PWD}:/project homebrew_on_menu_plugin-builder make clean 81 | ``` 82 | 83 | ## Format the code via docker 84 | 85 | `docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src -i` -------------------------------------------------------------------------------- /src/fs/FSUtils.cpp: -------------------------------------------------------------------------------- 1 | #include "fs/FSUtils.h" 2 | #include "fs/CFile.hpp" 3 | #include "utils/logger.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | int32_t FSUtils::LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size) { 11 | //! always initialze input 12 | *inbuffer = NULL; 13 | if (size) 14 | *size = 0; 15 | 16 | int32_t iFd = open(filepath, O_RDONLY); 17 | if (iFd < 0) 18 | return -1; 19 | 20 | uint32_t filesize = lseek(iFd, 0, SEEK_END); 21 | lseek(iFd, 0, SEEK_SET); 22 | 23 | uint8_t *buffer = (uint8_t *) memalign(0x40, filesize); 24 | if (buffer == NULL) { 25 | close(iFd); 26 | return -2; 27 | } 28 | 29 | uint32_t blocksize = 0x100000; 30 | uint32_t done = 0; 31 | int32_t readBytes = 0; 32 | 33 | while (done < filesize) { 34 | if (done + blocksize > filesize) { 35 | blocksize = filesize - done; 36 | } 37 | readBytes = read(iFd, buffer + done, blocksize); 38 | if (readBytes <= 0) 39 | break; 40 | done += readBytes; 41 | } 42 | 43 | close(iFd); 44 | 45 | if (done != filesize) { 46 | free(buffer); 47 | buffer = nullptr; 48 | return -3; 49 | } 50 | 51 | *inbuffer = buffer; 52 | 53 | //! sign is optional input 54 | if (size) { 55 | *size = filesize; 56 | } 57 | 58 | return filesize; 59 | } 60 | 61 | int32_t FSUtils::CheckFile(const char *filepath) { 62 | if (!filepath) 63 | return 0; 64 | 65 | struct stat filestat {}; 66 | 67 | char dirnoslash[strlen(filepath) + 2]; 68 | snprintf(dirnoslash, sizeof(dirnoslash), "%s", filepath); 69 | 70 | while (dirnoslash[strlen(dirnoslash) - 1] == '/') 71 | dirnoslash[strlen(dirnoslash) - 1] = '\0'; 72 | 73 | char *notRoot = strrchr(dirnoslash, '/'); 74 | if (!notRoot) { 75 | strcat(dirnoslash, "/"); 76 | } 77 | 78 | if (stat(dirnoslash, &filestat) == 0) 79 | return 1; 80 | 81 | return 0; 82 | } 83 | 84 | int32_t FSUtils::CreateSubfolder(const char *fullpath) { 85 | if (!fullpath) 86 | return 0; 87 | 88 | int32_t result = 0; 89 | 90 | char dirnoslash[strlen(fullpath) + 1]; 91 | strcpy(dirnoslash, fullpath); 92 | 93 | int32_t pos = strlen(dirnoslash) - 1; 94 | while (dirnoslash[pos] == '/') { 95 | dirnoslash[pos] = '\0'; 96 | pos--; 97 | } 98 | 99 | if (CheckFile(dirnoslash)) { 100 | return 1; 101 | } else { 102 | char parentpath[strlen(dirnoslash) + 2]; 103 | strcpy(parentpath, dirnoslash); 104 | char *ptr = strrchr(parentpath, '/'); 105 | 106 | if (!ptr) { 107 | //!Device root directory (must be with '/') 108 | strcat(parentpath, "/"); 109 | struct stat filestat; 110 | if (stat(parentpath, &filestat) == 0) 111 | return 1; 112 | 113 | return 0; 114 | } 115 | 116 | ptr++; 117 | ptr[0] = '\0'; 118 | 119 | result = CreateSubfolder(parentpath); 120 | } 121 | 122 | if (!result) 123 | return 0; 124 | 125 | if (mkdir(dirnoslash, 0777) == -1) { 126 | return 0; 127 | } 128 | 129 | return 1; 130 | } 131 | 132 | int32_t FSUtils::saveBufferToFile(const char *path, void *buffer, uint32_t size) { 133 | CFile file(path, CFile::WriteOnly); 134 | if (!file.isOpen()) { 135 | DEBUG_FUNCTION_LINE_ERR("Failed to open %s\n", path); 136 | return 0; 137 | } 138 | int32_t written = file.write((const uint8_t *) buffer, size); 139 | file.close(); 140 | return written; 141 | } 142 | 143 | bool FSUtils::copyFile(const std::string &in, const std::string &out) { 144 | // Using C++ buffers is **really** slow. Copying in 1023 byte chunks. 145 | // Let's do it the old way. 146 | size_t size; 147 | 148 | int source = open(in.c_str(), O_RDONLY, 0); 149 | if (source < 0) { 150 | DEBUG_FUNCTION_LINE_ERR("Failed to open source %s", in.c_str()); 151 | 152 | return false; 153 | } 154 | int dest = open(out.c_str(), 0x602, 0644); 155 | if (dest < 0) { 156 | DEBUG_FUNCTION_LINE_ERR("Failed to open dest %s", out.c_str()); 157 | close(source); 158 | return false; 159 | } 160 | 161 | auto bufferSize = 128 * 1024; 162 | char *buf = (char *) malloc(bufferSize); 163 | if (buf == nullptr) { 164 | DEBUG_FUNCTION_LINE_ERR("Failed to alloc buffer"); 165 | return false; 166 | } 167 | 168 | while ((size = read(source, buf, bufferSize)) > 0) { 169 | write(dest, buf, size); 170 | } 171 | 172 | free(buf); 173 | 174 | close(source); 175 | close(dest); 176 | return true; 177 | } 178 | -------------------------------------------------------------------------------- /src/utils/ini.h: -------------------------------------------------------------------------------- 1 | /* inih -- simple .INI file parser 2 | 3 | SPDX-License-Identifier: BSD-3-Clause 4 | 5 | Copyright (C) 2009-2020, Ben Hoyt 6 | 7 | inih is released under the New BSD license (see LICENSE.txt). Go to the project 8 | home page for more info: 9 | 10 | https://github.com/benhoyt/inih 11 | 12 | */ 13 | // clang-format off 14 | #ifndef INI_H 15 | #define INI_H 16 | 17 | /* Make this header file easier to include in C++ code */ 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | #include 23 | 24 | /* Nonzero if ini_handler callback should accept lineno parameter. */ 25 | #ifndef INI_HANDLER_LINENO 26 | #define INI_HANDLER_LINENO 0 27 | #endif 28 | 29 | /* Typedef for prototype of handler function. */ 30 | #if INI_HANDLER_LINENO 31 | typedef int (*ini_handler)(void* user, const char* section, 32 | const char* name, const char* value, 33 | int lineno); 34 | #else 35 | typedef int (*ini_handler)(void* user, const char* section, 36 | const char* name, const char* value); 37 | #endif 38 | 39 | /* Typedef for prototype of fgets-style reader function. */ 40 | typedef char* (*ini_reader)(char* str, int num, void* stream); 41 | 42 | /* Parse given INI-style file. May have [section]s, name=value pairs 43 | (whitespace stripped), and comments starting with ';' (semicolon). Section 44 | is "" if name=value pair parsed before any section heading. name:value 45 | pairs are also supported as a concession to Python's configparser. 46 | 47 | For each name=value pair parsed, call handler function with given user 48 | pointer as well as section, name, and value (data only valid for duration 49 | of handler call). Handler should return nonzero on success, zero on error. 50 | 51 | Returns 0 on success, line number of first error on parse error (doesn't 52 | stop on first error), -1 on file open error, or -2 on memory allocation 53 | error (only when INI_USE_STACK is zero). 54 | */ 55 | int ini_parse(const char* filename, ini_handler handler, void* user); 56 | 57 | /* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't 58 | close the file when it's finished -- the caller must do that. */ 59 | int ini_parse_file(FILE* file, ini_handler handler, void* user); 60 | 61 | /* Same as ini_parse(), but takes an ini_reader function pointer instead of 62 | filename. Used for implementing custom or string-based I/O (see also 63 | ini_parse_string). */ 64 | int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, 65 | void* user); 66 | 67 | /* Same as ini_parse(), but takes a zero-terminated string with the INI data 68 | instead of a file. Useful for parsing INI data from a network socket or 69 | already in memory. */ 70 | int ini_parse_string(const char* string, ini_handler handler, void* user); 71 | 72 | /* Nonzero to allow multi-line value parsing, in the style of Python's 73 | configparser. If allowed, ini_parse() will call the handler with the same 74 | name for each subsequent line parsed. */ 75 | #ifndef INI_ALLOW_MULTILINE 76 | #define INI_ALLOW_MULTILINE 1 77 | #endif 78 | 79 | /* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of 80 | the file. See https://github.com/benhoyt/inih/issues/21 */ 81 | #ifndef INI_ALLOW_BOM 82 | #define INI_ALLOW_BOM 1 83 | #endif 84 | 85 | /* Chars that begin a start-of-line comment. Per Python configparser, allow 86 | both ; and # comments at the start of a line by default. */ 87 | #ifndef INI_START_COMMENT_PREFIXES 88 | #define INI_START_COMMENT_PREFIXES ";#" 89 | #endif 90 | 91 | /* Nonzero to allow inline comments (with valid inline comment characters 92 | specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match 93 | Python 3.2+ configparser behaviour. */ 94 | #ifndef INI_ALLOW_INLINE_COMMENTS 95 | #define INI_ALLOW_INLINE_COMMENTS 1 96 | #endif 97 | #ifndef INI_INLINE_COMMENT_PREFIXES 98 | #define INI_INLINE_COMMENT_PREFIXES ";" 99 | #endif 100 | 101 | /* Nonzero to use stack for line buffer, zero to use heap (malloc/free). */ 102 | #ifndef INI_USE_STACK 103 | #define INI_USE_STACK 1 104 | #endif 105 | 106 | /* Maximum line length for any line in INI file (stack or heap). Note that 107 | this must be 3 more than the longest line (due to '\r', '\n', and '\0'). */ 108 | #ifndef INI_MAX_LINE 109 | #define INI_MAX_LINE 200 110 | #endif 111 | 112 | /* Nonzero to allow heap line buffer to grow via realloc(), zero for a 113 | fixed-size buffer of INI_MAX_LINE bytes. Only applies if INI_USE_STACK is 114 | zero. */ 115 | #ifndef INI_ALLOW_REALLOC 116 | #define INI_ALLOW_REALLOC 0 117 | #endif 118 | 119 | /* Initial size in bytes for heap line buffer. Only applies if INI_USE_STACK 120 | is zero. */ 121 | #ifndef INI_INITIAL_ALLOC 122 | #define INI_INITIAL_ALLOC 200 123 | #endif 124 | 125 | /* Stop parsing on first error (default is to keep parsing). */ 126 | #ifndef INI_STOP_ON_FIRST_ERROR 127 | #define INI_STOP_ON_FIRST_ERROR 0 128 | #endif 129 | 130 | /* Nonzero to call the handler at the start of each new section (with 131 | name and value NULL). Default is to only call the handler on 132 | each name=value pair. */ 133 | #ifndef INI_CALL_HANDLER_ON_NEW_SECTION 134 | #define INI_CALL_HANDLER_ON_NEW_SECTION 0 135 | #endif 136 | 137 | /* Nonzero to allow a name without a value (no '=' or ':' on the line) and 138 | call the handler with value NULL in this case. Default is to treat 139 | no-value lines as an error. */ 140 | #ifndef INI_ALLOW_NO_VALUE 141 | #define INI_ALLOW_NO_VALUE 0 142 | #endif 143 | 144 | /* Nonzero to use custom ini_malloc, ini_free, and ini_realloc memory 145 | allocation functions (INI_USE_STACK must also be 0). These functions must 146 | have the same signatures as malloc/free/realloc and behave in a similar 147 | way. ini_realloc is only needed if INI_ALLOW_REALLOC is set. */ 148 | #ifndef INI_CUSTOM_ALLOCATOR 149 | #define INI_CUSTOM_ALLOCATOR 0 150 | #endif 151 | 152 | 153 | #ifdef __cplusplus 154 | } 155 | #endif 156 | 157 | #endif /* INI_H */ 158 | -------------------------------------------------------------------------------- /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)/wups/share/wups_rules 12 | 13 | WUT_ROOT := $(DEVKITPRO)/wut 14 | WUMS_ROOT := $(DEVKITPRO)/wums 15 | 16 | #------------------------------------------------------------------------------- 17 | # TARGET is the name of the output 18 | # BUILD is the directory where object files & intermediate files will be placed 19 | # SOURCES is a list of directories containing source code 20 | # DATA is a list of directories containing data files 21 | # INCLUDES is a list of directories containing header files 22 | #------------------------------------------------------------------------------- 23 | TARGET := homebrew_on_menu 24 | BUILD := build 25 | SOURCES := src \ 26 | src/fs \ 27 | src/utils 28 | DATA := data 29 | INCLUDES := src 30 | 31 | #------------------------------------------------------------------------------- 32 | # options for code generation 33 | #------------------------------------------------------------------------------- 34 | CFLAGS := -Wall -O2 -ffunction-sections \ 35 | $(MACHDEP) 36 | 37 | CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__ -D__WUPS__ 38 | 39 | CXXFLAGS := $(CFLAGS) -std=c++20 40 | 41 | ASFLAGS := -g $(ARCH) 42 | LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) $(WUPSSPECS) 43 | 44 | ifeq ($(DEBUG),1) 45 | CXXFLAGS += -DDEBUG -g 46 | CFLAGS += -DDEBUG -g 47 | endif 48 | 49 | ifeq ($(DEBUG),VERBOSE) 50 | CXXFLAGS += -DDEBUG -DVERBOSE_DEBUG -g 51 | CFLAGS += -DDEBUG -DVERBOSE_DEBUG -g 52 | endif 53 | 54 | LIBS := -lwups -lwut -lwuhbutils -lcontentredirection -lrpxloader -lsdutils -lnotifications 55 | 56 | #------------------------------------------------------------------------------- 57 | # list of directories containing libraries, this must be the top level 58 | # containing include and lib 59 | #------------------------------------------------------------------------------- 60 | LIBDIRS := $(PORTLIBS) $(WUPS_ROOT) $(WUMS_ROOT) $(WUT_ROOT) 61 | 62 | #------------------------------------------------------------------------------- 63 | # no real need to edit anything past this point unless you need to add additional 64 | # rules for different file extensions 65 | #------------------------------------------------------------------------------- 66 | ifneq ($(BUILD),$(notdir $(CURDIR))) 67 | #------------------------------------------------------------------------------- 68 | 69 | export OUTPUT := $(CURDIR)/$(TARGET) 70 | export TOPDIR := $(CURDIR) 71 | 72 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 73 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 74 | 75 | export DEPSDIR := $(CURDIR)/$(BUILD) 76 | 77 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) 78 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) 79 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) 80 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 81 | 82 | #------------------------------------------------------------------------------- 83 | # use CXX for linking C++ projects, CC for standard C 84 | #------------------------------------------------------------------------------- 85 | ifeq ($(strip $(CPPFILES)),) 86 | #------------------------------------------------------------------------------- 87 | export LD := $(CC) 88 | #------------------------------------------------------------------------------- 89 | else 90 | #------------------------------------------------------------------------------- 91 | export LD := $(CXX) 92 | #------------------------------------------------------------------------------- 93 | endif 94 | #------------------------------------------------------------------------------- 95 | 96 | export OFILES_BIN := $(addsuffix .o,$(BINFILES)) 97 | export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) 98 | export OFILES := $(OFILES_BIN) $(OFILES_SRC) 99 | export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) 100 | 101 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ 102 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 103 | -I$(CURDIR)/$(BUILD) 104 | 105 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) 106 | 107 | .PHONY: $(BUILD) clean all 108 | 109 | #------------------------------------------------------------------------------- 110 | all: $(BUILD) 111 | 112 | $(BUILD): 113 | @$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD)) 114 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 115 | 116 | #------------------------------------------------------------------------------- 117 | clean: 118 | @echo clean ... 119 | @rm -fr $(BUILD) $(TARGET).wps $(TARGET).elf 120 | 121 | #------------------------------------------------------------------------------- 122 | else 123 | .PHONY: all 124 | 125 | DEPENDS := $(OFILES:.o=.d) 126 | 127 | #------------------------------------------------------------------------------- 128 | # main targets 129 | #------------------------------------------------------------------------------- 130 | all : $(OUTPUT).wps 131 | 132 | $(OUTPUT).wps : $(OUTPUT).elf 133 | $(OUTPUT).elf : $(OFILES) 134 | 135 | $(OFILES_SRC) : $(HFILES_BIN) 136 | 137 | #------------------------------------------------------------------------------- 138 | # you need a rule like this for each extension you use as binary data 139 | #------------------------------------------------------------------------------- 140 | %.bin.o %_bin.h : %.bin 141 | #------------------------------------------------------------------------------- 142 | @echo $(notdir $<) 143 | @$(bin2o) 144 | 145 | #--------------------------------------------------------------------------------- 146 | %.tga.o %_tga.h : %.tga 147 | @echo $(notdir $<) 148 | @$(bin2o) 149 | 150 | #--------------------------------------------------------------------------------- 151 | %.h264.o %_h264.h : %.h264 152 | @echo $(notdir $<) 153 | @$(bin2o) 154 | 155 | #--------------------------------------------------------------------------------- 156 | 157 | -include $(DEPENDS) 158 | 159 | #------------------------------------------------------------------------------- 160 | endif 161 | #------------------------------------------------------------------------------- 162 | -------------------------------------------------------------------------------- /src/fs/DirList.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * Copyright (C) 2010 3 | * by Dimok 4 | * 5 | * This software is provided 'as-is', without any express or implied 6 | * warranty. In no event will the authors be held liable for any 7 | * damages arising from the use of this software. 8 | * 9 | * Permission is granted to anyone to use this software for any 10 | * purpose, including commercial applications, and to alter it and 11 | * redistribute it freely, subject to the following restrictions: 12 | * 13 | * 1. The origin of this software must not be misrepresented; you 14 | * must not claim that you wrote the original software. If you use 15 | * this software in a product, an acknowledgment in the product 16 | * documentation would be appreciated but is not required. 17 | * 18 | * 2. Altered source versions must be plainly marked as such, and 19 | * must not be misrepresented as being the original software. 20 | * 21 | * 3. This notice may not be removed or altered from any source 22 | * distribution. 23 | * 24 | * DirList Class 25 | * for WiiXplorer 2010 26 | ***************************************************************************/ 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #include 37 | #include 38 | 39 | DirList::DirList() { 40 | Flags = 0; 41 | Filter = 0; 42 | Depth = 0; 43 | } 44 | 45 | DirList::DirList(const std::string &path, const char *filter, uint32_t flags, uint32_t maxDepth) { 46 | this->LoadPath(path, filter, flags, maxDepth); 47 | this->SortList(); 48 | } 49 | 50 | DirList::~DirList() { 51 | ClearList(); 52 | } 53 | 54 | BOOL DirList::LoadPath(const std::string &folder, const char *filter, uint32_t flags, uint32_t maxDepth) { 55 | if (folder.empty()) 56 | return false; 57 | 58 | Flags = flags; 59 | Filter = filter; 60 | Depth = maxDepth; 61 | 62 | std::string folderpath(folder); 63 | uint32_t length = folderpath.size(); 64 | 65 | //! clear relativeFilepath of double slashes 66 | StringTools::RemoveDoubleSlashs(folderpath); 67 | 68 | //! remove last slash if exists 69 | if (length > 0 && folderpath[length - 1] == '/') 70 | folderpath.erase(length - 1); 71 | 72 | //! add root slash if missing 73 | if (folderpath.find('/') == std::string::npos) { 74 | folderpath += '/'; 75 | } 76 | 77 | return InternalLoadPath(folderpath); 78 | } 79 | 80 | BOOL DirList::InternalLoadPath(std::string &folderpath) { 81 | if (folderpath.size() < 3) 82 | return false; 83 | 84 | struct dirent *dirent = NULL; 85 | DIR *dir = NULL; 86 | 87 | dir = opendir(folderpath.c_str()); 88 | if (dir == NULL) 89 | return false; 90 | 91 | while ((dirent = readdir(dir)) != 0) { 92 | BOOL isDir = dirent->d_type & DT_DIR; 93 | const char *filename = dirent->d_name; 94 | 95 | if (isDir) { 96 | if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) 97 | continue; 98 | 99 | if ((Flags & CheckSubfolders) && (Depth > 0)) { 100 | int32_t length = folderpath.size(); 101 | if (length > 2 && folderpath[length - 1] != '/') { 102 | folderpath += '/'; 103 | } 104 | folderpath += filename; 105 | 106 | Depth--; 107 | InternalLoadPath(folderpath); 108 | folderpath.erase(length); 109 | Depth++; 110 | } 111 | 112 | if (!(Flags & Dirs)) 113 | continue; 114 | } else if (!(Flags & Files)) { 115 | continue; 116 | } 117 | 118 | if (Filter) { 119 | char *fileext = strrchr(filename, '.'); 120 | if (!fileext) 121 | continue; 122 | 123 | if (StringTools::strtokcmp(fileext, Filter, ",") == 0) 124 | AddEntrie(folderpath, filename, isDir); 125 | } else { 126 | AddEntrie(folderpath, filename, isDir); 127 | } 128 | } 129 | closedir(dir); 130 | 131 | return true; 132 | } 133 | 134 | void DirList::AddEntrie(const std::string &filepath, const char *filename, BOOL isDir) { 135 | if (!filename) 136 | return; 137 | 138 | int32_t pos = FileInfo.size(); 139 | 140 | FileInfo.resize(pos + 1); 141 | 142 | FileInfo[pos].FilePath = (char *) malloc(filepath.size() + strlen(filename) + 2); 143 | if (!FileInfo[pos].FilePath) { 144 | FileInfo.resize(pos); 145 | return; 146 | } 147 | 148 | sprintf(FileInfo[pos].FilePath, "%s/%s", filepath.c_str(), filename); 149 | FileInfo[pos].isDir = isDir; 150 | } 151 | 152 | void DirList::ClearList() { 153 | for (uint32_t i = 0; i < FileInfo.size(); ++i) { 154 | if (FileInfo[i].FilePath) { 155 | free(FileInfo[i].FilePath); 156 | FileInfo[i].FilePath = NULL; 157 | } 158 | } 159 | 160 | FileInfo.clear(); 161 | std::vector().swap(FileInfo); 162 | } 163 | 164 | const char *DirList::GetFilename(int32_t ind) const { 165 | if (!valid(ind)) 166 | return ""; 167 | 168 | return StringTools::FullpathToFilename(FileInfo[ind].FilePath); 169 | } 170 | 171 | static BOOL SortCallback(const DirEntry &f1, const DirEntry &f2) { 172 | if (f1.isDir && !(f2.isDir)) 173 | return true; 174 | if (!(f1.isDir) && f2.isDir) 175 | return false; 176 | 177 | if (f1.FilePath && !f2.FilePath) 178 | return true; 179 | if (!f1.FilePath) 180 | return false; 181 | 182 | if (strcasecmp(f1.FilePath, f2.FilePath) > 0) 183 | return false; 184 | 185 | return true; 186 | } 187 | 188 | void DirList::SortList() { 189 | if (FileInfo.size() > 1) 190 | std::sort(FileInfo.begin(), FileInfo.end(), SortCallback); 191 | } 192 | 193 | void DirList::SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b)) { 194 | if (FileInfo.size() > 1) 195 | std::sort(FileInfo.begin(), FileInfo.end(), SortFunc); 196 | } 197 | 198 | uint64_t DirList::GetFilesize(int32_t index) const { 199 | struct stat st; 200 | const char *path = GetFilepath(index); 201 | 202 | if (!path || stat(path, &st) != 0) 203 | return 0; 204 | 205 | return st.st_size; 206 | } 207 | 208 | int32_t DirList::GetFileIndex(const char *filename) const { 209 | if (!filename) 210 | return -1; 211 | 212 | for (uint32_t i = 0; i < FileInfo.size(); ++i) { 213 | if (strcasecmp(GetFilename(i), filename) == 0) 214 | return i; 215 | } 216 | 217 | return -1; 218 | } 219 | -------------------------------------------------------------------------------- /src/SaveRedirection.cpp: -------------------------------------------------------------------------------- 1 | #include "SaveRedirection.h" 2 | #include "globals.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | bool gInWiiUMenu __attribute__((section(".data"))) = false; 17 | CRLayerHandle saveLayer __attribute__((section(".data"))) = 0; 18 | 19 | static inline std::string getBaseSavePathLegacy() { 20 | return std::string(HOMEBREW_ON_MENU_PLUGIN_DATA_PATH) + "/save"; 21 | } 22 | 23 | static inline std::string getBaseSavePathLegacyFS() { 24 | return std::string("fs:") + getBaseSavePathLegacy(); 25 | } 26 | 27 | static inline std::string getBaseSavePath() { 28 | return string_format(HOMEBREW_ON_MENU_PLUGIN_DATA_PATH "/%s/save", gSerialId.c_str()); 29 | } 30 | 31 | static inline std::string getBaseSavePathFS() { 32 | return "fs:" + getBaseSavePath(); 33 | } 34 | 35 | void SaveRedirectionCleanUp() { 36 | if (saveLayer != 0) { 37 | DEBUG_FUNCTION_LINE("Remove save redirection: %s -> %s", "/vol/save", getBaseSavePathFS().c_str()); 38 | auto res = ContentRedirection_RemoveFSLayer(saveLayer); 39 | if (res != CONTENT_REDIRECTION_RESULT_SUCCESS) { 40 | DEBUG_FUNCTION_LINE_ERR("Failed to remove save FSLayer"); 41 | } 42 | saveLayer = 0; 43 | } 44 | } 45 | 46 | void CopyExistingFiles() { 47 | nn::act::Initialize(); 48 | nn::act::PersistentId persistentId = nn::act::GetPersistentId(); 49 | nn::act::Finalize(); 50 | 51 | std::string user = string_format("%s/%08X", getBaseSavePathFS().c_str(), 0x80000000 | persistentId); 52 | std::string userLegacy = string_format("%s/%08X", getBaseSavePathLegacyFS().c_str(), 0x80000000 | persistentId); 53 | std::string userOriginal = string_format("fs:/vol/save/%08X", 0x80000000 | persistentId); 54 | 55 | FSUtils::CreateSubfolder(user.c_str()); 56 | 57 | auto BaristaAccountSaveFilePathNew = user + "/BaristaAccountSaveFile.dat"; 58 | auto BaristaAccountSaveFilePathOriginal = userOriginal + "/BaristaAccountSaveFile.dat"; 59 | auto BaristaAccountSaveFilePathLegacy = userLegacy + "/BaristaAccountSaveFile.dat"; 60 | if (!FSUtils::CheckFile(BaristaAccountSaveFilePathNew.c_str())) { 61 | if (FSUtils::CheckFile(BaristaAccountSaveFilePathLegacy.c_str())) { 62 | DEBUG_FUNCTION_LINE("Copy %s to %s", BaristaAccountSaveFilePathLegacy.c_str(), BaristaAccountSaveFilePathNew.c_str()); 63 | if (!FSUtils::copyFile(BaristaAccountSaveFilePathLegacy, BaristaAccountSaveFilePathNew)) { 64 | DEBUG_FUNCTION_LINE_ERR("Failed to copy file: %s -> %s", BaristaAccountSaveFilePathLegacy.c_str(), BaristaAccountSaveFilePathNew.c_str()); 65 | } else { 66 | if (remove(BaristaAccountSaveFilePathLegacy.c_str()) < 0) { 67 | DEBUG_FUNCTION_LINE_ERR("Failed to delete %s", BaristaAccountSaveFilePathLegacy.c_str()); 68 | } 69 | } 70 | } else { 71 | DEBUG_FUNCTION_LINE("Copy %s to %s", BaristaAccountSaveFilePathOriginal.c_str(), BaristaAccountSaveFilePathNew.c_str()); 72 | if (!FSUtils::copyFile(BaristaAccountSaveFilePathOriginal, BaristaAccountSaveFilePathNew)) { 73 | DEBUG_FUNCTION_LINE_ERR("Failed to copy file: %s -> %s", BaristaAccountSaveFilePathOriginal.c_str(), BaristaAccountSaveFilePathNew.c_str()); 74 | } 75 | } 76 | } 77 | } 78 | 79 | void initSaveData() { 80 | SaveRedirectionCleanUp(); 81 | CopyExistingFiles(); 82 | 83 | nn::act::Initialize(); 84 | nn::act::PersistentId persistentId = nn::act::GetPersistentId(); 85 | nn::act::Finalize(); 86 | 87 | std::string replaceDir = string_format("%s/%08X", getBaseSavePathFS().c_str(), 0x80000000 | persistentId); 88 | DEBUG_FUNCTION_LINE("Setup save redirection: %s -> %s", string_format("/vol/save/%08X", 0x80000000 | persistentId), replaceDir.c_str()); 89 | auto res = ContentRedirection_AddFSLayer(&saveLayer, "homp_save_redirection", replaceDir.c_str(), FS_LAYER_TYPE_SAVE_REPLACE_FOR_CURRENT_USER); 90 | if (res != CONTENT_REDIRECTION_RESULT_SUCCESS) { 91 | DEBUG_FUNCTION_LINE_ERR("Failed to add save FS Layer: %d", res); 92 | NotificationModule_AddErrorNotification("homebrew on menu plugin: Failed to initialize /vol/save redirection"); 93 | } 94 | } 95 | 96 | DECL_FUNCTION(int32_t, LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, nn::act::SlotNo slot, nn::act::ACTLoadOption unk1, char const *unk2, bool unk3) { 97 | int32_t result = real_LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb(slot, unk1, unk2, unk3); 98 | if (result >= 0 && gInWiiUMenu) { 99 | DEBUG_FUNCTION_LINE("Changed account, we need to init the save data"); 100 | // If the account has changed, we need to init save data for this account 101 | initSaveData(); 102 | } 103 | 104 | return result; 105 | } 106 | 107 | extern bool gHideHomebrew; 108 | extern bool sSDIsMounted; 109 | DECL_FUNCTION(int32_t, SAVEInit) { 110 | auto res = real_SAVEInit(); 111 | if (res >= 0) { 112 | if (!sSDIsMounted || gHideHomebrew) { 113 | DEBUG_FUNCTION_LINE_VERBOSE("Skip SD redirection, no SD Card is mounted"); 114 | return res; 115 | } 116 | if (OSGetTitleID() == 0x0005001010040000L || // Wii U Menu JPN 117 | OSGetTitleID() == 0x0005001010040100L || // Wii U Menu USA 118 | OSGetTitleID() == 0x0005001010040200L) { // Wii U Menu EUR 119 | 120 | initSaveData(); 121 | gInWiiUMenu = true; 122 | } else { 123 | gInWiiUMenu = false; 124 | } 125 | } 126 | 127 | return res; 128 | } 129 | 130 | DECL_FUNCTION(FSError, FSGetLastErrorCodeForViewer, FSClient *client) { 131 | auto res = real_FSGetLastErrorCodeForViewer(client); 132 | if (!gInWiiUMenu) { 133 | return res; 134 | } 135 | if ((uint32_t) res == 1503030) { 136 | // If we encounter error 1503030 when running the Wii U Menu we probably hit a Wii U Menu save related issue 137 | // Either the sd card is write locked or the save on the sd card it corrupted. Let the user now about this. 138 | 139 | std::string deleteHint = string_format("If not write locked, backup and delete this directory: \"sd:" HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE "/%s\".", gSerialId.c_str()); 140 | NotificationModuleHandle handle; 141 | 142 | NotificationModule_AddDynamicNotification("Caution: This resets the order of application on the Wii U Menu when using Aroma.", &handle); 143 | NotificationModule_AddDynamicNotification("", &handle); 144 | NotificationModule_AddDynamicNotification(deleteHint.c_str(), &handle); 145 | NotificationModule_AddDynamicNotification("", &handle); 146 | NotificationModule_AddDynamicNotification("", &handle); 147 | NotificationModule_AddDynamicNotification("The SD card appears to be write-locked or the Wii U Menu save on the SD card is corrupted. Check the SD card write lock.", &handle); 148 | } 149 | return res; 150 | } 151 | 152 | WUPS_MUST_REPLACE_FOR_PROCESS(SAVEInit, WUPS_LOADER_LIBRARY_NN_SAVE, SAVEInit, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 153 | WUPS_MUST_REPLACE_FOR_PROCESS(LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, WUPS_LOADER_LIBRARY_NN_ACT, LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 154 | WUPS_MUST_REPLACE_FOR_PROCESS(FSGetLastErrorCodeForViewer, WUPS_LOADER_LIBRARY_COREINIT, FSGetLastErrorCodeForViewer, WUPS_FP_TARGET_PROCESS_WII_U_MENU); -------------------------------------------------------------------------------- /src/utils/fnmatch.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1989, 1993, 1994 3 | * The Regents of the University of California. All rights reserved. 4 | * 5 | * This code is derived from software contributed to Berkeley by 6 | * Guido van Rossum. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions 10 | * are met: 11 | * 1. Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * 2. Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * 3. All advertising materials mentioning features or use of this software 17 | * must display the following acknowledgement: 18 | * This product includes software developed by the University of 19 | * California, Berkeley and its contributors. 20 | * 4. Neither the name of the University nor the names of its contributors 21 | * may be used to endorse or promote products derived from this software 22 | * without specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 | * SUCH DAMAGE. 35 | * 36 | * From FreeBSD fnmatch.c 1.11 37 | * $Id: fnmatch.c,v 1.3 1997/08/19 02:34:30 jdp Exp $ 38 | */ 39 | 40 | #define _GNU_SOURCE 41 | 42 | #if defined(LIBC_SCCS) && !defined(lint) 43 | static char sccsid[] = "@(#)fnmatch.c 8.2 (Berkeley) 4/16/94"; 44 | #endif /* LIBC_SCCS and not lint */ 45 | 46 | /* 47 | * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. 48 | * Compares a filename or pathname to a pattern. 49 | */ 50 | 51 | #include 52 | #include 53 | #include 54 | 55 | #include "fnmatch.h" 56 | 57 | #define EOS '\0' 58 | 59 | #define FNM_PREFIX_DIRS 0x20 /* Directory prefixes of pattern match too. */ 60 | 61 | static const char *rangematch(const char *, char, int); 62 | 63 | int fnmatch(const char *pattern, const char *string, int flags) { 64 | const char *stringstart; 65 | char c, test; 66 | 67 | for (stringstart = string;;) 68 | switch (c = *pattern++) { 69 | case EOS: 70 | if ((flags & FNM_LEADING_DIR) && *string == '/') 71 | return (0); 72 | return (*string == EOS ? 0 : FNM_NOMATCH); 73 | case '?': 74 | if (*string == EOS) 75 | return (FNM_NOMATCH); 76 | if (*string == '/' && (flags & FNM_PATHNAME)) 77 | return (FNM_NOMATCH); 78 | if (*string == '.' && (flags & FNM_PERIOD) && 79 | (string == stringstart || 80 | ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) 81 | return (FNM_NOMATCH); 82 | ++string; 83 | break; 84 | case '*': 85 | c = *pattern; 86 | /* Collapse multiple stars. */ 87 | while (c == '*') 88 | c = *++pattern; 89 | 90 | if (*string == '.' && (flags & FNM_PERIOD) && 91 | (string == stringstart || 92 | ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) 93 | return (FNM_NOMATCH); 94 | 95 | /* Optimize for pattern with * at end or before /. */ 96 | if (c == EOS) 97 | if (flags & FNM_PATHNAME) 98 | return ((flags & FNM_LEADING_DIR) || 99 | strchr(string, '/') == NULL 100 | ? 0 101 | : FNM_NOMATCH); 102 | else 103 | return (0); 104 | else if (c == '/' && flags & FNM_PATHNAME) { 105 | if ((string = strchr(string, '/')) == NULL) 106 | return (FNM_NOMATCH); 107 | break; 108 | } 109 | 110 | /* General case, use recursion. */ 111 | while ((test = *string) != EOS) { 112 | if (!fnmatch(pattern, string, flags & ~FNM_PERIOD)) 113 | return (0); 114 | if (test == '/' && flags & FNM_PATHNAME) 115 | break; 116 | ++string; 117 | } 118 | return (FNM_NOMATCH); 119 | case '[': 120 | if (*string == EOS) 121 | return (FNM_NOMATCH); 122 | if (*string == '/' && flags & FNM_PATHNAME) 123 | return (FNM_NOMATCH); 124 | if ((pattern = 125 | rangematch(pattern, *string, flags)) == NULL) 126 | return (FNM_NOMATCH); 127 | ++string; 128 | break; 129 | case '\\': 130 | if (!(flags & FNM_NOESCAPE)) { 131 | if ((c = *pattern++) == EOS) { 132 | c = '\\'; 133 | --pattern; 134 | } 135 | } 136 | /* FALLTHROUGH */ 137 | default: 138 | if (c == *string) 139 | ; 140 | else if ((flags & FNM_CASEFOLD) && 141 | (tolower((unsigned char) c) == 142 | tolower((unsigned char) *string))) 143 | ; 144 | else if ((flags & FNM_PREFIX_DIRS) && *string == EOS && 145 | ((c == '/' && string != stringstart) || 146 | (string == stringstart + 1 && *stringstart == '/'))) 147 | return (0); 148 | else 149 | return (FNM_NOMATCH); 150 | string++; 151 | break; 152 | } 153 | /* NOTREACHED */ 154 | } 155 | 156 | static const char * 157 | rangematch(const char *pattern, char test, int flags) { 158 | int negate, ok; 159 | char c, c2; 160 | 161 | /* 162 | * A bracket expression starting with an unquoted circumflex 163 | * character produces unspecified results (IEEE 1003.2-1992, 164 | * 3.13.2). This implementation treats it like '!', for 165 | * consistency with the regular expression syntax. 166 | * J.T. Conklin (conklin@ngai.kaleida.com) 167 | */ 168 | if ((negate = (*pattern == '!' || *pattern == '^'))) 169 | ++pattern; 170 | 171 | if (flags & FNM_CASEFOLD) 172 | test = tolower((unsigned char) test); 173 | 174 | for (ok = 0; (c = *pattern++) != ']';) { 175 | if (c == '\\' && !(flags & FNM_NOESCAPE)) 176 | c = *pattern++; 177 | if (c == EOS) 178 | return (NULL); 179 | 180 | if (flags & FNM_CASEFOLD) 181 | c = tolower((unsigned char) c); 182 | 183 | if (*pattern == '-' && (c2 = *(pattern + 1)) != EOS && c2 != ']') { 184 | pattern += 2; 185 | if (c2 == '\\' && !(flags & FNM_NOESCAPE)) 186 | c2 = *pattern++; 187 | if (c2 == EOS) 188 | return (NULL); 189 | 190 | if (flags & FNM_CASEFOLD) 191 | c2 = tolower((unsigned char) c2); 192 | 193 | if ((unsigned char) c <= (unsigned char) test && 194 | (unsigned char) test <= (unsigned char) c2) 195 | ok = 1; 196 | } else if (c == test) 197 | ok = 1; 198 | } 199 | return (ok == negate ? NULL : pattern); 200 | } 201 | -------------------------------------------------------------------------------- /src/utils/ini.c: -------------------------------------------------------------------------------- 1 | /* inih -- simple .INI file parser 2 | 3 | SPDX-License-Identifier: BSD-3-Clause 4 | 5 | Copyright (C) 2009-2020, Ben Hoyt 6 | 7 | inih is released under the New BSD license (see LICENSE.txt). Go to the project 8 | home page for more info: 9 | 10 | https://github.com/benhoyt/inih 11 | 12 | */ 13 | // clang-format off 14 | #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) 15 | #define _CRT_SECURE_NO_WARNINGS 16 | #endif 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | #include "ini.h" 23 | 24 | #if !INI_USE_STACK 25 | #if INI_CUSTOM_ALLOCATOR 26 | #include 27 | void* ini_malloc(size_t size); 28 | void ini_free(void* ptr); 29 | void* ini_realloc(void* ptr, size_t size); 30 | #else 31 | #include 32 | #define ini_malloc malloc 33 | #define ini_free free 34 | #define ini_realloc realloc 35 | #endif 36 | #endif 37 | 38 | #define MAX_SECTION 50 39 | #define MAX_NAME 50 40 | 41 | /* Used by ini_parse_string() to keep track of string parsing state. */ 42 | typedef struct { 43 | const char* ptr; 44 | size_t num_left; 45 | } ini_parse_string_ctx; 46 | 47 | /* Strip whitespace chars off end of given string, in place. Return s. */ 48 | static char* rstrip(char* s) 49 | { 50 | char* p = s + strlen(s); 51 | while (p > s && isspace((unsigned char)(*--p))) 52 | *p = '\0'; 53 | return s; 54 | } 55 | 56 | /* Return pointer to first non-whitespace char in given string. */ 57 | static char* lskip(const char* s) 58 | { 59 | while (*s && isspace((unsigned char)(*s))) 60 | s++; 61 | return (char*)s; 62 | } 63 | 64 | /* Return pointer to first char (of chars) or inline comment in given string, 65 | or pointer to NUL at end of string if neither found. Inline comment must 66 | be prefixed by a whitespace character to register as a comment. */ 67 | static char* find_chars_or_comment(const char* s, const char* chars) 68 | { 69 | #if INI_ALLOW_INLINE_COMMENTS 70 | int was_space = 0; 71 | while (*s && (!chars || !strchr(chars, *s)) && 72 | !(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) { 73 | was_space = isspace((unsigned char)(*s)); 74 | s++; 75 | } 76 | #else 77 | while (*s && (!chars || !strchr(chars, *s))) { 78 | s++; 79 | } 80 | #endif 81 | return (char*)s; 82 | } 83 | 84 | /* Similar to strncpy, but ensures dest (size bytes) is 85 | NUL-terminated, and doesn't pad with NULs. */ 86 | static char* strncpy0(char* dest, const char* src, size_t size) 87 | { 88 | /* Could use strncpy internally, but it causes gcc warnings (see issue #91) */ 89 | size_t i; 90 | for (i = 0; i < size - 1 && src[i]; i++) 91 | dest[i] = src[i]; 92 | dest[i] = '\0'; 93 | return dest; 94 | } 95 | 96 | /* See documentation in header file. */ 97 | int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, 98 | void* user) 99 | { 100 | /* Uses a fair bit of stack (use heap instead if you need to) */ 101 | #if INI_USE_STACK 102 | char line[INI_MAX_LINE]; 103 | int max_line = INI_MAX_LINE; 104 | #else 105 | char* line; 106 | size_t max_line = INI_INITIAL_ALLOC; 107 | #endif 108 | #if INI_ALLOW_REALLOC && !INI_USE_STACK 109 | char* new_line; 110 | size_t offset; 111 | #endif 112 | char section[MAX_SECTION] = ""; 113 | char prev_name[MAX_NAME] = ""; 114 | 115 | char* start; 116 | char* end; 117 | char* name; 118 | char* value; 119 | int lineno = 0; 120 | int error = 0; 121 | 122 | #if !INI_USE_STACK 123 | line = (char*)ini_malloc(INI_INITIAL_ALLOC); 124 | if (!line) { 125 | return -2; 126 | } 127 | #endif 128 | 129 | #if INI_HANDLER_LINENO 130 | #define HANDLER(u, s, n, v) handler(u, s, n, v, lineno) 131 | #else 132 | #define HANDLER(u, s, n, v) handler(u, s, n, v) 133 | #endif 134 | 135 | /* Scan through stream line by line */ 136 | while (reader(line, (int)max_line, stream) != NULL) { 137 | #if INI_ALLOW_REALLOC && !INI_USE_STACK 138 | offset = strlen(line); 139 | while (offset == max_line - 1 && line[offset - 1] != '\n') { 140 | max_line *= 2; 141 | if (max_line > INI_MAX_LINE) 142 | max_line = INI_MAX_LINE; 143 | new_line = ini_realloc(line, max_line); 144 | if (!new_line) { 145 | ini_free(line); 146 | return -2; 147 | } 148 | line = new_line; 149 | if (reader(line + offset, (int)(max_line - offset), stream) == NULL) 150 | break; 151 | if (max_line >= INI_MAX_LINE) 152 | break; 153 | offset += strlen(line + offset); 154 | } 155 | #endif 156 | 157 | lineno++; 158 | 159 | start = line; 160 | #if INI_ALLOW_BOM 161 | if (lineno == 1 && (unsigned char)start[0] == 0xEF && 162 | (unsigned char)start[1] == 0xBB && 163 | (unsigned char)start[2] == 0xBF) { 164 | start += 3; 165 | } 166 | #endif 167 | start = lskip(rstrip(start)); 168 | 169 | if (strchr(INI_START_COMMENT_PREFIXES, *start)) { 170 | /* Start-of-line comment */ 171 | } 172 | #if INI_ALLOW_MULTILINE 173 | else if (*prev_name && *start && start > line) { 174 | /* Non-blank line with leading whitespace, treat as continuation 175 | of previous name's value (as per Python configparser). */ 176 | if (!HANDLER(user, section, prev_name, start) && !error) 177 | error = lineno; 178 | } 179 | #endif 180 | else if (*start == '[') { 181 | /* A "[section]" line */ 182 | end = find_chars_or_comment(start + 1, "]"); 183 | if (*end == ']') { 184 | *end = '\0'; 185 | strncpy0(section, start + 1, sizeof(section)); 186 | *prev_name = '\0'; 187 | #if INI_CALL_HANDLER_ON_NEW_SECTION 188 | if (!HANDLER(user, section, NULL, NULL) && !error) 189 | error = lineno; 190 | #endif 191 | } 192 | else if (!error) { 193 | /* No ']' found on section line */ 194 | error = lineno; 195 | } 196 | } 197 | else if (*start) { 198 | /* Not a comment, must be a name[=:]value pair */ 199 | end = find_chars_or_comment(start, "=:"); 200 | if (*end == '=' || *end == ':') { 201 | *end = '\0'; 202 | name = rstrip(start); 203 | value = end + 1; 204 | #if INI_ALLOW_INLINE_COMMENTS 205 | end = find_chars_or_comment(value, NULL); 206 | if (*end) 207 | *end = '\0'; 208 | #endif 209 | value = lskip(value); 210 | rstrip(value); 211 | 212 | /* Valid name[=:]value pair found, call handler */ 213 | strncpy0(prev_name, name, sizeof(prev_name)); 214 | if (!HANDLER(user, section, name, value) && !error) 215 | error = lineno; 216 | } 217 | else if (!error) { 218 | /* No '=' or ':' found on name[=:]value line */ 219 | #if INI_ALLOW_NO_VALUE 220 | *end = '\0'; 221 | name = rstrip(start); 222 | if (!HANDLER(user, section, name, NULL) && !error) 223 | error = lineno; 224 | #else 225 | error = lineno; 226 | #endif 227 | } 228 | } 229 | 230 | #if INI_STOP_ON_FIRST_ERROR 231 | if (error) 232 | break; 233 | #endif 234 | } 235 | 236 | #if !INI_USE_STACK 237 | ini_free(line); 238 | #endif 239 | 240 | return error; 241 | } 242 | 243 | /* See documentation in header file. */ 244 | int ini_parse_file(FILE* file, ini_handler handler, void* user) 245 | { 246 | return ini_parse_stream((ini_reader)fgets, file, handler, user); 247 | } 248 | 249 | /* See documentation in header file. */ 250 | int ini_parse(const char* filename, ini_handler handler, void* user) 251 | { 252 | FILE* file; 253 | int error; 254 | 255 | file = fopen(filename, "r"); 256 | if (!file) 257 | return -1; 258 | error = ini_parse_file(file, handler, user); 259 | fclose(file); 260 | return error; 261 | } 262 | 263 | /* An ini_reader function to read the next line from a string buffer. This 264 | is the fgets() equivalent used by ini_parse_string(). */ 265 | static char* ini_reader_string(char* str, int num, void* stream) { 266 | ini_parse_string_ctx* ctx = (ini_parse_string_ctx*)stream; 267 | const char* ctx_ptr = ctx->ptr; 268 | size_t ctx_num_left = ctx->num_left; 269 | char* strp = str; 270 | char c; 271 | 272 | if (ctx_num_left == 0 || num < 2) 273 | return NULL; 274 | 275 | while (num > 1 && ctx_num_left != 0) { 276 | c = *ctx_ptr++; 277 | ctx_num_left--; 278 | *strp++ = c; 279 | if (c == '\n') 280 | break; 281 | num--; 282 | } 283 | 284 | *strp = '\0'; 285 | ctx->ptr = ctx_ptr; 286 | ctx->num_left = ctx_num_left; 287 | return str; 288 | } 289 | 290 | /* See documentation in header file. */ 291 | int ini_parse_string(const char* string, ini_handler handler, void* user) { 292 | ini_parse_string_ctx ctx; 293 | 294 | ctx.ptr = string; 295 | ctx.num_left = strlen(string); 296 | return ini_parse_stream((ini_reader)ini_reader_string, &ctx, handler, 297 | user); 298 | } 299 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include "FileInfos.h" 3 | #include "SaveRedirection.h" 4 | #include "bootLogoTex_tga.h" 5 | #include "bootMovie_h264.h" 6 | #include "fs/CFile.hpp" 7 | #include "fs/FileReader.h" 8 | #include "fs/FileReaderWUHB.h" 9 | #include "globals.h" 10 | #include "iconTex_tga.h" 11 | #include "utils/StringTools.h" 12 | #include "utils/ini.h" 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | 41 | typedef struct ACPMetaData { 42 | char bootmovie[80696]; 43 | char bootlogo[28604]; 44 | } ACPMetaData; 45 | 46 | WUPS_PLUGIN_NAME("Homebrew on Wii U menu"); 47 | WUPS_PLUGIN_DESCRIPTION("Allows the user to load homebrew from the Wii U menu"); 48 | WUPS_PLUGIN_VERSION(VERSION_FULL); 49 | WUPS_PLUGIN_AUTHOR("Maschell"); 50 | WUPS_PLUGIN_LICENSE("GPL"); 51 | 52 | #define UPPER_TITLE_ID_HOMEBREW 0x0005000F 53 | #define TITLE_ID_HOMEBREW_MASK (((uint64_t) UPPER_TITLE_ID_HOMEBREW) << 32) 54 | 55 | ACPMetaXml gLaunchXML = {}; 56 | MCPTitleListType current_launched_title_info = {}; 57 | BOOL gHomebrewLaunched = {}; 58 | 59 | std::mutex fileInfosMutex; 60 | std::forward_list> fileInfos; 61 | 62 | std::mutex fileReaderListMutex; 63 | std::forward_list> openFileReaders; 64 | 65 | void readCustomTitlesFromSD(); 66 | 67 | WUPS_USE_WUT_DEVOPTAB(); 68 | WUPS_USE_STORAGE("homebrew_on_menu"); // Use the storage API 69 | 70 | #define HIDE_HOMEBREW_STRING "hideHomebrew" 71 | #define PREFER_WUHB_OVER_RPX_STRING "hideRPXIfWUHBExists" 72 | #define HIDE_ALL_RPX_STRING "hideAllRPX" 73 | 74 | #define HOMEBREW_APPS_DIRECTORY "fs:/vol/external01/wiiu/apps" 75 | #define IGNORE_FILE_PATH HOMEBREW_APPS_DIRECTORY "/.ignore" 76 | #define HOMEBREW_LAUNCHER_FILENAME "homebrew_launcher.wuhb" 77 | #define HOMEBREW_LAUNCHER_OPTIONAL_DIRECTORY "homebrew_launcher" 78 | 79 | #define HOMEBREW_LAUNCHER_PATH HOMEBREW_APPS_DIRECTORY "/" HOMEBREW_LAUNCHER_FILENAME 80 | #define HOMEBREW_LAUNCHER_PATH2 HOMEBREW_APPS_DIRECTORY "/" HOMEBREW_LAUNCHER_OPTIONAL_DIRECTORY "/" HOMEBREW_LAUNCHER_FILENAME 81 | 82 | 83 | #define DEFAULT_HIDE_HOMEBREW_VALUE false 84 | #define DEFAULT_PREFER_WUHB_OVER_RPX_VALUE true 85 | #define DEFAULT_HIDE_ALL_RPX_VALUE false 86 | bool gHideHomebrew = DEFAULT_HIDE_HOMEBREW_VALUE; 87 | bool gPreferWUHBOverRPX = DEFAULT_PREFER_WUHB_OVER_RPX_VALUE; 88 | bool gHideAllRPX = DEFAULT_HIDE_ALL_RPX_VALUE; 89 | 90 | bool prevHideValue = false; 91 | bool prevPreferWUHBOverRPXValue = false; 92 | bool prevHideAllRPX = false; 93 | 94 | bool gHomebrewLauncherExists = false; 95 | 96 | std::vector gIgnorePatterns; 97 | 98 | WUPSConfigAPICallbackStatus ConfigMenuOpenedCallback(WUPSConfigCategoryHandle rootHandle); 99 | void ConfigMenuClosedCallback(); 100 | 101 | INITIALIZE_PLUGIN() { 102 | memset((void *) ¤t_launched_title_info, 0, sizeof(current_launched_title_info)); 103 | memset((void *) &gLaunchXML, 0, sizeof(gLaunchXML)); 104 | gHomebrewLaunched = FALSE; 105 | 106 | gSerialId = {}; 107 | if (!Utils::GetSerialId(gSerialId) || gSerialId.empty()) { 108 | DEBUG_FUNCTION_LINE_ERR("Homebrew on Menu Plugin: Failed to get the serial id"); 109 | OSFatal("Homebrew on menu plugin: Failed to get the serial id"); 110 | } 111 | 112 | // Use libwuhbutils. 113 | WUHBUtilsStatus error; 114 | if ((error = WUHBUtils_InitLibrary()) != WUHB_UTILS_RESULT_SUCCESS) { 115 | DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init WUHBUtils. Error %s [%d]", WUHBUtils_GetStatusStr(error), error); 116 | OSFatal("Homebrew on menu plugin: Failed to init WUHBUtils."); 117 | } 118 | 119 | // Use libcontentredirection. 120 | ContentRedirectionStatus error2; 121 | if ((error2 = ContentRedirection_InitLibrary()) != CONTENT_REDIRECTION_RESULT_SUCCESS) { 122 | DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init ContentRedirection. Error %s [%d]", ContentRedirection_GetStatusStr(error2), error2); 123 | OSFatal("Homebrew on menu plugin: Failed to init ContentRedirection."); 124 | } 125 | 126 | // Use librpxloader. 127 | RPXLoaderStatus error3; 128 | if ((error3 = RPXLoader_InitLibrary()) != RPX_LOADER_RESULT_SUCCESS) { 129 | DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init RPXLoader. Error %s [%d]", RPXLoader_GetStatusStr(error3), error3); 130 | OSFatal("Homebrew on menu plugin: Failed to init RPXLoader."); 131 | } 132 | 133 | // Use libnotifications. 134 | NotificationModuleStatus error4; 135 | if ((error4 = NotificationModule_InitLibrary()) != NOTIFICATION_MODULE_RESULT_SUCCESS) { 136 | DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init NotificationModule. Error %s [%d]", NotificationModule_GetStatusStr(error4), error4); 137 | OSFatal("Homebrew on menu plugin: Failed to init NotificationModule."); 138 | } 139 | 140 | WUPSConfigAPIOptionsV1 configOptions = {.name = "Homebrew On Wii U Menu Plugin"}; 141 | if (WUPSConfigAPI_Init(configOptions, ConfigMenuOpenedCallback, ConfigMenuClosedCallback) != WUPSCONFIG_API_RESULT_SUCCESS) { 142 | DEBUG_FUNCTION_LINE_ERR("Failed to init config api"); 143 | } 144 | 145 | WUPSStorageError storageError; 146 | storageError = WUPSStorageAPI::GetOrStoreDefault(HIDE_HOMEBREW_STRING, gHideHomebrew, DEFAULT_HIDE_HOMEBREW_VALUE); 147 | if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { 148 | DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); 149 | } 150 | 151 | storageError = WUPSStorageAPI::GetOrStoreDefault(PREFER_WUHB_OVER_RPX_STRING, gPreferWUHBOverRPX, DEFAULT_PREFER_WUHB_OVER_RPX_VALUE); 152 | if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { 153 | DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); 154 | } 155 | 156 | storageError = WUPSStorageAPI::GetOrStoreDefault(HIDE_ALL_RPX_STRING, gHideAllRPX, DEFAULT_HIDE_ALL_RPX_VALUE); 157 | if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { 158 | DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); 159 | } 160 | 161 | // save storage 162 | storageError = WUPSStorageAPI::SaveStorage(); 163 | if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { 164 | DEBUG_FUNCTION_LINE_ERR("Failed to save storage: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); 165 | } 166 | 167 | prevHideValue = gHideHomebrew; 168 | prevPreferWUHBOverRPXValue = gPreferWUHBOverRPX; 169 | prevHideAllRPX = gHideAllRPX; 170 | } 171 | 172 | void hideHomebrewChanged(ConfigItemBoolean *item, bool newValue) { 173 | DEBUG_FUNCTION_LINE_VERBOSE("New value in gHideHomebrew: %d", newValue); 174 | gHideHomebrew = newValue; 175 | 176 | // If the value has changed, we store it in the storage. 177 | WUPSStorageError storageRes = WUPSStorageAPI::Store(HIDE_HOMEBREW_STRING, gHideHomebrew); 178 | if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { 179 | DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); 180 | } 181 | } 182 | 183 | void preferWUHBOverRPXChanged(ConfigItemBoolean *item, bool newValue) { 184 | DEBUG_FUNCTION_LINE_VERBOSE("New value in gPreferWUHBOverRPX: %d", newValue); 185 | gPreferWUHBOverRPX = newValue; 186 | 187 | // If the value has changed, we store it in the storage. 188 | WUPSStorageError storageRes = WUPSStorageAPI::Store(PREFER_WUHB_OVER_RPX_STRING, gPreferWUHBOverRPX); 189 | if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { 190 | DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); 191 | } 192 | } 193 | 194 | void hideAllRPXChanged(ConfigItemBoolean *item, bool newValue) { 195 | DEBUG_FUNCTION_LINE_VERBOSE("New value in gHideAllRPX: %d", newValue); 196 | gHideAllRPX = newValue; 197 | 198 | // If the value has changed, we store it in the storage. 199 | WUPSStorageError storageRes = WUPSStorageAPI::Store(HIDE_ALL_RPX_STRING, gHideAllRPX); 200 | if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { 201 | DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); 202 | } 203 | } 204 | 205 | WUPSConfigAPICallbackStatus ConfigMenuOpenedCallback(WUPSConfigCategoryHandle rootHandle) { 206 | try { 207 | WUPSConfigCategory root = WUPSConfigCategory(rootHandle); 208 | 209 | root.add(WUPSConfigItemBoolean::Create(HIDE_HOMEBREW_STRING, 210 | gHomebrewLauncherExists ? "Hide all homebrew except Homebrew Launcher" : "Hide all homebrew", 211 | DEFAULT_HIDE_HOMEBREW_VALUE, gHideHomebrew, 212 | &hideHomebrewChanged)); 213 | 214 | root.add(WUPSConfigItemBoolean::Create(PREFER_WUHB_OVER_RPX_STRING, 215 | "Prefer .wuhb over .rpx", 216 | DEFAULT_PREFER_WUHB_OVER_RPX_VALUE, gPreferWUHBOverRPX, 217 | &preferWUHBOverRPXChanged)); 218 | 219 | root.add(WUPSConfigItemBoolean::Create(HIDE_ALL_RPX_STRING, 220 | "Hide all .rpx", 221 | DEFAULT_HIDE_ALL_RPX_VALUE, gHideAllRPX, 222 | &hideAllRPXChanged)); 223 | } catch (std::exception &e) { 224 | OSReport("Exception: %s\n", e.what()); 225 | return WUPSCONFIG_API_CALLBACK_RESULT_ERROR; 226 | } 227 | return WUPSCONFIG_API_CALLBACK_RESULT_SUCCESS; 228 | } 229 | 230 | bool sSDUtilsInitDone = false; 231 | bool sSDIsMounted = false; 232 | bool sTitleRebooting = false; 233 | 234 | void ConfigMenuClosedCallback() { 235 | // Save all changes 236 | auto saveErr = WUPSStorageAPI::SaveStorage(); 237 | if (saveErr != WUPS_STORAGE_ERROR_SUCCESS) { 238 | DEBUG_FUNCTION_LINE_ERR("Failed to save storage: %s", WUPSStorageAPI::GetStatusStr(saveErr).data()); 239 | } 240 | 241 | if (prevHideValue != gHideHomebrew || prevPreferWUHBOverRPXValue != gPreferWUHBOverRPX || prevHideAllRPX != gHideAllRPX) { 242 | if (!sTitleRebooting) { 243 | _SYSLaunchTitleWithStdArgsInNoSplash(OSGetTitleID(), nullptr); 244 | sTitleRebooting = true; 245 | } 246 | } 247 | prevHideValue = gHideHomebrew; 248 | prevPreferWUHBOverRPXValue = gPreferWUHBOverRPX; 249 | prevHideAllRPX = gHideAllRPX; 250 | } 251 | 252 | void Cleanup() { 253 | { 254 | const std::lock_guard lock1(fileReaderListMutex); 255 | openFileReaders.clear(); 256 | } 257 | { 258 | const std::lock_guard lock(fileInfosMutex); 259 | fileInfos.clear(); 260 | } 261 | } 262 | 263 | void SDCleanUpHandlesHandler() { 264 | Cleanup(); 265 | } 266 | 267 | void SDAttachedHandler([[maybe_unused]] SDUtilsAttachStatus status) { 268 | if (OSGetForegroundBucket(nullptr, nullptr) && !sTitleRebooting) { 269 | _SYSLaunchTitleWithStdArgsInNoSplash(OSGetTitleID(), nullptr); 270 | sTitleRebooting = true; 271 | } 272 | } 273 | 274 | ON_APPLICATION_START() { 275 | Cleanup(); 276 | initLogging(); 277 | sSDIsMounted = false; 278 | 279 | if (OSGetTitleID() == 0x0005001010040000L || // Wii U Menu JPN 280 | OSGetTitleID() == 0x0005001010040100L || // Wii U Menu USA 281 | OSGetTitleID() == 0x0005001010040200L) { // Wii U Menu EUR 282 | 283 | CFile file(IGNORE_FILE_PATH, CFile::ReadOnly); 284 | if (file.isOpen()) { 285 | std::string strBuffer; 286 | strBuffer.resize(file.size()); 287 | file.read((uint8_t *) &strBuffer[0], strBuffer.size()); 288 | file.close(); 289 | 290 | //! remove all windows crap signs 291 | size_t position; 292 | while (true) { 293 | position = strBuffer.find('\r'); 294 | if (position == std::string::npos) { 295 | break; 296 | } 297 | 298 | strBuffer.erase(position, 1); 299 | } 300 | 301 | gIgnorePatterns = StringTools::StringSplit(strBuffer, "\n"); 302 | 303 | // Ignore all lines that start with '#' 304 | gIgnorePatterns.erase(std::remove_if(gIgnorePatterns.begin(), gIgnorePatterns.end(), [](auto &line) { return line.starts_with('#'); }), gIgnorePatterns.end()); 305 | } else { 306 | DEBUG_FUNCTION_LINE_INFO("No ignore found"); 307 | } 308 | 309 | gInWiiUMenu = true; 310 | 311 | struct stat st {}; 312 | if (stat(HOMEBREW_LAUNCHER_PATH, &st) >= 0 || stat(HOMEBREW_LAUNCHER_PATH2, &st) >= 0) { 313 | gHomebrewLauncherExists = true; 314 | } else { 315 | gHomebrewLauncherExists = false; 316 | } 317 | 318 | if (SDUtils_InitLibrary() == SDUTILS_RESULT_SUCCESS) { 319 | sSDUtilsInitDone = true; 320 | sTitleRebooting = false; 321 | if (SDUtils_AddAttachHandler(SDAttachedHandler) != SDUTILS_RESULT_SUCCESS) { 322 | DEBUG_FUNCTION_LINE_ERR("Failed to add AttachedHandler"); 323 | } 324 | if (SDUtils_AddCleanUpHandlesHandler(SDCleanUpHandlesHandler) != SDUTILS_RESULT_SUCCESS) { 325 | DEBUG_FUNCTION_LINE_ERR("Failed to add CleanUpHandlesHandler"); 326 | } 327 | if (SDUtils_IsSdCardMounted(&sSDIsMounted) != SDUTILS_RESULT_SUCCESS) { 328 | DEBUG_FUNCTION_LINE_ERR("IsSdCardMounted failed"); 329 | } 330 | } else { 331 | DEBUG_FUNCTION_LINE_WARN("Failed to init SDUtils. Make sure to have the SDHotSwapModule loaded!"); 332 | } 333 | } else { 334 | gInWiiUMenu = false; 335 | } 336 | 337 | if (_SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY) != OSGetTitleID()) { 338 | gHomebrewLaunched = FALSE; 339 | } 340 | } 341 | 342 | ON_APPLICATION_ENDS() { 343 | Cleanup(); 344 | SaveRedirectionCleanUp(); 345 | deinitLogging(); 346 | gInWiiUMenu = false; 347 | if (sSDUtilsInitDone) { 348 | SDUtils_RemoveAttachHandler(SDAttachedHandler); 349 | SDUtils_RemoveCleanUpHandlesHandler(SDCleanUpHandlesHandler); 350 | SDUtils_DeInitLibrary(); 351 | sSDUtilsInitDone = false; 352 | } 353 | sSDIsMounted = false; 354 | } 355 | 356 | std::optional> getIDByLowerTitleID(uint32_t titleid_lower) { 357 | std::lock_guard lock(fileInfosMutex); 358 | for (auto &cur : fileInfos) { 359 | if (cur->lowerTitleID == titleid_lower) { 360 | return cur; 361 | } 362 | } 363 | return {}; 364 | } 365 | 366 | void fillXmlForTitleID(uint32_t titleid_upper, uint32_t titleid_lower, ACPMetaXml *out_buf) { 367 | auto titleIdInfoOpt = getIDByLowerTitleID(titleid_lower); 368 | if (!titleIdInfoOpt.has_value()) { 369 | DEBUG_FUNCTION_LINE_ERR("Failed to get info by titleid"); 370 | return; 371 | } 372 | auto &titleInfo = titleIdInfoOpt.value(); 373 | 374 | out_buf->title_id = (((uint64_t) titleid_upper) << 32) + titleid_lower; 375 | strncpy(out_buf->longname_en, titleInfo->longname.c_str(), sizeof(out_buf->longname_en) - 1); 376 | strncpy(out_buf->shortname_en, titleInfo->shortname.c_str(), sizeof(out_buf->shortname_en) - 1); 377 | strncpy(out_buf->publisher_en, titleInfo->author.c_str(), sizeof(out_buf->publisher_en) - 1); 378 | out_buf->e_manual = 1; 379 | out_buf->e_manual_version = 0; 380 | out_buf->title_version = 1; 381 | out_buf->network_use = 1; 382 | out_buf->launching_flag = 4; 383 | out_buf->online_account_use = 1; 384 | out_buf->os_version = 0x000500101000400A; 385 | out_buf->region = 0xFFFFFFFF; 386 | out_buf->common_save_size = 0x0000000001790000; 387 | out_buf->group_id = 0x400; 388 | out_buf->drc_use = 1; 389 | out_buf->version = 1; 390 | out_buf->reserved_flag0 = 0x00010001; 391 | out_buf->reserved_flag6 = 0x00000003; 392 | out_buf->pc_usk = 128; 393 | strncpy(out_buf->product_code, "WUP-P-HBLD", sizeof(out_buf->product_code) - 1); 394 | strncpy(out_buf->content_platform, "WUP", sizeof(out_buf->content_platform) - 1); 395 | strncpy(out_buf->company_code, "0001", sizeof(out_buf->company_code) - 1); 396 | } 397 | 398 | static int handler(void *user, const char *section, const char *name, 399 | const char *value) { 400 | auto *fInfo = (std::shared_ptr *) user; 401 | #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 402 | 403 | if (MATCH("menu", "longname")) { 404 | fInfo->operator->()->longname = value; 405 | } else if (MATCH("menu", "shortname")) { 406 | fInfo->operator->()->shortname = value; 407 | } else if (MATCH("menu", "author")) { 408 | fInfo->operator->()->author = value; 409 | } else { 410 | return 0; /* unknown section/name, error */ 411 | } 412 | 413 | return 1; 414 | } 415 | 416 | bool CheckFileExistsHelper(const char *path); 417 | void readCustomTitlesFromSD() { 418 | std::lock_guard lock(fileInfosMutex); 419 | if (!fileInfos.empty()) { 420 | DEBUG_FUNCTION_LINE_VERBOSE("Using cached value"); 421 | return; 422 | } 423 | 424 | std::vector listOfExecutables; 425 | 426 | if (gHideHomebrew) { 427 | struct stat st {}; 428 | if (stat(HOMEBREW_LAUNCHER_PATH, &st) >= 0) { 429 | listOfExecutables.emplace_back(HOMEBREW_LAUNCHER_PATH); 430 | } else if (stat(HOMEBREW_LAUNCHER_PATH2, &st) >= 0) { 431 | listOfExecutables.emplace_back(HOMEBREW_LAUNCHER_PATH2); 432 | } 433 | } else { 434 | // Reset current infos 435 | DirList dirList(HOMEBREW_APPS_DIRECTORY, ".rpx,.wuhb", DirList::Files | DirList::CheckSubfolders, 1); 436 | dirList.SortList(); 437 | 438 | if (gHideAllRPX) { 439 | for (int i = 0; i < dirList.GetFilecount(); i++) { 440 | if (dirList.GetFilepath(i) != nullptr && !std::string_view(dirList.GetFilepath(i)).ends_with(".rpx")) { 441 | listOfExecutables.emplace_back(dirList.GetFilepath(i)); 442 | } 443 | } 444 | } else if (gPreferWUHBOverRPX) { 445 | // map<[path without extension], vector<[extension]>> 446 | std::map> pathWithoutExtensionMap; 447 | for (int i = 0; i < dirList.GetFilecount(); i++) { 448 | std::string pathNoExtension = StringTools::remove_extension(dirList.GetFilepath(i)); 449 | if (pathWithoutExtensionMap.count(pathNoExtension) == 0) { 450 | pathWithoutExtensionMap[pathNoExtension] = std::vector(); 451 | } 452 | pathWithoutExtensionMap[pathNoExtension].push_back(StringTools::get_extension(dirList.GetFilename(i))); 453 | } 454 | 455 | for (auto &l : pathWithoutExtensionMap) { 456 | if (l.second.size() == 1 && l.second.at(0) == ".rpx") { 457 | listOfExecutables.push_back(l.first + ".rpx"); 458 | } else { 459 | listOfExecutables.push_back(l.first + ".wuhb"); 460 | } 461 | } 462 | } else { 463 | for (int i = 0; i < dirList.GetFilecount(); i++) { 464 | listOfExecutables.emplace_back(dirList.GetFilepath(i)); 465 | } 466 | } 467 | 468 | // Remove any executable that matches the ignore pattern. 469 | listOfExecutables.erase(std::remove_if(listOfExecutables.begin(), listOfExecutables.end(), [&](const auto &item) { 470 | auto path = item.substr(strlen(HOMEBREW_APPS_DIRECTORY) + 1); 471 | return std::ranges::any_of(gIgnorePatterns.begin(), gIgnorePatterns.end(), 472 | [&](const auto &pattern) { 473 | if (fnmatch(pattern.c_str(), path.c_str(), FNM_CASEFOLD) == 0) { 474 | DEBUG_FUNCTION_LINE_INFO("Ignore \"%s\" because it matched pattern \"%s\"", path.c_str(), pattern.c_str()); 475 | return true; 476 | } 477 | return false; 478 | }); 479 | }), 480 | listOfExecutables.end()); 481 | } 482 | 483 | for (auto &filePath : listOfExecutables) { 484 | auto filename = StringTools::FullpathToFilename(filePath.c_str()); 485 | 486 | //! skip wiiload temp files 487 | if (strcasecmp(filename, "temp.rpx") == 0) { 488 | continue; 489 | } 490 | 491 | //! skip wiiload temp files 492 | if (strcasecmp(filename, "temp.wuhb") == 0) { 493 | continue; 494 | } 495 | 496 | //! skip wiiload temp files 497 | if (strcasecmp(filename, "temp2.wuhb") == 0) { 498 | continue; 499 | } 500 | 501 | //! skip hidden linux and mac files 502 | if (filename[0] == '.' || filename[0] == '_') { 503 | continue; 504 | } 505 | 506 | auto repl = "fs:/vol/external01/"; 507 | auto input = filePath.c_str(); 508 | const char *relativeFilepath; 509 | 510 | if (filePath.starts_with(repl)) { 511 | relativeFilepath = &input[strlen(repl)]; 512 | } else { 513 | DEBUG_FUNCTION_LINE_ERR("Skip %s, Path doesn't start with %s (This should never happen", input, repl); 514 | continue; 515 | } 516 | 517 | auto fileInfo = make_shared_nothrow(relativeFilepath); 518 | if (!fileInfo) { 519 | DEBUG_FUNCTION_LINE_ERR("No more memory"); 520 | break; 521 | } 522 | 523 | std::lock_guard infoLock(fileInfo->accessLock); 524 | 525 | auto *cur_title_info = &(fileInfo->titleInfo); 526 | 527 | snprintf(cur_title_info->path, sizeof(cur_title_info->path), "/custom/%08X%08X", UPPER_TITLE_ID_HOMEBREW, fileInfo->lowerTitleID); 528 | 529 | const char *indexedDevice = "mlc"; 530 | strncpy(cur_title_info->indexedDevice, indexedDevice, sizeof(cur_title_info->indexedDevice) - 1); 531 | 532 | fileInfo->filename = filename; 533 | fileInfo->longname = filename; 534 | fileInfo->shortname = filename; 535 | fileInfo->author = filename; 536 | 537 | // System apps don't have a splash screen. 538 | cur_title_info->appType = MCP_APP_TYPE_SYSTEM_APPS; 539 | 540 | DEBUG_FUNCTION_LINE_VERBOSE("Check %s", fileInfo->filename.c_str()); 541 | 542 | // Check if the bootTvTex and bootDrcTex exists 543 | if (std::string_view(fileInfo->filename).ends_with(".wuhb")) { 544 | int result = 0; 545 | 546 | #define TMP_BUNDLE_NAME "romfscheck" 547 | 548 | if (WUHBUtils_MountBundle(TMP_BUNDLE_NAME, filePath.c_str(), BundleSource_FileDescriptor, &result) == WUHB_UTILS_RESULT_SUCCESS && result >= 0) { 549 | fileInfo->isBundle = true; 550 | uint8_t *buffer; 551 | uint32_t bufferSize; 552 | 553 | auto readRes = WUHBUtils_ReadWholeFile(TMP_BUNDLE_NAME ":/meta/meta.ini", &buffer, &bufferSize); 554 | if (readRes == WUHB_UTILS_RESULT_SUCCESS) { 555 | buffer[bufferSize - 1] = '\0'; 556 | if (ini_parse_string((const char *) buffer, handler, &fileInfo) < 0) { 557 | DEBUG_FUNCTION_LINE_ERR("Failed to parse meta.ini"); 558 | } 559 | free(buffer); 560 | buffer = nullptr; 561 | } else { 562 | DEBUG_FUNCTION_LINE_ERR("Failed to open or read meta.ini: %d", readRes); 563 | } 564 | 565 | auto bootTvTexPath = TMP_BUNDLE_NAME ":/meta/bootTvTex.tga"; 566 | auto bootDrcTexPath = TMP_BUNDLE_NAME ":/meta/bootDrcTex.tga"; 567 | if (CheckFileExistsHelper(bootTvTexPath) && CheckFileExistsHelper(bootDrcTexPath)) { 568 | // Show splash screens 569 | cur_title_info->appType = MCP_APP_TYPE_GAME; 570 | DEBUG_FUNCTION_LINE_VERBOSE("Title has splashscreen"); 571 | } 572 | 573 | int32_t unmountRes; 574 | if (WUHBUtils_UnmountBundle(TMP_BUNDLE_NAME, &unmountRes) == WUHB_UTILS_RESULT_SUCCESS) { 575 | if (unmountRes != 0) { 576 | DEBUG_FUNCTION_LINE_ERR("Unmount result was \"%s\"", TMP_BUNDLE_NAME); 577 | } 578 | } else { 579 | DEBUG_FUNCTION_LINE_ERR("Failed to unmount \"%s\"", TMP_BUNDLE_NAME); 580 | } 581 | } else { 582 | DEBUG_FUNCTION_LINE_ERR("%s is not a valid .wuhb file: %d", filePath.c_str(), result); 583 | continue; 584 | } 585 | } 586 | 587 | cur_title_info->titleId = TITLE_ID_HOMEBREW_MASK | fileInfo->lowerTitleID; 588 | cur_title_info->titleVersion = 1; 589 | cur_title_info->groupId = 0x400; 590 | 591 | cur_title_info->osVersion = OSGetOSID(); 592 | cur_title_info->sdkVersion = __OSGetProcessSDKVersion(); 593 | cur_title_info->unk0x60 = 0; 594 | 595 | fileInfos.push_front(fileInfo); 596 | } 597 | OSMemoryBarrier(); 598 | } 599 | 600 | bool CheckFileExistsHelper(const char *path) { 601 | int32_t exists; 602 | int32_t res; 603 | if ((res = WUHBUtils_FileExists(path, &exists)) == WUHB_UTILS_RESULT_SUCCESS) { 604 | if (!exists) { 605 | DEBUG_FUNCTION_LINE_VERBOSE("## WARN ##: Missing %s", path); 606 | return false; 607 | } 608 | return true; 609 | } 610 | DEBUG_FUNCTION_LINE_ERR("Failed to check if %s exists: %d", path, res); 611 | 612 | return false; 613 | } 614 | 615 | DECL_FUNCTION(int32_t, MCP_TitleList, uint32_t handle, uint32_t *outTitleCount, MCPTitleListType *titleList, uint32_t size) { 616 | int32_t result = real_MCP_TitleList(handle, outTitleCount, titleList, size); 617 | 618 | if (!gInWiiUMenu) { 619 | DEBUG_FUNCTION_LINE_VERBOSE("Not in Wii U Menu"); 620 | return result; 621 | } 622 | 623 | uint32_t titleCount = *outTitleCount; 624 | 625 | { 626 | std::lock_guard lock(fileInfosMutex); 627 | readCustomTitlesFromSD(); 628 | 629 | for (auto &gFileInfo : fileInfos) { 630 | memcpy(&(titleList[titleCount]), &(gFileInfo->titleInfo), sizeof(MCPTitleListType)); 631 | titleCount++; 632 | } 633 | } 634 | 635 | *outTitleCount = titleCount; 636 | 637 | return result; 638 | } 639 | 640 | DECL_FUNCTION(int32_t, ACPCheckTitleLaunchByTitleListTypeEx, MCPTitleListType *title, uint32_t u2) { 641 | if ((title->titleId & TITLE_ID_HOMEBREW_MASK) == TITLE_ID_HOMEBREW_MASK) { 642 | std::lock_guard lock(fileInfosMutex); 643 | auto fileInfo = getIDByLowerTitleID(title->titleId & 0xFFFFFFFF); 644 | if (fileInfo.has_value()) { 645 | DEBUG_FUNCTION_LINE("Starting a homebrew title"); 646 | 647 | fillXmlForTitleID((title->titleId & 0xFFFFFFFF00000000) >> 32, (title->titleId & 0xFFFFFFFF), &gLaunchXML); 648 | 649 | gHomebrewLaunched = TRUE; 650 | 651 | if (RPXLoader_PrepareLaunchFromSD(fileInfo.value()->relativeFilepath.c_str()) == RPX_LOADER_RESULT_SUCCESS) { 652 | return 0; 653 | } 654 | 655 | DEBUG_FUNCTION_LINE_ERR("Failed to prepare launch for %s", fileInfo.value()->relativeFilepath.c_str()); 656 | } else { 657 | DEBUG_FUNCTION_LINE_ERR("Failed to get info for titleID %016llX", title->titleId); 658 | } 659 | } 660 | 661 | return real_ACPCheckTitleLaunchByTitleListTypeEx(title, u2); 662 | } 663 | 664 | 665 | DECL_FUNCTION(int, FSOpenFile, FSClient *client, FSCmdBlock *block, char *path, const char *mode, uint32_t *handle, int error) { 666 | const char *start = "/vol/storage_mlc01/sys/title/0005000F"; 667 | const char *tga = ".tga"; 668 | const char *iconTex = "iconTex.tga"; 669 | const char *sound = ".btsnd"; 670 | 671 | std::string_view pathStr = path; 672 | 673 | if (pathStr.starts_with(start)) { 674 | std::unique_ptr reader; 675 | if (pathStr.ends_with(tga) || pathStr.ends_with(sound)) { 676 | char *id = path + 1 + strlen(start); 677 | id[8] = 0; 678 | char *relativePath = id + 9; 679 | auto lowerTitleID = strtoul(id, 0, 16); 680 | auto fileInfo = getIDByLowerTitleID(lowerTitleID); 681 | if (fileInfo.has_value()) { 682 | reader = make_unique_nothrow(fileInfo.value(), relativePath, !gHomebrewLaunched); 683 | if (reader && !reader->isReady()) { 684 | reader.reset(); 685 | } 686 | } 687 | } 688 | // If the icon is requested and loading it from a bundle failed, we fall back to a default one. 689 | if (reader == nullptr && pathStr.ends_with(iconTex)) { 690 | reader = make_unique_nothrow((uint8_t *) iconTex_tga, iconTex_tga_size); 691 | if (reader && !reader->isReady()) { 692 | reader.reset(); 693 | } 694 | } 695 | if (reader) { 696 | std::lock_guard lock(fileReaderListMutex); 697 | *handle = reader->getHandle(); 698 | openFileReaders.push_front(std::move(reader)); 699 | return FS_STATUS_OK; 700 | } 701 | } 702 | 703 | int result = real_FSOpenFile(client, block, path, mode, handle, error); 704 | return result; 705 | } 706 | 707 | DECL_FUNCTION(FSStatus, FSCloseFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t flags) { 708 | if (remove_locked_first_if(fileReaderListMutex, openFileReaders, [handle](auto &cur) { return cur->getHandle() == handle; })) { 709 | return FS_STATUS_OK; 710 | } 711 | 712 | return real_FSCloseFile(client, block, handle, flags); 713 | } 714 | 715 | DECL_FUNCTION(FSStatus, FSReadFile, FSClient *client, FSCmdBlock *block, uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, uint32_t flags) { 716 | { 717 | const std::lock_guard lock(fileReaderListMutex); 718 | for (auto &reader : openFileReaders) { 719 | if ((uint32_t) reader.get() == (uint32_t) handle) { 720 | return (FSStatus) (reader->read(buffer, size * count) / size); 721 | } 722 | } 723 | } 724 | FSStatus result = real_FSReadFile(client, block, buffer, size, count, handle, unk1, flags); 725 | return result; 726 | } 727 | 728 | DECL_FUNCTION(int32_t, ACPGetTitleMetaXmlByDevice, uint32_t titleid_upper, uint32_t titleid_lower, ACPMetaXml *out_buf, uint32_t device, uint32_t u1) { 729 | int result = real_ACPGetTitleMetaXmlByDevice(titleid_upper, titleid_lower, out_buf, device, u1); 730 | if (titleid_upper == UPPER_TITLE_ID_HOMEBREW) { 731 | fillXmlForTitleID(titleid_upper, titleid_lower, out_buf); 732 | result = 0; 733 | } 734 | return result; 735 | } 736 | 737 | DECL_FUNCTION(int32_t, ACPGetTitleMetaDirByDevice, uint32_t titleid_upper, uint32_t titleid_lower, char *out_buf, uint32_t size, int device) { 738 | if (titleid_upper == UPPER_TITLE_ID_HOMEBREW) { 739 | snprintf(out_buf, 53, "/vol/storage_mlc01/sys/title/%08X/%08X/meta", titleid_upper, titleid_lower); 740 | return 0; 741 | } 742 | int result = real_ACPGetTitleMetaDirByDevice(titleid_upper, titleid_lower, out_buf, size, device); 743 | return result; 744 | } 745 | 746 | /* 747 | * Load the H&S app instead 748 | */ 749 | DECL_FUNCTION(int32_t, _SYSLaunchTitleByPathFromLauncher, char *pathToLoad, uint32_t u2) { 750 | const char *start = "/custom/"; 751 | if (strncmp(pathToLoad, start, strlen(start)) == 0) { 752 | strcpy(current_launched_title_info.path, pathToLoad); 753 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 754 | snprintf(pathToLoad, 47, "/vol/storage_mlc01/sys/title/%08x/%08x", (uint32_t) (titleID >> 32), (uint32_t) (0x00000000FFFFFFFF & titleID)); 755 | } 756 | 757 | int32_t result = real__SYSLaunchTitleByPathFromLauncher(pathToLoad, strlen(pathToLoad)); 758 | return result; 759 | } 760 | 761 | DECL_FUNCTION(int32_t, ACPGetLaunchMetaXml, ACPMetaXml *metaxml) { 762 | int result = real_ACPGetLaunchMetaXml(metaxml); 763 | if (gHomebrewLaunched) { 764 | memcpy(metaxml, &gLaunchXML, sizeof(gLaunchXML)); 765 | } 766 | return result; 767 | } 768 | 769 | DECL_FUNCTION(uint32_t, ACPGetApplicationBox, uint32_t *u1, uint32_t *u2, uint32_t u3, uint32_t u4) { 770 | if (u3 == UPPER_TITLE_ID_HOMEBREW) { 771 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 772 | u3 = (uint32_t) (titleID >> 32); 773 | u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); 774 | } 775 | uint32_t result = real_ACPGetApplicationBox(u1, u2, u3, u4); 776 | return result; 777 | } 778 | 779 | /* 780 | * Redirect the launchable check to H&S 781 | */ 782 | DECL_FUNCTION(uint32_t, PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, uint32_t *param) { 783 | if (param[2] == UPPER_TITLE_ID_HOMEBREW) { 784 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 785 | param[2] = (uint32_t) (titleID >> 32); 786 | param[3] = (uint32_t) (0x00000000FFFFFFFF & titleID); 787 | } 788 | uint32_t result = real_PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg(param); 789 | return result; 790 | } 791 | 792 | /* 793 | * Redirect the launchable check to H&S 794 | */ 795 | DECL_FUNCTION(uint32_t, MCP_RightCheckLaunchable, uint32_t *u1, uint32_t *u2, uint32_t u3, uint32_t u4, uint32_t u5) { 796 | if (u3 == UPPER_TITLE_ID_HOMEBREW) { 797 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 798 | u3 = (uint32_t) (titleID >> 32); 799 | u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); 800 | } 801 | uint32_t result = real_MCP_RightCheckLaunchable(u1, u2, u3, u4, u5); 802 | return result; 803 | } 804 | 805 | /* 806 | * Patch the boot movie and and boot logo 807 | */ 808 | DECL_FUNCTION(uint32_t, ACPGetLaunchMetaData, struct ACPMetaData *metadata) { 809 | uint32_t result = real_ACPGetLaunchMetaData(metadata); 810 | 811 | if (gHomebrewLaunched) { 812 | memcpy(metadata->bootmovie, bootMovie_h264, bootMovie_h264_size); 813 | memcpy(metadata->bootlogo, bootLogoTex_tga, bootLogoTex_tga_size); 814 | DCFlushRange(metadata->bootmovie, bootMovie_h264_size); 815 | DCFlushRange(metadata->bootlogo, bootMovie_h264_size); 816 | } 817 | 818 | return result; 819 | } 820 | 821 | typedef struct TitleVersionInfo TitleVersionInfo; 822 | 823 | struct WUT_PACKED TitleVersionInfo { 824 | uint16_t currentVersion; 825 | uint16_t neededVersion; 826 | uint8_t needsUpdate; 827 | }; 828 | WUT_CHECK_OFFSET(TitleVersionInfo, 0x00, currentVersion); 829 | WUT_CHECK_OFFSET(TitleVersionInfo, 0x02, neededVersion); 830 | WUT_CHECK_OFFSET(TitleVersionInfo, 0x04, needsUpdate); 831 | WUT_CHECK_SIZE(TitleVersionInfo, 0x05); 832 | 833 | 834 | DECL_FUNCTION(uint32_t, GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, TitleVersionInfo *titleVersionInfo, uint32_t u2, uint32_t u3, uint32_t u4, uint32_t u5) { 835 | int32_t result = real_GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType(titleVersionInfo, u2, u3, u4, u5); 836 | 837 | if (result < 0) { 838 | // Fake result if it's H&S 839 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 840 | auto expected_u3 = (uint32_t) (titleID >> 32); 841 | auto expected_u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); 842 | 843 | if (expected_u3 == u3 && expected_u4 == u4) { 844 | if (titleVersionInfo != nullptr) { 845 | titleVersionInfo->currentVersion = 129; 846 | titleVersionInfo->neededVersion = 129; 847 | titleVersionInfo->needsUpdate = 0; 848 | } 849 | return 0; 850 | } 851 | } 852 | 853 | return result; 854 | } 855 | 856 | DECL_FUNCTION(uint32_t, GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, uint32_t u1, uint32_t u2, uint32_t u3, uint32_t u4, uint32_t u5, uint32_t u6) { 857 | uint32_t result = real_GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType(u1, u2, u3, u4, u5, u6); 858 | 859 | uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); 860 | auto expected_u3 = (uint32_t) (titleID >> 32); 861 | auto expected_u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); 862 | 863 | if (expected_u3 == u3 && expected_u4 == u4) { 864 | return 0xa121f480; 865 | } 866 | 867 | return result; 868 | } 869 | 870 | DECL_FUNCTION(uint32_t, MCPGetTitleInternal, uint32_t mcp_handle, void *input, uint32_t type, MCPTitleListType *titles, uint32_t out_cnt) { 871 | if (input != nullptr) { 872 | auto *inputPtrAsU32 = (uint32_t *) input; 873 | if (inputPtrAsU32[0] == UPPER_TITLE_ID_HOMEBREW && out_cnt >= 1) { 874 | for (auto &gFileInfo : fileInfos) { 875 | if (gFileInfo->lowerTitleID == inputPtrAsU32[1]) { 876 | memcpy(&titles[0], &(gFileInfo->titleInfo), sizeof(MCPTitleListType)); 877 | return 1; 878 | } 879 | } 880 | DEBUG_FUNCTION_LINE_ERR("Failed to find lower TID %08X", inputPtrAsU32[1]); 881 | } 882 | } 883 | 884 | uint32_t result = real_MCPGetTitleInternal(mcp_handle, input, type, titles, out_cnt); 885 | 886 | return result; 887 | } 888 | 889 | WUPS_MUST_REPLACE_FOR_PROCESS(GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, WUPS_LOADER_LIBRARY_NN_VCTL, GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 890 | WUPS_MUST_REPLACE_FOR_PROCESS(GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, WUPS_LOADER_LIBRARY_NN_VCTL, GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 891 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetApplicationBox, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetApplicationBox, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 892 | WUPS_MUST_REPLACE_FOR_PROCESS(PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, WUPS_LOADER_LIBRARY_DRMAPP, PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 893 | WUPS_MUST_REPLACE_FOR_PROCESS(MCP_RightCheckLaunchable, WUPS_LOADER_LIBRARY_COREINIT, MCP_RightCheckLaunchable, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 894 | 895 | WUPS_MUST_REPLACE_FOR_PROCESS(MCP_TitleList, WUPS_LOADER_LIBRARY_COREINIT, MCP_TitleList, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 896 | 897 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPCheckTitleLaunchByTitleListTypeEx, WUPS_LOADER_LIBRARY_NN_ACP, ACPCheckTitleLaunchByTitleListTypeEx, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 898 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetTitleMetaXmlByDevice, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetTitleMetaXmlByDevice, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 899 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetLaunchMetaXml, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetLaunchMetaXml, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 900 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetTitleMetaDirByDevice, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetTitleMetaDirByDevice, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 901 | WUPS_MUST_REPLACE_FOR_PROCESS(_SYSLaunchTitleByPathFromLauncher, WUPS_LOADER_LIBRARY_SYSAPP, _SYSLaunchTitleByPathFromLauncher, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 902 | WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetLaunchMetaData, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetLaunchMetaData, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 903 | 904 | WUPS_MUST_REPLACE_FOR_PROCESS(FSReadFile, WUPS_LOADER_LIBRARY_COREINIT, FSReadFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 905 | WUPS_MUST_REPLACE_FOR_PROCESS(FSOpenFile, WUPS_LOADER_LIBRARY_COREINIT, FSOpenFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 906 | WUPS_MUST_REPLACE_FOR_PROCESS(FSCloseFile, WUPS_LOADER_LIBRARY_COREINIT, FSCloseFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); 907 | 908 | WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MCPGetTitleInternal, (0x3001C400 + 0x0205a590), (0x0205a590 - 0xFE3C00), WUPS_FP_TARGET_PROCESS_WII_U_MENU); 909 | --------------------------------------------------------------------------------