Compare commits

...

75 Commits

Author SHA1 Message Date
Maschell
3ac4d19ad7 Update Dockerfile 2024-05-06 10:29:35 +02:00
Maschell
e9d8f970b2 Bump softprops/action-gh-release@v2 from 1 to 2 2024-05-06 10:29:35 +02:00
Maschell
6c05c4dbdc Bump version to 0.2.3 2024-04-24 19:08:04 +02:00
Maschell
df287468a1 Update Dockerfile 2024-04-24 19:08:04 +02:00
Maschell
52192d0cb4 Update .gitignore to ignore all files with .zip extension 2024-04-24 19:08:04 +02:00
Maschell
8de9c37137 Fix some jumps to original functions by placing the replaced intruction after setting CTR 2024-04-24 19:08:04 +02:00
dependabot[bot]
597788ff96 Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-04 22:48:19 +02:00
Maschell
e4dc696c34 Create dependabot.yml 2023-07-23 10:21:31 +02:00
Maschell
0169ae441a Bump version 2023-07-19 18:36:06 +02:00
Maschell
1c293a5e24 Update Dockerfile 2023-07-19 16:19:19 +02:00
Maschell
865d6c58c1 Update Dockerfile 2023-07-06 15:50:11 +02:00
Maschell
0d0c819f11 Update Dockerfile, fix compiling with wut 1.3.0 2023-04-23 11:39:12 +02:00
Maschell
b2b8ff2083 Change default branch to main 2023-03-28 20:38:50 +02:00
Maschell
214369da29 Bump Version 2023-03-28 20:22:29 +02:00
Maschell
fa3292fa28 memset the memory to 0 before freeing 2023-03-26 15:49:04 +02:00
Maschell
54d0f80426 Change docker registry to ghcr.io 2023-03-18 14:31:59 +01:00
Maschell
35f2c495cc Bump version to 0.2 2023-01-10 18:05:29 +01:00
Maschell
1c7a6ac333 Add support for function patcher struct version 3 2023-01-07 23:55:23 +01:00
Maschell
f6cc151506 Fix typo in ci.yml 2023-01-07 23:55:23 +01:00
Maschell
c074ca4892 Use WUMS 0.3.2 2023-01-07 23:55:23 +01:00
Maschell
1d13bc62e5 Remove unused variable from the ci.yml 2023-01-07 23:55:23 +01:00
Maschell
9485cc7e15 Rename toRemoved to toBeRemoved 2023-01-06 14:31:14 +01:00
Maschell
ecc109af50 Only try to restore a function if it's actually patched 2023-01-06 14:31:14 +01:00
Maschell
5adf6c3688 Implement v2 of the FunctionPatcherModule API 2023-01-06 14:31:14 +01:00
Maschell
1e2457b266 PatchedFunctionData. Actually return on error instead of allocating even more memory 2023-01-06 14:31:14 +01:00
Maschell
b1320f0c8d Improve logging 2023-01-06 14:31:14 +01:00
Maschell
fa815f17c0 Update the CI to use a non-deprecated release action 2023-01-06 14:31:14 +01:00
Maschell
8d853d6320 Simplify reading the existing instruction when patching a function 2023-01-06 14:31:14 +01:00
Maschell
e85d383ec4 Log the module version on each application start 2023-01-04 22:40:13 +01:00
Maschell
7d67184cfd Improve commit messages for nightly releases 2023-01-04 22:40:13 +01:00
Maschell
ac0c341eb4 Reset the cached function handle if RPL has been unloaded 2023-01-02 17:06:07 +01:00
Maschell
e51e6a9509 Reset function patch state if a RPL has been unloaded. 2023-01-02 17:06:07 +01:00
Maschell
d3a65723bc Update Makefile to be compatible with CLion 2023-01-02 17:06:07 +01:00
Maschell
663e3e513d Update CI files to use actions/checkout@v3 2023-01-02 15:44:27 +01:00
Maschell
7703eac375 Fix restoring "dynamic" functions. Instead of predicting an unload of a RPL we now check if the replaced instruction has been changed. 2023-01-02 15:44:27 +01:00
Maschell
182c6d2f92 Check if the function is already patched before updating the addresses 2023-01-02 15:44:27 +01:00
Maschell
f94b857f12 Use std::list instead of array 2023-01-02 15:44:27 +01:00
Maschell
c719b4c8ac Remove call of OSDynLoad_Release for handles that have not been acquired 2023-01-02 15:44:27 +01:00
Maschell
9ad95fe6a8 Use ubuntu-22.04 in CI 2022-09-04 18:14:09 +02:00
Maschell
eec6ba5610 Update Dockerfile 2022-09-04 18:14:09 +02:00
Maschell
777eda1b19 Add LICENSE 2022-09-04 18:14:09 +02:00
Maschell
ced1e27b53 Fix patching dynamic function in WUMS_INITIALIZE hooks 2022-08-21 22:47:37 +02:00
Maschell
5b87a89650 Update Dockerfile to use latest wut 2022-08-06 22:44:59 +02:00
Maschell
1a33517f0e Fix patching of functions that only consist of one branch instruction outside of nn::acp 2022-08-06 22:44:59 +02:00
Maschell
874e5d9923 Fix function patching for functions with an effective address between 0x20000000 - 0x3FFFFFFC 2022-08-06 22:44:59 +02:00
Maschell
d602d17034 Update the malloc/free pointers used for threads to fix apps which use a custom heap 2022-07-28 02:44:13 -07:00
Maschell
4569e407ae Update Dockerfile to use latest wut version 2022-07-25 13:14:32 -07:00
Maschell
343e8da82d Update Dockerfile to use latest WUMS version 2022-05-13 00:29:53 +02:00
Maschell
f37216db4e Add logging instructions to the README 2022-05-08 19:26:06 +02:00
Maschell
f95f00e6f2 Rewrite of Function Patcher to match libfunctionpatcher 2022-05-08 19:26:06 +02:00
Maschell
a6eb4eeb88 Check all logging macros in the PR pipeline 2022-05-08 19:26:06 +02:00
Maschell
e0f745f0c9 Improve logging to include module name 2022-05-08 19:26:06 +02:00
Maschell
ec285320d8 Add release badge to README 2022-02-03 20:57:25 +01:00
Maschell
a8b4f7188b Format the code via clang-format 2022-02-03 20:57:25 +01:00
Maschell
2e5e3d1d2f Fix dynamic_function detection 2022-01-31 16:12:51 +01:00
Maschell
fc3eea16fb Change the layout of the release .zip 2022-01-30 16:56:52 +01:00
Maschell
96f8410612 Fix building with make DEBUG=1 2022-01-30 13:36:47 +01:00
Maschell
2db7befb4b Move logging logic into a seperate file 2022-01-24 18:52:59 +01:00
Maschell
ffd4c4f894 Only declare variables when needed 2022-01-24 18:49:31 +01:00
Maschell
c9c0aeaa2b WUMS 0.3.1 support 2022-01-24 18:48:11 +01:00
Maschell
0678949900 Remove WUMS_MODULE_INIT_BEFORE_RELOCATION_DONE_HOOK 2022-01-24 18:46:22 +01:00
Maschell
925aa353bd Avoid using the "new" operator to reduce the filesize 2022-01-12 23:07:39 +01:00
Maschell
f5f9c5f8ff Only do logging when built with make DEBUG=1 2022-01-12 23:07:09 +01:00
Maschell
37259a10d8 Fix make clean 2022-01-12 23:06:34 +01:00
Maschell
77b805a592 [CI] Fix the content_type of the release_assets 2022-01-12 23:06:20 +01:00
Maschell
5fac45e1c6 Update Dockerfile to use WUMS 0.3 2021-12-07 20:15:45 +01:00
Maschell
120f7f9943 Update Dockerfile 2021-09-24 16:47:20 +02:00
Maschell
4553a06f9b Formatting and cleanup 2021-09-24 14:49:20 +02:00
Maschell
551144ddbd Do an OSFatal if the getting the PA from EA fails 2021-09-23 23:05:15 +02:00
Maschell
dd3709ad48 Fix PA fallback calcuation 2021-09-23 23:03:48 +02:00
Maschell
38b58faf88 Reenable logging, Update Dockerfile to use WUMS 0.2 2021-09-17 18:27:12 +02:00
Maschell
ee76aba48e Compile with latest wut 2021-04-17 12:13:22 +02:00
Maschell
e92f79b976 Compile using the latest WUMS version 2021-03-13 14:03:19 +01:00
Maschell
57a932888a Reduce the amount of logged messages 2021-03-13 14:03:07 +01:00
Maschell
c8df49e85c Use WUMS_MODULE_SKIP_WUT_INIT 2021-02-19 17:10:17 +01:00
30 changed files with 2372 additions and 510 deletions

67
.clang-format Normal file
View File

@ -0,0 +1,67 @@
# Generated from CLion C/C++ Code Style settings
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: Consecutive
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignOperands: Align
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Always
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterReturnType: None
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: true
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
ColumnLimit: 0
CompactNamespaces: false
ContinuationIndentWidth: 8
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PointerAlignment: Right
ReflowComments: false
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Never

10
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"

View File

@ -3,13 +3,28 @@ name: CI-Release
on: on:
push: push:
branches: branches:
- master - main
jobs: jobs:
build-binary: clang-format:
runs-on: ubuntu-18.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./source
build-binary:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v4
- name: create version.h
run: |
git_hash=$(git rev-parse --short "$GITHUB_SHA")
cat <<EOF > ./source/version.h
#pragma once
#define MODULE_VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary - name: build binary
run: | run: |
docker build . -t builder docker build . -t builder
@ -20,7 +35,7 @@ jobs:
path: "*.wms" path: "*.wms"
deploy-binary: deploy-binary:
needs: build-binary needs: build-binary
runs-on: ubuntu-18.04 runs-on: ubuntu-22.04
steps: steps:
- name: Get environment variables - name: Get environment variables
id: get_repository_name id: get_repository_name
@ -30,29 +45,15 @@ jobs:
- uses: actions/download-artifact@master - uses: actions/download-artifact@master
with: with:
name: binary name: binary
path: wiiu/modules
- name: zip artifact - name: zip artifact
run: zip -r ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip wiiu run: zip -r ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip *.wms
- name: Create Release - name: Create Release
id: create_release uses: "softprops/action-gh-release@v2"
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }} tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
release_name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
draft: false draft: false
prerelease: true prerelease: true
body: | generate_release_notes: true
Not a stable release: name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
${{ github.event.head_commit.message }} files: |
- name: Upload Release Asset ./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip
asset_name: ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip
asset_content_type: application/unknown

View File

@ -3,10 +3,36 @@ name: CI-PR
on: [pull_request] on: [pull_request]
jobs: jobs:
build-binary: clang-format:
runs-on: ubuntu-18.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./source
check-build-with-logging:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v4
- name: build binary with logging
run: |
docker build . -t builder
docker run --rm -v ${PWD}:/project builder make DEBUG=VERBOSE
docker run --rm -v ${PWD}:/project builder make clean
docker run --rm -v ${PWD}:/project builder make DEBUG=1
build-binary:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v4
- name: create version.h
run: |
git_hash=$(git rev-parse --short "${{ github.event.pull_request.head.sha }}")
cat <<EOF > ./source/version.h
#pragma once
#define MODULE_VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary - name: build binary
run: | run: |
docker build . -t builder docker build . -t builder

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ build/
cmake-build-debug/ cmake-build-debug/
CMakeLists.txt CMakeLists.txt
*.wms *.wms
*.zip

View File

@ -1,7 +1,7 @@
FROM wiiuenv/devkitppc:20210101 FROM ghcr.io/wiiu-env/devkitppc:20240505
COPY --from=wiiuenv/libkernel:20210109 /artifacts $DEVKITPRO COPY --from=ghcr.io/wiiu-env/libkernel:20230621 /artifacts $DEVKITPRO
COPY --from=wiiuenv/libfunctionpatcher:20210109 /artifacts $DEVKITPRO COPY --from=ghcr.io/wiiu-env/libfunctionpatcher:20230621 /artifacts $DEVKITPRO
COPY --from=wiiuenv/wiiumodulesystem:20210101 /artifacts $DEVKITPRO COPY --from=ghcr.io/wiiu-env/wiiumodulesystem:20240424 /artifacts $DEVKITPRO
WORKDIR project WORKDIR project

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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
them 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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
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.
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
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
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 3 of the License, or
(at your option) any later version.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program 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.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU 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 Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -21,23 +21,33 @@ WUT_ROOT := $(DEVKITPRO)/wut
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
TARGET := FunctionPatcherModule TARGET := FunctionPatcherModule
BUILD := build BUILD := build
SOURCES := source SOURCES := source source/utils
DATA := data DATA := data
INCLUDES := source INCLUDES := source
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# options for code generation # options for code generation
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
CFLAGS := -g -Wall -O2 -ffunction-sections\ CFLAGS := -Wall -Os -ffunction-sections\
$(MACHDEP) $(MACHDEP)
CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__ CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CXXFLAGS := $(CFLAGS) -std=c++17 CXXFLAGS := $(CFLAGS) -std=c++20 -fno-exceptions -fno-rtti
ASFLAGS := -g $(ARCH) ASFLAGS := -g $(ARCH)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libkernel.ld $(WUMSSPECS) LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libkernel.ld $(WUMSSPECS)
ifeq ($(DEBUG),1)
CXXFLAGS += -DDEBUG -g
CFLAGS += -DDEBUG -g
endif
ifeq ($(DEBUG),VERBOSE)
CXXFLAGS += -DDEBUG -DVERBOSE_DEBUG -g
CFLAGS += -DDEBUG -DVERBOSE_DEBUG -g
endif
LIBS := -lwums -lwut -lkernel LIBS := -lwums -lwut -lkernel
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
@ -98,13 +108,13 @@ export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
all: $(BUILD) all: $(BUILD)
$(BUILD): $(BUILD):
@[ -d $@ ] || mkdir -p $@ @$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD))
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
clean: clean:
@echo clean ... @echo clean ...
@rm -fr $(BUILD) $(TARGET).rpx $(TARGET).elf @rm -fr $(BUILD) $(TARGET).wms $(TARGET).elf
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
else else

