├── .gitignore ├── HBC ├── icon.png └── meta.xml ├── LICENSE.md ├── Makefile ├── README.md ├── portlibs ├── include │ └── runtimeiospatch.h └── lib │ └── libruntimeiospatch.a └── source ├── ardb.c ├── ardb.h ├── main.c ├── sha1.c ├── sha1.h ├── u8.c ├── u8.h ├── utils.c └── utils.h /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.elf 3 | *.dol 4 | .vscode 5 | *.code-workspace 6 | -------------------------------------------------------------------------------- /HBC/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DarkMatterCore/ww-43db-patcher/983f2c5467f7661161d6c36620f813a6ec3ae103/HBC/icon.png -------------------------------------------------------------------------------- /HBC/meta.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ww-43db-patcher 4 | 0.4 5 | 20240922150000 6 | DarkMatterCore 7 | vWii WiiWare 43DB patcher. 8 | Patches the WiiWare 4:3 aspect ratio database (43DB) within vWii's System Menu U8 archive to remove WiiConnect24-related channel entries (Everybody Votes Channel, Check Mii Out Channel) from it, effectively enabling access to a 16:9 aspect ratio. 9 | 10 | 11 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 12 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. 15 | 16 | To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 21 | 22 | Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 23 | 24 | Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 25 | 26 | The precise terms and conditions for copying, distribution and modification follow. 27 | 28 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 29 | 30 | 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 31 | 32 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 33 | 34 | 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 35 | 36 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 37 | 38 | 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 39 | 40 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 41 | 42 | b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 43 | 44 | c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) 45 | 46 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 47 | 48 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 49 | 50 | In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 51 | 52 | 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: 53 | 54 | a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 55 | 56 | b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 57 | 58 | c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 59 | 60 | The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 61 | 62 | If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 63 | 64 | 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 65 | 66 | 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 67 | 68 | 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 69 | 70 | 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 71 | 72 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 73 | 74 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 75 | 76 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 77 | 78 | 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 79 | 80 | 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 81 | 82 | Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 83 | 84 | 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 85 | 86 | NO WARRANTY 87 | 88 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 89 | 90 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 91 | 92 | END OF TERMS AND CONDITIONS 93 | 94 | How to Apply These Terms to Your New Programs 95 | 96 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 97 | 98 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 99 | 100 | One line to give the program's name and a brief idea of what it does. 101 | Copyright (C) 102 | 103 | This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 104 | 105 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 106 | 107 | You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 108 | 109 | Also add information on how to contact you by electronic and paper mail. 110 | 111 | If the program is interactive, make it output a short notice like this when it starts in an interactive mode: 112 | 113 | Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 114 | 115 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. 116 | 117 | You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: 118 | 119 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. 120 | 121 | signature of Ty Coon, 1 April 1989 122 | Ty Coon, President of Vice 123 | 124 | This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. 125 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #--------------------------------------------------------------------------------- 2 | # Clear the implicit built in rules 3 | #--------------------------------------------------------------------------------- 4 | .SUFFIXES: 5 | #--------------------------------------------------------------------------------- 6 | ifeq ($(strip $(DEVKITPPC)),) 7 | $(error "Please set DEVKITPPC in your environment. export DEVKITPPC=devkitPPC") 8 | endif 9 | 10 | include $(DEVKITPPC)/wii_rules 11 | 12 | #--------------------------------------------------------------------------------- 13 | # TARGET is the name of the output 14 | # BUILD is the directory where object files & intermediate files will be placed 15 | # SOURCES is a list of directories containing source code 16 | # INCLUDES is a list of directories containing extra header files 17 | #--------------------------------------------------------------------------------- 18 | 19 | GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) 20 | GIT_COMMIT := $(shell git rev-parse --short HEAD) 21 | GIT_REV := ${GIT_BRANCH}-${GIT_COMMIT} 22 | 23 | ifneq (,$(strip $(shell git status --porcelain 2>/dev/null))) 24 | GIT_REV := $(GIT_REV)-dirty 25 | endif 26 | 27 | VERSION_MAJOR := 0 28 | VERSION_MINOR := 4 29 | 30 | APP_TITLE := ww-43db-patcher 31 | APP_AUTHOR := DarkMatterCore 32 | APP_VERSION := ${VERSION_MAJOR}.${VERSION_MINOR} 33 | 34 | BUILD_TIMESTAMP := $(strip $(shell date --utc '+%Y-%m-%d %T UTC')) 35 | 36 | TARGET := boot 37 | BUILD := build 38 | SOURCES := source 39 | DATA := 40 | INCLUDES := 41 | 42 | #--------------------------------------------------------------------------------- 43 | # options for code generation 44 | #--------------------------------------------------------------------------------- 45 | 46 | CFLAGS := -g -O2 -Wall -Wextra -Werror $(MACHDEP) $(INCLUDE) 47 | CFLAGS += -DGIT_BRANCH=\"${GIT_BRANCH}\" -DGIT_COMMIT=\"${GIT_COMMIT}\" -DGIT_REV=\"${GIT_REV}\" 48 | CFLAGS += -DVERSION_MAJOR=${VERSION_MAJOR} -DVERSION_MINOR=${VERSION_MINOR} 49 | CFLAGS += -DAPP_TITLE=\"${APP_TITLE}\" -DAPP_AUTHOR=\"${APP_AUTHOR}\" -DAPP_VERSION=\"${APP_VERSION}\" 50 | CFLAGS += -DBUILD_TIMESTAMP="\"${BUILD_TIMESTAMP}\"" 51 | 52 | CXXFLAGS := $(CFLAGS) 53 | 54 | LDFLAGS := -g $(MACHDEP) -Wl,-Map,$(notdir $@).map 55 | 56 | #--------------------------------------------------------------------------------- 57 | # any extra libraries we wish to link with the project 58 | #--------------------------------------------------------------------------------- 59 | LIBS := -lfat -lwiiuse -lbte -lm -logc -lruntimeiospatch 60 | 61 | #--------------------------------------------------------------------------------- 62 | # list of directories containing libraries, this must be the top level containing 63 | # include and lib 64 | #--------------------------------------------------------------------------------- 65 | LIBDIRS := $(CURDIR)/portlibs 66 | 67 | #--------------------------------------------------------------------------------- 68 | # no real need to edit anything past this point unless you need to add additional 69 | # rules for different file extensions 70 | #--------------------------------------------------------------------------------- 71 | ifneq ($(BUILD),$(notdir $(CURDIR))) 72 | #--------------------------------------------------------------------------------- 73 | 74 | export OUTPUT := $(CURDIR)/$(TARGET) 75 | 76 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 77 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 78 | 79 | export DEPSDIR := $(CURDIR)/$(BUILD) 80 | 81 | #--------------------------------------------------------------------------------- 82 | # automatically build a list of object files for our project 83 | #--------------------------------------------------------------------------------- 84 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) 85 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) 86 | sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) 87 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S))) 88 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 89 | 90 | #--------------------------------------------------------------------------------- 91 | # use CXX for linking C++ projects, CC for standard C 92 | #--------------------------------------------------------------------------------- 93 | ifeq ($(strip $(CPPFILES)),) 94 | export LD := $(CC) 95 | else 96 | export LD := $(CXX) 97 | endif 98 | 99 | export OFILES := $(addsuffix .o,$(BINFILES)) \ 100 | $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \ 101 | $(sFILES:.s=.o) $(SFILES:.S=.o) 102 | 103 | #--------------------------------------------------------------------------------- 104 | # build a list of include paths 105 | #--------------------------------------------------------------------------------- 106 | export INCLUDE := $(foreach dir,$(INCLUDES), -iquote $(CURDIR)/$(dir)) \ 107 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 108 | -I$(CURDIR)/$(BUILD) \ 109 | -I$(LIBOGC_INC) 110 | 111 | #--------------------------------------------------------------------------------- 112 | # build a list of library paths 113 | #--------------------------------------------------------------------------------- 114 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \ 115 | -L$(LIBOGC_LIB) 116 | 117 | export OUTPUT := $(CURDIR)/$(TARGET) 118 | .PHONY: $(BUILD) clean 119 | 120 | #--------------------------------------------------------------------------------- 121 | #lets see what OS we are on and then create svnref file 122 | UNAME := $(shell uname) 123 | #and now make the build list 124 | 125 | all: 126 | @[ -d $(BUILD) ] || mkdir -p $(BUILD) 127 | @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 128 | 129 | $(BUILD): 130 | @[ -d $@ ] || mkdir -p $@ 131 | @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 132 | 133 | #--------------------------------------------------------------------------------- 134 | clean: 135 | @echo clean ... 136 | @rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).dol 137 | #--------------------------------------------------------------------------------- 138 | run: 139 | wiiload $(TARGET).elf 140 | 141 | 142 | #--------------------------------------------------------------------------------- 143 | else 144 | 145 | DEPENDS := $(OFILES:.o=.d) 146 | 147 | #--------------------------------------------------------------------------------- 148 | # main targets 149 | #--------------------------------------------------------------------------------- 150 | $(OUTPUT).dol: $(OUTPUT).elf 151 | $(OUTPUT).elf: $(OFILES) 152 | 153 | #--------------------------------------------------------------------------------- 154 | # This rule links in binary data 155 | #--------------------------------------------------------------------------------- 156 | %.sys.o : %.sys 157 | @echo $(notdir $<) 158 | $(bin2o) 159 | 160 | -include $(DEPENDS) 161 | 162 | #--------------------------------------------------------------------------------- 163 | endif 164 | #--------------------------------------------------------------------------------- 165 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ww-43db-patcher 2 | vWii WiiWare 43DB patcher. 3 | 4 | This is a Wii homebrew application that patches the WiiWare 4:3 aspect ratio database (43DB) within vWii's System Menu U8 archive to remove WiiConnect24-related channel entries (Everybody Votes Channel, Check Mii Out Channel) from it, effectively enabling access to a 16:9 aspect ratio. The System Menu TMD isn't modified in this process. 5 | 6 | A backup of the unpatched System Menu U8 archive content file is created at `sd:/ww-43db-patcher_bkp/.app`. It is recommended to copy it to a safer location. The application is also capable of restoring such backup on its own, as long as it is available in the SD card. 7 | 8 | If the U8 archive has been modified in some kind of way and its hash no longer matches the one from the System Menu TMD, backup generation and restoring features won't work. 9 | 10 | For obvious reasons, this only works under Wii U consoles. 11 | 12 | License 13 | -------------- 14 | 15 | ww-43db-patcher is licensed under GPLv2. 16 | 17 | Acknowledgments 18 | -------------- 19 | 20 | * [InvoxiPlayGames](https://github.com/InvoxiPlayGames) for both testing and providing the icon. 21 | * [Ingunar](https://github.com/Ingunar), for helping with some extra tests. 22 | 23 | Changelog 24 | -------------- 25 | 26 | **v0.4:** 27 | 28 | * Change ARDB patching behavior: instead of stubbing all title records to `ZZZ.`, the desired entries are simply removed from the target ARDB. 29 | * Remove option to patch all entries from the WW ARDB. 30 | 31 | **v0.3:** 32 | 33 | * Fix borked error message output due to missing function attributes. 34 | * Check free space on the inserted SD card before attempting to write a System Menu U8 archive backup. 35 | * Migrate to hardware-based SHA-1 hash calculation. 36 | * Add option to only patch most demanded WC24 channel entries (Everybody Votes Channel, Check Mii Out Channel). 37 | * Display git branch and commit hash. 38 | * Display build date in UTC format. 39 | * Reset screen on user input to better accommodate for any possible error messages (except when the HOME button is pressed). 40 | * Other minor fixes and improvements. 41 | 42 | **v0.2:** 43 | 44 | * Now capable of restoring a previously generated System Menu U8 archive backup. 45 | * System Menu U8 archive content hash is now verified before attempting to save a backup or restore it. 46 | * Moved all SD card I/O in ardb.c to utils.c. 47 | * Minor optimizations. 48 | 49 | **v0.1:** 50 | 51 | * Initial release. 52 | -------------------------------------------------------------------------------- /portlibs/include/runtimeiospatch.h: -------------------------------------------------------------------------------- 1 | // This program is free software: you can redistribute it and/or modify 2 | // it under the terms of the GNU General Public License as published by 3 | // the Free Software Foundation, version 2.0. 4 | 5 | // This program is distributed in the hope that it will be useful, 6 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 7 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 8 | // GNU General Public License 2.0 for more details. 9 | 10 | // Copyright (C) 2010 Joseph Jordan 11 | // Copyright (C) 2012-2013 damysteryman 12 | // Copyright (C) 2012-2015 Christopher Bratusek 13 | // Copyright (C) 2013 DarkMatterCore 14 | // Copyright (C) 2014 megazig 15 | // Copyright (C) 2015 FIX94 16 | 17 | #ifndef __RUNTIMEIOSPATCH_H__ 18 | #define __RUNTIMEIOSPATCH_H__ 19 | 20 | /** 21 | * Version information for Libruntimeiospatch. 22 | */ 23 | #define LIB_RUNTIMEIOSPATCH_VERSION "1.5.4" 24 | 25 | //============================================================================== 26 | // HW_RVL header 27 | //============================================================================== 28 | #if defined(HW_RVL) /* defined(HW_RVL) */ 29 | 30 | /** 31 | *Returns true when HW_AHBPROT access can be applied 32 | */ 33 | #define AHBPROT_DISABLED (*(vu32*)0xcd800064 == 0xFFFFFFFF) 34 | 35 | //============================================================================== 36 | // Error code definitions: 37 | //============================================================================== 38 | #define ERROR_AHBPROT -5 39 | #define ERROR_PATCH -7 40 | 41 | //============================================================================== 42 | // C++ header 43 | //============================================================================== 44 | #ifdef __cplusplus 45 | extern "C" { 46 | #endif 47 | /* __cplusplus */ 48 | 49 | //============================================================================== 50 | // Patchsets: 51 | //============================================================================== 52 | /* 53 | Wii: 54 | * DI Readlimit 55 | * ISFS Permissions 56 | * ES SetUID 57 | * ES SetIdentify 58 | * Hash Check (aka Trucha) 59 | * New Hash Check (aka New Trucha) 60 | * SSL patches 61 | 62 | Sciifii: 63 | * MEM2 Prot 64 | * ES OpenTitleContent 1 & 2 65 | * ES ReadContent Prot 66 | * ES CloseContent 67 | * ES TitleVersionCheck 68 | * ES TitleDeleteCheck 69 | 70 | vWii: 71 | * Kill Anti-SystemTitle-Install 1, 2, 3, 4 & 5 72 | */ 73 | 74 | 75 | //============================================================================== 76 | // Functions: 77 | //============================================================================== 78 | 79 | /** 80 | * This function can be used to keep HW_AHBPROT access when going to reload IOS 81 | * @param verbose Flag determing whether or not to print messages on-screen 82 | * @example 83 | * if(AHBPROT_DISABLED) { 84 | * s32 ret; 85 | * ret = IosPatch_AHBPROT(false); 86 | * if (ret) { 87 | * IOS_ReloadIOS(36); 88 | * } else { 89 | * printf("IosPatch_AHBPROT failed."); 90 | * } 91 | * } 92 | * @return Signed 32bit integer representing code 93 | * > 0 : Success - return equals to number of applied patches 94 | * ERROR_AHBPROT : Error - No HW_AHBPROT access 95 | */ 96 | s32 IosPatch_AHBPROT(bool verbose); 97 | 98 | 99 | /** 100 | * This function applies patches on current IOS 101 | * @see Patchsets 102 | * @param wii Flag determing whether or not to apply Wii patches. 103 | * @param sciifii Flag determing whether or not to apply extra Sciifii patches. 104 | * @param vwii Flag determing whether or not to apply extra vWii patches. 105 | * @param verbose Flag determing whether or not to print messages on-screen. 106 | * @example if(AHBPROT_DISABLED) IosPatch_FULL(true, false, false, false); 107 | * @return Signed 32bit integer representing code 108 | * > 0 : Success - return equals to number of applied patches 109 | * ERROR_AHBPROT : Error - No HW_AHBPROT access 110 | * ERROR_PATCH : Error - Patching HW_AHBPROT access failed 111 | */ 112 | s32 IosPatch_RUNTIME(bool wii, bool sciifii, bool vwii, bool verbose); 113 | 114 | 115 | /** 116 | * This function combines IosPatch_AHBPROT + IOS_ReloadIOS + IosPatch_RUNTIME 117 | * @see Patchsets 118 | * @param wii Flag determing whether or not to apply Wii patches. 119 | * @param sciifii Flag determing whether or not to apply extra Sciifii patches. 120 | * @param vwii Flag determing whether or not to apply extra vWii patches. 121 | * @param verbose Flag determing whether or not to print messages on-screen. 122 | * @param IOS Which IOS to reload into. 123 | * @example if(AHBPROT_DISABLED) IosPatch_FULL(true, false, false, false, 58); 124 | * @return Signed 32bit integer representing code 125 | * > 0 : Success - return equals to number of applied patches 126 | * ERROR_AHBPROT : Error - No HW_AHBPROT access 127 | * ERROR_PATCH : Error - Patching HW_AHBPROT access failed 128 | */ 129 | s32 IosPatch_FULL(bool wii, bool sciifii, bool vwii, bool verbose, int IOS); 130 | 131 | //============================================================================== 132 | // C++ footer 133 | //============================================================================== 134 | #ifdef __cplusplus 135 | } 136 | #endif /* __cplusplus */ 137 | 138 | //============================================================================== 139 | // HW_RVL footer 140 | //============================================================================== 141 | #endif /* defined(HW_RVL) */ 142 | 143 | #endif 144 | -------------------------------------------------------------------------------- /portlibs/lib/libruntimeiospatch.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DarkMatterCore/ww-43db-patcher/983f2c5467f7661161d6c36620f813a6ec3ae103/portlibs/lib/libruntimeiospatch.a -------------------------------------------------------------------------------- /source/ardb.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ardb.c 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "utils.h" 22 | #include "ardb.h" 23 | #include "u8.h" 24 | #include "sha1.h" 25 | 26 | static const char *g_ardbArchivePaths[AspectRatioDatabaseType_Count] = { 27 | "/titlelist/discdb.bin", 28 | "/titlelist/vcadb.bin", 29 | "/titlelist/wwdb.bin" 30 | }; 31 | 32 | bool ardbPatchDatabaseFromSystemMenuArchive(u8 type, const u32 *entries, const u32 entry_count) 33 | { 34 | if (type >= AspectRatioDatabaseType_Count) 35 | { 36 | ERROR_MSG("Invalid aspect ratio database type value!"); 37 | return false; 38 | } 39 | 40 | if (!entries || !entry_count) 41 | { 42 | ERROR_MSG("Invalid patch entries array / count!"); 43 | return false; 44 | } 45 | 46 | signed_blob *sysmenu_stmd = NULL; 47 | u32 sysmenu_stmd_size = 0; 48 | 49 | tmd *sysmenu_tmd = NULL; 50 | tmd_content *sysmenu_archive_content = NULL; 51 | 52 | char content_path[ISFS_MAXPATH] = {0}; 53 | u8 *sysmenu_archive_content_data = NULL; 54 | u32 sysmenu_archive_content_size = 0; 55 | 56 | U8Context u8_ctx = {0}; 57 | u32 u8_node_idx = 0; 58 | 59 | u8 *ardb_data = NULL; 60 | u32 ardb_data_size = 0, ardb_orig_entry_count = 0; 61 | AspectRatioDatabase *ardb = NULL; 62 | 63 | bool success = false; 64 | 65 | #ifdef BACKUP_U8_ARCHIVE 66 | char backup_path[ISFS_MAXPATH] = {0}; 67 | sha1 sysmenu_archive_content_hash = {0}; 68 | bool hash_match = false, backup_created = false; 69 | #endif /* BACKUP_U8_ARCHIVE */ 70 | 71 | /* Get System Menu TMD. */ 72 | sysmenu_stmd = utilsGetSignedTMDFromTitle(SYSTEM_MENU_TID, &sysmenu_stmd_size); 73 | if (!sysmenu_stmd) 74 | { 75 | ERROR_MSG("Error retrieving System Menu TMD!"); 76 | goto out; 77 | } 78 | 79 | sysmenu_tmd = utilsGetTMDFromSignedBlob(sysmenu_stmd); 80 | 81 | /* Look for the biggest content record (U8 archive with resources). */ 82 | sysmenu_archive_content = &(sysmenu_tmd->contents[0]); 83 | for(u16 i = 0; i < sysmenu_tmd->num_contents; i++) 84 | { 85 | if (sysmenu_tmd->contents[i].size > sysmenu_archive_content->size) sysmenu_archive_content = &(sysmenu_tmd->contents[i]); 86 | } 87 | 88 | /* Generate U8 archive content path and read the whole content file. */ 89 | sprintf(content_path, "/title/%08x/%08x/content/%08x.app", TITLE_UPPER(SYSTEM_MENU_TID), TITLE_LOWER(SYSTEM_MENU_TID), sysmenu_archive_content->cid); 90 | sysmenu_archive_content_data = (u8*)utilsReadFileFromIsfs(content_path, &sysmenu_archive_content_size); 91 | if (!sysmenu_archive_content_data) 92 | { 93 | ERROR_MSG("Failed to read System Menu U8 archive content data!"); 94 | goto out; 95 | } 96 | 97 | #ifdef BACKUP_U8_ARCHIVE 98 | /* Calculate U8 archive content hash. */ 99 | sha1CalculateHash(sysmenu_archive_content_data, sysmenu_archive_content_size, sysmenu_archive_content_hash); 100 | 101 | /* Compare hashes. */ 102 | hash_match = (memcmp(sysmenu_archive_content->hash, sysmenu_archive_content_hash, SHA1_HASH_SIZE) == 0); 103 | if (hash_match) 104 | { 105 | /* Create output directory. */ 106 | sprintf(backup_path, "sd:/" APP_TITLE "_bkp"); 107 | mkdir(backup_path, 0777); 108 | 109 | /* Generate backup content path. */ 110 | strcat(backup_path, strrchr(content_path, '/')); 111 | 112 | /* Write backup content file. */ 113 | backup_created = utilsWriteFileToMountedDevice(backup_path, sysmenu_archive_content_data, sysmenu_archive_content_size); 114 | if (!backup_created) 115 | { 116 | ERROR_MSG("Failed to write U8 archive backup!"); 117 | goto out; 118 | } 119 | 120 | printf("Saved System Menu U8 archive backup to \"%s\".\nPlease copy it to a safe location.\n\n", backup_path); 121 | } else { 122 | printf("U8 archive content hash mismatch! Skipping backup generation.\n\n"); 123 | } 124 | #endif /* BACKUP_U8_ARCHIVE */ 125 | 126 | /* Initialize U8 context. */ 127 | if (!u8ContextInit(sysmenu_archive_content_data, sysmenu_archive_content_size, &u8_ctx)) 128 | { 129 | ERROR_MSG("Failed to initialize System Menu U8 archive context!"); 130 | goto out; 131 | } 132 | 133 | /* Get U8 node for the aspect ratio database path. */ 134 | if (!u8GetFileNodeByPath(&u8_ctx, g_ardbArchivePaths[type], &u8_node_idx)) 135 | { 136 | ERROR_MSG("Failed to retrieve U8 node for \"%s\"!", g_ardbArchivePaths[type]); 137 | goto out; 138 | } 139 | 140 | /* Read aspect ratio database data. */ 141 | if (!(ardb_data = u8LoadFileData(&u8_ctx, u8_node_idx, &ardb_data_size)) || ardb_data_size < sizeof(AspectRatioDatabase)) 142 | { 143 | ERROR_MSG("Failed to read \"%s\" contents from U8 archive!", g_ardbArchivePaths[type]); 144 | goto out; 145 | } 146 | 147 | /* Parse aspect ratio database. */ 148 | ardb = (AspectRatioDatabase*)ardb_data; 149 | 150 | if (ardb->magic != ARDB_MAGIC) 151 | { 152 | ERROR_MSG("Invalid ARDB magic word for \"%s\": 0x%08X.", g_ardbArchivePaths[type], ardb->magic); 153 | goto out; 154 | } 155 | 156 | if (!ardb->entry_count || ardb_data_size < (sizeof(AspectRatioDatabase) + (sizeof(u32) * ardb->entry_count))) 157 | { 158 | ERROR_MSG("Invalid ARDB entry count for \"%s\": %u", g_ardbArchivePaths[type], ardb->entry_count); 159 | goto out; 160 | } 161 | 162 | ardb_orig_entry_count = ardb->entry_count; 163 | 164 | printf("Loaded \"%s\" (v%u, holding %u %s)", g_ardbArchivePaths[type], ardb->version, ardb->entry_count, (ardb->entry_count == 1 ? "entry" : "entries")); 165 | 166 | #ifdef DISPLAY_ARDB_ENTRIES 167 | if (ardb->entry_count) 168 | { 169 | printf(":\n"); 170 | 171 | for(u32 i = 0; i < ardb->entry_count; i++) 172 | { 173 | printf("%.*s", 3, (char*)&(ardb->entries[i])); 174 | if (i < (ardb->entry_count - 1)) printf(", "); 175 | } 176 | 177 | printf("\n\n"); 178 | } else { 179 | printf(".\n\n"); 180 | } 181 | #else /* DISPLAY_ARDB_ENTRIES */ 182 | printf(".\n\n"); 183 | #endif /* DISPLAY_ARDB_ENTRIES */ 184 | 185 | fflush(stdout); 186 | 187 | /* Patch aspect ratio database. */ 188 | for(u32 i = 0, j = 0; i < ardb->entry_count; i++, j++) 189 | { 190 | for(u32 k = 0; k < entry_count; k++) 191 | { 192 | u32 val = (ardb->entries[i] >> 8); 193 | if (val != entries[k]) continue; 194 | 195 | /* Jackpot. */ 196 | printf("Removing 43DB entry #%u: %.*s. (0x%X).\n", j, 3, (char*)&val, val); 197 | fflush(stdout); 198 | 199 | if ((i + 1) < ardb->entry_count) memmove(&(ardb->entries[i]), &(ardb->entries[i + 1]), sizeof(u32) * (ardb->entry_count - i - 1)); 200 | memset(&(ardb->entries[ardb->entry_count - 1]), 0, sizeof(u32)); 201 | 202 | ardb->entry_count--; 203 | i--; 204 | 205 | break; 206 | } 207 | } 208 | 209 | if (ardb->entry_count == ardb_orig_entry_count) 210 | { 211 | ERROR_MSG("Unable to locate desired TIDs within \"%s\". No changes have been made.", g_ardbArchivePaths[type]); 212 | goto out; 213 | } 214 | 215 | printf("\n"); 216 | fflush(stdout); 217 | 218 | /* Save modified aspect ratio database data to U8 archive buffer. */ 219 | ardb_data_size = (sizeof(AspectRatioDatabase) + (sizeof(u32) * ardb->entry_count)); 220 | 221 | if (!u8SaveFileData(&u8_ctx, u8_node_idx, ardb_data, ardb_data_size)) 222 | { 223 | ERROR_MSG("Failed to save modified aspect ratio database data into U8 archive!"); 224 | goto out; 225 | } 226 | 227 | /* Write modified U8 archive buffer to the NAND storage. */ 228 | if (!utilsWriteFileToIsfs(content_path, sysmenu_archive_content_data, sysmenu_archive_content_size)) 229 | { 230 | ERROR_MSG("Failed to write modified U8 archive to \"%s\"!", content_path); 231 | goto out; 232 | } 233 | 234 | /* Update output flag. */ 235 | success = true; 236 | 237 | out: 238 | if (ardb_data) free(ardb_data); 239 | 240 | u8ContextFree(&u8_ctx); 241 | 242 | if (sysmenu_archive_content_data) free(sysmenu_archive_content_data); 243 | 244 | if (sysmenu_stmd) free(sysmenu_stmd); 245 | 246 | #ifdef BACKUP_U8_ARCHIVE 247 | if (hash_match && !backup_created) 248 | { 249 | sprintf(backup_path, "sd:/" APP_TITLE "_bkp"); 250 | remove(backup_path); 251 | } 252 | #endif /* BACKUP_U8_ARCHIVE */ 253 | 254 | return success; 255 | } 256 | 257 | #ifdef BACKUP_U8_ARCHIVE 258 | bool ardbRestoreSystemMenuArchive(void) 259 | { 260 | signed_blob *sysmenu_stmd = NULL; 261 | u32 sysmenu_stmd_size = 0; 262 | 263 | tmd *sysmenu_tmd = NULL; 264 | tmd_content *sysmenu_archive_content = NULL; 265 | 266 | char content_path[ISFS_MAXPATH] = {0}; 267 | 268 | char backup_path[ISFS_MAXPATH] = {0}; 269 | u8 *backup_content_data = NULL; 270 | u32 backup_content_size = 0; 271 | sha1 backup_content_hash = {0}; 272 | 273 | bool success = false; 274 | 275 | /* Get System Menu TMD. */ 276 | sysmenu_stmd = utilsGetSignedTMDFromTitle(SYSTEM_MENU_TID, &sysmenu_stmd_size); 277 | if (!sysmenu_stmd) 278 | { 279 | ERROR_MSG("Error retrieving System Menu TMD!"); 280 | goto out; 281 | } 282 | 283 | sysmenu_tmd = utilsGetTMDFromSignedBlob(sysmenu_stmd); 284 | 285 | /* Look for the biggest content record (U8 archive with resources). */ 286 | sysmenu_archive_content = &(sysmenu_tmd->contents[0]); 287 | for(u16 i = 0; i < sysmenu_tmd->num_contents; i++) 288 | { 289 | if (sysmenu_tmd->contents[i].size > sysmenu_archive_content->size) sysmenu_archive_content = &(sysmenu_tmd->contents[i]); 290 | } 291 | 292 | /* Generate U8 archive content path. */ 293 | sprintf(content_path, "/title/%08x/%08x/content/%08x.app", TITLE_UPPER(SYSTEM_MENU_TID), TITLE_LOWER(SYSTEM_MENU_TID), sysmenu_archive_content->cid); 294 | 295 | /* Generate backup content path. */ 296 | sprintf(backup_path, "sd:/" APP_TITLE "_bkp"); 297 | strcat(backup_path, strrchr(content_path, '/')); 298 | 299 | /* Read whole backup content file. */ 300 | backup_content_data = (u8*)utilsReadFileFromMountedDevice(backup_path, &backup_content_size); 301 | if (!backup_content_data) 302 | { 303 | ERROR_MSG("Failed to read System Menu U8 archive backup!"); 304 | goto out; 305 | } 306 | 307 | /* Calculate U8 archive content hash. */ 308 | sha1CalculateHash(backup_content_data, backup_content_size, backup_content_hash); 309 | 310 | /* Compare hashes. */ 311 | if (memcmp(sysmenu_archive_content->hash, backup_content_hash, SHA1_HASH_SIZE) != 0) 312 | { 313 | ERROR_MSG("U8 archive content backup hash mismatch!"); 314 | goto out; 315 | } 316 | 317 | /* Write U8 archive buffer to the NAND storage. */ 318 | if (!utilsWriteFileToIsfs(content_path, backup_content_data, backup_content_size)) 319 | { 320 | ERROR_MSG("Failed to write U8 archive backup to \"%s\"!", content_path); 321 | goto out; 322 | } 323 | 324 | /* Update output flag. */ 325 | success = true; 326 | 327 | out: 328 | if (backup_content_data) free(backup_content_data); 329 | 330 | if (sysmenu_stmd) free(sysmenu_stmd); 331 | 332 | return success; 333 | } 334 | #endif /* BACKUP_U8_ARCHIVE */ 335 | -------------------------------------------------------------------------------- /source/ardb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ardb.h 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #ifndef __ARDB_H__ 24 | #define __ARDB_H__ 25 | 26 | #define ARDB_MAGIC (u32)0x34334442 /* "43DB". */ 27 | 28 | #define ARDB_WC24_EVC_ENTRY 0x48414A /* "HAJ" - Everybody Votes Channel. */ 29 | #define ARDB_WC24_CMOC_ENTRY 0x484150 /* "HAP" - Check Mii Out Channel. */ 30 | 31 | typedef struct { 32 | u32 magic; ///< ARDB_MAGIC. 33 | u32 version; ///< Database version number. 34 | u32 entry_count; ///< Entry count. 35 | u32 reserved; ///< Reserved. 36 | u32 entries[]; ///< C99 flexible array with entries. 37 | } AspectRatioDatabase; 38 | 39 | SIZE_ASSERT(AspectRatioDatabase, 0x10); 40 | 41 | typedef enum { 42 | AspectRatioDatabaseType_Disc = 0, 43 | AspectRatioDatabaseType_VirtualConsole = 1, 44 | AspectRatioDatabaseType_WiiWare = 2, 45 | AspectRatioDatabaseType_Count = 3 46 | } AspectRatioDatabaseType; 47 | 48 | /// Patches an aspect ratio database stored inside the System Menu's U8 archive by removing the desired title IDs from its records. 49 | /// The entries from the provided u32 array must use a 3-byte representation of the desired title IDs, ignoring the last byte value. 50 | bool ardbPatchDatabaseFromSystemMenuArchive(u8 type, const u32 *entries, const u32 entry_count); 51 | 52 | #ifdef BACKUP_U8_ARCHIVE 53 | /// Restores a previously created System Menu U8 archive from the inserted SD card. 54 | bool ardbRestoreSystemMenuArchive(void); 55 | #endif /* BACKUP_U8_ARCHIVE */ 56 | 57 | #endif /* __ARDB_H__ */ 58 | -------------------------------------------------------------------------------- /source/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * main.c 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "utils.h" 22 | #include "ardb.h" 23 | 24 | #include 25 | 26 | static const u32 g_ardbWc24Entries[] = { 27 | ARDB_WC24_EVC_ENTRY, 28 | ARDB_WC24_CMOC_ENTRY 29 | }; 30 | 31 | static const u32 g_ardbWc24EntriesCount = MAX_ELEMENTS(g_ardbWc24Entries); 32 | 33 | extern void __exception_setreload(int t); 34 | 35 | int main(int argc, char **argv) 36 | { 37 | (void)argc; 38 | (void)argv; 39 | 40 | int ret = 0; 41 | bool vwii = utilsIsWiiU(), bail = false; 42 | 43 | /* Set reload time to 10 seconds in case an exception is triggered. */ 44 | __exception_setreload(10); 45 | 46 | /* Initialize video output and controllers. */ 47 | utilsInitConsole(vwii); 48 | utilsInitPads(); 49 | 50 | /* Print headline. */ 51 | utilsPrintHeadline(); 52 | 53 | /* Check if we're running under vWii (Wii U). */ 54 | if (!vwii) 55 | { 56 | printf("Error: not running on a Wii U!"); 57 | ret = -1; 58 | goto out; 59 | } 60 | 61 | /* Check if we have full hardware access (HW_AHBPROT flag disabled). */ 62 | if (!AHBPROT_DISABLED) 63 | { 64 | printf("The HW_AHBPROT hardware register is not disabled.\n"); 65 | printf("Maybe you didn't load the application from a loader\n"); 66 | printf("capable of passing arguments (you should use HBC\n"); 67 | printf("1.1.0 or later). Or, perhaps, you don't have the\n"); 68 | printf("\"\" element in the meta.xml file, which\n"); 69 | printf("is very important.\n\n"); 70 | printf("This application can't do its job without full\n"); 71 | printf("hardware access rights."); 72 | ret = -2; 73 | goto out; 74 | } 75 | 76 | /* Apply runtime IOS patches. */ 77 | printf("Applying runtime IOS patches, please wait... "); 78 | 79 | ret = IosPatch_RUNTIME(true, false, false, false); 80 | if (ret <= 0) 81 | { 82 | printf("FAILED!"); 83 | ret = -3; 84 | goto out; 85 | } 86 | 87 | printf("OK!\n"); 88 | 89 | /* Initialize NAND filesystem driver. */ 90 | printf("Initializing NAND FS driver... "); 91 | 92 | ret = ISFS_Initialize(); 93 | if (ret < 0) 94 | { 95 | printf("FAILED!"); 96 | ret = -4; 97 | goto out; 98 | } 99 | 100 | printf("OK!\n"); 101 | 102 | #ifdef BACKUP_U8_ARCHIVE 103 | /* Mount SD card. */ 104 | printf("Mounting SD card... "); 105 | 106 | if (!utilsMountSdCard()) 107 | { 108 | printf("FAILED!"); 109 | ret = -5; 110 | goto out; 111 | } 112 | 113 | printf("OK!\n\n"); 114 | #else 115 | printf("\n"); 116 | #endif /* BACKUP_U8_ARCHIVE */ 117 | 118 | printf("Press 1/X to patch WC24 channel entries within the WW 43DB.\n\n"); 119 | #ifdef BACKUP_U8_ARCHIVE 120 | printf("Press - to restore a backup of the System Menu U8 archive.\n\n"); 121 | #endif /* BACKUP_U8_ARCHIVE */ 122 | printf("Press HOME to exit.\n\n"); 123 | 124 | fflush(stdout); 125 | 126 | while(true) 127 | { 128 | u32 pressed = utilsGetInput(UtilsInputType_Down); 129 | 130 | if (pressed == WPAD_BUTTON_1) 131 | { 132 | /* Patch WiiWare aspect ratio database. */ 133 | utilsPrintHeadline(); 134 | printf("Patching WC24 entries within WW 43DB...\n\n"); 135 | 136 | if (!ardbPatchDatabaseFromSystemMenuArchive(AspectRatioDatabaseType_WiiWare, g_ardbWc24Entries, g_ardbWc24EntriesCount)) 137 | { 138 | ret = -6; 139 | goto out; 140 | } 141 | 142 | break; 143 | } else 144 | #ifdef BACKUP_U8_ARCHIVE 145 | if (pressed == WPAD_BUTTON_MINUS) 146 | { 147 | /* Restore System Menu U8 archive backup. */ 148 | utilsPrintHeadline(); 149 | printf("Restoring System Menu U8 archive...\n\n"); 150 | 151 | if (!ardbRestoreSystemMenuArchive()) 152 | { 153 | ret = -7; 154 | goto out; 155 | } 156 | 157 | break; 158 | } else 159 | #endif /* BACKUP_U8_ARCHIVE */ 160 | if (pressed == WPAD_BUTTON_HOME) 161 | { 162 | /* Exit. */ 163 | bail = true; 164 | break; 165 | } 166 | } 167 | 168 | if (!bail) printf("Process completed. Press any button to exit."); 169 | 170 | out: 171 | #ifdef BACKUP_U8_ARCHIVE 172 | utilsUnmountSdCard(); 173 | #endif /* BACKUP_U8_ARCHIVE */ 174 | 175 | ISFS_Deinitialize(); 176 | 177 | if (ret != 0) printf("\n\nProcess cannot continue. Press any button to exit."); 178 | 179 | if (!bail) utilsWaitForButtonPress(); 180 | 181 | utilsReboot(); 182 | 183 | return ret; 184 | } 185 | -------------------------------------------------------------------------------- /source/sha1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * sha1.c 3 | * 4 | * Copyright (c) 2023-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "utils.h" 22 | #include "sha1.h" 23 | 24 | static bool g_sha1EngineInitialized = false; 25 | 26 | static bool sha1EngineInitialize(void); 27 | static void sha1EngineClose(void); 28 | 29 | #define SHA_ENGINE_WRAPPER(func, ...) \ 30 | bool ret = false; \ 31 | if (sha1EngineInitialize()) { \ 32 | s32 rc = func(__VA_ARGS__); \ 33 | ret = (rc >= 0); \ 34 | if (!ret) ERROR_MSG(#func "() failed! (%d).", rc); \ 35 | } \ 36 | sha1EngineClose(); \ 37 | return ret; 38 | 39 | bool sha1ContextCreate(sha_context *ctx) 40 | { 41 | SHA_ENGINE_WRAPPER(SHA_InitializeContext, ctx); 42 | } 43 | 44 | bool sha1ContextUpdate(sha_context *ctx, const void *src, const u32 size) 45 | { 46 | SHA_ENGINE_WRAPPER(SHA_Input, ctx, src, size); 47 | } 48 | 49 | bool sha1ContextGetHash(sha_context *ctx, const void *src, const u32 size, void *dst) 50 | { 51 | SHA_ENGINE_WRAPPER(SHA_Calculate, ctx, src, size, dst); 52 | } 53 | 54 | #undef SHA_ENGINE_WRAPPER 55 | 56 | bool sha1CalculateHash(const void *src, const u32 size, void *dst) 57 | { 58 | if (!src || !size || !dst) return false; 59 | 60 | bool ret = false; 61 | 62 | s32 rc = 0; 63 | 64 | u8 *src_u8 = NULL; 65 | bool src_aligned = IS_ALIGNED((u32)src, 64); 66 | 67 | sha_context ctx ATTRIBUTE_ALIGN(32) = {0}; 68 | u8 hash[SHA1_HASH_SIZE] ATTRIBUTE_ALIGN(32) = {0}; 69 | 70 | /* Handle data alignment (if needed). */ 71 | if (!src_aligned) 72 | { 73 | u8 *tmp = utilsAllocateMemory(size); 74 | if (!tmp) 75 | { 76 | ERROR_MSG("Failed to allocate memory for aligned 0x%X-byte long buffer!", size); 77 | goto end; 78 | } 79 | 80 | memcpy(tmp, src, size); 81 | 82 | src_u8 = tmp; 83 | } else { 84 | src_u8 = (u8*)src; 85 | } 86 | 87 | /* Initialize SHA engine. */ 88 | if (!sha1EngineInitialize()) goto end; 89 | 90 | /* Initialize SHA context. */ 91 | rc = SHA_InitializeContext(&ctx); 92 | if (rc < 0) 93 | { 94 | ERROR_MSG("SHA_InitializeContext() failed! (%d).", rc); 95 | goto end; 96 | } 97 | 98 | /* Calculate SHA checksum. */ 99 | rc = SHA_Calculate(&ctx, src_u8, size, hash); 100 | if (rc < 0) 101 | { 102 | ERROR_MSG("SHA_InitializeContext() failed! (%d).", rc); 103 | goto end; 104 | } 105 | 106 | /* Copy checksum to destination pointer. */ 107 | memcpy(dst, hash, sizeof(hash)); 108 | 109 | /* Update return value. */ 110 | ret = true; 111 | 112 | end: 113 | /* Close SHA engine. */ 114 | sha1EngineClose(); 115 | 116 | /* Free allocated buffer, if needed. */ 117 | if (!src_aligned && src_u8) free(src_u8); 118 | 119 | return ret; 120 | } 121 | 122 | static bool sha1EngineInitialize(void) 123 | { 124 | if (g_sha1EngineInitialized) return true; 125 | 126 | s32 rc = SHA_Init(); 127 | g_sha1EngineInitialized = (rc >= 0); 128 | if (!g_sha1EngineInitialized) ERROR_MSG("SHA_Init() failed! (%d).", rc); 129 | 130 | return g_sha1EngineInitialized; 131 | } 132 | 133 | static void sha1EngineClose(void) 134 | { 135 | if (!g_sha1EngineInitialized) return; 136 | 137 | SHA_Close(); 138 | 139 | g_sha1EngineInitialized = false; 140 | } 141 | -------------------------------------------------------------------------------- /source/sha1.h: -------------------------------------------------------------------------------- 1 | /* 2 | * sha1.h 3 | * 4 | * Copyright (c) 2023-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #ifndef __SHA1_H__ 24 | #define __SHA1_H__ 25 | 26 | #include 27 | 28 | #define SHA1_HASH_SIZE 20 29 | 30 | /// Wrappers for SHA_*() functions within libogc. These make sure the SHA engine is initialized before doing anything. 31 | /// These do not, however, take care of handling I/O alignment. 32 | 33 | bool sha1ContextCreate(sha_context *ctx); 34 | bool sha1ContextUpdate(sha_context *ctx, const void *src, const u32 size); 35 | bool sha1ContextGetHash(sha_context *ctx, const void *src, const u32 size, void *dst); 36 | 37 | /// Simple all-in-one SHA-1 calculator. Handles I/O alignment if needed. 38 | bool sha1CalculateHash(const void *src, const u32 size, void *dst); 39 | 40 | #endif /* __SHA1_H__ */ 41 | -------------------------------------------------------------------------------- /source/u8.c: -------------------------------------------------------------------------------- 1 | /* 2 | * u8.c 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "utils.h" 22 | #include "u8.h" 23 | 24 | #define U8_FILE_ALIGNMENT 0x20 25 | 26 | static U8Node *u8GetChildNodeByName(U8Context *ctx, U8Node *dir_node, u32 *node_idx, const char *name, u8 type); 27 | 28 | bool u8ContextInit(void *buf, u32 buf_size, U8Context *ctx) 29 | { 30 | if (!buf || buf_size <= (u32)sizeof(U8Header) || !ctx) 31 | { 32 | ERROR_MSG("Invalid parameters!"); 33 | return false; 34 | } 35 | 36 | u8 *u8_buf = (u8*)buf; 37 | U8Header u8_header = {0}; 38 | U8Node root_node = {0}, *nodes = NULL; 39 | u32 node_count = 0, node_section_size = 0, str_table_size = 0; 40 | char *str_table = NULL; 41 | bool success = false; 42 | 43 | /* Read U8 header. */ 44 | memcpy(&u8_header, u8_buf, sizeof(U8Header)); 45 | 46 | /* Check header fields. */ 47 | if (u8_header.magic != U8_MAGIC || u8_header.root_node_offset <= (u32)sizeof(U8Header) || u8_header.node_info_block_size <= (u32)sizeof(U8Node) || \ 48 | u8_header.data_offset != ALIGN_UP(u8_header.root_node_offset + u8_header.node_info_block_size, 0x40) || u8_header.data_offset >= buf_size) 49 | { 50 | ERROR_MSG("Invalid U8 header!"); 51 | return false; 52 | } 53 | 54 | /* Read root U8 node. */ 55 | memcpy(&root_node, u8_buf + u8_header.root_node_offset, sizeof(U8Node)); 56 | 57 | /* Validate root U8 node. */ 58 | if (root_node.type != U8NodeType_Directory || root_node.name_offset != 0 || root_node.data_offset != 0 || root_node.size <= 1) 59 | { 60 | ERROR_MSG("Invalid root U8 node!"); 61 | return false; 62 | } 63 | 64 | /* Calculate node section size. */ 65 | node_count = root_node.size; 66 | node_section_size = (u32)(sizeof(U8Node) * node_count); 67 | if (node_section_size >= u8_header.node_info_block_size) 68 | { 69 | ERROR_MSG("Node section size exceeds node info block size in U8 header!"); 70 | return false; 71 | } 72 | 73 | /* Calculate U8 string table size. */ 74 | str_table_size = (u8_header.node_info_block_size - node_section_size); 75 | if ((node_section_size + str_table_size) != u8_header.node_info_block_size) 76 | { 77 | ERROR_MSG("Node info block size in U8 header doesn't match calculated node section and string table sizes!"); 78 | return false; 79 | } 80 | 81 | /* Allocate memory for the U8 nodes. */ 82 | nodes = (U8Node*)utilsAllocateMemory(node_count * sizeof(U8Node)); 83 | if (!nodes) 84 | { 85 | ERROR_MSG("Error allocating memory for U8 nodes!"); 86 | return false; 87 | } 88 | 89 | /* Read all U8 nodes. */ 90 | memcpy(nodes, u8_buf + u8_header.root_node_offset, node_count * sizeof(U8Node)); 91 | 92 | /* Allocate memory for the U8 string table. */ 93 | str_table = (char*)utilsAllocateMemory(str_table_size * sizeof(char)); 94 | if (!str_table) 95 | { 96 | ERROR_MSG("Error allocating memory for U8 string table!"); 97 | goto out; 98 | } 99 | 100 | /* Read U8 string table. */ 101 | memcpy(str_table, u8_buf + u8_header.root_node_offset + (node_count * sizeof(U8Node)), str_table_size); 102 | 103 | /* Check all U8 nodes. */ 104 | for(u32 i = 1; i < node_count; i++) 105 | { 106 | U8Node *cur_node = &(nodes[i]); 107 | u32 node_number = (i + 1); 108 | 109 | /* Check node type. */ 110 | if (cur_node->type != U8NodeType_File && cur_node->type != U8NodeType_Directory) 111 | { 112 | ERROR_MSG("Invalid entry type for U8 node #%u! (0x%X).", node_number, cur_node->type); 113 | goto out; 114 | } 115 | 116 | /* Check name offset. */ 117 | if (cur_node->name_offset >= str_table_size) 118 | { 119 | ERROR_MSG("Name offset for U8 node #%u exceeds string table size!", node_number); 120 | goto out; 121 | } 122 | 123 | /* Check name. */ 124 | if (!*(str_table + cur_node->name_offset)) 125 | { 126 | ERROR_MSG("Empty name for U8 node #%u!", node_number); 127 | goto out; 128 | } 129 | 130 | /* Check data offset. */ 131 | /* Files: check if the data offset is lower than the data offset from the U8 header, or greater than our buffer size. */ 132 | /* Directories: check if the data offset is equal to or greater than the node count. */ 133 | 134 | /* Note: don't check if the node pointed to by the data offset field in directory nodes actually *is* a directory node. */ 135 | /* Some custom tools don't set proper data offset values for directory nodes. */ 136 | if ((cur_node->type == U8NodeType_File && (cur_node->data_offset < u8_header.data_offset || cur_node->data_offset >= buf_size)) || \ 137 | (cur_node->type == U8NodeType_Directory && cur_node->data_offset >= node_count)) 138 | { 139 | ERROR_MSG("Invalid data offset for U8 node #%u! (0x%X).", node_number, cur_node->data_offset); 140 | goto out; 141 | } 142 | 143 | /* Check size. */ 144 | /* Files: check if the size doesn't exceed our buffer size. */ 145 | /* Directories: check if size value points to a node number *lower* than this directory's node number, or if it exceeds the total node count. */ 146 | 147 | /* Note: we could be dealing with an empty directory, so don't check if the size value is equal to this directory's node number. */ 148 | if ((cur_node->type == U8NodeType_File && (cur_node->data_offset + cur_node->size) > buf_size) || \ 149 | (cur_node->type == U8NodeType_Directory && (cur_node->size < node_number || cur_node->size > node_count))) 150 | { 151 | ERROR_MSG("Invalid size for U8 node #%u! (0x%X).", node_number, cur_node->size); 152 | goto out; 153 | } 154 | } 155 | 156 | /* Update output context. */ 157 | ctx->u8_buf = u8_buf; 158 | memcpy(&(ctx->u8_header), &u8_header, sizeof(U8Header)); 159 | ctx->node_count = node_count; 160 | ctx->nodes = nodes; 161 | ctx->str_table = str_table; 162 | 163 | success = true; 164 | 165 | out: 166 | if (!success) 167 | { 168 | if (str_table) free(str_table); 169 | if (nodes) free(nodes); 170 | } 171 | 172 | return success; 173 | } 174 | 175 | void u8ContextFree(U8Context *ctx) 176 | { 177 | if (!ctx) return; 178 | if (ctx->nodes) free(ctx->nodes); 179 | if (ctx->str_table) free(ctx->str_table); 180 | memset(ctx, 0, sizeof(U8Context)); 181 | } 182 | 183 | U8Node *u8GetDirectoryNodeByPath(U8Context *ctx, const char *path, u32 *out_node_idx) 184 | { 185 | u32 path_len = 0; 186 | char *path_dup = NULL, *pch = NULL; 187 | U8Node *dir_node = NULL; 188 | u32 node_idx = 0; 189 | 190 | if (!ctx || !ctx->str_table || !path || *path != '/' || !(path_len = strlen(path)) || !(dir_node = u8GetNodeByOffset(ctx, 0)) || !out_node_idx) 191 | { 192 | ERROR_MSG("Invalid parameters!"); 193 | return NULL; 194 | } 195 | 196 | /* Check if the root directory was requested. */ 197 | if (path_len == 1) 198 | { 199 | if (out_node_idx) *out_node_idx = 0; 200 | return dir_node; 201 | } 202 | 203 | /* Duplicate path to avoid problems with strtok(). */ 204 | if (!(path_dup = strdup(path))) 205 | { 206 | ERROR_MSG("Unable to duplicate input path!"); 207 | return NULL; 208 | } 209 | 210 | pch = strtok(path_dup, "/"); 211 | if (!pch) 212 | { 213 | ERROR_MSG("Failed to tokenize input path!"); 214 | dir_node = NULL; 215 | goto out; 216 | } 217 | 218 | while(pch) 219 | { 220 | if (!(dir_node = u8GetChildNodeByName(ctx, dir_node, &node_idx, pch, U8NodeType_Directory))) 221 | { 222 | ERROR_MSG("Failed to retrieve directory node by name!"); 223 | goto out; 224 | } 225 | 226 | pch = strtok(NULL, "/"); 227 | } 228 | 229 | *out_node_idx = node_idx; 230 | 231 | out: 232 | if (path_dup) free(path_dup); 233 | 234 | return dir_node; 235 | } 236 | 237 | U8Node *u8GetFileNodeByPath(U8Context *ctx, const char *path, u32 *out_node_idx) 238 | { 239 | u32 path_len = 0; 240 | char *path_dup = NULL, *filename = NULL; 241 | U8Node *dir_node = NULL, *file_node = NULL; 242 | u32 node_idx = 0; 243 | 244 | if (!ctx || !ctx->str_table || !path || *path != '/' || (path_len = strlen(path)) <= 1 || !out_node_idx) 245 | { 246 | ERROR_MSG("Invalid parameters!"); 247 | return NULL; 248 | } 249 | 250 | /* Duplicate path. */ 251 | if (!(path_dup = strdup(path))) 252 | { 253 | ERROR_MSG("Unable to duplicate input path!"); 254 | return NULL; 255 | } 256 | 257 | /* Remove any trailing slashes. */ 258 | while(path_dup[path_len - 1] == '/') 259 | { 260 | path_dup[path_len - 1] = '\0'; 261 | path_len--; 262 | } 263 | 264 | /* Safety check. */ 265 | if (!path_len || !(filename = strrchr(path_dup, '/'))) 266 | { 267 | ERROR_MSG("Invalid input path!"); 268 | goto out; 269 | } 270 | 271 | /* Remove leading slash and adjust filename string pointer. */ 272 | *filename++ = '\0'; 273 | 274 | /* Retrieve directory node. */ 275 | /* If the first character is NULL, then just retrieve the root directory node. */ 276 | if (!(dir_node = (*path_dup ? u8GetDirectoryNodeByPath(ctx, path_dup, &node_idx) : u8GetNodeByOffset(ctx, 0)))) 277 | { 278 | ERROR_MSG("Failed to retrieve directory node!"); 279 | goto out; 280 | } 281 | 282 | /* Retrieve file node. */ 283 | if (!(file_node = u8GetChildNodeByName(ctx, dir_node, &node_idx, filename, U8NodeType_File))) 284 | { 285 | ERROR_MSG("Failed to retrieve file node by name!"); 286 | goto out; 287 | } 288 | 289 | *out_node_idx = node_idx; 290 | 291 | out: 292 | if (path_dup) free(path_dup); 293 | 294 | return file_node; 295 | } 296 | 297 | u8 *u8LoadFileData(U8Context *ctx, u32 file_node_idx, u32 *out_size) 298 | { 299 | if (!ctx || !ctx->u8_buf || !ctx->u8_header.data_offset || !ctx->nodes || file_node_idx >= ctx->node_count || !out_size) 300 | { 301 | ERROR_MSG("Invalid parameters!"); 302 | return NULL; 303 | } 304 | 305 | /* Get U8 file node. */ 306 | U8Node *file_node = &(ctx->nodes[file_node_idx]); 307 | if (file_node->type != U8NodeType_File || !file_node->size) 308 | { 309 | ERROR_MSG("Invalid U8 file node!"); 310 | return NULL; 311 | } 312 | 313 | /* Allocate memory for the file buffer. */ 314 | u8 *buf = (u8*)utilsAllocateMemory(file_node->size); 315 | if (!buf) 316 | { 317 | ERROR_MSG("Error allocating memory for file buffer!"); 318 | return NULL; 319 | } 320 | 321 | /* Read file data. */ 322 | memcpy(buf, ctx->u8_buf + file_node->data_offset, file_node->size); 323 | *out_size = file_node->size; 324 | 325 | return buf; 326 | } 327 | 328 | bool u8SaveFileData(U8Context *ctx, u32 file_node_idx, void *buf, u32 size) 329 | { 330 | u8 *buf_u8 = NULL; 331 | 332 | if (!ctx || !ctx->u8_buf || !ctx->u8_header.data_offset || !ctx->nodes || file_node_idx >= ctx->node_count || \ 333 | !(buf_u8 = (u8*)buf) || !size) 334 | { 335 | ERROR_MSG("Invalid parameters!"); 336 | return false; 337 | } 338 | 339 | /* Get U8 file node. */ 340 | U8Node *file_node = &(ctx->nodes[file_node_idx]); 341 | if (file_node->type != U8NodeType_File || !file_node->size) 342 | { 343 | ERROR_MSG("Invalid U8 file node!"); 344 | return false; 345 | } 346 | 347 | /* Validate provided file size. */ 348 | if (size > file_node->size) 349 | { 350 | ERROR_MSG("Provided file size exceeds U8 file node data size!"); 351 | return false; 352 | } 353 | 354 | /* Save file data. */ 355 | memcpy(ctx->u8_buf + file_node->data_offset, buf_u8, size); 356 | 357 | /* Update U8 entry file size, if needed. */ 358 | /* Don't forget to flush the modified U8 node to our parent buffer. */ 359 | if (size < file_node->size) 360 | { 361 | memset(ctx->u8_buf + file_node->data_offset + size, 0, file_node->size - size); 362 | file_node->size = size; 363 | memcpy(ctx->u8_buf + ctx->u8_header.root_node_offset + (sizeof(U8Node) * file_node_idx), file_node, sizeof(U8Node)); 364 | } 365 | 366 | return true; 367 | } 368 | 369 | static U8Node *u8GetChildNodeByName(U8Context *ctx, U8Node *dir_node, u32 *node_idx, const char *name, u8 type) 370 | { 371 | if (!ctx || !ctx->nodes || !ctx->str_table || !dir_node || dir_node->type != U8NodeType_Directory || !node_idx || *node_idx >= ctx->node_count || (*node_idx + 1) >= dir_node->size || \ 372 | !name || !*name || (type != U8NodeType_File && type != U8NodeType_Directory)) return NULL; 373 | 374 | for(u32 i = (*node_idx + 1); i < dir_node->size; i++) 375 | { 376 | U8Node *cur_node = &(ctx->nodes[i]); 377 | if (cur_node->type == type && !strcmp(ctx->str_table + cur_node->name_offset, name)) 378 | { 379 | *node_idx = i; 380 | return cur_node; 381 | } 382 | } 383 | 384 | return NULL; 385 | } 386 | -------------------------------------------------------------------------------- /source/u8.h: -------------------------------------------------------------------------------- 1 | /* 2 | * u8.h 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #ifndef __U8_H__ 24 | #define __U8_H__ 25 | 26 | #define U8_MAGIC (u32)0x55AA382D /* "U.8-". */ 27 | 28 | typedef struct { 29 | u32 magic; ///< U8_MAGIC. 30 | u32 root_node_offset; ///< Root node offset, relative to the start of this header. 31 | u32 node_info_block_size; ///< Node table size + string table size, starting from the root node offset. 32 | u32 data_offset; ///< Root node offset + node info block size, aligned to 0x40. Relative to the start of this header. 33 | } U8Header; 34 | 35 | SIZE_ASSERT(U8Header, 0x10); 36 | 37 | typedef enum { 38 | U8NodeType_File = 0, 39 | U8NodeType_Directory = 1 40 | } U8NodeType; 41 | 42 | typedef struct { 43 | struct { 44 | u32 type : 8; ///< U8NodeType. 45 | u32 name_offset : 24; ///< Offset to node name. Relative to the start of the string table. 46 | }; 47 | u32 data_offset; ///< Files: offset to file data (relative to the start of the U8 header). Directories: parent dir node index (0-based). 48 | u32 size; ///< Files: data size. Directories: node number from the last file inside this directory (root node is number 1). 49 | } U8Node; 50 | 51 | SIZE_ASSERT(U8Node, 0xC); 52 | 53 | typedef struct { 54 | u8 *u8_buf; 55 | U8Header u8_header; 56 | u32 node_count; 57 | U8Node *nodes; 58 | char *str_table; 59 | } U8Context; 60 | 61 | /// Initializes a U8 context. 62 | bool u8ContextInit(void *buf, u32 buf_size, U8Context *ctx); 63 | 64 | /// Frees a U8 context. 65 | void u8ContextFree(U8Context *ctx); 66 | 67 | /// Retrieves a U8 directory node by its path. 68 | /// Its index is saved to the out_node_idx pointer. 69 | U8Node *u8GetDirectoryNodeByPath(U8Context *ctx, const char *path, u32 *out_node_idx); 70 | 71 | /// Retrieves a U8 file node by its path. 72 | /// Its index is saved to the out_node_idx pointer. 73 | U8Node *u8GetFileNodeByPath(U8Context *ctx, const char *path, u32 *out_node_idx); 74 | 75 | /// Loads file data from a U8 file node into memory. 76 | /// The returned pointer must be freed by the user. 77 | u8 *u8LoadFileData(U8Context *ctx, u32 file_node_idx, u32 *out_size); 78 | 79 | /// Saves file data into a U8 archive loaded into memory. 80 | bool u8SaveFileData(U8Context *ctx, u32 file_node_idx, void *buf, u32 size); 81 | 82 | /// Retrieves a U8 node by its offset. 83 | ALWAYS_INLINE U8Node *u8GetNodeByOffset(U8Context *ctx, u32 offset) 84 | { 85 | u32 node_idx = 0; 86 | if (!ctx || !ctx->nodes || !IS_ALIGNED(offset, sizeof(U8Node)) || (node_idx = (u32)(offset / sizeof(U8Node))) >= ctx->node_count) return NULL; 87 | return &(ctx->nodes[node_idx]); 88 | } 89 | 90 | #endif /* __U8_H__ */ 91 | -------------------------------------------------------------------------------- /source/utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | * utils.c 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | #include "utils.h" 25 | 26 | #define BC_NAND_TID TITLE_ID(1, 0x200) 27 | 28 | /* Global variables. */ 29 | 30 | static void *g_xfb = NULL; 31 | static GXRModeObj *g_rmode = NULL; 32 | 33 | static u64 g_tmdTitleId ATTRIBUTE_ALIGN(32) = 0; 34 | static u32 g_tmdSize ATTRIBUTE_ALIGN(32) = 0; 35 | 36 | static s32 g_isfsFd ATTRIBUTE_ALIGN(32) = 0; 37 | static char g_isfsFilePath[ISFS_MAXPATH] ATTRIBUTE_ALIGN(32) = {0}; 38 | static fstats g_isfsFileStats ATTRIBUTE_ALIGN(32) = {0}; 39 | 40 | #ifdef BACKUP_U8_ARCHIVE 41 | static bool g_sdCardMounted = false; 42 | #endif /* BACKUP_U8_ARCHIVE */ 43 | 44 | /* Function prototypes. */ 45 | 46 | static u32 utilsButtonsDownAll(void); 47 | static u32 utilsButtonsHeldAll(void); 48 | 49 | void *utilsAllocateMemory(size_t size) 50 | { 51 | void *ptr = NULL; 52 | size_t aligned_size = ALIGN_UP(size, 64); 53 | 54 | ptr = memalign(64, aligned_size); 55 | if (ptr) memset(ptr, 0, aligned_size); 56 | 57 | return ptr; 58 | } 59 | 60 | __attribute__((format(printf, 2, 3))) void utilsPrintErrorMessage(const char *func_name, const char *fmt, ...) 61 | { 62 | va_list args; 63 | 64 | printf("%s: ", func_name); 65 | 66 | va_start(args, fmt); 67 | vprintf(fmt, args); 68 | va_end(args); 69 | 70 | printf("\n"); 71 | } 72 | 73 | bool utilsIsWiiU(void) 74 | { 75 | s32 ret = 0; 76 | u32 x = 0; 77 | 78 | ret = ES_GetTitleContentsCount(BC_NAND_TID, &x); 79 | if (ret < 0 || x == 0) return false; 80 | 81 | return true; 82 | } 83 | 84 | void utilsReboot(void) 85 | { 86 | if (*(u32*)0x80001800) exit(0); 87 | SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0); 88 | } 89 | 90 | void utilsInitPads(void) 91 | { 92 | WPAD_Init(); 93 | WPAD_SetDataFormat(WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR); 94 | } 95 | 96 | u32 utilsGetInput(int type) 97 | { 98 | if (type < UtilsInputType_Down || type > UtilsInputType_Held) return 0; 99 | 100 | VIDEO_WaitVSync(); 101 | 102 | if (WPAD_ScanPads() <= WPAD_ERR_NONE) return 0; 103 | 104 | u32 pressed = (type == UtilsInputType_Down ? utilsButtonsDownAll() : utilsButtonsHeldAll()); 105 | 106 | /* Convert Classic Controller values to WiiMote values. */ 107 | if (pressed & WPAD_CLASSIC_BUTTON_ZR) pressed |= WPAD_BUTTON_PLUS; 108 | if (pressed & WPAD_CLASSIC_BUTTON_ZL) pressed |= WPAD_BUTTON_MINUS; 109 | 110 | if (pressed & WPAD_CLASSIC_BUTTON_PLUS) pressed |= WPAD_BUTTON_PLUS; 111 | if (pressed & WPAD_CLASSIC_BUTTON_MINUS) pressed |= WPAD_BUTTON_MINUS; 112 | 113 | if (pressed & WPAD_CLASSIC_BUTTON_A) pressed |= WPAD_BUTTON_A; 114 | if (pressed & WPAD_CLASSIC_BUTTON_B) pressed |= WPAD_BUTTON_B; 115 | if (pressed & WPAD_CLASSIC_BUTTON_X) pressed |= WPAD_BUTTON_1; 116 | if (pressed & WPAD_CLASSIC_BUTTON_Y) pressed |= WPAD_BUTTON_2; 117 | if (pressed & WPAD_CLASSIC_BUTTON_HOME) pressed |= WPAD_BUTTON_HOME; 118 | 119 | if (pressed & WPAD_CLASSIC_BUTTON_UP) pressed |= WPAD_BUTTON_UP; 120 | if (pressed & WPAD_CLASSIC_BUTTON_DOWN) pressed |= WPAD_BUTTON_DOWN; 121 | if (pressed & WPAD_CLASSIC_BUTTON_LEFT) pressed |= WPAD_BUTTON_LEFT; 122 | if (pressed & WPAD_CLASSIC_BUTTON_RIGHT) pressed |= WPAD_BUTTON_RIGHT; 123 | 124 | /* Keep only the lower u16. */ 125 | pressed &= 0xFFFF; 126 | 127 | return pressed; 128 | } 129 | 130 | void utilsInitConsole(bool vwii) 131 | { 132 | s32 x = 0, y = 0, w = 0, h = 0; 133 | 134 | /* Initialise the video system. */ 135 | VIDEO_Init(); 136 | 137 | /* Obtain the preferred video mode from the system. */ 138 | /* This will correspond to the settings in the Wii menu. */ 139 | g_rmode = VIDEO_GetPreferredMode(NULL); 140 | 141 | /* Set proper aspect ratio. */ 142 | g_rmode->viWidth = 672; 143 | if (vwii) 144 | { 145 | /* Poke DMCU to turn off pillarboxing. */ 146 | write32(0xd8006a0, (CONF_GetAspectRatio() == CONF_ASPECT_16_9 ? 0x30000004 : 0x10000002)); 147 | mask32(0xd8006a8, 0, 2); 148 | } 149 | 150 | /* Set proper origin coordinates according to the video mode used. */ 151 | if (g_rmode == &TVPal576IntDfScale || g_rmode == &TVPal576ProgScale) 152 | { 153 | g_rmode->viXOrigin = ((VI_MAX_WIDTH_PAL - g_rmode->viWidth) / 2); 154 | g_rmode->viYOrigin = ((VI_MAX_HEIGHT_PAL - g_rmode->viHeight) / 2); 155 | } else { 156 | g_rmode->viXOrigin = ((VI_MAX_WIDTH_NTSC - g_rmode->viWidth) / 2); 157 | g_rmode->viYOrigin = ((VI_MAX_HEIGHT_NTSC - g_rmode->viHeight) / 2); 158 | } 159 | 160 | /* Blackout display. */ 161 | VIDEO_SetBlack(true); 162 | 163 | /* Set up the video registers with the chosen mode. */ 164 | VIDEO_Configure(g_rmode); 165 | 166 | /* Flush the video register changes to the hardware. */ 167 | VIDEO_Flush(); 168 | 169 | /* Wait for video setup to complete. */ 170 | VIDEO_WaitVSync(); 171 | 172 | /* Allocate memory for the display in the uncached region. */ 173 | g_xfb = SYS_AllocateFramebuffer(g_rmode); 174 | DCInvalidateRange(g_xfb, VIDEO_GetFrameBufferSize(g_rmode)); 175 | g_xfb = MEM_K0_TO_K1(g_xfb); 176 | 177 | /* Clear the garbage around the edges. */ 178 | VIDEO_ClearFrameBuffer(g_rmode, g_xfb, COLOR_BLACK); 179 | 180 | /* Tell the video hardware where our display memory is. */ 181 | VIDEO_SetNextFramebuffer(g_xfb); 182 | 183 | /* Make the display visible. */ 184 | VIDEO_SetBlack(false); 185 | 186 | /* Flush the video register changes to the hardware. */ 187 | VIDEO_Flush(); 188 | 189 | /* Wait for video setup to complete. */ 190 | for(u8 i = 0; i < 4; i++) VIDEO_WaitVSync(); 191 | 192 | /* Set console parameters. */ 193 | x = 24; 194 | y = 32; 195 | w = (g_rmode->fbWidth - 32); 196 | h = (g_rmode->efbHeight - 48); 197 | 198 | /* Initialize the console - CON_InitEx works after VIDEO_ calls. */ 199 | CON_InitEx(g_rmode, x, y, w, h); 200 | 201 | /* Set foreground color to white and reset all display attributes. */ 202 | printf("\x1b[%u;%um", 37, false); 203 | } 204 | 205 | void utilsPrintHeadline(void) 206 | { 207 | char ios_info[64] = {0}; 208 | s32 rows = 0, cols = 0; 209 | 210 | utilsClearScreen(); 211 | 212 | CON_GetMetrics(&cols, &rows); 213 | 214 | printf(APP_TITLE " v" APP_VERSION " (" GIT_REV ")."); 215 | 216 | sprintf(ios_info, "IOS%d (v%d)", IOS_GetVersion(), IOS_GetRevision()); 217 | printf("\x1b[%d;%dH", 0, cols - strlen(ios_info) - 1); 218 | printf(ios_info); 219 | 220 | printf("\nBuilt on " BUILD_TIMESTAMP ".\n"); 221 | printf("Made by " APP_AUTHOR ".\n\n"); 222 | } 223 | 224 | signed_blob *utilsGetSignedTMDFromTitle(u64 title_id, u32 *out_size) 225 | { 226 | if (!out_size) return NULL; 227 | 228 | s32 ret = 0; 229 | signed_blob *stmd = NULL; 230 | bool success = false; 231 | 232 | g_tmdTitleId = title_id; 233 | 234 | ret = ES_GetStoredTMDSize(g_tmdTitleId, &g_tmdSize); 235 | if (ret < 0) 236 | { 237 | ERROR_MSG("ES_GetStoredTMDSize failed! (%d) (TID %08X-%08X).", ret, TITLE_UPPER(g_tmdTitleId), TITLE_LOWER(g_tmdTitleId)); 238 | return NULL; 239 | } 240 | 241 | stmd = (signed_blob*)utilsAllocateMemory(g_tmdSize); 242 | if (!stmd) 243 | { 244 | ERROR_MSG("Failed to allocate memory for TMD! (TID %08X-%08X).", TITLE_UPPER(g_tmdTitleId), TITLE_LOWER(g_tmdTitleId)); 245 | return NULL; 246 | } 247 | 248 | ret = ES_GetStoredTMD(g_tmdTitleId, stmd, g_tmdSize); 249 | if (ret < 0) 250 | { 251 | ERROR_MSG("ES_GetStoredTMD failed! (%d) (TID %08X-%08X).", ret, TITLE_UPPER(g_tmdTitleId), TITLE_LOWER(g_tmdTitleId)); 252 | goto out; 253 | } 254 | 255 | if (!IS_VALID_SIGNATURE(stmd)) 256 | { 257 | ERROR_MSG("Invalid TMD signature! (TID %08X-%08X).", TITLE_UPPER(g_tmdTitleId), TITLE_LOWER(g_tmdTitleId)); 258 | goto out; 259 | } 260 | 261 | *out_size = g_tmdSize; 262 | success = true; 263 | 264 | out: 265 | if (!success && stmd) 266 | { 267 | free(stmd); 268 | stmd = NULL; 269 | } 270 | 271 | return stmd; 272 | } 273 | 274 | void *utilsReadFileFromIsfs(const char *path, u32 *out_size) 275 | { 276 | if (!path || !*path || !out_size) return NULL; 277 | 278 | s32 ret = 0; 279 | u8 *buf = NULL; 280 | u32 file_size = 0; 281 | bool success = false; 282 | 283 | snprintf(g_isfsFilePath, ISFS_MAXPATH, "%s", path); 284 | 285 | g_isfsFd = ISFS_Open(g_isfsFilePath, ISFS_OPEN_READ); 286 | if (g_isfsFd < 0) 287 | { 288 | ERROR_MSG("ISFS_Open(\"%s\") failed! (%d).", g_isfsFilePath, g_isfsFd); 289 | return NULL; 290 | } 291 | 292 | ret = ISFS_GetFileStats(g_isfsFd, &g_isfsFileStats); 293 | if (ret < 0) 294 | { 295 | ERROR_MSG("ISFS_GetFileStats(\"%s\") failed! (%d).", g_isfsFilePath, ret); 296 | goto out; 297 | } 298 | 299 | file_size = g_isfsFileStats.file_length; 300 | if (!file_size) 301 | { 302 | ERROR_MSG("\"%s\" is empty!", g_isfsFilePath); 303 | goto out; 304 | } 305 | 306 | buf = (u8*)utilsAllocateMemory(file_size); 307 | if (!buf) 308 | { 309 | ERROR_MSG("Failed to allocate memory for \"%s\"!", g_isfsFilePath); 310 | goto out; 311 | } 312 | 313 | ret = ISFS_Read(g_isfsFd, buf, file_size); 314 | if (ret < 0) 315 | { 316 | ERROR_MSG("ISFS_Read(\"%s\") failed! (%d).", g_isfsFilePath, ret); 317 | goto out; 318 | } 319 | 320 | *out_size = file_size; 321 | success = true; 322 | 323 | out: 324 | if (!success && buf) 325 | { 326 | free(buf); 327 | buf = NULL; 328 | } 329 | 330 | ISFS_Close(g_isfsFd); 331 | g_isfsFd = 0; 332 | 333 | return (void*)buf; 334 | } 335 | 336 | bool utilsWriteFileToIsfs(const char *path, void *buf, u32 size) 337 | { 338 | if (!path || !*path || !buf || !size) return false; 339 | 340 | s32 ret = 0; 341 | bool success = false; 342 | 343 | snprintf(g_isfsFilePath, ISFS_MAXPATH, "%s", path); 344 | 345 | g_isfsFd = ISFS_Open(g_isfsFilePath, ISFS_OPEN_WRITE); 346 | if (g_isfsFd < 0) 347 | { 348 | ERROR_MSG("ISFS_Open(\"%s\") failed! (%d).", g_isfsFilePath, g_isfsFd); 349 | return false; 350 | } 351 | 352 | ret = ISFS_Write(g_isfsFd, buf, size); 353 | if (ret < 0) 354 | { 355 | ERROR_MSG("ISFS_Write(\"%s\") failed! (%d).", g_isfsFilePath, ret); 356 | goto out; 357 | } 358 | 359 | success = true; 360 | 361 | out: 362 | ISFS_Close(g_isfsFd); 363 | g_isfsFd = 0; 364 | 365 | return success; 366 | } 367 | 368 | #ifdef BACKUP_U8_ARCHIVE 369 | bool utilsMountSdCard(void) 370 | { 371 | if (g_sdCardMounted) return true; 372 | g_sdCardMounted = fatMountSimple("sd", &__io_wiisd); 373 | return g_sdCardMounted; 374 | } 375 | 376 | void utilsUnmountSdCard(void) 377 | { 378 | if (!g_sdCardMounted) return; 379 | fatUnmount("sd"); 380 | __io_wiisd.shutdown(); 381 | g_sdCardMounted = false; 382 | } 383 | 384 | bool utilsGetFileSystemStatsByPath(const char *path, u64 *out_total, u64 *out_free) 385 | { 386 | char *name_end = NULL, stat_path[32] = {0}; 387 | struct statvfs info = {0}; 388 | int ret = -1; 389 | 390 | if (!path || !*path || !(name_end = strchr(path, ':')) || *(name_end + 1) != '/' || (!out_total && !out_free)) 391 | { 392 | ERROR_MSG("Invalid parameters!"); 393 | return false; 394 | } 395 | 396 | name_end += 2; 397 | sprintf(stat_path, "%.*s", (int)(name_end - path), path); 398 | 399 | if ((ret = statvfs(stat_path, &info)) != 0) 400 | { 401 | ERROR_MSG("statvfs(\"%s\") failed! (%d, %d).", path, ret, errno); 402 | return false; 403 | } 404 | 405 | if (out_total) *out_total = ((u64)info.f_blocks * (u64)info.f_frsize); 406 | if (out_free) *out_free = ((u64)info.f_bfree * (u64)info.f_frsize); 407 | 408 | return true; 409 | } 410 | 411 | void *utilsReadFileFromMountedDevice(const char *path, u32 *out_size) 412 | { 413 | if (!path || !*path || !out_size) return NULL; 414 | 415 | FILE *fd = NULL; 416 | size_t filesize = 0, res = 0; 417 | u8 *buf = NULL; 418 | bool success = false; 419 | 420 | fd = fopen(path, "rb"); 421 | if (!fd) 422 | { 423 | ERROR_MSG("fopen(\"%s\") failed! (%d).", path, errno); 424 | return NULL; 425 | } 426 | 427 | fseek(fd, 0, SEEK_END); 428 | filesize = (u32)ftell(fd); 429 | rewind(fd); 430 | 431 | if (!filesize) 432 | { 433 | ERROR_MSG("\"%s\" is empty!", path); 434 | goto out; 435 | } 436 | 437 | buf = (u8*)utilsAllocateMemory(filesize); 438 | if (!buf) 439 | { 440 | ERROR_MSG("Failed to allocate memory for \"%s\"!", path); 441 | goto out; 442 | } 443 | 444 | res = fread(buf, 1, filesize, fd); 445 | if (res != filesize) 446 | { 447 | ERROR_MSG("fread(\"%s\") failed! (%d). Read 0x%X, expected 0x%X.", path, errno, res, filesize); 448 | goto out; 449 | } 450 | 451 | *out_size = filesize; 452 | success = true; 453 | 454 | out: 455 | if (!success && buf) 456 | { 457 | free(buf); 458 | buf = NULL; 459 | } 460 | 461 | fclose(fd); 462 | 463 | return (void*)buf; 464 | } 465 | 466 | bool utilsWriteFileToMountedDevice(const char *path, const void *buf, u32 size) 467 | { 468 | if (!path || !*path || !buf || !size) return false; 469 | 470 | FILE *fd = NULL; 471 | size_t res = 0; 472 | bool success = false; 473 | u64 free_space = 0; 474 | 475 | if (!utilsGetFileSystemStatsByPath(path, NULL, &free_space)) 476 | { 477 | ERROR_MSG("Failed to retrieve free FS space!"); 478 | return false; 479 | } 480 | 481 | if (free_space < (u64)size) 482 | { 483 | ERROR_MSG("Not enough free space available! Required 0x%X, available 0x%llX.", size, free_space); 484 | return false; 485 | } 486 | 487 | fd = fopen(path, "wb"); 488 | if (!fd) 489 | { 490 | ERROR_MSG("fopen(\"%s\") failed! (%d).", path, errno); 491 | return false; 492 | } 493 | 494 | res = fwrite(buf, 1, size, fd); 495 | if (res != size) 496 | { 497 | ERROR_MSG("fwrite(\"%s\") failed! (%d). Wrote 0x%X, expected 0x%X.", path, errno, res, size); 498 | goto out; 499 | } 500 | 501 | success = true; 502 | 503 | out: 504 | fclose(fd); 505 | 506 | return success; 507 | } 508 | #endif /* BACKUP_U8_ARCHIVE */ 509 | 510 | static u32 utilsButtonsDownAll(void) 511 | { 512 | int chan = 0; 513 | u32 pressed = 0; 514 | 515 | for(chan = WPAD_CHAN_0; chan <= WPAD_CHAN_3; chan++) pressed |= WPAD_ButtonsDown(chan); 516 | 517 | return pressed; 518 | } 519 | 520 | static u32 utilsButtonsHeldAll(void) 521 | { 522 | int chan = 0; 523 | u32 pressed = 0; 524 | 525 | for(chan = WPAD_CHAN_0; chan <= WPAD_CHAN_3; chan++) pressed |= WPAD_ButtonsHeld(chan); 526 | 527 | return pressed; 528 | } 529 | -------------------------------------------------------------------------------- /source/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * utils.h 3 | * 4 | * Copyright (c) 2020-2024, DarkMatterCore . 5 | * 6 | * This file is part of ww-43db-patcher (https://github.com/DarkMatterCore/ww-43db-patcher). 7 | * 8 | * ww-43db-patcher is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, version 2.0. 11 | * 12 | * ww-43db-patcher is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #ifndef __UTILS_H__ 24 | #define __UTILS_H__ 25 | 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 | 39 | /* These macros control the behaviour of aspect ratio database patching. */ 40 | #define BACKUP_U8_ARCHIVE 41 | //#define DISPLAY_ARDB_ENTRIES 42 | 43 | #define ERROR_MSG(...) utilsPrintErrorMessage(__func__, __VA_ARGS__) 44 | 45 | #define MEMBER_SIZE(type, member) sizeof(((type*)NULL)->member) 46 | 47 | #define MAX_ELEMENTS(x) ((sizeof((x))) / (sizeof((x)[0]))) 48 | 49 | #define ALIGN_DOWN(x, y) ((x) & ~((y) - 1)) 50 | #define ALIGN_UP(x, y) ((((y) - 1) + (x)) & ~((y) - 1)) 51 | #define IS_ALIGNED(x, y) (((x) & ((y) - 1)) == 0) 52 | 53 | #define TITLE_UPPER(x) ((u32)((x) >> 32)) 54 | #define TITLE_LOWER(x) ((u32)(x)) 55 | #define TITLE_ID(x, y) (((u64)(x) << 32) | (y)) 56 | 57 | #define SYSTEM_MENU_TID TITLE_ID(1, 2) 58 | 59 | /// Flags a function as (always) inline. 60 | #ifndef ALWAYS_INLINE 61 | #define ALWAYS_INLINE __attribute__((always_inline)) static inline 62 | #endif 63 | 64 | #define SIZE_ASSERT(name, size) static_assert(sizeof(name) == (size), "Bad size for " #name "! Expected " #size ".") 65 | 66 | typedef enum { 67 | UtilsInputType_Down = 0, 68 | UtilsInputType_Held = 1 69 | } UtilsInputType; 70 | 71 | void *utilsAllocateMemory(size_t size); 72 | 73 | __attribute__((format(printf, 2, 3))) void utilsPrintErrorMessage(const char *func_name, const char *fmt, ...); 74 | 75 | bool utilsIsWiiU(void); 76 | 77 | void utilsReboot(void); 78 | 79 | void utilsInitPads(void); 80 | u32 utilsGetInput(int type); 81 | 82 | ALWAYS_INLINE void utilsWaitForButtonPress(void) 83 | { 84 | while(true) 85 | { 86 | if (utilsGetInput(UtilsInputType_Down) != 0) break; 87 | } 88 | } 89 | 90 | ALWAYS_INLINE void utilsClearScreen(void) 91 | { 92 | printf("\x1b[2J"); 93 | } 94 | 95 | void utilsInitConsole(bool vwii); 96 | void utilsPrintHeadline(void); 97 | 98 | signed_blob *utilsGetSignedTMDFromTitle(u64 title_id, u32 *out_size); 99 | 100 | ALWAYS_INLINE tmd *utilsGetTMDFromSignedBlob(signed_blob *stmd) 101 | { 102 | if (!stmd || !IS_VALID_SIGNATURE(stmd)) return NULL; 103 | return (tmd*)((u8*)stmd + SIGNATURE_SIZE(stmd)); 104 | } 105 | 106 | /* Hint: ISFS means "Internal Storage File System". */ 107 | void *utilsReadFileFromIsfs(const char *path, u32 *out_size); 108 | bool utilsWriteFileToIsfs(const char *path, void *buf, u32 size); 109 | 110 | #ifdef BACKUP_U8_ARCHIVE 111 | bool utilsMountSdCard(void); 112 | void utilsUnmountSdCard(void); 113 | 114 | bool utilsGetFileSystemStatsByPath(const char *path, u64 *out_total, u64 *out_free); 115 | 116 | void *utilsReadFileFromMountedDevice(const char *path, u32 *out_size); 117 | bool utilsWriteFileToMountedDevice(const char *path, const void *buf, u32 size); 118 | #endif /* BACKUP_U8_ARCHIVE */ 119 | 120 | #endif /* __UTILS_H__ */ 121 | --------------------------------------------------------------------------------