View File

@ -1,4 +1,21 @@
Run via [SetupPayload](https://github.com/wiiu-env/SetupPayload). Requires [wut](https://github.com/decaf-emu/wut), [wums](https://github.com/wiiu-env/WiiUModuleSystem), [libkernel](https://github.com/wiiu-env/libkernel) and [libfunctionpatcher](https://github.com/wiiu-env/libfunctionpatcher) for building. [![CI-Release](https://github.com/wiiu-env/FunctionPatcherModule/actions/workflows/ci.yml/badge.svg)](https://github.com/wiiu-env/FunctionPatcherModule/actions/workflows/ci.yml)
## Usage
(`[ENVIRONMENT]` is a placeholder for the actual environment name.)
1. Copy the file `FunctionPatcherModule.wms` into `sd:/wiiu/environments/[ENVIRONMENT]/modules`.
2. Requires the [WUMSLoader](https://github.com/wiiu-env/WUMSLoader) in `sd:/wiiu/environments/[ENVIRONMENT]/modules/setup`.
## Buildflags
### Logging
Building via `make` only logs errors (via OSReport). To enable logging via the [LoggingModule](https://github.com/wiiu-env/LoggingModule) set `DEBUG` to `1` or `VERBOSE`.
`make` Logs errors only (via OSReport).
`make DEBUG=1` Enables information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule).
`make DEBUG=VERBOSE` Enables verbose information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule).
If the [LoggingModule](https://github.com/wiiu-env/LoggingModule) is not present, it'll fallback to UDP (Port 4405) and [CafeOS](https://github.com/wiiu-env/USBSerialLoggingModule) logging.
## Building using the Dockerfile ## Building using the Dockerfile
@ -14,3 +31,7 @@ docker run -it --rm -v ${PWD}:/project functionpatchermodule-builder make
# make clean # make clean
docker run -it --rm -v ${PWD}:/project functionpatchermodule-builder make clean docker run -it --rm -v ${PWD}:/project functionpatchermodule-builder make clean
``` ```
## Format the code via docker
`docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./source -i`

View File

@ -0,0 +1,78 @@
#include "FunctionAddressProvider.h"
#include "utils/logger.h"
#include <coreinit/dynload.h>
#include <function_patcher/fpatching_defines.h>
uint32_t FunctionAddressProvider::getEffectiveAddressOfFunction(function_replacement_library_type_t library, const char *functionName) {
uint32_t real_addr = 0;
OSDynLoad_Module rpl_handle = nullptr;
OSDynLoad_Error err = OS_DYNLOAD_OK;
for (auto &rplHandle : rpl_handles) {
if (rplHandle.library == library) {
if (rplHandle.handle == nullptr) {
DEBUG_FUNCTION_LINE_VERBOSE("Lets check if rpl is loaded: %s", rplHandle.rplname);
err = OSDynLoad_IsModuleLoaded((char *) rplHandle.rplname, &rplHandle.handle);
}
if (err != OS_DYNLOAD_OK || !rplHandle.handle) {
DEBUG_FUNCTION_LINE_VERBOSE("%s is not loaded yet", rplHandle.rplname, err, rplHandle.handle);
return 0;
}
rpl_handle = rplHandle.handle;
break;
}
}
if (!rpl_handle) {
DEBUG_FUNCTION_LINE_ERR("Failed to find the RPL handle for %s", functionName);
return 0;
}
OSDynLoad_FindExport(rpl_handle, OS_DYNLOAD_EXPORT_FUNC, functionName, reinterpret_cast<void **>(&real_addr));
if (!real_addr) {
DEBUG_FUNCTION_LINE_VERBOSE("OSDynLoad_FindExport failed for %s", functionName);
return 0;
}
uint32_t realAddrData = *((volatile uint32_t *) real_addr);
if ((realAddrData & 0xFC000003) == 0x48000000) {
auto address_diff = (uint32_t) (realAddrData & 0x01FFFFFC);
if ((realAddrData & 0x02000000) == 0x02000000) {
address_diff = 0xFE000000 + address_diff;
}
real_addr += (int32_t) address_diff;
}
return real_addr;
}
void FunctionAddressProvider::resetHandles() {
for (auto &rplHandle : rpl_handles) {
if (rplHandle.handle != nullptr) {
DEBUG_FUNCTION_LINE_VERBOSE("Resetting handle for rpl: %s", rplHandle.rplname);
}
rplHandle.handle = nullptr;
}
}
function_replacement_library_type_t FunctionAddressProvider::getTypeForHandle(OSDynLoad_Module handle) {
for (auto &rplHandle : rpl_handles) {
if (rplHandle.handle == handle) {
return rplHandle.library;
}
}
return LIBRARY_OTHER;
}
bool FunctionAddressProvider::resetHandle(OSDynLoad_Module handle) {
for (auto &rplHandle : rpl_handles) {
if (rplHandle.handle == handle) {
rplHandle.handle = nullptr;
return true;
}
}
return false;
}

View File

@ -0,0 +1,90 @@
#pragma once
#include <coreinit/dynload.h>
#include <cstdint>
#include <function_patcher/fpatching_defines.h>
#include <list>
typedef struct rpl_handling {
function_replacement_library_type_t library;
const char rplname[15];
OSDynLoad_Module handle;
} rpl_handling;
class FunctionAddressProvider {
public:
uint32_t getEffectiveAddressOfFunction(function_replacement_library_type_t library, const char *functionName);
void resetHandles();
function_replacement_library_type_t getTypeForHandle(OSDynLoad_Module toReset);
bool resetHandle(OSDynLoad_Module handle);
std::list<rpl_handling> rpl_handles = {
{LIBRARY_AVM, "avm.rpl", nullptr},
{LIBRARY_CAMERA, "camera.rpl", nullptr},
{LIBRARY_COREINIT, "coreinit.rpl", nullptr},
{LIBRARY_DC, "dc.rpl", nullptr},
{LIBRARY_DMAE, "dmae.rpl", nullptr},
{LIBRARY_DRMAPP, "drmapp.rpl", nullptr},
{LIBRARY_ERREULA, "erreula.rpl", nullptr},
{LIBRARY_GX2, "gx2.rpl", nullptr},
{LIBRARY_H264, "h264.rpl", nullptr},
{LIBRARY_LZMA920, "lzma920.rpl", nullptr},
{LIBRARY_MIC, "mic.rpl", nullptr},
{LIBRARY_NFC, "nfc.rpl", nullptr},
{LIBRARY_NIO_PROF, "nio_prof.rpl", nullptr},
{LIBRARY_NLIBCURL, "nlibcurl.rpl", nullptr},
{LIBRARY_NLIBNSS, "nlibnss.rpl", nullptr},
{LIBRARY_NLIBNSS2, "nlibnss2.rpl", nullptr},
{LIBRARY_NN_AC, "nn_ac.rpl", nullptr},
{LIBRARY_NN_ACP, "nn_acp.rpl", nullptr},
{LIBRARY_NN_ACT, "nn_act.rpl", nullptr},
{LIBRARY_NN_AOC, "nn_aoc.rpl", nullptr},
{LIBRARY_NN_BOSS, "nn_boss.rpl", nullptr},
{LIBRARY_NN_CCR, "nn_ccr.rpl", nullptr},
{LIBRARY_NN_CMPT, "nn_cmpt.rpl", nullptr},
{LIBRARY_NN_DLP, "nn_dlp.rpl", nullptr},
{LIBRARY_NN_EC, "nn_ec.rpl", nullptr},
{LIBRARY_NN_FP, "nn_fp.rpl", nullptr},
{LIBRARY_NN_HAI, "nn_hai.rpl", nullptr},
{LIBRARY_NN_HPAD, "nn_hpad.rpl", nullptr},
{LIBRARY_NN_IDBE, "nn_idbe.rpl", nullptr},
{LIBRARY_NN_NDM, "nn_ndm.rpl", nullptr},
{LIBRARY_NN_NETS2, "nn_nets2.rpl", nullptr},
{LIBRARY_NN_NFP, "nn_nfp.rpl", nullptr},
{LIBRARY_NN_NIM, "nn_nim.rpl", nullptr},
{LIBRARY_NN_OLV, "nn_olv.rpl", nullptr},
{LIBRARY_NN_PDM, "nn_pdm.rpl", nullptr},
{LIBRARY_NN_SAVE, "nn_save.rpl", nullptr},
{LIBRARY_NN_SL, "nn_sl.rpl", nullptr},
{LIBRARY_NN_SPM, "nn_spm.rpl", nullptr},
{LIBRARY_NN_TEMP, "nn_temp.rpl", nullptr},
{LIBRARY_NN_UDS, "nn_uds.rpl", nullptr},
{LIBRARY_NN_VCTL, "nn_vctl.rpl", nullptr},
{LIBRARY_NSYSCCR, "nsysccr.rpl", nullptr},
{LIBRARY_NSYSHID, "nsyshid.rpl", nullptr},
{LIBRARY_NSYSKBD, "nsyskbd.rpl", nullptr},
{LIBRARY_NSYSNET, "nsysnet.rpl", nullptr},
{LIBRARY_NSYSUHS, "nsysuhs.rpl", nullptr},
{LIBRARY_NSYSUVD, "nsysuvd.rpl", nullptr},
{LIBRARY_NTAG, "ntag.rpl", nullptr},
{LIBRARY_PADSCORE, "padscore.rpl", nullptr},
{LIBRARY_PROC_UI, "proc_ui.rpl", nullptr},
{LIBRARY_SNDCORE2, "sndcore2.rpl", nullptr},
{LIBRARY_SNDUSER2, "snduser2.rpl", nullptr},
{LIBRARY_SND_CORE, "snd_core.rpl", nullptr},
{LIBRARY_SND_USER, "snd_user.rpl", nullptr},
{LIBRARY_SWKBD, "swkbd.rpl", nullptr},
{LIBRARY_SYSAPP, "sysapp.rpl", nullptr},
{LIBRARY_TCL, "tcl.rpl", nullptr},
{LIBRARY_TVE, "tve.rpl", nullptr},
{LIBRARY_UAC, "uac.rpl", nullptr},
{LIBRARY_UAC_RPL, "uac_rpl.rpl", nullptr},
{LIBRARY_USB_MIC, "usb_mic.rpl", nullptr},
{LIBRARY_UVC, "uvc.rpl", nullptr},
{LIBRARY_UVD, "uvd.rpl", nullptr},
{LIBRARY_VPAD, "vpad.rpl", nullptr},
{LIBRARY_VPADBASE, "vpadbase.rpl", nullptr},
{LIBRARY_ZLIB125, "zlib125.rpl", nullptr}};
};

View File

@ -0,0 +1,365 @@
#include "PatchedFunctionData.h"
#include "utils/KernelFindExport.h"
#include "utils/utils.h"
#include <coreinit/mcp.h>
#include <coreinit/title.h>
#include <vector>
std::optional<std::shared_ptr<PatchedFunctionData>> PatchedFunctionData::make_shared_v3(std::shared_ptr<FunctionAddressProvider> functionAddressProvider,
function_replacement_data_v3_t *replacementData,
MEMHeapHandle heapHandle) {
if (!replacementData) {
return {};
}
auto ptr = make_shared_nothrow<PatchedFunctionData>(std::move(functionAddressProvider));
if (!ptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to alloc PatchedFunctionData");
return {};
}
ptr->isPatched = false;
ptr->heapHandle = heapHandle;
ptr->replacementFunctionAddress = replacementData->replaceAddr;
ptr->realCallFunctionAddressPtr = replacementData->replaceCall;
ptr->targetProcess = replacementData->targetProcess;
ptr->type = replacementData->type;
switch (replacementData->type) {
case FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_NAME:
case FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_ADDRESS: {
ptr->library = {};
for (uint32_t i = 0; i < replacementData->ReplaceInRPX.targetTitleIdsCount; i++) {
ptr->titleIds.insert(replacementData->ReplaceInRPX.targetTitleIds[i]);
}
ptr->titleVersionMin = replacementData->ReplaceInRPX.versionMin;
ptr->titleVersionMax = replacementData->ReplaceInRPX.versionMax;
ptr->executableName = replacementData->ReplaceInRPX.executableName;
if (replacementData->type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_ADDRESS) {
ptr->textOffset = replacementData->ReplaceInRPX.textOffset;
} else if (replacementData->type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_NAME) {
ptr->functionName = replacementData->ReplaceInRPX.functionName;
}
break;
}
case FUNCTION_PATCHER_REPLACE_BY_LIB_OR_ADDRESS: {
ptr->library = replacementData->ReplaceInRPL.library;
if (replacementData->ReplaceInRPL.library != LIBRARY_OTHER) {
ptr->functionName = replacementData->ReplaceInRPL.function_name;
} else {
ptr->realEffectiveFunctionAddress = replacementData->virtualAddr;
ptr->realPhysicalFunctionAddress = replacementData->physicalAddr;
}
break;
}
}
if (!ptr->allocateDataForJumps()) {
return {};
}
return ptr;
}
std::optional<std::shared_ptr<PatchedFunctionData>> PatchedFunctionData::make_shared_v2(std::shared_ptr<FunctionAddressProvider> functionAddressProvider,
function_replacement_data_v2_t *replacementData,
MEMHeapHandle heapHandle) {
if (!replacementData) {
return {};
}
auto ptr = make_shared_nothrow<PatchedFunctionData>(std::move(functionAddressProvider));
if (!ptr) {
return {};
}
ptr->type = FUNCTION_PATCHER_REPLACE_BY_LIB_OR_ADDRESS;
ptr->isPatched = false;
ptr->heapHandle = heapHandle;
ptr->library = replacementData->library;
ptr->targetProcess = replacementData->targetProcess;
ptr->replacementFunctionAddress = replacementData->replaceAddr;
ptr->realCallFunctionAddressPtr = replacementData->replaceCall;
if (replacementData->library != LIBRARY_OTHER) {
ptr->functionName = replacementData->function_name;
} else {
ptr->realEffectiveFunctionAddress = replacementData->virtualAddr;
ptr->realPhysicalFunctionAddress = replacementData->physicalAddr;
}
if (!ptr->allocateDataForJumps()) {
return {};
}
return ptr;
}
bool PatchedFunctionData::allocateDataForJumps() {
if (this->jumpData != nullptr && this->jumpToOriginal != nullptr) {
return true;
}
if (this->replacementFunctionAddress > 0x01FFFFFC || this->targetProcess != FP_TARGET_PROCESS_ALL) {
this->jumpDataSize = 15; // We could predict the actual size and save some memory, but at the moment we don't need it.
this->jumpData = (uint32_t *) MEMAllocFromExpHeapEx(this->heapHandle, this->jumpDataSize * sizeof(uint32_t), 4);
if (!this->jumpData) {
DEBUG_FUNCTION_LINE_ERR("Failed to alloc jump data");
return false;
}
}
this->jumpToOriginal = (uint32_t *) MEMAllocFromExpHeapEx(this->heapHandle, 0x5 * sizeof(uint32_t), 4);
if (!this->jumpToOriginal) {
DEBUG_FUNCTION_LINE_ERR("Failed to alloc jump data");
return false;
}
return true;
}
bool PatchedFunctionData::getAddressForExecutable(uint32_t *outAddress) const {
if (!outAddress) {
return false;
}
if (!executableName.has_value()) {
return false;
}
uint32_t result = 0;
if (type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_ADDRESS) {
int num_rpls = OSDynLoad_GetNumberOfRPLs();
if (num_rpls == 0) {
DEBUG_FUNCTION_LINE_ERR("OSDynLoad_GetNumberOfRPLs failed. Missing patches?");
OSFatal("OSDynLoad_GetNumberOfRPLs failed. This shouldn't happen. Missing patches?");
return false;
}
std::vector<OSDynLoad_NotifyData> rpls;
rpls.resize(num_rpls);
bool ret = OSDynLoad_GetRPLInfo(0, num_rpls, rpls.data());
if (!ret) {
DEBUG_FUNCTION_LINE_ERR("OSDynLoad_GetRPLInfo failed. Missing patches?");
OSFatal("OSDynLoad_GetNumberOfRPLs failed. This shouldn't happen. Missing patches?");
return false;
}
bool found = false;
for (auto &rpl : rpls) {
if (std::string_view(rpl.name).ends_with(executableName.value())) {
result = rpl.textAddr + textOffset;
found = true;
break;
}
}
if (!found) {
if (executableName->ends_with(".rpx")) {
DEBUG_FUNCTION_LINE_ERR("Can't patch function. \"%s\" is not loaded.", executableName->c_str());
} else {
DEBUG_FUNCTION_LINE_WARN("Can't patch function. \"%s\" is not loaded.", executableName->c_str());
}
return false;
}
} else if (type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_NAME) {
if (!this->functionName) {
DEBUG_FUNCTION_LINE_ERR("Function name was empty. This should never happen.");
OSFatal("Function name was empty. This should never happen. Check logs for more information.");
return false;
}
result = KernelFindExport(executableName.value(), functionName.value());
if (result == 0) {
DEBUG_FUNCTION_LINE_WARN("Failed to find function \"%s\" in \"%s\".", functionName->c_str(), executableName->c_str());
return false;
}
} else {
DEBUG_FUNCTION_LINE_ERR("Unexpected function patching type. %d", type);
OSFatal("Unexpected function patching type.");
return false;
}
*outAddress = result;
return true;
}
bool PatchedFunctionData::updateFunctionAddresses() {
uint32_t real_address;
if (type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_NAME || type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_ADDRESS) {
if (!getAddressForExecutable(&real_address)) {
return false;
}
} else {
if (!this->library) {
DEBUG_FUNCTION_LINE_ERR("library name was empty. This should never happen.");
OSFatal("library was empty. This should never happen. Check logs for more information.");
return false;
}
if (this->library == LIBRARY_OTHER) {
// Use the provided physical/effective address!
return true;
}
if (!this->functionName) {
DEBUG_FUNCTION_LINE_ERR("Function name was empty. This should never happen.");
OSFatal("Function name was empty. This should never happen. Check logs for more information.");
return false;
}
real_address = functionAddressProvider->getEffectiveAddressOfFunction(library.value(), this->functionName->c_str());
if (!real_address) {
DEBUG_FUNCTION_LINE("OSDynLoad_FindExport failed for %s, updating address not possible.", this->functionName->c_str());
return false;
}
}
this->realEffectiveFunctionAddress = real_address;
auto physicalFunctionAddress = (uint32_t) OSEffectiveToPhysical(real_address);
if (!physicalFunctionAddress) {
DEBUG_FUNCTION_LINE_ERR("Error. Something is wrong with the physical address");
OSFatal("Error. Something is wrong with the physical address");
return false;
}
this->realPhysicalFunctionAddress = physicalFunctionAddress;
return true;
}
void PatchedFunctionData::generateJumpToOriginal() {
if (!this->jumpToOriginal) {
DEBUG_FUNCTION_LINE_ERR("this->jumpToOriginal is not allocated");
OSFatal("FunctionPatcherModule: this->jumpToOriginal is not allocated");
}
uint32_t jumpToAddress = this->realEffectiveFunctionAddress + 4;
if (((uint32_t) jumpToAddress & 0x01FFFFFC) != (uint32_t) jumpToAddress) {
// We need to do a long jump
this->jumpToOriginal[0] = 0x3d600000 | ((jumpToAddress >> 16) & 0x0000FFFF); // lis r11 ,0x1234
this->jumpToOriginal[1] = 0x616b0000 | (jumpToAddress & 0x0000ffff); // ori r11 ,r11 ,0x5678
this->jumpToOriginal[2] = 0x7d6903a6; // mtspr CTR ,r11
this->jumpToOriginal[3] = this->replacedInstruction;
this->jumpToOriginal[4] = 0x4e800420; // bctr
} else {
this->jumpToOriginal[0] = this->replacedInstruction;
this->jumpToOriginal[1] = 0x48000002 | (jumpToAddress & 0x01FFFFFC);
}
DCFlushRange((void *) this->jumpToOriginal, sizeof(uint32_t) * 5);
ICInvalidateRange((void *) this->jumpToOriginal, sizeof(uint32_t) * 5);
*(this->realCallFunctionAddressPtr) = (uint32_t) this->jumpToOriginal;
OSMemoryBarrier();
}
void PatchedFunctionData::generateReplacementJump() {
//setting jump back
this->replaceWithInstruction = 0x48000002 | (this->replacementFunctionAddress & 0x01FFFFFC);
// If the jump is too big, or we want only patch for certain processes we need a trampoline
if (this->replacementFunctionAddress > 0x01FFFFFC || this->targetProcess != FP_TARGET_PROCESS_ALL) {
if (!this->jumpData) {
DEBUG_FUNCTION_LINE_ERR("jumpData was not allocated");
OSFatal("FunctionPatcherModule: jumpData was not allocated");
}
uint32_t offset = 0;
if (this->targetProcess != FP_TARGET_PROCESS_ALL) {
auto originalFunctionAddrWithOffset = this->realEffectiveFunctionAddress + 4;
bool shortBranchToOriginalPossible = ((uint32_t) originalFunctionAddrWithOffset & 0x01FFFFFC) == (uint32_t) originalFunctionAddrWithOffset;
// Only use patched function if OSGetUPID matches function_data->targetProcess
this->jumpData[offset++] = 0x3d600000 | (((uint32_t *) OSGetUPID)[0] & 0x0000FFFF); // lis r11 ,0x0
this->jumpData[offset++] = 0x816b0000 | (((uint32_t *) OSGetUPID)[1] & 0x0000FFFF); // lwz r11 ,0x0(r11)
if (this->targetProcess == FP_TARGET_PROCESS_GAME_AND_MENU) {
this->jumpData[offset++] = 0x2c0b0000 | FP_TARGET_PROCESS_WII_U_MENU; // cmpwi r11 ,FP_TARGET_PROCESS_WII_U_MENU
this->jumpData[offset++] = 0x41820000 | (shortBranchToOriginalPossible ? 0x00000014 : 0x00000020); // beq myfunc
this->jumpData[offset++] = 0x2c0b0000 | FP_TARGET_PROCESS_GAME; // cmpwi r11 ,FP_TARGET_PROCESS_GAME
this->jumpData[offset++] = 0x41820000 | (shortBranchToOriginalPossible ? 0x0000000C : 0x00000018); // beq myfunc
} else {
this->jumpData[offset++] = 0x2c0b0000 | this->targetProcess; // cmpwi r11 ,function_data->targetProcess
this->jumpData[offset++] = 0x41820000 | (shortBranchToOriginalPossible ? 0x0000000C : 0x00000018); // beq myfunc
}
this->jumpData[offset++] = this->replacedInstruction;
if (((uint32_t) originalFunctionAddrWithOffset & 0x01FFFFFC) != (uint32_t) originalFunctionAddrWithOffset) {
this->jumpData[offset++] = 0x3d600000 | (((this->realEffectiveFunctionAddress + 4) >> 16) & 0x0000FFFF); // lis r11 ,(real_addr + 4)@hi
this->jumpData[offset++] = 0x616b0000 | ((this->realEffectiveFunctionAddress + 4) & 0x0000ffff); // ori r11 ,(real_addr + 4)@lo
this->jumpData[offset++] = 0x7d6903a6; // mtspr CTR ,r11
this->jumpData[offset++] = 0x4e800420; // bctr
} else {
this->jumpData[offset++] = 0x48000002 | (originalFunctionAddrWithOffset & 0x01FFFFFC);
}
}
// myfunc:
if (((uint32_t) this->replacementFunctionAddress & 0x01FFFFFC) != (uint32_t) this->replacementFunctionAddress) {
this->jumpData[offset++] = 0x3d600000 | (((this->replacementFunctionAddress) >> 16) & 0x0000FFFF); // lis r11 ,repl_addr@hi
this->jumpData[offset++] = 0x616b0000 | ((this->replacementFunctionAddress) & 0x0000ffff); // ori r11 ,r11 ,repl_addr@lo
this->jumpData[offset++] = 0x7d6903a6; // mtspr CTR ,r11
this->jumpData[offset] = 0x4e800420; // bctr
} else {
this->jumpData[offset] = 0x48000002 | (replacementFunctionAddress & 0x01FFFFFC);
}
if (offset >= this->jumpDataSize) {
DEBUG_FUNCTION_LINE_ERR("Tried to overflow buffer. offset: %08X vs array size: %08X", offset, this->jumpDataSize);
OSFatal("FunctionPatcherModule: Wrote too much data");
}
// Make sure the trampoline itself is usable.
if (((uint32_t) this->jumpData & 0x01FFFFFC) != (uint32_t) this->jumpData) {
DEBUG_FUNCTION_LINE_ERR("Jump is impossible");
OSFatal("FunctionPatcherModule: Jump is impossible");
}
this->replaceWithInstruction = 0x48000002 | ((uint32_t) this->jumpData & 0x01FFFFFC);
DCFlushRange((void *) this->jumpData, sizeof(uint32_t) * 15);
ICInvalidateRange((void *) this->jumpData, sizeof(uint32_t) * 15);
}
DCFlushRange((void *) &replaceWithInstruction, 4);
ICInvalidateRange((void *) &replaceWithInstruction, 4);
OSMemoryBarrier();
}
PatchedFunctionData::~PatchedFunctionData() {
if (this->jumpToOriginal) {
MEMFreeToExpHeap(this->heapHandle, this->jumpToOriginal);
this->jumpToOriginal = nullptr;
}
if (this->jumpData) {
MEMFreeToExpHeap(this->heapHandle, this->jumpData);
this->jumpData = nullptr;
}
}
bool PatchedFunctionData::shouldBePatched() const {
if (type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_NAME || type == FUNCTION_PATCHER_REPLACE_FOR_EXECUTABLE_BY_ADDRESS) {
uint64_t curTitleId = OSGetTitleID();
if (!this->titleIds.contains(curTitleId)) {
DEBUG_FUNCTION_LINE_VERBOSE("Skip function patch. Patch is not for title %016llX", curTitleId);
return false;
}
auto mcpHandle = MCP_Open();
MCPTitleListType titleInfo;
int32_t res = -1;
if ((curTitleId & 0x0000000F00000000) == 0) {
res = MCP_GetTitleInfo(mcpHandle, curTitleId | 0x0000000E00000000, &titleInfo);
}
if (res != 0) {
res = MCP_GetTitleInfo(mcpHandle, curTitleId, &titleInfo);
}
MCP_Close(mcpHandle);
if (res != 0) {
DEBUG_FUNCTION_LINE_WARN("Failed to get title version of %016llX.", curTitleId);
OSFatal("Failed to get title version. This should not happen.\n"
"Please report this with a crash log.");
return false;
}
MCP_Close(mcpHandle);
if (titleInfo.titleVersion < titleVersionMin || titleInfo.titleVersion > titleVersionMax) {
DEBUG_FUNCTION_LINE("Skipping function patch. Title version does not match: Expected >= %d && <= %d. Real version: %d", titleVersionMin, titleVersionMax, titleInfo.titleVersion);
return false;
}
}
return true;
}

View File

@ -0,0 +1,77 @@
#pragma once
#include "FunctionAddressProvider.h"
#include "PatchedFunctionData.h"
#include "utils/logger.h"
#include <coreinit/cache.h>
#include <coreinit/debug.h>
#include <coreinit/memexpheap.h>
#include <coreinit/memorymap.h>
#include <cstdint>
#include <function_patcher/fpatching_defines.h>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
class PatchedFunctionData {
public:
~PatchedFunctionData();
explicit PatchedFunctionData(std::shared_ptr<FunctionAddressProvider> functionAddressProvider) : functionAddressProvider(std::move(functionAddressProvider)) {
}
static std::optional<std::shared_ptr<PatchedFunctionData>> make_shared_v2(std::shared_ptr<FunctionAddressProvider> functionAddressProvider,
function_replacement_data_v2_t *replacementData,
MEMHeapHandle heapHandle);
static std::optional<std::shared_ptr<PatchedFunctionData>> make_shared_v3(std::shared_ptr<FunctionAddressProvider> functionAddressProvider,
function_replacement_data_v3_t *replacementData,
MEMHeapHandle heapHandle);
bool allocateDataForJumps();
bool getAddressForExecutable(uint32_t *outAddress) const;
bool updateFunctionAddresses();
void generateJumpToOriginal();
void generateReplacementJump();
[[nodiscard]] bool shouldBePatched() const;
uint32_t getHandle() {
return (uint32_t) this;
}
uint32_t *jumpToOriginal = {};
uint32_t *jumpData = {};
uint32_t realEffectiveFunctionAddress = {};
uint32_t realPhysicalFunctionAddress = {};
uint32_t *realCallFunctionAddressPtr = {};
uint32_t replacementFunctionAddress = {};
uint32_t replacedInstruction = {};
uint32_t replaceWithInstruction = {};
uint32_t jumpDataSize = 15;
MEMHeapHandle heapHandle = nullptr;
FunctionPatcherFunctionType type = {};
std::set<uint64_t> titleIds;
uint16_t titleVersionMin = 0;
uint16_t titleVersionMax = 0xFFFF;
std::optional<std::string> executableName = {};
uint32_t textOffset = 0;
bool isPatched = {};
std::optional<function_replacement_library_type_t> library = {};
FunctionPatcherTargetProcess targetProcess = {};
std::optional<std::string> functionName = {};
std::shared_ptr<FunctionAddressProvider> functionAddressProvider = {};
};

148
source/export.cpp Normal file
View File

@ -0,0 +1,148 @@
#include "export.h"
#include "PatchedFunctionData.h"
#include "function_patcher.h"
#include "utils/globals.h"
#include <ranges>
#include <vector>
#include <wums/exports.h>
WUT_CHECK_OFFSET(function_replacement_data_v2_t, 0x00, VERSION);
WUT_CHECK_OFFSET(function_replacement_data_v3_t, 0x00, version);
FunctionPatcherStatus FPAddFunctionPatch(function_replacement_data_t *function_data, PatchedFunctionHandle *outHandle, bool *outHasBeenPatched) {
if (function_data == nullptr) {
DEBUG_FUNCTION_LINE_ERR("function_data was NULL");
return FUNCTION_PATCHER_RESULT_INVALID_ARGUMENT;
}
if (function_data->version < 2 || function_data->version > 3) {
DEBUG_FUNCTION_LINE_ERR("Failed to patch function. struct version mismatch");
return FUNCTION_PATCHER_RESULT_UNSUPPORTED_STRUCT_VERSION;
}
std::optional<std::shared_ptr<PatchedFunctionData>> functionDataOpt;
if (function_data->version == 2) {
functionDataOpt = PatchedFunctionData::make_shared_v2(gFunctionAddressProvider, (function_replacement_data_v2_t *) function_data, gJumpHeapHandle);
} else if (function_data->version == 3) {
functionDataOpt = PatchedFunctionData::make_shared_v3(gFunctionAddressProvider, (function_replacement_data_v3_t *) function_data, gJumpHeapHandle);
} else {
// Should never happen.
DEBUG_FUNCTION_LINE_ERR("Unknown function_replacement_data_t struct version");
OSFatal("Unknown function patching struct version. Update FunctionPatcherModule/Aroma.");
}
if (!functionDataOpt) {
return FUNCTION_PATCHER_RESULT_UNKNOWN_ERROR;
}
auto &functionData = functionDataOpt.value();
// PatchFunction calls OSFatal on fatal errors.
// If this function returns false the target function was not patched
// Usually this means the target RPL is not (yet) loaded.
auto patchResult = PatchFunction(functionData);
if (outHasBeenPatched) {
*outHasBeenPatched = patchResult;
}
if (outHandle) {
*outHandle = functionData->getHandle();
}
{
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
gPatchedFunctions.push_back(std::move(functionData));
OSMemoryBarrier();
}
return FUNCTION_PATCHER_RESULT_SUCCESS;
}
bool FunctionPatcherPatchFunction(function_replacement_data_t *function_data, PatchedFunctionHandle *outHandle) {
return FPAddFunctionPatch(function_data, outHandle, nullptr) == FUNCTION_PATCHER_RESULT_SUCCESS;
}
FunctionPatcherStatus FPRemoveFunctionPatch(PatchedFunctionHandle handle) {
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
std::vector<std::shared_ptr<PatchedFunctionData>> toBeTempRestored;
bool found = false;
int32_t erasePosition = 0;
std::shared_ptr<PatchedFunctionData> toBeRemoved;
for (auto &cur : gPatchedFunctions) {
if (cur->getHandle() == handle) {
toBeRemoved = cur;
found = true;
if (!cur->isPatched) {
// Early return if the function is not patched.
break;
}
continue;
}
// Check if something else patched the same function afterwards.
if (found) {
if (cur->realPhysicalFunctionAddress == toBeRemoved->realPhysicalFunctionAddress) {
toBeTempRestored.push_back(cur);
}
} else {
erasePosition++;
}
}
if (!found) {
DEBUG_FUNCTION_LINE_ERR("Failed to find PatchedFunctionData by handle %08X", handle);
return FUNCTION_PATCHER_RESULT_PATCH_NOT_FOUND;
}
if (toBeRemoved->isPatched) {
// Restore function patches that were done after the patch we actually want to restore.
for (auto &cur : std::ranges::reverse_view(toBeTempRestored)) {
RestoreFunction(cur);
}
// Restore the function we actually want to restore
RestoreFunction(toBeRemoved);
}
gPatchedFunctions.erase(gPatchedFunctions.begin() + erasePosition);
if (toBeRemoved->isPatched) {
// Apply the other patches again
for (auto &cur : toBeTempRestored) {
PatchFunction(cur);
}
}
OSMemoryBarrier();
return FUNCTION_PATCHER_RESULT_SUCCESS;
}
bool FunctionPatcherRestoreFunction(PatchedFunctionHandle handle) {
return FPRemoveFunctionPatch(handle) == FUNCTION_PATCHER_RESULT_SUCCESS;
}
FunctionPatcherStatus FPGetVersion(FunctionPatcherAPIVersion *outVersion) {
if (outVersion == nullptr) {
return FUNCTION_PATCHER_RESULT_INVALID_ARGUMENT;
}
*outVersion = 2;
return FUNCTION_PATCHER_RESULT_SUCCESS;
}
FunctionPatcherStatus FPIsFunctionPatched(PatchedFunctionHandle handle, bool *outIsFunctionPatched) {
if (outIsFunctionPatched == nullptr) {
return FUNCTION_PATCHER_RESULT_INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
for (auto &cur : gPatchedFunctions) {
if (cur->getHandle() == handle) {
*outIsFunctionPatched = cur->isPatched;
return FUNCTION_PATCHER_RESULT_SUCCESS;
}
}
return FUNCTION_PATCHER_RESULT_PATCH_NOT_FOUND;
}
WUMS_EXPORT_FUNCTION(FPGetVersion);
WUMS_EXPORT_FUNCTION(FPAddFunctionPatch);
WUMS_EXPORT_FUNCTION(FPRemoveFunctionPatch);
WUMS_EXPORT_FUNCTION(FPIsFunctionPatched);

6
source/export.h Normal file
View File

@ -0,0 +1,6 @@
#pragma once
#include <function_patcher/fpatching_defines.h>
bool FunctionPatcherPatchFunction(function_replacement_data_t *function_data, PatchedFunctionHandle *outHandle);
bool FunctionPatcherRestoreFunction(PatchedFunctionHandle handle);

View File

@ -1,30 +1,25 @@
#include <coreinit/dynload.h> #include "function_patcher.h"
#include "FunctionAddressProvider.h"
#include "PatchedFunctionData.h"
#include "utils/CThread.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <coreinit/cache.h> #include <coreinit/cache.h>
#include <coreinit/debug.h> #include <coreinit/debug.h>
#include <coreinit/memorymap.h> #include <coreinit/memorymap.h>
#include <coreinit/memdefaultheap.h>
#include <kernel/kernel.h> #include <kernel/kernel.h>
#include "function_patcher.h" #include <memory>
#include "logger.h"
#include "CThread.h"
#define DEBUG_LOG_DYN 0 static void writeDataAndFlushIC(CThread *thread, void *arg) {
auto *data = (PatchedFunctionData *) arg;
void writeDataAndFlushIC(CThread *thread, void *arg) { uint32_t replace_instruction = data->replaceWithInstruction;
uint32_t *data = (uint32_t *) arg; uint32_t physical_address = data->realPhysicalFunctionAddress;
uint16_t core = OSGetThreadAffinity(OSGetCurrentThread()); uint32_t effective_address = data->realEffectiveFunctionAddress;
DCFlushRange(data, sizeof(uint32_t) * 3);
uint32_t replace_instruction = data[0];
uint32_t physical_address = data[1];
uint32_t effective_address = data[2];
DCFlushRange(&replace_instruction, 4); DCFlushRange(&replace_instruction, 4);
DCFlushRange(&physical_address, 4); DCFlushRange(&physical_address, 4);
//DEBUG_FUNCTION_LINE("Write instruction %08X to %08X [%08X] on core %d", replace_instruction, effective_address, physical_address, core / 2); auto replace_instruction_physical = (uint32_t) &replace_instruction;
uint32_t replace_instruction_physical = (uint32_t) &replace_instruction;
if (replace_instruction_physical < 0x00800000 || replace_instruction_physical >= 0x01000000) { if (replace_instruction_physical < 0x00800000 || replace_instruction_physical >= 0x01000000) {
replace_instruction_physical = OSEffectiveToPhysical(replace_instruction_physical); replace_instruction_physical = OSEffectiveToPhysical(replace_instruction_physical);
@ -36,367 +31,94 @@ void writeDataAndFlushIC(CThread *thread, void *arg) {
ICInvalidateRange((void *) (effective_address), 4); ICInvalidateRange((void *) (effective_address), 4);
} }
void FunctionPatcherRestoreDynamicFunctions(function_replacement_data_t *replacements, uint32_t size) { bool PatchFunction(std::shared_ptr<PatchedFunctionData> &patchedFunction) {
for (uint32_t i = 0; i < size; i++) { if (patchedFunction->isPatched) {
function_replacement_data_t *function_data = &replacements[i]; return true;
if (function_data->VERSION != FUNCTION_REPLACEMENT_DATA_STRUCT_VERSION) {
OSFatal("Failed to patch function. struct version mismatch");
}
uint32_t targetAddrPhys = function_data->physicalAddr;
if (function_data->library != LIBRARY_OTHER) {
targetAddrPhys = (uint32_t) OSEffectiveToPhysical(function_data->realAddr);
}
if (isDynamicFunction(targetAddrPhys)) {
DEBUG_FUNCTION_LINE("Setting alreadyPatched to false for %s because it's a dynamic function", function_data->function_name);
function_data->alreadyPatched = 0;
}
} }
if (!patchedFunction->shouldBePatched()) {
return false;
}
// The addresses of a function might change every time with run another application.
if (!patchedFunction->updateFunctionAddresses()) {
return false;
}
if (patchedFunction->functionName) {
DEBUG_FUNCTION_LINE("Patching function %s...", patchedFunction->functionName->c_str());
} else {
DEBUG_FUNCTION_LINE("Patching function @ %08X", patchedFunction->realEffectiveFunctionAddress);
}
if (!ReadFromPhysicalAddress(patchedFunction->realPhysicalFunctionAddress, &patchedFunction->replacedInstruction)) {
DEBUG_FUNCTION_LINE_ERR("Failed to read instruction.");
OSFatal("FunctionPatcherModule: Failed to read instruction.");
return false;
}
// Generate a jump to the original function so the unpatched function can still be called
patchedFunction->generateJumpToOriginal();
// Generate a code that is run when somebody calls the patched function.
// If the correct process calls this, it'll jump the function replacement, otherwise the original function will be called.
patchedFunction->generateReplacementJump();
// Write this->replaceWithInstruction to the first instruction of the function we want to replace.
CThread::runOnAllCores(writeDataAndFlushIC, patchedFunction.get());
// Set patch status
patchedFunction->isPatched = true;
return true;
} }
void FunctionPatcherPatchFunction(function_replacement_data_t *replacements, uint32_t size) { bool RestoreFunction(std::shared_ptr<PatchedFunctionData> &patchedFunction) {
for (uint32_t i = 0; i < size; i++) { if (!patchedFunction->isPatched) {
function_replacement_data_t *function_data = &replacements[i]; DEBUG_FUNCTION_LINE_VERBOSE("Skip restoring function because it's not patched");
if (function_data->VERSION != FUNCTION_REPLACEMENT_DATA_STRUCT_VERSION) { return true;
OSFatal("Failed to patch function. struct version mismatch"); }
} if (patchedFunction->replacedInstruction == 0 || patchedFunction->realEffectiveFunctionAddress == 0) {
/* Patch branches to it. */ DEBUG_FUNCTION_LINE_ERR("Failed to restore function, information is missing.");
volatile uint32_t *space = function_data->replace_data; return false;
if (function_data->library == LIBRARY_OTHER) {
//WHBLogWritef("Oh, using straight PA/VA\n");
if (function_data->alreadyPatched == 1) {
//DEBUG_FUNCTION_LINE("Skipping %s, its already patched\n", function_data->function_name);
continue;
}
} else {
if (function_data->alreadyPatched == 1) {
/*if (isDynamicFunction((uint32_t) OSEffectiveToPhysical(function_data->realAddr))) {
WHBLogWritef("INFO: The function %s is a dynamic function.\n", function_data->function_name);
function_data->functionType = FUNCTION_PATCHER_DYNAMIC_FUNCTION;
} else {*/
//WHBLogPrintf("Skipping %s, its already patched\n", function_data->function_name);
continue;
//}
}
}
DEBUG_FUNCTION_LINE("Patching %s ...", function_data->function_name);
uint32_t physical = function_data->physicalAddr;
uint32_t repl_addr = (uint32_t) function_data->replaceAddr;
uint32_t call_addr = (uint32_t) function_data->replaceCall;
uint32_t real_addr = function_data->virtualAddr;
if (function_data->library != LIBRARY_OTHER) {
real_addr = getAddressOfFunction(function_data->function_name, function_data->library);
}
if (!real_addr) {
WHBLogWritef("");
DEBUG_FUNCTION_LINE("OSDynLoad_FindExport failed for %s", function_data->function_name);
continue;
}
if (DEBUG_LOG_DYN) {
DEBUG_FUNCTION_LINE("%s is located at %08X!", function_data->function_name, real_addr);
}
if (function_data->library != LIBRARY_OTHER) {
physical = (uint32_t) OSEffectiveToPhysical(real_addr);
}
if (!physical) {
WHBLogWritef("Error. Something is wrong with the physical address");
continue;
}
if (DEBUG_LOG_DYN) {
DEBUG_FUNCTION_LINE("%s physical is located at %08X!", function_data->function_name, physical);
}
*(volatile uint32_t *) (call_addr) = (uint32_t) (space);
uint32_t targetAddr = (uint32_t) space;
if (targetAddr < 0x00800000 || targetAddr >= 0x01000000) {
targetAddr = (uint32_t) OSEffectiveToPhysical(targetAddr);
} else {
targetAddr = targetAddr + 0x30800000 - 0x00800000;
}
KernelCopyData(targetAddr, physical, 4);
ICInvalidateRange((void *) (space), 4);
DCFlushRange((void *) (space), 4);
space++;
// fill the restore instruction section
function_data->realAddr = real_addr;
function_data->restoreInstruction = space[-1];
if (DEBUG_LOG_DYN) {
DEBUG_FUNCTION_LINE("function_data->realAddr = %08X!", function_data->realAddr);
DEBUG_FUNCTION_LINE("function_data->restoreInstruction = %08X!", function_data->restoreInstruction);
}
/*
00808cfc 3d601234 lis r11 ,0x1234
00808d00 616b5678 ori r11 ,r11 ,0x5678
00808d04 7d6903a6 mtspr CTR ,r11
00808d08 4e800420 bctr
*/
*space = 0x3d600000 | (((real_addr + 4) >> 16) & 0x0000FFFF); space++; // lis r11 ,0x1234
*space = 0x616b0000 | ((real_addr + 4) & 0x0000ffff); space++; // ori r11 ,r11 ,0x5678
*space = 0x7d6903a6; space++; // mtspr CTR ,r11
*space = 0x4e800420; space++; // bctr
//setting jump back
uint32_t replace_instr = 0x48000002 | (repl_addr & 0x03FFFFFC);
// If the jump is too big or we want only patch for certain processes we need a trampoline
if (repl_addr > 0x03FFFFFC || function_data->targetProcess != FP_TARGET_PROCESS_ALL) {
uint32_t repl_addr_test = (uint32_t) space;
if (function_data->targetProcess != FP_TARGET_PROCESS_ALL) {
// Only use patched function if OSGetUPID matches function_data->targetProcess
*space = 0x3d600000 | (((uint32_t*) OSGetUPID)[0] & 0x0000FFFF); space++; // lis r11 ,0x0
*space = 0x816b0000 | (((uint32_t*) OSGetUPID)[1] & 0x0000FFFF); space++; // lwz r11 ,0x0(r11)
if(function_data->targetProcess == FP_TARGET_PROCESS_GAME_AND_MENU){
*space = 0x2c0b0000 | FP_TARGET_PROCESS_WII_U_MENU; space++; // cmpwi r11 ,FP_TARGET_PROCESS_WII_U_MENU
*space = 0x41820000 | 0x00000020; space++; // beq myfunc
*space = 0x2c0b0000 | FP_TARGET_PROCESS_GAME; space++; // cmpwi r11 ,FP_TARGET_PROCESS_GAME
*space = 0x41820000 | 0x00000018; space++; // beq myfunc
} else {
*space = 0x2c0b0000 | function_data->targetProcess; space++; // cmpwi r11 ,function_data->targetProcess
*space = 0x41820000 | 0x00000018; space++; // beq myfunc
}
*space = 0x3d600000 | (((real_addr + 4) >> 16) & 0x0000FFFF); space++; // lis r11 ,(real_addr + 4)@hi
*space = 0x616b0000 | ((real_addr + 4) & 0x0000ffff); space++; // ori r11 ,(real_addr + 4)@lo
*space = 0x7d6903a6; space++; // mtspr CTR ,r11
*space = function_data->restoreInstruction; space++; //
*space = 0x4e800420; space++; // bctr
}
// myfunc:
*space = 0x3d600000 | (((repl_addr) >> 16) & 0x0000FFFF); space++; // lis r11 ,repl_addr@hi
*space = 0x616b0000 | ((repl_addr) & 0x0000ffff); space++; // ori r11 ,r11 ,repl_addr@lo
*space = 0x7d6903a6; space++; // mtspr CTR ,r11
*space = 0x4e800420; space++; // bctr
// Make sure the trampoline itself is usable.
if ((repl_addr_test & 0x03FFFFFC) != repl_addr_test) {
OSFatal("Jump is impossible");
}
replace_instr = 0x48000002 | (repl_addr_test & 0x03FFFFFC);
}
if (space > &function_data->replace_data[FUNCTION_PATCHER_METHOD_STORE_SIZE]) {
OSFatal("The replacement data is too long.");
}
DCFlushRange((void *) function_data->replace_data, FUNCTION_PATCHER_METHOD_STORE_SIZE * 4);
ICInvalidateRange((void *) function_data->replace_data, FUNCTION_PATCHER_METHOD_STORE_SIZE * 4);
uint32_t data[] = {
replace_instr,
physical,
real_addr
};
CThread::runOnAllCores(writeDataAndFlushIC, data);
function_data->alreadyPatched = 1;
DEBUG_FUNCTION_LINE("done with patching %s!", function_data->function_name);
} }
//DEBUG_FUNCTION_LINE("Done with patching given functions!");
} auto targetAddrPhys = (uint32_t) patchedFunction->realPhysicalFunctionAddress;
void FunctionPatcherRestoreFunctions(function_replacement_data_t *replacements, uint32_t size) { if (patchedFunction->library != LIBRARY_OTHER) {
DEBUG_FUNCTION_LINE("Restoring given functions!"); targetAddrPhys = (uint32_t) OSEffectiveToPhysical(patchedFunction->realEffectiveFunctionAddress);
for (uint32_t i = 0; i < size; i++) { }
DEBUG_FUNCTION_LINE("Restoring %s... ", replacements[i].function_name);
if (replacements[i].restoreInstruction == 0 || replacements[i].realAddr == 0) { // Check if patched instruction is still loaded.
DEBUG_FUNCTION_LINE("I dont have the information for the restore =( skip"); uint32_t currentInstruction;
continue; if (!ReadFromPhysicalAddress(patchedFunction->realPhysicalFunctionAddress, &currentInstruction)) {
} DEBUG_FUNCTION_LINE_ERR("Failed to read instruction.");
return false;
uint32_t targetAddrPhys = (uint32_t) replacements[i].physicalAddr; }
if (replacements[i].library != LIBRARY_OTHER) { if (currentInstruction != patchedFunction->replaceWithInstruction) {
targetAddrPhys = (uint32_t) OSEffectiveToPhysical(replacements[i].realAddr); DEBUG_FUNCTION_LINE_WARN("Instruction is different than expected. Skip restoring. Expected: %08X Real: %08X", currentInstruction, patchedFunction->replaceWithInstruction);
} return false;
}
if (isDynamicFunction(targetAddrPhys) &&
// Other processes than the wii u menu and game one seem to keep their rpl's loaded. DEBUG_FUNCTION_LINE_VERBOSE("Restoring %08X to %08X [%08X]", (uint32_t) patchedFunction->replacedInstruction, patchedFunction->realEffectiveFunctionAddress, targetAddrPhys);
replacements[i].targetProcess != FP_TARGET_PROCESS_GAME_AND_MENU && auto sourceAddr = (uint32_t) &patchedFunction->replacedInstruction;
replacements[i].targetProcess != FP_TARGET_PROCESS_GAME &&
replacements[i].targetProcess != FP_TARGET_PROCESS_WII_U_MENU auto sourceAddrPhys = (uint32_t) OSEffectiveToPhysical(sourceAddr);
) {
WHBLogPrintf("Its a dynamic function. We don't need to restore it!", replacements[i].function_name); // These hardcoded values should be replaced with something more dynamic.
replacements[i].alreadyPatched = false; if (sourceAddrPhys == 0 && (sourceAddr >= 0x00800000 && sourceAddr < 0x01000000)) {
} else { sourceAddrPhys = sourceAddr + (0x30800000 - 0x00800000);
if (DEBUG_LOG_DYN) { }
WHBLogPrintf("");
DEBUG_FUNCTION_LINE("Restoring %08X to %08X [%08X]", (uint32_t) replacements[i].restoreInstruction, replacements[i].realAddr, targetAddrPhys); if (sourceAddrPhys == 0) {
} OSFatal("FunctionPatcherModule: Failed to get physical address");
uint32_t sourceAddr = (uint32_t) &replacements[i].restoreInstruction; }
uint32_t sourceAddrPhys = (uint32_t) OSEffectiveToPhysical(sourceAddr); KernelCopyData(targetAddrPhys, sourceAddrPhys, 4);
ICInvalidateRange((void *) patchedFunction->realEffectiveFunctionAddress, 4);
// These hardcoded values should be replaced with something more dynamic. DCFlushRange((void *) patchedFunction->realEffectiveFunctionAddress, 4);
if (sourceAddrPhys == 0 && (sourceAddr >= 0x00800000 || sourceAddr < 0x01000000)) {
sourceAddrPhys = sourceAddr + 0x30800000 - 0x00800000; patchedFunction->isPatched = false;
} return true;
KernelCopyData(targetAddrPhys, sourceAddrPhys, 4);
if (DEBUG_LOG_DYN) {
WHBLogPrintf("");
DEBUG_FUNCTION_LINE("ICInvalidateRange %08X", (void *) replacements[i].realAddr);
}
ICInvalidateRange((void *) replacements[i].realAddr, 4);
WHBLogWritef("done\n");
}
replacements[i].alreadyPatched = 0; // In case a
}
DEBUG_FUNCTION_LINE("Done with restoring given functions!");
}
bool isDynamicFunction(uint32_t physicalAddress) {
if ((physicalAddress & 0x80000000) == 0x80000000) {
return 1;
}
return 0;
}
rpl_handling rpl_handles[] __attribute__((section(".data"))) = {
{LIBRARY_AVM, "avm.rpl", 0},
{LIBRARY_CAMERA, "camera.rpl", 0},
{LIBRARY_COREINIT, "coreinit.rpl", 0},
{LIBRARY_DC, "dc.rpl", 0},
{LIBRARY_DMAE, "dmae.rpl", 0},
{LIBRARY_DRMAPP, "drmapp.rpl", 0},
{LIBRARY_ERREULA, "erreula.rpl", 0},
{LIBRARY_GX2, "gx2.rpl", 0},
{LIBRARY_H264, "h264.rpl", 0},
{LIBRARY_LZMA920, "lzma920.rpl", 0},
{LIBRARY_MIC, "mic.rpl", 0},
{LIBRARY_NFC, "nfc.rpl", 0},
{LIBRARY_NIO_PROF, "nio_prof.rpl", 0},
{LIBRARY_NLIBCURL, "nlibcurl.rpl", 0},
{LIBRARY_NLIBNSS, "nlibnss.rpl", 0},
{LIBRARY_NLIBNSS2, "nlibnss2.rpl", 0},
{LIBRARY_NN_AC, "nn_ac.rpl", 0},
{LIBRARY_NN_ACP, "nn_acp.rpl", 0},
{LIBRARY_NN_ACT, "nn_act.rpl", 0},
{LIBRARY_NN_AOC, "nn_aoc.rpl", 0},
{LIBRARY_NN_BOSS, "nn_boss.rpl", 0},
{LIBRARY_NN_CCR, "nn_ccr.rpl", 0},
{LIBRARY_NN_CMPT, "nn_cmpt.rpl", 0},
{LIBRARY_NN_DLP, "nn_dlp.rpl", 0},
{LIBRARY_NN_EC, "nn_ec.rpl", 0},
{LIBRARY_NN_FP, "nn_fp.rpl", 0},
{LIBRARY_NN_HAI, "nn_hai.rpl", 0},
{LIBRARY_NN_HPAD, "nn_hpad.rpl", 0},
{LIBRARY_NN_IDBE, "nn_idbe.rpl", 0},
{LIBRARY_NN_NDM, "nn_ndm.rpl", 0},
{LIBRARY_NN_NETS2, "nn_nets2.rpl", 0},
{LIBRARY_NN_NFP, "nn_nfp.rpl", 0},
{LIBRARY_NN_NIM, "nn_nim.rpl", 0},
{LIBRARY_NN_OLV, "nn_olv.rpl", 0},
{LIBRARY_NN_PDM, "nn_pdm.rpl", 0},
{LIBRARY_NN_SAVE, "nn_save.rpl", 0},
{LIBRARY_NN_SL, "nn_sl.rpl", 0},
{LIBRARY_NN_SPM, "nn_spm.rpl", 0},
{LIBRARY_NN_TEMP, "nn_temp.rpl", 0},
{LIBRARY_NN_UDS, "nn_uds.rpl", 0},
{LIBRARY_NN_VCTL, "nn_vctl.rpl", 0},
{LIBRARY_NSYSCCR, "nsysccr.rpl", 0},
{LIBRARY_NSYSHID, "nsyshid.rpl", 0},
{LIBRARY_NSYSKBD, "nsyskbd.rpl", 0},
{LIBRARY_NSYSNET, "nsysnet.rpl", 0},
{LIBRARY_NSYSUHS, "nsysuhs.rpl", 0},
{LIBRARY_NSYSUVD, "nsysuvd.rpl", 0},
{LIBRARY_NTAG, "ntag.rpl", 0},
{LIBRARY_PADSCORE, "padscore.rpl", 0},
{LIBRARY_PROC_UI, "proc_ui.rpl", 0},
{LIBRARY_SNDCORE2, "sndcore2.rpl", 0},
{LIBRARY_SNDUSER2, "snduser2.rpl", 0},
{LIBRARY_SND_CORE, "snd_core.rpl", 0},
{LIBRARY_SND_USER, "snd_user.rpl", 0},
{LIBRARY_SWKBD, "swkbd.rpl", 0},
{LIBRARY_SYSAPP, "sysapp.rpl", 0},
{LIBRARY_TCL, "tcl.rpl", 0},
{LIBRARY_TVE, "tve.rpl", 0},
{LIBRARY_UAC, "uac.rpl", 0},
{LIBRARY_UAC_RPL, "uac_rpl.rpl", 0},
{LIBRARY_USB_MIC, "usb_mic.rpl", 0},
{LIBRARY_UVC, "uvc.rpl", 0},
{LIBRARY_UVD, "uvd.rpl", 0},
{LIBRARY_VPAD, "vpad.rpl", 0},
{LIBRARY_VPADBASE, "vpadbase.rpl", 0},
{LIBRARY_ZLIB125, "zlib125.rpl", 0}
};
uint32_t getAddressOfFunction(char *functionName, function_replacement_library_type_t library) {
uint32_t real_addr = 0;
OSDynLoad_Module rpl_handle = nullptr;
int err = 0;
int32_t rpl_handles_size = sizeof rpl_handles / sizeof rpl_handles[0];
for (int32_t i = 0; i < rpl_handles_size; i++) {
if (rpl_handles[i].library == library) {
if (rpl_handles[i].handle == nullptr) {
//DEBUG_FUNCTION_LINE("Lets acquire handle for rpl: %s", rpl_handles[i].rplname);
err = OSDynLoad_IsModuleLoaded((char *) rpl_handles[i].rplname, &rpl_handles[i].handle);
}
if (err || !rpl_handles[i].handle) {
WHBLogWritef("%s failed to acquire %d %08X\n", rpl_handles[i].rplname, err, rpl_handles[i].handle);
return 0;
}
rpl_handle = rpl_handles[i].handle;
break;
}
}
if (err || !rpl_handle) {
DEBUG_FUNCTION_LINE("Failed to find the RPL handle for %s", functionName);
return 0;
}
OSDynLoad_FindExport(rpl_handle, 0, functionName, reinterpret_cast<void **>(&real_addr));
if (!real_addr) {
DEBUG_FUNCTION_LINE("OSDynLoad_FindExport failed for %s", functionName);
return 0;
}
if ((library == LIBRARY_NN_ACP) && (uint32_t) (*(volatile uint32_t *) (real_addr) & 0x48000002) == 0x48000000) {
uint32_t address_diff = (uint32_t) (*(volatile uint32_t *) (real_addr) & 0x03FFFFFC);
if ((address_diff & 0x03000000) == 0x03000000) {
address_diff |= 0xFC000000;
}
real_addr += (int32_t) address_diff;
if ((uint32_t) (*(volatile uint32_t *) (real_addr) & 0x48000002) == 0x48000000) {
return 0;
}
}
return real_addr;
}
void FunctionPatcherResetLibHandles() {
int32_t rpl_handles_size = sizeof rpl_handles / sizeof rpl_handles[0];
for (int32_t i = 0; i < rpl_handles_size; i++) {
if (rpl_handles[i].handle != 0) {
DEBUG_FUNCTION_LINE("Resetting handle for rpl: %s", rpl_handles[i].rplname);
}
rpl_handles[i].handle = 0;
// Release handle?
}
} }

View File

@ -1,28 +1,17 @@
#pragma once #pragma once
#include <function_patcher/fpatching_defines.h>
#include "PatchedFunctionData.h"
#include <coreinit/dynload.h> #include <coreinit/dynload.h>
#include <function_patcher/fpatching_defines.h>
#include <memory>
#include <vector>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
typedef struct rpl_handling { bool PatchFunction(std::shared_ptr<PatchedFunctionData> &patchedFunction);
function_replacement_library_type_t library; bool RestoreFunction(std::shared_ptr<PatchedFunctionData> &patchedFunction);
const char rplname[15];
OSDynLoad_Module handle;
} rpl_handling;
void FunctionPatcherRestoreDynamicFunctions(function_replacement_data_t *replacements, uint32_t size);
void FunctionPatcherPatchFunction(function_replacement_data_t *replacements, uint32_t size);
void FunctionPatcherRestoreFunctions(function_replacement_data_t *replacements, uint32_t size);
void FunctionPatcherResetLibHandles();
uint32_t getAddressOfFunction(char * functionName, function_replacement_library_type_t type);
bool isDynamicFunction(uint32_t physicalAddress);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -1,30 +0,0 @@
#ifndef __LOGGER_H_
#define __LOGGER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include <whb/log.h>
#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__)
#define OSFATAL_FUNCTION_LINE(FMT, ARGS...)do { \
OSFatal_printf("[%s]%s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0)
#define DEBUG_FUNCTION_LINE(FMT, ARGS...)do { \
WHBLogPrintf("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0);
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...)do { \
WHBLogWritef("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,19 +1,186 @@
#include <wums.h> #include "FunctionAddressProvider.h"
#include <whb/log_udp.h> #include "export.h"
#include "function_patcher.h" #include "function_patcher.h"
WUMS_MODULE_EXPORT_NAME("homebrew_functionpatcher"); #include "utils/globals.h"
WUMS_MODULE_SKIP_ENTRYPOINT(); #include "utils/logger.h"
WUMS_MODULE_INIT_BEFORE_RELOCATION_DONE_HOOK(); #include "utils/utils.h"
#include <coreinit/memdefaultheap.h>
#include <coreinit/memexpheap.h>
#include <kernel/kernel.h>
#include <ranges>
#include <set>
#include <wums.h>
WUMS_INITIALIZE(){ WUMS_MODULE_EXPORT_NAME("homebrew_functionpatcher");
WHBLogUdpInit(); WUMS_MODULE_INIT_BEFORE_RELOCATION_DONE_HOOK();
WUMS_DEPENDS_ON(homebrew_kernel);
void UpdateFunctionPointer() {
// We need the real MEMAllocFromDefaultHeapEx/MEMFreeToDefaultHeap function pointer to force-allocate memory on the default heap.
// Our custom heap doesn't work (yet) for threads and causes an app panic.
OSDynLoad_Module coreinitModule;
if (OSDynLoad_Acquire("coreinit", &coreinitModule) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to acquire coreinit.rpl");
OSFatal("FunctionPatcherModule: Failed to acquire coreinit.rpl");
}
/* Memory allocation functions */
uint32_t *allocPtr, *freePtr;
if (OSDynLoad_FindExport(coreinitModule, OS_DYNLOAD_EXPORT_DATA, "MEMAllocFromDefaultHeapEx", reinterpret_cast<void **>(&allocPtr)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_ERR("OSDynLoad_FindExport for MEMAllocFromDefaultHeapEx");
OSFatal("FunctionPatcherModule: OSDynLoad_FindExport for MEMAllocFromDefaultHeapEx");
}
if (OSDynLoad_FindExport(coreinitModule, OS_DYNLOAD_EXPORT_DATA, "MEMFreeToDefaultHeap", reinterpret_cast<void **>(&freePtr)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_ERR("OSDynLoad_FindExport for MEMFreeToDefaultHeap");
OSFatal("FunctionPatcherModule: OSDynLoad_FindExport for MEMFreeToDefaultHeap");
}
gMEMAllocFromDefaultHeapExForThreads = (void *(*) (uint32_t, int) ) * allocPtr;
gMEMFreeToDefaultHeapForThreads = (void (*)(void *)) * freePtr;
OSDynLoad_Release(coreinitModule);
}
void CheckIfPatchedFunctionsAreStillInMemory() {
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
// Check if rpl has been unloaded by comparing the instruction.
std::set<uint32_t> physicalAddressesUnchanged;
std::set<uint32_t> physicalAddressesChanged;
// Restore function patches that were done after the patch we actually want to restore.
for (auto &cur : std::ranges::reverse_view(gPatchedFunctions)) {
if (!cur->isPatched || physicalAddressesUnchanged.contains(cur->realPhysicalFunctionAddress)) {
continue;
}
if (physicalAddressesChanged.contains(cur->realPhysicalFunctionAddress)) {
cur->isPatched = false;
continue;
}
// Check if patched instruction is still loaded.
uint32_t currentInstruction;
if (!ReadFromPhysicalAddress(cur->realPhysicalFunctionAddress, &currentInstruction)) {
DEBUG_FUNCTION_LINE_ERR("Failed to read instruction.");
continue;
}
if (currentInstruction == cur->replaceWithInstruction) {
physicalAddressesUnchanged.insert(cur->realPhysicalFunctionAddress);
} else {
cur->isPatched = false;
physicalAddressesChanged.insert(cur->realPhysicalFunctionAddress);
}
}
}
bool PatchInstruction(void *instr, uint32_t original, uint32_t replacement) {
uint32_t current = *(uint32_t *) instr;
if (current != original) {
return current == replacement;
}
KernelCopyData(OSEffectiveToPhysical((uint32_t) instr), OSEffectiveToPhysical((uint32_t) &replacement), sizeof(replacement));
DCFlushRange(instr, 4);
ICInvalidateRange(instr, 4);
current = *(uint32_t *) instr;
return true;
}
bool PatchDynLoadFunctions() {
uint32_t *patch1 = ((uint32_t *) &OSDynLoad_GetNumberOfRPLs) + 6;
uint32_t *patch2 = ((uint32_t *) &OSDynLoad_GetRPLInfo) + 22;
if (!PatchInstruction(patch1, 0x41820038 /* beq +38 */, 0x60000000 /*nop*/)) {
return false;
}
if (!PatchInstruction(patch2, 0x41820100 /* beq +100 */, 0x60000000 /*nop*/)) {
return false;
}
return true;
}
WUMS_INITIALIZE() {
UpdateFunctionPointer();
initLogging();
if (!PatchDynLoadFunctions()) {
DEBUG_FUNCTION_LINE_ERR("Failed to patch OSDynLoad_GetRPLInfo or OSDynLoad_GetNumberOfRPLs");
OSFatal("Failed to patch OSDynLoad_GetRPLInfo or OSDynLoad_GetNumberOfRPLs");
}
memset(gJumpHeapData, 0, JUMP_HEAP_DATA_SIZE);
gJumpHeapHandle = MEMCreateExpHeapEx((void *) (gJumpHeapData), JUMP_HEAP_DATA_SIZE, 1);
if (gJumpHeapHandle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to create heap for jump data");
OSFatal("FunctionPatcherModule: Failed to create heap for jump data");
}
gFunctionAddressProvider = make_shared_nothrow<FunctionAddressProvider>();
if (!gFunctionAddressProvider) {
DEBUG_FUNCTION_LINE_ERR("Failed to create gFunctionAddressProvider");
OSFatal("FunctionPatcherModule: Failed to create gFunctionAddressProvider");
}
}
void notify_callback(OSDynLoad_Module module,
void *userContext,
OSDynLoad_NotifyReason reason,
OSDynLoad_NotifyData *infos) {
if (reason == OS_DYNLOAD_NOTIFY_LOADED) {
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
for (auto &cur : gPatchedFunctions) {
PatchFunction(cur);
}
} else if (reason == OS_DYNLOAD_NOTIFY_UNLOADED) {
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
auto library = gFunctionAddressProvider->getTypeForHandle(module);
if (library != LIBRARY_OTHER) {
for (auto &cur : gPatchedFunctions) {
if (cur->type == FUNCTION_PATCHER_REPLACE_BY_LIB_OR_ADDRESS && cur->library.has_value() && cur->library == library) {
cur->isPatched = false;
}
}
}
gFunctionAddressProvider->resetHandle(module);
CheckIfPatchedFunctionsAreStillInMemory();
}
} }
WUMS_APPLICATION_STARTS() { WUMS_APPLICATION_STARTS() {
WHBLogUdpInit(); uint32_t upid = OSGetUPID();
FunctionPatcherResetLibHandles(); if (upid != 2 && upid != 15) {
return;
}
OSReport("Running FunctionPatcherModule " MODULE_VERSION_FULL "\n");
// Now we can update the pointer with the "real" functions
gMEMAllocFromDefaultHeapExForThreads = MEMAllocFromDefaultHeapEx;
gMEMFreeToDefaultHeapForThreads = MEMFreeToDefaultHeap;
initLogging();
{
std::lock_guard<std::mutex> lock(gPatchedFunctionsMutex);
// reset function patch status if the rpl they were patching has been unloaded from memory.
CheckIfPatchedFunctionsAreStillInMemory();
DEBUG_FUNCTION_LINE_VERBOSE("Patch all functions");
for (auto &cur : gPatchedFunctions) {
PatchFunction(cur);
}
OSMemoryBarrier();
OSDynLoad_AddNotifyCallback(notify_callback, nullptr);
}
}
WUMS_APPLICATION_REQUESTS_EXIT() {
deinitLogging();
}
WUMS_APPLICATION_ENDS() {
gFunctionAddressProvider->resetHandles();
} }
WUMS_EXPORT_FUNCTION(FunctionPatcherPatchFunction); WUMS_EXPORT_FUNCTION(FunctionPatcherPatchFunction);
WUMS_EXPORT_FUNCTION(FunctionPatcherRestoreFunctions); WUMS_EXPORT_FUNCTION(FunctionPatcherRestoreFunction);
WUMS_EXPORT_FUNCTION(FunctionPatcherRestoreDynamicFunctions);

View File

@ -16,27 +16,32 @@
****************************************************************************/ ****************************************************************************/
#pragma once #pragma once
#include "globals.h"
#include "logger.h"
#include <coreinit/thread.h>
#include <cstdint>
#include <malloc.h> #include <malloc.h>
#include <unistd.h> #include <unistd.h>
#include <cstdint>
#include <coreinit/thread.h>
class CThread { class CThread {
public: public:
typedef void (*Callback)(CThread *thread, void *arg); typedef void (*Callback)(CThread *thread, void *arg);
//! constructor //! constructor
CThread(int32_t iAttr, int32_t iPriority = 16, int32_t iStackSize = 0x8000, CThread::Callback callback = NULL, void *callbackArg = NULL) explicit CThread(int32_t iAttr, int32_t iPriority = 16, int32_t stacksize = 0x8000, CThread::Callback callback = nullptr, void *callbackArg = nullptr)
: pThread(NULL), pThreadStack(NULL), pCallback(callback), pCallbackArg(callbackArg) { : pThread(nullptr), pThreadStack(nullptr), pCallback(callback), pCallbackArg(callbackArg) {
//! save attribute assignment //! save attribute assignment
iAttributes = iAttr; iAttributes = iAttr;
//! allocate the thread iStackSize = stacksize;
pThread = (OSThread *) memalign(0x10, sizeof(OSThread)); //! allocate the thread on the default Cafe OS heap
//! allocate the stack pThread = (OSThread *) gMEMAllocFromDefaultHeapExForThreads(sizeof(OSThread), 0x10);
pThreadStack = (uint8_t *) memalign(0x20, iStackSize); //! allocate the stack on the default Cafe OS heap
pThreadStack = (uint8_t *) gMEMAllocFromDefaultHeapExForThreads(iStackSize, 0x20);
//! create the thread //! create the thread
if (pThread && pThreadStack) { if (pThread && pThreadStack) {
OSCreateThread(pThread, (int (*)(int, const char **)) &CThread::threadCallback, 1, (char *) this, (void *) (pThreadStack + iStackSize), iStackSize, iPriority, iAttributes); // clang-format off
OSCreateThread(pThread, (int(*)(int, const char **)) & CThread::threadCallback, 1, (char *) this, (void *) (pThreadStack + iStackSize), iStackSize, iPriority, iAttributes);
// clang-format on
} }
} }
@ -51,35 +56,35 @@ public:
static void runOnAllCores(CThread::Callback callback, void *callbackArg, int32_t iAttr = 0, int32_t iPriority = 16, int32_t iStackSize = 0x8000) { static void runOnAllCores(CThread::Callback callback, void *callbackArg, int32_t iAttr = 0, int32_t iPriority = 16, int32_t iStackSize = 0x8000) {
int32_t aff[] = {CThread::eAttributeAffCore2, CThread::eAttributeAffCore1, CThread::eAttributeAffCore0}; int32_t aff[] = {CThread::eAttributeAffCore2, CThread::eAttributeAffCore1, CThread::eAttributeAffCore0};
for (int i : aff) {
for (uint32_t i = 0; i < (sizeof(aff) / sizeof(aff[0])); i++) { CThread thread(iAttr | i, iPriority, iStackSize, callback, callbackArg);
CThread *thread = CThread::create(callback, callbackArg, iAttr | aff[i], iPriority, iStackSize); thread.resumeThread();
thread->resumeThread();
delete thread;
} }
} }
//! Get thread ID //! Get thread ID
virtual void *getThread() const { [[nodiscard]] virtual void *getThread() const {
return pThread; return pThread;
} }
//! Thread entry function //! Thread entry function
virtual void executeThread(void) { virtual void executeThread() {
if (pCallback) if (pCallback)
pCallback(this, pCallbackArg); pCallback(this, pCallbackArg);
} }
//! Suspend thread //! Suspend thread
virtual void suspendThread(void) { virtual void suspendThread() {
if (isThreadSuspended()) return; if (isThreadSuspended()) return;
if (pThread) OSSuspendThread(pThread); if (pThread) OSSuspendThread(pThread);
} }
//! Resume thread //! Resume thread
virtual void resumeThread(void) { virtual void resumeThread() {
if (!isThreadSuspended()) return; if (!isThreadSuspended()) return;
if (pThread) OSResumeThread(pThread); if (pThread) {
OSResumeThread(pThread);
}
} }
//! Set thread priority //! Set thread priority
@ -88,57 +93,62 @@ public:
} }
//! Check if thread is suspended //! Check if thread is suspended
virtual bool isThreadSuspended(void) const { [[nodiscard]] virtual bool isThreadSuspended() const {
if (pThread) return OSIsThreadSuspended(pThread); if (pThread) return OSIsThreadSuspended(pThread);
return false; return false;
} }
//! Check if thread is terminated //! Check if thread is terminated
virtual bool isThreadTerminated(void) const { [[nodiscard]] virtual bool isThreadTerminated() const {
if (pThread) return OSIsThreadTerminated(pThread); if (pThread) return OSIsThreadTerminated(pThread);
return false; return false;
} }
//! Check if thread is running //! Check if thread is running
virtual bool isThreadRunning(void) const { [[nodiscard]] virtual bool isThreadRunning() const {
return !isThreadSuspended() && !isThreadRunning(); return !isThreadSuspended() && !isThreadRunning();
} }
//! Gets the thread affinity. //! Gets the thread affinity.
virtual uint16_t getThreadAffinity(void) const { [[nodiscard]] virtual uint16_t getThreadAffinity() const {
if (pThread) return OSGetThreadAffinity(pThread); if (pThread) return OSGetThreadAffinity(pThread);
return 0; return 0;
} }
//! Shutdown thread //! Shutdown thread
virtual void shutdownThread(void) { void shutdownThread() {
//! wait for thread to finish //! wait for thread to finish
if (pThread && !(iAttributes & eAttributeDetach)) { if (pThread && !(iAttributes & eAttributeDetach)) {
while (isThreadSuspended()) { while (isThreadSuspended()) {
resumeThread(); resumeThread();
} }
OSJoinThread(pThread, NULL); OSJoinThread(pThread, nullptr);
} }
// Some games (e.g. Minecraft) expect the default heap to be empty.
// Make sure to clean up the memory after using it
//! free the thread stack buffer //! free the thread stack buffer
if (pThreadStack) { if (pThreadStack) {
free(pThreadStack); memset(pThreadStack, 0, iStackSize);
gMEMFreeToDefaultHeapForThreads(pThreadStack);
} }
if (pThread) { if (pThread) {
free(pThread); memset(pThread, 0, sizeof(OSThread));
gMEMFreeToDefaultHeapForThreads(pThread);
} }
pThread = NULL; pThread = nullptr;
pThreadStack = NULL; pThreadStack = nullptr;
} }
//! Thread attributes //! Thread attributes
enum eCThreadAttributes { enum eCThreadAttributes {
eAttributeNone = 0x07, eAttributeNone = 0x07,
eAttributeAffCore0 = 0x01, eAttributeAffCore0 = 0x01,
eAttributeAffCore1 = 0x02, eAttributeAffCore1 = 0x02,
eAttributeAffCore2 = 0x04, eAttributeAffCore2 = 0x04,
eAttributeDetach = 0x08, eAttributeDetach = 0x08,
eAttributePinnedAff = 0x10 eAttributePinnedAff = 0x10
}; };
private: private:
static int32_t threadCallback(int32_t argc, void *arg) { static int32_t threadCallback(int32_t argc, void *arg) {
//! After call to start() continue with the internal function //! After call to start() continue with the internal function
@ -146,6 +156,7 @@ private:
return 0; return 0;
} }
uint32_t iStackSize;
int32_t iAttributes; int32_t iAttributes;
OSThread *pThread; OSThread *pThread;
uint8_t *pThreadStack; uint8_t *pThreadStack;

View File

@ -0,0 +1,94 @@
#include "KernelFindExport.h"
#include <coreinit/cache.h>
#include <elf.h>
#include <kernel/kernel.h>
#include <string_view>
#define KernelGetLoadedRPL ((LOADED_RPL * (*) (uint32_t))(0xfff13524))
#define KernelGetRAMPID ((int32_t(*)(uint32_t *))(0xfff10ea0))
#define KernelSetRAMPID ((uint32_t(*)(uint32_t, uint32_t))(0xfff10cc0))
#define ELF_ST_TYPE(i) ((i) &0xf)
/*
* Based on the findClosestSymbol implementation. See:
* https://github.com/decaf-emu/decaf-emu/blob/e8c9af3057a7d94f6e970406eb1ba1c37c87b4d1/src/libdecaf/src/cafe/kernel/cafe_kernel_loader.cpp#L251
*/
uint32_t FindExportKernel(const char *rplName, const char *functionName) {
if (rplName == nullptr || functionName == nullptr) {
return 0;
}
uint32_t result = 0;
uint32_t currentRamPID;
auto err = KernelGetRAMPID(&currentRamPID);
if (err != -1) {
// Switch to loader address space view.
KernelSetRAMPID(err, 2);
for (auto rpl = KernelGetLoadedRPL(0); rpl != nullptr; rpl = rpl->nextLoadedRpl) {
if (std::string_view(rpl->moduleNameBuffer) != rplName) {
continue;
}
uint32_t textSectionIndex = 0xFFFFFFFF;
for (auto i = 0u; i < rpl->elfHeader.shnum; ++i) {
auto sectionAddress = rpl->sectionAddressBuffer[i];
if (!sectionAddress) {
continue;
}
auto sectionHeader = (ElfSectionHeader *) (((uint32_t) (rpl->sectionHeaderBuffer)) + rpl->elfHeader.shentsize * i);
if (auto shstrndx = rpl->elfHeader.shstrndx) {
auto shStrSection = (char *) (rpl->sectionAddressBuffer[shstrndx]);
auto sectionName = (shStrSection + sectionHeader->name);
if (std::string_view(sectionName) == ".text") {
textSectionIndex = i;
}
}
}
for (auto i = 0u; i < rpl->elfHeader.shnum; ++i) {
auto sectionAddress = rpl->sectionAddressBuffer[i];
if (!sectionAddress) {
continue;
}
auto sectionHeader = (ElfSectionHeader *) (((uint32_t) (rpl->sectionHeaderBuffer)) + rpl->elfHeader.shentsize * i);
if (sectionHeader->type == SHT_SYMTAB) {
auto strTab = rpl->sectionAddressBuffer[sectionHeader->link];
auto symTabEntSize = sectionHeader->entsize ? static_cast<uint32_t>(sectionHeader->entsize) : sizeof(ElfSymbol);
auto numSymbols = sectionHeader->size / symTabEntSize;
bool found = false;
for (auto j = 0u; j < numSymbols; ++j) {
auto symbol = (ElfSymbol *) (sectionAddress + j * symTabEntSize);
if (symbol->shndx == textSectionIndex && ELF_ST_TYPE(symbol->info) == STT_FUNC) {
auto symbolName = (const char *) (strTab + symbol->name);
if (std::string_view(symbolName) == functionName) {
result = symbol->value;
found = true;
break;
}
}
}
if (found) {
break;
}
}
}
break;
}
// Switch back to "old" space address view
KernelSetRAMPID(err, currentRamPID);
}
return result;
}
extern "C" uint32_t SC_0x51(const char *rplname, const char *functionName);
uint32_t KernelFindExport(const std::string_view &rplName, const std::string_view &functionName) {
KernelPatchSyscall(0x51, (uint32_t) &FindExportKernel);
OSMemoryBarrier();
if (rplName.ends_with(".rpx") || rplName.ends_with(".rpl")) {
auto pureRPLName = std::string(rplName).substr(0, rplName.length() - 4);
return SC_0x51(pureRPLName.c_str(), functionName.data());
}
return SC_0x51(rplName.data(), functionName.data());
}

View File

@ -0,0 +1,151 @@
#pragma once
#include <cstdint>
#include <string>
#include <wut.h>
/*
* https://github.com/decaf-emu/decaf-emu/blob/e8c9af3057a7d94f6e970406eb1ba1c37c87b4d1/src/libdecaf/src/cafe/loader/cafe_loader_rpl.h#L150
*/
struct ElfHeader {
uint8_t magic[4]; // File identification.
uint8_t fileClass; // File class.
uint8_t encoding; // Data encoding.
uint8_t elfVersion; // File version.
uint8_t abi; // OS/ABI identification.
uint8_t abiVersion; // OS/ABI version.
uint8_t pad[7];
uint16_t type; // Type of file (ET_*)
uint16_t machine; // Required architecture for this file (EM_*)
uint32_t version; // Must be equal to 1
uint32_t entry; // Address to jump to in order to start program
uint32_t phoff; // Program header table's file offset, in bytes
uint32_t shoff; // Section header table's file offset, in bytes
uint32_t flags; // Processor-specific flags
uint16_t ehsize; // Size of ELF header, in bytes
uint16_t phentsize; // Size of an entry in the program header table
uint16_t phnum; // Number of entries in the program header table
uint16_t shentsize; // Size of an entry in the section header table
uint16_t shnum; // Number of entries in the section header table
uint16_t shstrndx; // Sect hdr table index of sect name string table
};
WUT_CHECK_OFFSET(ElfHeader, 0x00, magic);
WUT_CHECK_OFFSET(ElfHeader, 0x04, fileClass);
WUT_CHECK_OFFSET(ElfHeader, 0x05, encoding);
WUT_CHECK_OFFSET(ElfHeader, 0x06, elfVersion);
WUT_CHECK_OFFSET(ElfHeader, 0x07, abi);
WUT_CHECK_OFFSET(ElfHeader, 0x08, abiVersion);
WUT_CHECK_OFFSET(ElfHeader, 0x10, type);
WUT_CHECK_OFFSET(ElfHeader, 0x12, machine);
WUT_CHECK_OFFSET(ElfHeader, 0x14, version);
WUT_CHECK_OFFSET(ElfHeader, 0x18, entry);
WUT_CHECK_OFFSET(ElfHeader, 0x1C, phoff);
WUT_CHECK_OFFSET(ElfHeader, 0x20, shoff);
WUT_CHECK_OFFSET(ElfHeader, 0x24, flags);
WUT_CHECK_OFFSET(ElfHeader, 0x28, ehsize);
WUT_CHECK_OFFSET(ElfHeader, 0x2A, phentsize);
WUT_CHECK_OFFSET(ElfHeader, 0x2C, phnum);
WUT_CHECK_OFFSET(ElfHeader, 0x2E, shentsize);
WUT_CHECK_OFFSET(ElfHeader, 0x30, shnum);
WUT_CHECK_OFFSET(ElfHeader, 0x32, shstrndx);
WUT_CHECK_SIZE(ElfHeader, 0x34);
/*
* https://github.com/decaf-emu/decaf-emu/blob/e8c9af3057a7d94f6e970406eb1ba1c37c87b4d1/src/libdecaf/src/cafe/loader/cafe_loader_rpl.h#L216
*/
struct ElfSectionHeader {
//! Section name (index into string table)
uint32_t name;
//! Section type (SHT_*)
uint32_t type;
//! Section flags (SHF_*)
uint32_t flags;
//! Address where section is to be loaded
uint32_t addr;
//! File offset of section data, in bytes
uint32_t offset;
//! Size of section, in bytes
uint32_t size;
//! Section type-specific header table index link
uint32_t link;
//! Section type-specific extra information
uint32_t info;
//! Section address alignment
uint32_t addralign;
//! Size of records contained within the section
uint32_t entsize;
};
WUT_CHECK_OFFSET(ElfSectionHeader, 0x00, name);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x04, type);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x08, flags);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x0C, addr);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x10, offset);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x14, size);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x18, link);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x1C, info);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x20, addralign);
WUT_CHECK_OFFSET(ElfSectionHeader, 0x24, entsize);
WUT_CHECK_SIZE(ElfSectionHeader, 0x28);
/*
* https://github.com/decaf-emu/decaf-emu/blob/e8c9af3057a7d94f6e970406eb1ba1c37c87b4d1/src/libdecaf/src/cafe/loader/cafe_loader_rpl.h#L260
*/
struct ElfSymbol {
//! Symbol name (index into string table)
uint32_t name;
//! Value or address associated with the symbol
uint32_t value;
//! Size of the symbol
uint32_t size;
//! Symbol's type and binding attributes
uint8_t info;
//! Must be zero; reserved
uint8_t other;
//! Which section (header table index) it's defined in (SHN_*)
uint16_t shndx;
};
WUT_CHECK_OFFSET(ElfSymbol, 0x00, name);
WUT_CHECK_OFFSET(ElfSymbol, 0x04, value);
WUT_CHECK_OFFSET(ElfSymbol, 0x08, size);
WUT_CHECK_OFFSET(ElfSymbol, 0x0C, info);
WUT_CHECK_OFFSET(ElfSymbol, 0x0D, other);
WUT_CHECK_OFFSET(ElfSymbol, 0x0E, shndx);
WUT_CHECK_SIZE(ElfSymbol, 0x10);
/*
* https://github.com/decaf-emu/decaf-emu/blob/6feb1be1db3938e6da2d4a65fc0a7a8599fc8dd6/src/libdecaf/src/cafe/loader/cafe_loader_loaded_rpl.h#L26
*/
struct LOADED_RPL {
WUT_UNKNOWN_BYTES(0x08);
char *moduleNameBuffer;
WUT_UNKNOWN_BYTES(0x10);
ElfHeader elfHeader;
void *sectionHeaderBuffer;
WUT_UNKNOWN_BYTES(0xA0);
uint32_t *sectionAddressBuffer;
WUT_UNKNOWN_BYTES(0x1C);
LOADED_RPL *nextLoadedRpl;
};
WUT_CHECK_OFFSET(LOADED_RPL, 0x08, moduleNameBuffer);
WUT_CHECK_OFFSET(LOADED_RPL, 0x1C, elfHeader);
WUT_CHECK_OFFSET(LOADED_RPL, 0x50, sectionHeaderBuffer);
WUT_CHECK_OFFSET(LOADED_RPL, 0xF4, sectionAddressBuffer);
WUT_CHECK_OFFSET(LOADED_RPL, 0x114, nextLoadedRpl);
WUT_CHECK_SIZE(LOADED_RPL, 0x118);
uint32_t KernelFindExport(const std::string_view &rplName, const std::string_view &functioName);

11
source/utils/globals.cpp Normal file
View File

@ -0,0 +1,11 @@
#include "globals.h"
char gJumpHeapData[JUMP_HEAP_DATA_SIZE] __attribute__((section(".data")));
MEMHeapHandle gJumpHeapHandle __attribute__((section(".data")));
std::shared_ptr<FunctionAddressProvider> gFunctionAddressProvider;
std::mutex gPatchedFunctionsMutex;
std::vector<std::shared_ptr<PatchedFunctionData>> gPatchedFunctions;
void *(*gMEMAllocFromDefaultHeapExForThreads)(uint32_t size, int align);
void (*gMEMFreeToDefaultHeapForThreads)(void *ptr);

20
source/utils/globals.h Normal file
View File

@ -0,0 +1,20 @@
#pragma once
#include "../PatchedFunctionData.h"
#include "version.h"
#include <coreinit/memheap.h>
#include <memory>
#include <vector>
#define MODULE_VERSION "v0.2.3"
#define MODULE_VERSION_FULL MODULE_VERSION MODULE_VERSION_EXTRA
#define JUMP_HEAP_DATA_SIZE (32 * 1024)
extern char gJumpHeapData[];
extern MEMHeapHandle gJumpHeapHandle;
extern std::shared_ptr<FunctionAddressProvider> gFunctionAddressProvider;
extern std::mutex gPatchedFunctionsMutex;
extern std::vector<std::shared_ptr<PatchedFunctionData>> gPatchedFunctions;
extern void *(*gMEMAllocFromDefaultHeapExForThreads)(uint32_t size, int align);
extern void (*gMEMFreeToDefaultHeapForThreads)(void *ptr);

36
source/utils/logger.c Normal file
View File

@ -0,0 +1,36 @@
#ifdef DEBUG
#include <stdint.h>
#include <whb/log_cafe.h>
#include <whb/log_module.h>
#include <whb/log_udp.h>
uint32_t moduleLogInit = false;
uint32_t cafeLogInit = false;
uint32_t udpLogInit = false;
#endif // DEBUG
void initLogging() {
#ifdef DEBUG
if (!(moduleLogInit = WHBLogModuleInit())) {
cafeLogInit = WHBLogCafeInit();
udpLogInit = WHBLogUdpInit();
}
#endif // DEBUG
}
void deinitLogging() {
#ifdef DEBUG
if (moduleLogInit) {
WHBLogModuleDeinit();
moduleLogInit = false;
}
if (cafeLogInit) {
WHBLogCafeDeinit();
cafeLogInit = false;
}
if (udpLogInit) {
WHBLogUdpDeinit();
udpLogInit = false;
}
#endif // DEBUG
}

68
source/utils/logger.h Normal file
View File

@ -0,0 +1,68 @@
#pragma once
#include <coreinit/debug.h>
#include <string.h>
#include <whb/log.h>
#ifdef __cplusplus
extern "C" {
#endif
#define LOG_APP_TYPE "M"
#define LOG_APP_NAME "function_patcher"
#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__)
#define LOG(LOG_FUNC, FMT, ARGS...) LOG_EX_DEFAULT(LOG_FUNC, "", "", FMT, ##ARGS)
#define LOG_EX_DEFAULT(LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) LOG_EX(__FILENAME__, __FUNCTION__, __LINE__, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ##ARGS)
#define LOG_EX(FILENAME, FUNCTION, LINE, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) \
do { \
LOG_FUNC("[(%s)%18s][%23s]%30s@L%04d: " LOG_LEVEL "" FMT "" LINE_END, LOG_APP_TYPE, LOG_APP_NAME, FILENAME, FUNCTION, LINE, ##ARGS); \
} while (0)
#ifdef DEBUG
#ifdef VERBOSE_DEBUG
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "", "", FMT, ##ARGS);
#else
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0)
#endif
#define DEBUG_FUNCTION_LINE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "## WARN## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS);
#else
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##ERROR## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "## WARN## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, OSReport, "##ERROR## ", "\n", FMT, ##ARGS);
#endif
void initLogging();
void deinitLogging();
#ifdef __cplusplus
}
#endif

5
source/utils/syscall.s Normal file
View File

@ -0,0 +1,5 @@
.global SC_0x51
SC_0x51:
li %r0, 0x5100
sc
blr

28
source/utils/utils.cpp Normal file
View File

@ -0,0 +1,28 @@
#include <coreinit/cache.h>
#include <coreinit/memorymap.h>
#include <kernel/kernel.h>
bool ReadFromPhysicalAddress(uint32_t srcPhys, uint32_t *out) {
if (!out) {
return false;
}
// Check if patched instruction is still loaded.
volatile uint32_t currentInstruction;
auto currentInstructionAddress = (uint32_t) &currentInstruction;
uint32_t currentInstructionAddressPhys;
if (currentInstructionAddress < 0x00800000 || currentInstructionAddress >= 0x01000000) {
currentInstructionAddressPhys = (uint32_t) OSEffectiveToPhysical(currentInstructionAddress);
} else {
currentInstructionAddressPhys = currentInstructionAddress + 0x30800000 - 0x00800000;
}
if (currentInstructionAddressPhys == 0) {
return false;
}
// Save the instruction we will replace.
KernelCopyData(currentInstructionAddressPhys, srcPhys, 4);
DCFlushRange((void *) &currentInstruction, 4);
*out = currentInstruction;
return true;
}

14
source/utils/utils.h Normal file
View File

@ -0,0 +1,14 @@
#pragma once
#include <memory>
template<class T, class... Args>
std::unique_ptr<T> make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
template<class T, class... Args>
std::shared_ptr<T> make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
bool ReadFromPhysicalAddress(uint32_t srcPhys, uint32_t *out);

2
source/version.h Normal file
View File

@ -0,0 +1,2 @@
#pragma once
#define MODULE_VERSION_EXTRA ""