Compare commits

...

65 Commits

Author SHA1 Message Date
dependabot[bot]
d8ce4bc7e6 Bump wiiu-env/devkitppc from 20240423 to 20240505
Bumps wiiu-env/devkitppc from 20240423 to 20240505.

---
updated-dependencies:
- dependency-name: wiiu-env/devkitppc
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-06 10:20:01 +02:00
Maschell
86c1d20863 Remove allocMutex to avoid possible deadlocks 2024-05-03 22:33:18 +02:00
Maschell
bf99541449 Use custom function to check exp heap 2024-04-26 23:42:38 +02:00
dependabot[bot]
cca22cabfb Bump softprops/action-gh-release from 1 to 2
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-25 12:02:28 +02:00
Maschell
d76afc5673 Fix compiling with latest wut version 2024-04-25 12:02:28 +02:00
Maschell
8ae558e3ac Update Dockerfile 2024-04-25 12:02:28 +02:00
Maschell
0b8bb8668e Bump version to 0.2.6 2024-04-25 12:02:28 +02:00
dependabot[bot]
622ce1ef9d 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>
2024-04-25 12:02:28 +02:00
dependabot[bot]
60736e65c6 Bump wiiu-env/devkitppc from 20230621 to 20231112
Bumps wiiu-env/devkitppc from 20230621 to 20231112.

---
updated-dependencies:
- dependency-name: wiiu-env/devkitppc
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-25 12:02:28 +02:00
Maschell
8e53c22f2c Make sure we can execute code on all three cores, check heaps on application end 2024-04-25 12:02:28 +02:00
Maschell
5f249475c3 Allow logging in init hook 2024-04-25 12:02:28 +02:00
Maschell
4a386d59aa Create dependabot.yml 2023-07-23 10:16:44 +02:00
Maschell
a46f438db2 Bump version 2023-07-19 19:10:58 +02:00
Maschell
7f5fa7708c Update Dockerfile 2023-07-19 16:18:44 +02:00
Maschell
f902d649f1 Update Dockerfile 2023-07-06 16:01:03 +02:00
Maschell
887389f622 Add *.zip to .gitignore 2023-07-06 16:01:03 +02:00
Maschell
88cf0f2317 Change default branch to main 2023-03-28 20:45:25 +02:00
Maschell
09ca5144dd Update main.cpp 2023-03-28 20:35:30 +02:00
Maschell
f9b2bcd660 Allocate the page table on the heap to avoid a stack overflow 2023-03-27 18:22:05 +02:00
Maschell
f2333e37dc Use the default heap for threads, make sure to memset default heap allocations to 0 after using them 2023-03-26 16:03:34 +02:00
Maschell
6076c8726c Bump version 2023-03-23 14:59:44 +01:00
Maschell
f5267091da Avoid memory for mapping which is used when joining a game via friend list 2023-03-21 23:06:25 +01:00
Maschell
34195f9ffb Change docker registry to ghcr.io 2023-03-16 15:29:35 +01:00
Maschell
412b38be4c Bump Version 2023-02-19 19:18:44 +01:00
Maschell
d9457e8cdc Implement KiValidateUserDataRange and KiValidateUserCodeRange hook 2023-02-17 08:17:21 +01:00
Maschell
3a8d8a979c Fix KiGetOrPutUserData 2023-02-17 08:17:21 +01:00
Maschell
88de314828 Bump version to 0.2.1 2023-01-10 18:25:43 +01:00
Maschell
69b2ed5905 Use WUMS 0.3.2 2023-01-10 18:25:43 +01:00
Maschell
d3f874ed2e Use latest version of libfunctionpatcher 2023-01-06 16:02:58 +01:00
Maschell
77360e935d Update the CI to use a non-deprecated release action 2023-01-06 16:02:58 +01:00
Maschell
167881c357 Update CI to use actions/checkout@v3 2023-01-06 16:02:58 +01:00
Maschell
9bf4b02952 Update version to v0.2 2022-10-09 14:32:17 +02:00
Maschell
b69ddc1610 Update Makefile to support CLion 2022-10-09 14:32:17 +02:00
Maschell
8db58d3b32 Improve release description of nightlies 2022-10-09 14:32:17 +02:00
Maschell
4da0dd9e3f Log the module version on each application start 2022-10-09 14:32:17 +02:00
Maschell
d3629321e1 Update sCheckDataRange to support 0x00800000 - 0x010000000 memory region 2022-10-03 21:42:51 +02:00
Maschell
b66266af54 Patch LiValidateAddress to support OSDynLoad_SetAllocator with our region 2022-10-03 21:42:51 +02:00
Maschell
f80ddb450e Use ubuntu-22.04 in CI 2022-09-04 20:20:47 +02:00
Maschell
2a416d6510 Add Dockerfile 2022-09-04 20:20:47 +02:00
Maschell
83da715e63 Add LICENSE 2022-09-04 20:20:47 +02:00
Maschell
f7fd2b2969 Update Dockerfile to use latest wut version 2022-07-25 13:17:20 -07:00
Maschell
9c939fd819 Update Dockerfile to use latest WUMS version 2022-05-13 00:28:50 +02:00
Maschell
2e63108b5f format code 2022-05-09 19:34:19 +02:00
Maschell
13f27137eb Update the Dockerfile 2022-05-09 19:34:19 +02:00
Maschell
7bb906f83f Improve logging and resolve any compiler warnings 2022-05-09 19:34:19 +02:00
Maschell
59300aad22 Use latest version of libfunctionpatcher 2022-05-09 19:34:19 +02:00
Maschell
93fb8f7d84 Implement generic SR patching and generic sCheckDataRange replacement 2022-04-29 10:04:24 +02:00
Maschell
9a6b924aeb Fix negative alignments 2022-02-13 13:41:39 +01:00
Maschell
8203e92a2b Implement support for MEMFindContainHeap when using mapped memory 2022-02-13 13:41:39 +01:00
Maschell
79787e7dce The allocated size is now always an integral multiple of alignment. 2022-02-13 13:41:39 +01:00
Maschell
f513e1a374 Round up the size of the allocated memory to avoid heap corruption 2022-02-11 20:38:46 +01:00
Maschell
cd56a105e3 Add memory barrier to ensure memory coherence 2022-02-11 20:38:46 +01:00
Maschell
9e424205e0 Guard heap access with OSMutex 2022-02-11 20:38:46 +01:00
Maschell
f56e6938be Nop out additional branches to app panics 2022-02-11 20:33:27 +01:00
Maschell
bf67d7e029
Merge pull request #2 from wiiu-env/update_clang_format [no ci]
Update .clang-format to update the comment, macro and assignment form…
2022-02-03 15:53:29 +01:00
Maschell
cd18ab16a6 Update .clang-format to update the comment, macro and assignment formatting 2022-02-03 15:51:47 +01:00
Maschell
6db316c682 Use clang-format to format the code 2022-02-02 18:34:27 +01:00
Maschell
07259a4f01 Change the layout of the release .zip 2022-01-30 17:01:47 +01:00
Maschell
0c4381244c Fix building with make DEBUG=1 2022-01-30 13:40:09 +01:00
Maschell
5033473292 Formatting 2022-01-26 13:25:28 +01:00
Maschell
fcba5a9f1c Implement logging, but only when built with make DEBUG=1 2022-01-26 13:24:56 +01:00
Maschell
833a37e0cf WUMS 0.3.1 support 2022-01-26 13:21:07 +01:00
Maschell
88f4e0af29 Reduce the filesize by avoid "new" and any exceptions 2022-01-21 19:52:35 +01:00
Maschell
11d467e1c9 [CI] Fix the asset content type 2022-01-21 19:51:17 +01:00
Maschell
21e39fb642 Trust in CafeOS to figure it out 2021-12-15 17:01:36 +01:00
21 changed files with 1587 additions and 229 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:
push:
branches:
- master
- main
jobs:
build-binary:
runs-on: ubuntu-18.04
clang-format:
runs-on: ubuntu-22.04
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 VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary
run: |
docker build . -t builder
@ -20,7 +35,7 @@ jobs:
path: "*.wms"
deploy-binary:
needs: build-binary
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
steps:
- name: Get environment variables
id: get_repository_name
@ -30,29 +45,15 @@ jobs:
- uses: actions/download-artifact@master
with:
name: binary
path: wiiu/modules
- 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
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
uses: "softprops/action-gh-release@v2"
with:
tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
release_name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
draft: false
draft: falsee
prerelease: true
body: |
Not a stable release:
${{ github.event.head_commit.message }}
- name: Upload Release Asset
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
generate_release_notes: true
name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
files: |
./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip

View File

@ -3,10 +3,36 @@ name: CI-PR
on: [pull_request]
jobs:
build-binary:
runs-on: ubuntu-18.04
clang-format:
runs-on: ubuntu-22.04
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 VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary
run: |
docker build . -t builder

1
.gitignore vendored
View File

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

View File

@ -1,7 +1,7 @@
FROM wiiuenv/devkitppc:20211106
FROM ghcr.io/wiiu-env/devkitppc:20240505
COPY --from=wiiuenv/libkernel:20211031 /artifacts $DEVKITPRO
COPY --from=wiiuenv/libfunctionpatcher:20210924 /artifacts $DEVKITPRO
COPY --from=wiiuenv/wiiumodulesystem:20211207 /artifacts $DEVKITPRO
COPY --from=ghcr.io/wiiu-env/libkernel:20230621 /artifacts $DEVKITPRO
COPY --from=ghcr.io/wiiu-env/libfunctionpatcher:20230621 /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

@ -28,15 +28,25 @@ INCLUDES := source
#-------------------------------------------------------------------------------
# options for code generation
#-------------------------------------------------------------------------------
CFLAGS := -g -Wall -O2 -ffunction-sections\
CFLAGS := -Wall -O2 -ffunction-sections\
$(MACHDEP)
CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CXXFLAGS := $(CFLAGS) -std=c++17
CXXFLAGS := $(CFLAGS) -std=c++17 -fno-exceptions -fno-rtti
ASFLAGS := -g $(ARCH)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libkernel.ld -T$(WUMS_ROOT)/share/libfunctionpatcher.ld $(WUMSSPECS)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libkernel.ld -Tfunctionpatcher.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 -lfunctionpatcher
@ -64,6 +74,7 @@ export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
DEFFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.def)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#-------------------------------------------------------------------------------
@ -81,7 +92,7 @@ endif
#-------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES_SRC := $(DEFFILES:.def=.o) $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
@ -97,7 +108,7 @@ export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD))
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#-------------------------------------------------------------------------------
@ -128,7 +139,11 @@ $(OFILES_SRC) : $(HFILES_BIN)
#-------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
#---------------------------------------------------------------------------------
%.o: %.def
$(SILENTMSG) $(notdir $<)
$(SILENTCMD)rplimportgen $< $*.s $*.ld $(ERROR_FILTER)
$(SILENTCMD)$(CC) -x assembler-with-cpp $(ASFLAGS) -c $*.s -o $@ $(ERROR_FILTER)
#---------------------------------------------------------------------------------
%.o: %.s
@echo $(notdir $<)

View File

@ -1,4 +1,17 @@
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.
## Usage
(`[ENVIRONMENT]` is a placeholder for the actual environment name.)
1. Copy the file `MemoryMappingModule.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).
## Building using the Dockerfile
@ -13,4 +26,7 @@ docker run -it --rm -v ${PWD}:/project memorymappingmodule-builder make
# make clean
docker run -it --rm -v ${PWD}:/project memorymappingmodule-builder make clean
```
```
## Format the code via docker
`docker run --rm -it -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./source -i`

View File

@ -16,27 +16,32 @@
****************************************************************************/
#pragma once
#include "globals.h"
#include <coreinit/thread.h>
#include <cstdint>
#include <cstring>
#include <malloc.h>
#include <unistd.h>
#include <cstdint>
#include <coreinit/thread.h>
class CThread {
public:
typedef void (*Callback)(CThread *thread, void *arg);
//! constructor
explicit CThread(int32_t iAttr, int32_t iPriority = 16, int32_t iStackSize = 0x8000, CThread::Callback callback = nullptr, void *callbackArg = nullptr)
: pThread(nullptr), pThreadStack(nullptr), pCallback(callback), pCallbackArg(callbackArg) {
explicit CThread(int32_t iAttr, int32_t iPriority = 16, int32_t stacksize = 0x8000, CThread::Callback callback = nullptr, void *callbackArg = nullptr)
: pThread(nullptr), pThreadStack(nullptr), pCallback(callback), pCallbackArg(callbackArg) {
//! save attribute assignment
iAttributes = iAttr;
//! allocate the thread
pThread = (OSThread *) memalign(8, 0x1000);
//! allocate the stack
pThreadStack = (uint8_t *) memalign(0x20, iStackSize);
iStackSize = stacksize;
//! allocate the thread on the default Cafe OS heap
pThread = (OSThread *) gMEMAllocFromDefaultHeapExForThreads(sizeof(OSThread), 0x10);
//! allocate the stack on the default Cafe OS heap
pThreadStack = (uint8_t *) gMEMAllocFromDefaultHeapExForThreads(iStackSize, 0x20);
//! create the thread
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
}
}
@ -69,7 +74,9 @@ public:
//! Resume thread
virtual void resumeThread() {
if (!isThreadSuspended()) return;
if (pThread) OSResumeThread(pThread);
if (pThread) {
OSResumeThread(pThread);
}
}
//! Set thread priority
@ -109,26 +116,31 @@ public:
}
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
if (pThreadStack) {
free(pThreadStack);
memset(pThreadStack, 0, iStackSize);
gMEMFreeToDefaultHeapForThreads(pThreadStack);
}
if (pThread) {
free(pThread);
memset(pThread, 0, sizeof(OSThread));
gMEMFreeToDefaultHeapForThreads(pThread);
}
pThread = nullptr;
pThread = nullptr;
pThreadStack = nullptr;
}
//! Thread attributes
enum eCThreadAttributes {
eAttributeNone = 0x07,
eAttributeAffCore0 = 0x01,
eAttributeAffCore1 = 0x02,
eAttributeAffCore2 = 0x04,
eAttributeDetach = 0x08,
eAttributeNone = 0x07,
eAttributeAffCore0 = 0x01,
eAttributeAffCore1 = 0x02,
eAttributeAffCore2 = 0x04,
eAttributeDetach = 0x08,
eAttributePinnedAff = 0x10
};
private:
static int32_t threadCallback(int32_t argc, void *arg) {
//! After call to start() continue with the internal function
@ -136,6 +148,7 @@ private:
return 0;
}
uint32_t iStackSize;
int32_t iAttributes;
OSThread *pThread;
uint8_t *pThreadStack;

View File

@ -1,7 +1,6 @@
#include "function_replacements.h"
#include "memory_mapping.h"
#include <coreinit/memheap.h>
DECL_FUNCTION(uint32_t, KiEffectiveToPhysical, uint32_t addressSpace, uint32_t virtualAddress) {
uint32_t result = real_KiEffectiveToPhysical(addressSpace, virtualAddress);
@ -11,8 +10,25 @@ DECL_FUNCTION(uint32_t, KiEffectiveToPhysical, uint32_t addressSpace, uint32_t v
return result;
}
DECL_FUNCTION(int32_t, KiValidateUserDataRange, uint32_t address, uint32_t size) {
if ((address >= 0x00800000 && address < 0x01000000) || (address & 0xF0000000) == (MEMORY_START_BASE & 0xF0000000)) {
return 1;
}
return real_KiValidateUserDataRange(address, size);
}
DECL_FUNCTION(int32_t, KiValidateUserCodeRange, uint32_t address, uint32_t size) {
if ((address >= 0x00800000 && address < 0x01000000) || (address & 0xF0000000) == (MEMORY_START_BASE & 0xF0000000)) {
return 1;
}
return real_KiValidateUserCodeRange(address, size);
}
DECL_FUNCTION(int32_t, sCheckDataRange, uint32_t address, uint32_t maxDataSize) {
if ((address & 0xF0000000) == 0x80000000) {
if ((address >= 0x00800000 && address < 0x01000000) || (address & 0xF0000000) == (MEMORY_START_BASE & 0xF0000000)) {
return 1;
}
@ -31,7 +47,6 @@ DECL_FUNCTION(uint32_t, KiPhysicalToEffectiveUncached, uint32_t addressSpace, ui
uint32_t result = real_KiPhysicalToEffectiveUncached(addressSpace, virtualAddress);
if (result == 0) {
return MemoryMapping_PhysicalToEffective(virtualAddress);
}
return result;
}
@ -53,31 +68,66 @@ DECL_FUNCTION(uint32_t, KiIsEffectiveRangeValid, uint32_t addressSpace, uint32_t
return result;
}
#define k_memcpy ((void (*)( void*, void*,uint32_t))(0xfff09e44))
// clang-format off
#define k_memcpy ((void(*)(void *, void *, uint32_t))(0xfff09e44))
// clang-format on
DECL_FUNCTION(uint32_t, KiGetOrPutUserData, void *src, uint32_t size, void *dst, bool isRead) {
//
if (isRead && MemoryMapping_EffectiveToPhysical((uint32_t) src) > 0) {
k_memcpy(dst, src, size);
return 1;
} else if (!isRead && MemoryMapping_EffectiveToPhysical((uint32_t) dst) > 0) {
// src and dst are swapped here
k_memcpy(src, dst, size);
if (real_KiGetOrPutUserData(src, size, dst, isRead)) {
return 1;
}
return real_KiGetOrPutUserData(src, size, dst, isRead);
// check if the src (src is the destication for writes) buffer is valid
if (MemoryMapping_EffectiveToPhysical((uint32_t) src) == 0) {
return 0;
}
if (isRead) {
k_memcpy(dst, src, size);
} else if (!isRead && MemoryMapping_EffectiveToPhysical((uint32_t) src) > 0) {
// src and dst are swapped here
k_memcpy(src, dst, size);
}
return 1;
}
DECL_FUNCTION(MEMHeapHandle, MEMFindContainHeap, void *block) {
auto result = MemoryMapping_MEMFindContainHeap(block);
if (result == nullptr) {
return real_MEMFindContainHeap(block);
}
return result;
}
DECL_FUNCTION(int32_t, LiValidateAddress, void *ptr,
uint32_t size,
uint32_t alignMask,
int32_t errorCode,
void *minAddr,
void *maxAddr,
const char *name) {
if (((uint32_t) ptr >= 0x00800000 && (uint32_t) ptr < 0x01000000) || ((uint32_t) ptr & 0xF0000000) == (MEMORY_START_BASE & 0xF0000000)) {
return 0;
}
return real_LiValidateAddress(ptr, size, alignMask, errorCode, minAddr, maxAddr, name);
}
// clang-format off
function_replacement_data_t function_replacements[] __attribute__((section(".data"))) = {
REPLACE_FUNCTION_VIA_ADDRESS(LiValidateAddress, 0x32008904, 0x01008904),
REPLACE_FUNCTION_VIA_ADDRESS(sCheckDataRange, 0x3200cf60, 0x0100cf60),
REPLACE_FUNCTION_VIA_ADDRESS(KiEffectiveToPhysical, 0xffee0aac, 0xffee0aac),
REPLACE_FUNCTION_VIA_ADDRESS(KiPhysicalToEffectiveCached, 0xffee0a3c, 0xffee0a3c),
REPLACE_FUNCTION_VIA_ADDRESS(KiPhysicalToEffectiveUncached, 0xffee0a80, 0xffee0a80),
REPLACE_FUNCTION_VIA_ADDRESS(KiIsEffectiveRangeValid, 0xffee0d6c, 0xffee0d6c),
REPLACE_FUNCTION_VIA_ADDRESS(IPCKDriver_ValidatePhysicalAddress, 0xfff0cb5c, 0xfff0cb5c),
REPLACE_FUNCTION_VIA_ADDRESS(KiValidateUserDataRange, 0xffee10cc, 0xffee10cc),
REPLACE_FUNCTION_VIA_ADDRESS(KiValidateUserCodeRange, 0xffee1074, 0xffee1074),
REPLACE_FUNCTION_VIA_ADDRESS(KiGetOrPutUserData, 0xffee0794, 0xffee0794),
REPLACE_FUNCTION(MEMFindContainHeap, LIBRARY_COREINIT, MEMFindContainHeap),
};
// clang-format on
uint32_t function_replacements_size __attribute__((section(".data"))) = sizeof(function_replacements) / sizeof(function_replacement_data_t);

View File

@ -1,7 +1,7 @@
#pragma once
#include <function_patcher/function_patching.h>
#include <cstdint>
#include <function_patcher/function_patching.h>
extern function_replacement_data_t function_replacements[] __attribute__((section(".data")));

View File

@ -0,0 +1,4 @@
:NAME homebrew_functionpatcher
:TEXT
FPAddFunctionPatch

4
source/globals.c Normal file
View File

@ -0,0 +1,4 @@
#include "globals.h"
void *(*gMEMAllocFromDefaultHeapExForThreads)(uint32_t size, int align);
void (*gMEMFreeToDefaultHeapForThreads)(void *ptr);

5
source/globals.h Normal file
View File

@ -0,0 +1,5 @@
#pragma once
#include <stdint.h>
extern void *(*gMEMAllocFromDefaultHeapExForThreads)(uint32_t size, int align);
extern void (*gMEMFreeToDefaultHeapForThreads)(void *ptr);

36
source/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
}

View File

@ -1,29 +1,66 @@
#pragma once
#include <coreinit/debug.h>
#include <string.h>
#include <whb/log.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include <whb/log.h>
#define LOG_APP_TYPE "M"
#define LOG_APP_NAME "memory_mapping"
#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__)
#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); \
#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)
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while(0)
#ifdef DEBUG
#define DEBUG_FUNCTION_LINE(FMT, ARGS...)do { \
WHBLogPrintf("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0)
#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_WRITE(FMT, ARGS...)do { \
WHBLogWritef("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0);
#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_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_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
#endif

View File

@ -1,28 +1,108 @@
#include <wums.h>
#include <whb/log.h>
#include <whb/log_udp.h>
#include <coreinit/memexpheap.h>
#include "memory_mapping.h"
#include <function_patcher/function_patching.h>
#include "logger.h"
#include "function_replacements.h"
#include "globals.h"
#include "logger.h"
#include "memory_mapping.h"
#include "version.h"
#include <coreinit/debug.h>
#include <function_patcher/function_patching.h>
#include <wums.h>
#ifdef DEBUG
#include "logger.h"
#endif
#define VERSION "v0.2.6"
WUMS_MODULE_EXPORT_NAME("homebrew_memorymapping");
WUMS_MODULE_SKIP_ENTRYPOINT();
WUMS_MODULE_SKIP_INIT_FINI();
WUMS_MODULE_INIT_BEFORE_RELOCATION_DONE_HOOK();
WUMS_DEPENDS_ON(homebrew_kernel);
WUMS_DEPENDS_ON(homebrew_functionpatcher);
#include <coreinit/dynload.h>
#include <coreinit/memdefaultheap.h>
// We can't use the functions from libfunctionpatcher. Defined in functionpatcher.def
extern "C" FunctionPatcherStatus FPAddFunctionPatch(function_replacement_data_t *function_data, PatchedFunctionHandle *outHandle, bool *outHasBeenPatched);
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("MemoryMappingModule: 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("MemoryMappingModule: OSDynLoad_FindExport for MEMFreeToDefaultHeap");
}
gMEMAllocFromDefaultHeapExForThreads = (void *(*) (uint32_t, int) ) * allocPtr;
gMEMFreeToDefaultHeapForThreads = (void (*)(void *)) * freePtr;
}
WUMS_INITIALIZE(args) {
static uint8_t ucSetupRequired = 1;
if (!ucSetupRequired) {
return;
}
#ifdef DEBUG
initLogging();
#endif
UpdateFunctionPointer();
ucSetupRequired = 0;
MemoryMapping_setupMemoryMapping();
MemoryMapping_CreateHeaps();
FunctionPatcherPatchFunction(function_replacements, function_replacements_size);
/* We can not use FunctionPatcher_InitLibrary here because OSDynLoadAcquire is not patched yet.
if (FunctionPatcher_InitLibrary() != FUNCTION_PATCHER_RESULT_SUCCESS) {
OSFatal("homebrew_memorymapping: FunctionPatcher_InitLibrary failed");
}*/
for (uint32_t i = 0; i < function_replacements_size; i++) {
bool wasPatched = false;
// We don't need to save the handles because we never restore them anyway.
if (FPAddFunctionPatch(&function_replacements[i], nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) {
OSFatal("homebrew_memorymapping: Failed to patch function");
}
}
#ifdef DEBUG
deinitLogging();
#endif
}
WUMS_APPLICATION_STARTS() {
#ifdef DEBUG
initLogging();
#endif
OSReport("Running MemoryMappingModule " VERSION VERSION_EXTRA "\n");
MemoryMapping_checkHeaps();
// Now we can update the pointer with the "real" functions
gMEMAllocFromDefaultHeapExForThreads = MEMAllocFromDefaultHeapEx;
gMEMFreeToDefaultHeapForThreads = MEMFreeToDefaultHeap;
}
WUMS_APPLICATION_ENDS() {
MemoryMapping_checkHeaps();
#ifdef DEBUG
deinitLogging();
#endif
}
void MemoryMappingFree(void *ptr) {
//DEBUG_FUNCTION_LINE("[%08X] free", ptr);
MemoryMapping_free(ptr);
@ -54,10 +134,10 @@ void *MemoryMappingAllocForGX2Ex(uint32_t size, int32_t align) {
return res;
}
uint32_t MEMAllocFromMappedMemory __attribute__((__section__ (".data"))) = (uint32_t) MemoryMappingAlloc;
uint32_t MEMAllocFromMappedMemoryEx __attribute__((__section__ (".data"))) = (uint32_t) MemoryMappingAllocEx;
uint32_t MEMAllocFromMappedMemoryForGX2Ex __attribute__((__section__ (".data"))) = (uint32_t) MemoryMappingAllocForGX2Ex;
uint32_t MEMFreeToMappedMemory __attribute__((__section__ (".data"))) = (uint32_t) MemoryMappingFree;
uint32_t MEMAllocFromMappedMemory __attribute__((__section__(".data"))) = (uint32_t) MemoryMappingAlloc;
uint32_t MEMAllocFromMappedMemoryEx __attribute__((__section__(".data"))) = (uint32_t) MemoryMappingAllocEx;
uint32_t MEMAllocFromMappedMemoryForGX2Ex __attribute__((__section__(".data"))) = (uint32_t) MemoryMappingAllocForGX2Ex;
uint32_t MEMFreeToMappedMemory __attribute__((__section__(".data"))) = (uint32_t) MemoryMappingFree;
WUMS_EXPORT_FUNCTION(MemoryMappingEffectiveToPhysical);
WUMS_EXPORT_FUNCTION(MemoryMappingPhysicalToEffective);

View File

@ -1,50 +1,210 @@
#include "memory_mapping.h"
#include <coreinit/memorymap.h>
#include <coreinit/memdefaultheap.h>
#include <coreinit/cache.h>
#include <coreinit/memexpheap.h>
#include <coreinit/memorymap.h>
#include <coreinit/thread.h>
#include <vector>
#include "memory.h"
#include "logger.h"
#include "CThread.h"
#include "logger.h"
#include <coreinit/mutex.h>
#include <cstring>
OSSpinLock allocFreeSpinlock;
#include <vector>
// #define DEBUG_FUNCTION_LINE(x,...)
//OSMutex allocMutex;
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};
for (int i: aff) {
CThread *thread = CThread::create(callback, callbackArg, iAttr | i, iPriority, iStackSize);
thread->resumeThread();
delete thread;
for (int i : aff) {
CThread thread(iAttr | i, iPriority, iStackSize, callback, callbackArg);
thread.resumeThread();
}
}
void KernelWriteU32(uint32_t addr, uint32_t value) {
ICInvalidateRange(&value, 4);
DCFlushRange(&value, 4);
auto dst = (uint32_t) OSEffectiveToPhysical(addr);
auto src = (uint32_t) OSEffectiveToPhysical((uint32_t) &value);
KernelCopyData(dst, src, 4);
DCFlushRange((void *) addr, 4);
ICInvalidateRange((void *) addr, 4);
}
void KernelWrite(uint32_t addr, const void *data, uint32_t length) {
// This is a hacky workaround, but currently it only works this way. ("data" is always on the stack, so maybe a problem with mapping values from the JIT area?)
// further testing required.
for (uint32_t i = 0; i < length; i += 4) {
KernelWriteU32(addr + i, *(uint32_t *) (((uint32_t) data) + i));
}
}
/*
static void SCSetupIBAT4DBAT5() {
asm volatile("sync; eieio; isync");
// Give our and the kernel full execution rights.
// 00800000-01000000 => 30800000-31000000 (read/write, user/supervisor)
unsigned int ibat4u = 0x008000FF;
unsigned int ibat4l = 0x30800012;
asm volatile("mtspr 560, %0" :: "r"(ibat4u));
asm volatile("mtspr 561, %0" :: "r"(ibat4l));
// Give our and the kernel full data access rights.
// 00800000-01000000 => 30800000-31000000 (read/write, user/supervisor)
unsigned int dbat5u = ibat4u;
unsigned int dbat5l = ibat4l;
asm volatile("mtspr 570, %0" :: "r"(dbat5u));
asm volatile("mtspr 571, %0" :: "r"(dbat5l));
asm volatile("eieio; isync");
}
*/
const uint32_t sSCSetupIBAT4DBAT5Buffer[] = {0x7c0004ac,
0x7c0006ac,
0x4c00012c,
0x3d400080,
0x614a00ff,
0x7d508ba6,
0x3d203080,
0x61290012,
0x7d318ba6,
0x7d5a8ba6,
0x7d3b8ba6,
0x7c0006ac,
0x4c00012c,
0x4e800020};
#define TARGET_ADDRESS_EXECUTABLE_MEM 0x017FF000
#define SCSetupIBAT4DBAT5_ADDRESS TARGET_ADDRESS_EXECUTABLE_MEM
const uint32_t sSC0x51Buffer[] = {
0x7c7082a6, // mfspr r3, 528
0x60630003, // ori r3, r3, 0x03
0x7c7083a6, // mtspr 528, r3
0x7c7282a6, // mfspr r3, 530
0x60630003, // ori r3, r3, 0x03
0x7c7283a6, // mtspr 530, r3
0x7c0006ac, // eieio
0x4c00012c, // isync
0x3c600000 | (SCSetupIBAT4DBAT5_ADDRESS >> 16), // lis r3, SCSetupIBAT4DBAT5@h
0x60630000 | (SCSetupIBAT4DBAT5_ADDRESS & 0xFFFF), // ori r3, r3, SCSetupIBAT4DBAT5@l
0x7c6903a6, // mtctr r3
0x4e800420, // bctr
};
#define SC0x51Buffer_ADDRESS (SCSetupIBAT4DBAT5_ADDRESS + sizeof(sSCSetupIBAT4DBAT5Buffer))
#define SC0x51Call_ADDRESS (SC0x51Buffer_ADDRESS + sizeof(sSC0x51Buffer))
const uint32_t sSC0x51CallBuffer[] = {
0x38005100, //li %r0, 0x5100
0x44000002, // sc
0x4e800020 //blr
};
void SetupIBAT4DBAT5OnAllCores() {
unsigned char backupBuffer[0x74];
KernelWrite((uint32_t) backupBuffer, (void *) TARGET_ADDRESS_EXECUTABLE_MEM, sizeof(backupBuffer));
static_assert(sizeof(backupBuffer) >= (sizeof(sSC0x51Buffer) + sizeof(sSCSetupIBAT4DBAT5Buffer) + sizeof(sSC0x51CallBuffer)), "Not enough memory in backup buffer");
static_assert(SCSetupIBAT4DBAT5_ADDRESS >= TARGET_ADDRESS_EXECUTABLE_MEM && SCSetupIBAT4DBAT5_ADDRESS < (TARGET_ADDRESS_EXECUTABLE_MEM + sizeof(backupBuffer)), "buffer in wrong memory region");
static_assert(SC0x51Buffer_ADDRESS >= TARGET_ADDRESS_EXECUTABLE_MEM && SC0x51Buffer_ADDRESS < (TARGET_ADDRESS_EXECUTABLE_MEM + sizeof(backupBuffer)), "buffer in wrong memory region");
static_assert(SC0x51Call_ADDRESS >= TARGET_ADDRESS_EXECUTABLE_MEM && SC0x51Call_ADDRESS < (TARGET_ADDRESS_EXECUTABLE_MEM + sizeof(backupBuffer)), "buffer in wrong memory region");
static_assert(SCSetupIBAT4DBAT5_ADDRESS != SC0x51Buffer_ADDRESS && SCSetupIBAT4DBAT5_ADDRESS != SC0x51Call_ADDRESS && SC0x51Buffer_ADDRESS != SC0x51Call_ADDRESS, "buffer are not different");
// We need copy the functions to a memory region which is executable on all 3 cores
KernelWrite(SCSetupIBAT4DBAT5_ADDRESS, sSCSetupIBAT4DBAT5Buffer, sizeof(sSCSetupIBAT4DBAT5Buffer)); // Set IBAT5 and DBAT5 to map the memory region
KernelWrite(SC0x51Buffer_ADDRESS, sSC0x51Buffer, sizeof(sSC0x51Buffer)); // Implementation of 0x51 syscall
KernelWrite(SC0x51Call_ADDRESS, sSC0x51CallBuffer, sizeof(sSC0x51CallBuffer)); // Call of 0x51 syscall
/* set our setup syscall to an unused position */
KernelPatchSyscall(0x51, SCSetupIBAT4DBAT5_ADDRESS);
// We want to run this on all 3 cores.
{
int32_t aff[] = {CThread::eAttributeAffCore2, CThread::eAttributeAffCore1, CThread::eAttributeAffCore0};
int iStackSize = 0x200;
//! allocate the thread and stack on the default Cafe OS heap
auto *pThread = (OSThread *) gMEMAllocFromDefaultHeapExForThreads(sizeof(OSThread), 0x10);
auto *pThreadStack = (uint8_t *) gMEMAllocFromDefaultHeapExForThreads(iStackSize, 0x20);
//! create the thread
if (pThread && pThreadStack) {
for (int i : aff) {
*pThread = {};
memset(pThreadStack, 0, iStackSize);
OSCreateThread(pThread, reinterpret_cast<OSThreadEntryPointFn>(SC0x51Call_ADDRESS), 0, nullptr, (void *) (pThreadStack + iStackSize), iStackSize, 16, (OSThreadAttributes) i);
OSResumeThread(pThread);
while (OSIsThreadSuspended(pThread)) {
OSResumeThread(pThread);
}
OSJoinThread(pThread, nullptr);
}
}
//! free the thread stack buffer
if (pThreadStack) {
memset(pThreadStack, 0, iStackSize);
gMEMFreeToDefaultHeapForThreads(pThreadStack);
}
if (pThread) {
memset(pThread, 0, sizeof(OSThread));
gMEMFreeToDefaultHeapForThreads(pThread);
}
}
/* repair data */
KernelWrite(TARGET_ADDRESS_EXECUTABLE_MEM, backupBuffer, sizeof(backupBuffer));
DCFlushRange((void *) TARGET_ADDRESS_EXECUTABLE_MEM, sizeof(backupBuffer));
}
void writeKernelNOPs(CThread *thread, void *arg) {
DEBUG_FUNCTION_LINE_VERBOSE("Writing kernel NOPs on core %d", OSGetThreadAffinity(OSGetCurrentThread()) / 2);
KernelNOPAtPhysicalAddress(0xFFF1D754);
KernelNOPAtPhysicalAddress(0xFFF1D64C);
KernelNOPAtPhysicalAddress(0xFFE00638);
// Patch out any writes to SR
int sr = MEMORY_START_BASE >> 28;
KernelNOPAtPhysicalAddress(0xfff1d734 + 0x4 * sr);
if (sr < 7) {
KernelNOPAtPhysicalAddress(0xfff1d604 + 0x4 * sr);
} else {
KernelNOPAtPhysicalAddress(0xfff1d648 + 0x4 * (sr - 7));
}
KernelNOPAtPhysicalAddress(0xffe00618 + 0x4 * sr);
// nop out branches to app panic 0x17
KernelNOPAtPhysicalAddress(0xfff01db0);
KernelNOPAtPhysicalAddress(0xfff01db4);
KernelNOPAtPhysicalAddress(0xfff01a00);
KernelNOPAtPhysicalAddress(0xfff01a04);
KernelNOPAtPhysicalAddress(0xfff01e90);
KernelNOPAtPhysicalAddress(0xfff01ea0);
KernelNOPAtPhysicalAddress(0xfff01ea4);
// nop out branches to app panic 0x12
KernelNOPAtPhysicalAddress(0xfff01a00);
KernelNOPAtPhysicalAddress(0xfff01b68);
KernelNOPAtPhysicalAddress(0xfff01b70);
KernelNOPAtPhysicalAddress(0xfff01b7c);
KernelNOPAtPhysicalAddress(0xfff01b80);
// nop out branches to app panic 0x16
KernelNOPAtPhysicalAddress(0xfff0db24);
KernelNOPAtPhysicalAddress(0xfff0dbb4);
KernelNOPAtPhysicalAddress(0xfff0dbbc);
KernelNOPAtPhysicalAddress(0xfff0dbc8);
KernelNOPAtPhysicalAddress(0xfff0dbcc);
// nop out branches to app panic 0x14
KernelNOPAtPhysicalAddress(0xfff01cfc);
KernelNOPAtPhysicalAddress(0xfff01d4c);
KernelNOPAtPhysicalAddress(0xfff01d54);
KernelNOPAtPhysicalAddress(0xfff01d60);
KernelNOPAtPhysicalAddress(0xfff01d64);
}
void writeSegmentRegister(CThread *thread, void *arg) {
@ -64,7 +224,7 @@ void readAndPrintSegmentRegister(CThread *thread, void *arg) {
DCFlushRange(&srTable, sizeof(srTable));
for (int32_t i = 0; i < 16; i++) {
DEBUG_FUNCTION_LINE_VERBOSE("[%d] SR[%d]=%08X", core, i, srTable.value[i]);
DEBUG_FUNCTION_LINE_VERBOSE("[%d] SR[%d]=%08X", OSGetThreadAffinity(OSGetCurrentThread()) / 2, i, srTable.value[i]);
}
uint32_t pageTable[0x8000];
@ -92,6 +252,7 @@ bool MemoryMapping_isMemoryMapped() {
}
void MemoryMapping_searchEmptyMemoryRegions() {
#ifdef DEBUG
DEBUG_FUNCTION_LINE("Searching for empty memory.");
for (int32_t i = 0;; i++) {
@ -105,25 +266,25 @@ void MemoryMapping_searchEmptyMemoryRegions() {
uint32_t ea_size = 0;
for (uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if (pa_end_address == 0 && pa_start_address == 0) {
break;
}
ea_size += pa_end_address - pa_start_address;
}
auto *flush_start = (uint32_t *) ea_start_address;
auto *flush_start = (uint32_t *) ea_start_address;
uint32_t flush_size = ea_size;
DEBUG_FUNCTION_LINE("Flushing %08X (%d kB) at %08X.", flush_size, flush_size / 1024, flush_start);
DCFlushRange(flush_start, flush_size);
DEBUG_FUNCTION_LINE("Searching in memory region %d. 0x%08X - 0x%08X. Size 0x%08X (%d KBytes).", i + 1, ea_start_address, ea_start_address + ea_size, ea_size, ea_size / 1024);
bool success = true;
auto *memory_ptr = (uint32_t *) ea_start_address;
bool inFailRange = false;
bool success = true;
auto *memory_ptr = (uint32_t *) ea_start_address;
bool inFailRange = false;
uint32_t startFailing = 0;
uint32_t startGood = ea_start_address;
uint32_t startGood = ea_start_address;
for (uint32_t j = 0; j < ea_size / 4; j++) {
if (memory_ptr[j] != 0) {
success = false;
@ -134,22 +295,22 @@ void MemoryMapping_searchEmptyMemoryRegions() {
start_addr += 0x20000;
}
uint32_t end_addr = ((uint32_t) &memory_ptr[j]) - MEMORY_START_BASE;
end_addr = (end_addr & 0xFFFE0000);
end_addr = (end_addr & 0xFFFE0000);
DEBUG_FUNCTION_LINE("+ Free between 0x%08X and 0x%08X size: %u kB", start_addr - MEMORY_START_BASE, end_addr,
(((uint32_t) end_addr) - ((uint32_t) startGood - MEMORY_START_BASE)) / 1024);
}
startFailing = (uint32_t) &memory_ptr[j];
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000) - 1;
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000) - 1;
}
//break;
} else {
if (inFailRange) {
//DEBUG_FUNCTION_LINE("- Error between 0x%08X and 0x%08X size: %u kB",startFailing,&memory_ptr[j],(((uint32_t)&memory_ptr[j])-(uint32_t)startFailing)/1024);
startFailing = 0;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
}
}
}
@ -162,9 +323,9 @@ void MemoryMapping_searchEmptyMemoryRegions() {
if (success) {
DEBUG_FUNCTION_LINE("Test %d was successful!", i + 1);
}
}
DEBUG_FUNCTION_LINE("All tests done.");
#endif
}
void MemoryMapping_writeTestValuesToMemory() {
@ -181,10 +342,10 @@ void MemoryMapping_writeTestValuesToMemory() {
DEBUG_FUNCTION_LINE("Preparing memory test for region %d. Region start at effective address %08X.", i + 1, cur_ea_start_address);
const memory_values_t *mem_vals = mem_mapping[i].physical_addresses;
uint32_t counter = 0;
uint32_t counter = 0;
for (uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if (pa_end_address == 0 && pa_start_address == 0) {
break;
}
@ -203,7 +364,7 @@ void MemoryMapping_writeTestValuesToMemory() {
}
//DEBUG_FUNCTION_LINE("testBuffer[%d] = %d",i % chunk_size,i);
}
auto *flush_start = (uint32_t *) cur_ea_start_address;
auto *flush_start = (uint32_t *) cur_ea_start_address;
uint32_t flush_size = pa_size;
cur_ea_start_address += pa_size;
@ -217,6 +378,7 @@ void MemoryMapping_writeTestValuesToMemory() {
}
void MemoryMapping_readTestValuesFromMemory() {
#ifdef DEBUG
DEBUG_FUNCTION_LINE("Testing reading the written values.");
for (int32_t i = 0;; i++) {
@ -230,42 +392,42 @@ void MemoryMapping_readTestValuesFromMemory() {
uint32_t ea_size = 0;
for (uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if (pa_end_address == 0 && pa_start_address == 0) {
break;
}
ea_size += pa_end_address - pa_start_address;
}
auto *flush_start = (uint32_t *) ea_start_address;
auto *flush_start = (uint32_t *) ea_start_address;
uint32_t flush_size = ea_size;
DEBUG_FUNCTION_LINE("Flushing %08X (%d kB) at %08X to map memory.", flush_size, flush_size / 1024, flush_start);
DCFlushRange(flush_start, flush_size);
DEBUG_FUNCTION_LINE("Testing memory region %d. 0x%08X - 0x%08X. Size 0x%08X (%d KBytes).", i + 1, ea_start_address, ea_start_address + ea_size, ea_size, ea_size / 1024);
bool success = true;
auto *memory_ptr = (uint32_t *) ea_start_address;
bool inFailRange = false;
bool success = true;
auto *memory_ptr = (uint32_t *) ea_start_address;
bool inFailRange = false;
uint32_t startFailing = 0;
uint32_t startGood = ea_start_address;
uint32_t startGood = ea_start_address;
for (uint32_t j = 0; j < ea_size / 4; j++) {
if (memory_ptr[j] != j) {
success = false;
if (!inFailRange) {
DEBUG_FUNCTION_LINE("+ Good between 0x%08X and 0x%08X size: %u kB", startGood, &memory_ptr[j], (((uint32_t) &memory_ptr[j]) - (uint32_t) startGood) / 1024);
startFailing = (uint32_t) &memory_ptr[j];
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000) - 1;
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000) - 1;
}
//break;
} else {
if (inFailRange) {
DEBUG_FUNCTION_LINE("- Error between 0x%08X and 0x%08X size: %u kB", startFailing, &memory_ptr[j], (((uint32_t) &memory_ptr[j]) - (uint32_t) startFailing) / 1024);
startFailing = 0;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
}
}
}
@ -277,9 +439,9 @@ void MemoryMapping_readTestValuesFromMemory() {
if (success) {
DEBUG_FUNCTION_LINE("Test %d was successful!", i + 1);
}
}
DEBUG_FUNCTION_LINE("All tests done.");
#endif
}
void MemoryMapping_memoryMappingForRegions(const memory_mapping_t *memory_mapping, sr_table_t SRTable, uint32_t *translation_table) {
@ -297,7 +459,7 @@ void MemoryMapping_memoryMappingForRegions(const memory_mapping_t *memory_mappin
for (uint32_t j = 0;; j++) {
//DEBUG_FUNCTION_LINE("In inner loop %d",j);
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if (pa_end_address == 0 && pa_start_address == 0) {
//DEBUG_FUNCTION_LINE("inner break %d",j);
// Break if entry was empty.
@ -320,6 +482,11 @@ void MemoryMapping_memoryMappingForRegions(const memory_mapping_t *memory_mappin
}
void MemoryMapping_setupMemoryMapping() {
/*
* We need to make sure that with have full access to the 0x0080000-0x01000000 region on all 3 cores.
*/
SetupIBAT4DBAT5OnAllCores();
// Override all writes to SR8 with nops.
// Override some memory region checks inside the kernel
runOnAllCores(writeKernelNOPs, nullptr);
@ -327,13 +494,18 @@ void MemoryMapping_setupMemoryMapping() {
//runOnAllCores(readAndPrintSegmentRegister,nullptr,0,16,0x80000);
sr_table_t srTableCpy;
uint32_t pageTableCpy[0x8000];
uint32_t sizePageTable = sizeof(uint32_t) * 0x8000;
auto *pageTableCpy = (uint32_t *) gMEMAllocFromDefaultHeapExForThreads(sizePageTable, 0x10);
if (!pageTableCpy) {
OSFatal("MemoryMappingModule: Failed to alloc memory for page table");
}
KernelReadSRs(&srTableCpy);
KernelReadPTE((uint32_t) pageTableCpy, sizeof(pageTableCpy));
KernelReadPTE((uint32_t) pageTableCpy, sizePageTable);
DCFlushRange(&srTableCpy, sizeof(srTableCpy));
DCFlushRange(pageTableCpy, sizeof(pageTableCpy));
DCFlushRange(pageTableCpy, sizePageTable);
for (int32_t i = 0; i < 16; i++) {
DEBUG_FUNCTION_LINE_VERBOSE("SR[%d]=%08X", i, srTableCpy.value[i]);
@ -346,7 +518,7 @@ void MemoryMapping_setupMemoryMapping() {
// is currently unmapped.
// This is nice because it leads to SR[8] which also seems to be unused (was set to 0x30FFFFFF)
// The content of the segment was chosen randomly.
uint32_t segment_index = MEMORY_START_BASE >> 28;
uint32_t segment_index = MEMORY_START_BASE >> 28;
uint32_t segment_content = 0x00000000 | SEGMENT_UNIQUE_ID;
DEBUG_FUNCTION_LINE_VERBOSE("Setting SR[%d] to %08X", segment_index, segment_content);
@ -365,9 +537,9 @@ void MemoryMapping_setupMemoryMapping() {
//printPageTableTranslation(srTableCpy,pageTableCpy);
DEBUG_FUNCTION_LINE_VERBOSE("Writing PageTable... ");
DCFlushRange(pageTableCpy, sizeof(pageTableCpy));
KernelWritePTE((uint32_t) pageTableCpy, sizeof(pageTableCpy));
DCFlushRange(pageTableCpy, sizeof(pageTableCpy));
DCFlushRange(pageTableCpy, sizePageTable);
KernelWritePTE((uint32_t) pageTableCpy, sizePageTable);
DCFlushRange(pageTableCpy, sizePageTable);
DEBUG_FUNCTION_LINE_VERBOSE("done");
//printPageTableTranslation(srTableCpy,pageTableCpy);
@ -380,36 +552,129 @@ void MemoryMapping_setupMemoryMapping() {
//readTestValuesFromMemory();
//runOnAllCores(writeSegmentRegister,&srTableCpy);
// OSInitMutex(&allocMutex);
OSInitSpinLock(&allocFreeSpinlock);
memset(pageTableCpy, 0, sizePageTable);
gMEMFreeToDefaultHeapForThreads(pageTableCpy);
}
void *MemoryMapping_allocEx(uint32_t size, int32_t align, bool videoOnly) {
OSUninterruptibleSpinLock_Acquire(&allocFreeSpinlock);
//OSLockMutex(&allocMutex);
void *res = nullptr;
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
break;
}
uint32_t effectiveAddress = mem_mapping[i].effective_start_address;
auto heapHandle = (MEMHeapHandle) effectiveAddress;
auto *heap = (MEMExpHeap *) heapHandle;
auto heapHandle = (MEMHeapHandle) effectiveAddress;
// Skip non-video memory
if (videoOnly && ((effectiveAddress < MEMORY_START_VIDEO) || (effectiveAddress > MEMORY_END_VIDEO))) {
continue;
}
res = MEMAllocFromExpHeapEx(heapHandle, size, align);
auto cur = heap->usedList.head;
uint32_t allocSize;
if (align > 0) {
allocSize = (size + align - 1) & ~(align - 1);
} else {
uint32_t alignAbs = -align;
allocSize = (size + alignAbs - 1) & ~(alignAbs - 1);
}
res = MEMAllocFromExpHeapEx(heapHandle, allocSize, align);
if (res != nullptr) {
break;
}
}
OSUninterruptibleSpinLock_Release(&allocFreeSpinlock);
OSMemoryBarrier();
//OSUnlockMutex(&allocMutex);
return res;
}
bool CheckMemExpHeapBlock(MEMExpHeap *heap, MEMExpHeapBlockList *block, uint32_t tag, const char *listName, uint32_t &totalSizeOut) {
MEMExpHeapBlock *prevBlock = nullptr;
for (auto *cur = block->head; cur != nullptr; cur = cur->next) {
if (cur->prev != prevBlock) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] \"%s\" prev is invalid. expected %08X actual %08X", listName, prevBlock, cur->prev);
return false;
}
if (cur < heap->header.dataStart || cur > heap->header.dataEnd || ((uint32_t) cur + sizeof(MEMExpHeapBlock) + cur->blockSize) > (uint32_t) heap->header.dataEnd) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] Block is not inside heap. block: %08X size %d; heap start %08X heap end %08X", cur, sizeof(MEMExpHeapBlock) + cur->blockSize, heap->header.dataStart, heap->header.dataEnd);
return false;
}
if (cur->tag != tag) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] Invalid block tag expected %04X, actual %04X", tag, cur->tag);
return false;
}
totalSizeOut = totalSizeOut + cur->blockSize + (cur->attribs >> 8 & 0x7fffff) + sizeof(MEMExpHeapBlock);
prevBlock = cur;
}
if (prevBlock != block->tail) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] \"%s\" tail is unexpected! expected %08X, actual %08X", listName, heap->usedList.tail, prevBlock);
return false;
}
return true;
}
bool CheckMemExpHeapCore(MEMExpHeap *heap) {
uint32_t totalSize = 0;
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
if (!CheckMemExpHeapBlock(heap, &heap->usedList, 0x5544, "used", totalSize)) {
return false;
}
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
if (!CheckMemExpHeapBlock(heap, &heap->freeList, 0x4652, "free", totalSize)) {
return false;
}
if (totalSize != (uint32_t) heap->header.dataEnd - (uint32_t) heap->header.dataStart) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] heap size is unexpected! expected %08X, actual %08X", (uint32_t) heap->header.dataEnd - (uint32_t) heap->header.dataStart, totalSize);
return false;
}
return true;
}
bool CheckMemExpHeap(MEMExpHeap *heap) {
OSMemoryBarrier();
if (heap->header.tag != MEM_EXPANDED_HEAP_TAG) {
DEBUG_FUNCTION_LINE_ERR("[Exp Heap Check] Invalid heap handle. - %08X", heap->header.tag);
return false;
}
if (heap->header.flags & MEM_HEAP_FLAG_USE_LOCK) {
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
OSUninterruptibleSpinLock_Acquire(&(heap->header).lock);
}
auto result = CheckMemExpHeapCore(heap);
if (heap->header.flags & MEM_HEAP_FLAG_USE_LOCK) {
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
OSUninterruptibleSpinLock_Release(&(heap->header).lock);
}
return result;
}
void MemoryMapping_checkHeaps() {
//OSLockMutex(&allocMutex);
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
break;
}
auto heapHandle = (MEMHeapHandle) mem_mapping[i].effective_start_address;
if (!CheckMemExpHeap(reinterpret_cast<MEMExpHeap *>(heapHandle))) {
DEBUG_FUNCTION_LINE_ERR("MemoryMapping heap %08X (index %d) is corrupted.", heapHandle, i);
#ifdef DEBUG
OSFatal("MemoryMappingModule: Heap is corrupted");
#endif
}
}
//OSUnlockMutex(&allocMutex);
}
void *MemoryMapping_alloc(uint32_t size, int32_t align) {
return MemoryMapping_allocEx(size, align, false);
}
@ -418,11 +683,34 @@ void *MemoryMapping_allocVideoMemory(uint32_t size, int32_t align) {
return MemoryMapping_allocEx(size, align, true);
}
// clang-format off
#define FindHeapContainingBlock ((MEMHeapHandle (*) (MEMMemoryList *, void *) )(0x101C400 + 0x2f2d8))
// clang-format on
MEMHeapHandle MemoryMapping_MEMFindContainHeap(void *block) {
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
break;
}
uint32_t effectiveAddress = mem_mapping[i].effective_start_address;
auto heapHandle = (MEMHeapHandle) effectiveAddress;
auto *heap = (MEMExpHeap *) heapHandle;
if (block >= heap->header.dataStart &&
block < heap->header.dataEnd) {
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto child = FindHeapContainingBlock(&heap->header.list, block);
return child ? child : heapHandle;
}
}
return nullptr;
}
void MemoryMapping_free(void *ptr) {
if (ptr == nullptr) {
return;
}
OSUninterruptibleSpinLock_Acquire(&allocFreeSpinlock);
//OSLockMutex(&allocMutex);
auto ptr_val = (uint32_t) ptr;
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
@ -430,14 +718,12 @@ void MemoryMapping_free(void *ptr) {
}
if (ptr_val > mem_mapping[i].effective_start_address && ptr_val < mem_mapping[i].effective_end_address) {
auto heapHandle = (MEMHeapHandle) mem_mapping[i].effective_start_address;
auto *heap = (MEMExpHeap *) heapHandle;
MEMFreeToExpHeap((MEMHeapHandle) mem_mapping[i].effective_start_address, ptr);
auto cur = heap->usedList.head;
MEMFreeToExpHeap(heapHandle, ptr);
break;
}
}
OSUninterruptibleSpinLock_Release(&allocFreeSpinlock);
OSMemoryBarrier();
//OSUnlockMutex(&allocMutex);
}
uint32_t MemoryMapping_MEMGetAllocatableSize() {
@ -445,6 +731,7 @@ uint32_t MemoryMapping_MEMGetAllocatableSize() {
}
uint32_t MemoryMapping_MEMGetAllocatableSizeEx(uint32_t align) {
//OSLockMutex(&allocMutex);
uint32_t res = 0;
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
@ -456,10 +743,12 @@ uint32_t MemoryMapping_MEMGetAllocatableSizeEx(uint32_t align) {
res = curRes;
}
}
//OSUnlockMutex(&allocMutex);
return res;
}
uint32_t MemoryMapping_GetFreeSpace() {
//OSLockMutex(&allocMutex);
uint32_t res = 0;
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
@ -469,10 +758,12 @@ uint32_t MemoryMapping_GetFreeSpace() {
DEBUG_FUNCTION_LINE_VERBOSE("heap at %08X MEMGetTotalFreeSizeForExpHeap: %d KiB", mem_mapping[i].effective_start_address, curRes / 1024);
res += curRes;
}
//OSUnlockMutex(&allocMutex);
return res;
}
void MemoryMapping_CreateHeaps() {
//OSLockMutex(&allocMutex);
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
break;
@ -481,12 +772,19 @@ void MemoryMapping_CreateHeaps() {
uint32_t size = mem_mapping[i].effective_end_address - mem_mapping[i].effective_start_address;
memset(reinterpret_cast<void *>(mem_mapping[i].effective_start_address), 0, size);
MEMCreateExpHeapEx(address, size, MEM_HEAP_FLAG_USE_LOCK);
DEBUG_FUNCTION_LINE_VERBOSE("Created heap @%08X, size %d KiB", address, size / 1024);
#ifdef DEBUG
auto heap =
#endif
MEMCreateExpHeapEx(address, size, MEM_HEAP_FLAG_USE_LOCK);
#ifdef DEBUG
DEBUG_FUNCTION_LINE("Created heap @%08X, size %d KiB", heap, size / 1024);
#endif
}
//OSUnlockMutex(&allocMutex);
}
void MemoryMapping_DestroyHeaps() {
//OSLockMutex(&allocMutex);
for (int32_t i = 0; /* waiting for a break */; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
break;
@ -498,6 +796,7 @@ void MemoryMapping_DestroyHeaps() {
memset(address, 0, size);
DEBUG_FUNCTION_LINE_VERBOSE("Destroyed heap @%08X", address);
}
//OSUnlockMutex(&allocMutex);
}
uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize) {
@ -508,7 +807,7 @@ uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize
KernelReadPTE((uint32_t) pageTable, sizeof(pageTable));
uint32_t sr_start = start >> 28;
uint32_t sr_end = (start + maxSize) >> 28;
uint32_t sr_end = (start + maxSize) >> 28;
if (sr_end < sr_start) {
return 0;
@ -526,7 +825,7 @@ uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize
} else {
uint32_t vsid = sr & 0xFFFFFF;
uint32_t pageSize = 1 << PAGE_INDEX_SHIFT;
uint32_t pageSize = 1 << PAGE_INDEX_SHIFT;
uint32_t cur_end_addr = 0;
if (segment == sr_end) {
cur_end_addr = end_address;
@ -534,7 +833,7 @@ uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize
cur_end_addr = (segment + 1) * 0x10000000;
}
if (segment != sr_start) {
cur_address = (segment) * 0x10000000;
cur_address = (segment) *0x10000000;
}
bool success = true;
for (uint32_t addr = cur_address; addr < cur_end_addr; addr += pageSize) {
@ -556,8 +855,8 @@ uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize
}
bool MemoryMapping_getPageEntryForAddress(uint32_t SDR1, uint32_t addr, uint32_t vsid, uint32_t *translation_table, uint32_t *oPTEH, uint32_t *oPTEL, bool checkSecondHash) {
uint32_t pageMask = SDR1 & 0x1FF;
uint32_t pageIndex = (addr >> PAGE_INDEX_SHIFT) & PAGE_INDEX_MASK;
uint32_t pageMask = SDR1 & 0x1FF;
uint32_t pageIndex = (addr >> PAGE_INDEX_SHIFT) & PAGE_INDEX_MASK;
uint32_t primaryHash = (vsid & 0x7FFFF) ^ pageIndex;
if (MemoryMapping_getPageEntryForAddressEx(SDR1, addr, vsid, primaryHash, translation_table, oPTEH, oPTEL, 0)) {
@ -575,7 +874,7 @@ bool MemoryMapping_getPageEntryForAddress(uint32_t SDR1, uint32_t addr, uint32_t
bool MemoryMapping_getPageEntryForAddressEx(uint32_t pageMask, uint32_t addr, uint32_t vsid, uint32_t primaryHash, uint32_t *translation_table, uint32_t *oPTEH, uint32_t *oPTEL, uint32_t H) {
uint32_t maskedHash = primaryHash & ((pageMask << 10) | 0x3FF);
uint32_t api = (addr >> 22) & 0x3F;
uint32_t api = (addr >> 22) & 0x3F;
uint32_t pteAddrOffset = (maskedHash << 6);
@ -635,9 +934,9 @@ void MemoryMapping_printPageTableTranslation(sr_table_t srTable, uint32_t *trans
if (sr >> 31) {
DEBUG_FUNCTION_LINE_VERBOSE("Direct access not supported");
} else {
uint32_t ks = (sr >> 30) & 1;
uint32_t kp = (sr >> 29) & 1;
uint32_t nx = (sr >> 28) & 1;
uint32_t ks = (sr >> 30) & 1;
uint32_t kp = (sr >> 29) & 1;
uint32_t nx = (sr >> 28) & 1;
uint32_t vsid = sr & 0xFFFFFF;
DEBUG_FUNCTION_LINE_VERBOSE("ks %08X kp %08X nx %08X vsid %08X", ks, kp, nx, vsid);
@ -646,7 +945,7 @@ void MemoryMapping_printPageTableTranslation(sr_table_t srTable, uint32_t *trans
uint32_t PTEH = 0;
uint32_t PTEL = 0;
if (MemoryMapping_getPageEntryForAddress(SDR1, addr, vsid, translation_table, &PTEH, &PTEL, false)) {
uint32_t pp = PTEL & 3;
uint32_t pp = PTEL & 3;
uint32_t phys = PTEL & 0xFFFFF000;
//DEBUG_FUNCTION_LINE("current.phys == phys - current.size ( %08X %08X)",current.phys, phys - current.size);
@ -655,8 +954,7 @@ void MemoryMapping_printPageTableTranslation(sr_table_t srTable, uint32_t *trans
current.kp == kp &&
current.nx == nx &&
current.pp == pp &&
current.phys == phys - current.size
) {
current.phys == phys - current.size) {
current.size += pageSize;
//DEBUG_FUNCTION_LINE("New size of %08X is %08X",current.addr,current.size);
} else {
@ -672,10 +970,10 @@ void MemoryMapping_printPageTableTranslation(sr_table_t srTable, uint32_t *trans
//DEBUG_FUNCTION_LINE("Found new block at %08X",addr);
current.addr = addr;
current.size = pageSize;
current.kp = kp;
current.ks = ks;
current.nx = nx;
current.pp = pp;
current.kp = kp;
current.ks = ks;
current.nx = nx;
current.pp = pp;
current.phys = phys;
}
} else {
@ -688,14 +986,16 @@ void MemoryMapping_printPageTableTranslation(sr_table_t srTable, uint32_t *trans
}
}
#ifdef VERBOSE_DEBUG
const char *access1[] = {"read/write", "read/write", "read/write", "read only"};
const char *access2[] = {"no access", "read only", "read/write", "read only"};
for (auto cur: pageInfos) {
for (auto cur : pageInfos) {
DEBUG_FUNCTION_LINE_VERBOSE("%08X %08X -> %08X %08X. user access %s. supervisor access %s. %s", cur.addr, cur.addr + cur.size, cur.phys, cur.phys + cur.size,
cur.kp ? access2[cur.pp] : access1[cur.pp],
cur.ks ? access2[cur.pp] : access1[cur.pp], cur.nx ? "not executable" : "executable");
}
#endif
}
@ -707,7 +1007,7 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
// Information on page 5.
// https://www.nxp.com/docs/en/application-note/AN2794.pdf
uint32_t HTABORG = SRTable.sdr1 >> 16;
uint32_t HTABORG = SRTable.sdr1 >> 16;
uint32_t HTABMASK = SRTable.sdr1 & 0x1FF;
// Iterate to all possible pages. Each page is 1<<(PAGE_INDEX_SHIFT) big.
@ -722,7 +1022,7 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
// Unique ID from the segment which is the input for the hash function.
// Change it to prevent collisions.
uint32_t VSID = segment & 0x00FFFFFF;
uint32_t V = 1;
uint32_t V = 1;
//Indicated if second hash is used.
uint32_t H = 0;
@ -730,13 +1030,13 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
// Abbreviated Page Index
// Real page number
uint32_t RPN = (pa_start_address + i) >> 12;
uint32_t RC = 3;
uint32_t RPN = (pa_start_address + i) >> 12;
uint32_t RC = 3;
uint32_t WIMG = 0x02;
uint32_t PP = 0x02;
uint32_t PP = 0x02;
uint32_t page_index = (ea_addr >> PAGE_INDEX_SHIFT) & PAGE_INDEX_MASK;
uint32_t API = (ea_addr >> 22) & 0x3F;
uint32_t API = (ea_addr >> 22) & 0x3F;
uint32_t PTEH = (V << 31) | (VSID << 7) | (H << 6) | API;
uint32_t PTEL = (RPN << 12) | (RC << 7) | (WIMG << 3) | PP;
@ -774,9 +1074,9 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
if (pteh == 0) {
// If we found a free slot, set the PTEH and PTEL value.
//DEBUG_FUNCTION_LINE("Used slot %d. PTEGaddr1 %08X addr %08X",j+1,PTEGaddr1 - (HTABORG << 16),PTEGoffset);
translation_table[index] = PTEH;
translation_table[index] = PTEH;
translation_table[index + 1] = PTEL;
setSuccessfully = true;
setSuccessfully = true;
break;
} else {
//printf("PTEGoffset %08X was taken",PTEGoffset);
@ -789,8 +1089,8 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
// We still have a chance to find a slot in the PTEGaddr2 using the complement of the hash.
// We need to set the H flag in PTEH and use PTEGaddr2.
// (Not well tested)
H = 1;
PTEH = (V << 31) | (VSID << 7) | (H << 6) | API;
H = 1;
PTEH = (V << 31) | (VSID << 7) | (H << 6) | API;
PTEGoffset = PTEGaddr2 - (HTABORG << 16);
PTEGoffset += 7 * 8;
// Same as before.
@ -799,9 +1099,9 @@ bool MemoryMapping_mapMemory(uint32_t pa_start_address, uint32_t pa_end_address,
uint32_t pteh = translation_table[index];
//Check if it's already taken.
if (pteh == 0) {
translation_table[index] = PTEH;
translation_table[index] = PTEH;
translation_table[index + 1] = PTEL;
setSuccessfully = true;
setSuccessfully = true;
break;
} else {
//printf("PTEGoffset %08X was taken",PTEGoffset);
@ -824,7 +1124,7 @@ uint32_t MemoryMapping_PhysicalToEffective(uint32_t phyiscalAddress) {
return phyiscalAddress - (0x30800000 - 0x00800000);
}
uint32_t result = 0;
uint32_t result = 0;
const memory_values_t *curMemValues = nullptr;
//iterate through all own mapped memory regions
for (int32_t i = 0; true; i++) {
@ -832,7 +1132,7 @@ uint32_t MemoryMapping_PhysicalToEffective(uint32_t phyiscalAddress) {
break;
}
curMemValues = mem_mapping[i].physical_addresses;
curMemValues = mem_mapping[i].physical_addresses;
uint32_t curOffsetInEA = 0;
// iterate through all memory values of this region
for (int32_t j = 0; true; j++) {
@ -859,7 +1159,7 @@ uint32_t MemoryMapping_EffectiveToPhysical(uint32_t effectiveAddress) {
uint32_t result = 0;
// CAUTION: The data may be fragmented between multiple areas in PA.
const memory_values_t *curMemValues = nullptr;
uint32_t curOffset = 0;
uint32_t curOffset = 0;
for (int32_t i = 0; true; i++) {
if (mem_mapping[i].physical_addresses == nullptr) {
@ -867,7 +1167,7 @@ uint32_t MemoryMapping_EffectiveToPhysical(uint32_t effectiveAddress) {
}
if (effectiveAddress >= mem_mapping[i].effective_start_address && effectiveAddress < mem_mapping[i].effective_end_address) {
curMemValues = mem_mapping[i].physical_addresses;
curOffset = mem_mapping[i].effective_start_address;
curOffset = mem_mapping[i].effective_start_address;
break;
}
}
@ -889,5 +1189,3 @@ uint32_t MemoryMapping_EffectiveToPhysical(uint32_t effectiveAddress) {
}
return result;
}

View File

@ -1,14 +1,15 @@
#pragma once
#include <coreinit/memheap.h>
#include <cstddef>
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <kernel/kernel.h>
#include <kernel/kernel_defs.h>
#include <stdint.h>
typedef struct pageInformation_ {
uint32_t addr;
@ -31,47 +32,57 @@ typedef struct _memory_mapping_t {
const memory_values_t *physical_addresses;
} memory_mapping_t;
#define SEGMENT_UNIQUE_ID 0x00AABBCC // Unique ID. Chosen arbitrary.
#define PAGE_INDEX_SHIFT (32-15)
#define PAGE_INDEX_MASK ((1 << (28 - PAGE_INDEX_SHIFT)) - 1)
#define SEGMENT_UNIQUE_ID 0x00AABBCC // Unique ID. Chosen arbitrary.
#define PAGE_INDEX_SHIFT (32 - 15)
#define PAGE_INDEX_MASK ((1 << (28 - PAGE_INDEX_SHIFT)) - 1)
#define MEMORY_START_BASE 0x80000000
#define MEMORY_START_VIDEO_BASE (MEMORY_START_BASE + 0x08000000)
#define MEMORY_START_BASE 0x80000000
#define MEMORY_START_VIDEO_BASE (MEMORY_START_BASE + 0x08000000)
// clang-format off
const memory_values_t mem_vals_heap_1[] = {
{0x28000000 + 0x06620000, 0x28000000 + 0x07F80000}, // size: 25984 kB
{0x28000000 + 0x06620000 + 0x2A0000, 0x28000000 + 0x07F80000}, // size: 23296 kB
{0, 0}
};
// clang-format on
#define MEMORY_HEAP0_SIZE 0x1960000
#define MEMORY_HEAP0 MEMORY_START_BASE
#define MEMORY_HEAP0_SIZE 0x16C0000
#define MEMORY_HEAP0 MEMORY_START_BASE
// clang-format off
const memory_values_t mem_vals_heap_2[] = {
{0x28000000 + 0x09000000, 0x28000000 + 0x09E20000}, // size: 14464 kB
{0, 0}
};
// clang-format on
#define MEMORY_HEAP1_SIZE 0xE20000
#define MEMORY_HEAP1 (MEMORY_HEAP0 + MEMORY_HEAP0_SIZE)
#define MEMORY_HEAP1_SIZE 0xE20000
#define MEMORY_HEAP1 (MEMORY_HEAP0 + MEMORY_HEAP0_SIZE)
// clang-format off
const memory_values_t mem_vals_heap_3[] = {
{0x28000000 + 0x058E0000, 0x28000000 + 0x06000000}, // size: 7296 kB
{0, 0}
};
// clang-format on
#define MEMORY_HEAP2_SIZE 0x720000
#define MEMORY_HEAP2 (MEMORY_HEAP1 + MEMORY_HEAP1_SIZE)
#define MEMORY_HEAP2_SIZE 0x720000
#define MEMORY_HEAP2 (MEMORY_HEAP1 + MEMORY_HEAP1_SIZE)
// clang-format off
const memory_values_t mem_vals_heap_4[] = {
{0x28000000 + 0x053C0000, 0x28000000 + 0x05880000}, // size: 4864 kB
{0, 0}
};
// clang-format on
#define MEMORY_HEAP3_SIZE 0x4C0000
#define MEMORY_HEAP3 (MEMORY_HEAP2 + MEMORY_HEAP2_SIZE)
#define MEMORY_HEAP3_SIZE 0x4C0000
#define MEMORY_HEAP3 (MEMORY_HEAP2 + MEMORY_HEAP2_SIZE)
#define MEMORY_HEAP4 (MEMORY_HEAP3 + MEMORY_HEAP3_SIZE)
#define MEMORY_HEAP4 (MEMORY_HEAP3 + MEMORY_HEAP3_SIZE)
// clang-format off
const memory_values_t mem_vals_video[] = {
// The GPU doesn't have access to the 0x28000000 - 0x32000000 area, so we need memory from somewhere else.
// From the SharedReadHeap of the loader.
@ -105,20 +116,23 @@ const memory_values_t mem_vals_video[] = {
//{0x18000000 , 0x18000000 +0x3000000}, // size: 3840 kB
{0, 0}
};
// clang-format on
#define MEMORY_START_VIDEO MEMORY_START_VIDEO_BASE
#define MEMORY_END_VIDEO (MEMORY_START_VIDEO + 0xE60000)
#define MEMORY_START_VIDEO MEMORY_START_VIDEO_BASE
#define MEMORY_END_VIDEO (MEMORY_START_VIDEO + 0xE60000)
// clang-format off
const memory_mapping_t mem_mapping[] = {
{MEMORY_HEAP0, MEMORY_HEAP1, mem_vals_heap_1},
{MEMORY_HEAP1, MEMORY_HEAP2, mem_vals_heap_2},
{MEMORY_HEAP2, MEMORY_HEAP3, mem_vals_heap_3},
{MEMORY_HEAP3, MEMORY_HEAP4, mem_vals_heap_4},
{MEMORY_HEAP0, MEMORY_HEAP1, mem_vals_heap_1},
{MEMORY_HEAP1, MEMORY_HEAP2, mem_vals_heap_2},
{MEMORY_HEAP2, MEMORY_HEAP3, mem_vals_heap_3},
{MEMORY_HEAP3, MEMORY_HEAP4, mem_vals_heap_4},
{MEMORY_START_VIDEO, MEMORY_END_VIDEO, mem_vals_video},
{0, 0, nullptr}
};
// clang-format on
// clang-format off
// Values needs to be aligned to 0x20000 and size needs to be a multiple of 0x20000
const memory_values_t mem_vals_heap[] = {
// 5.5.2 EUR
@ -162,6 +176,7 @@ const memory_values_t mem_vals_heap[] = {
{0, 0}
};
// clang-format on
uint32_t MemoryMapping_MEMGetAllocatableSize();
@ -186,12 +201,16 @@ void MemoryMapping_readTestValuesFromMemory();
void MemoryMapping_searchEmptyMemoryRegions();
void MemoryMapping_checkHeaps();
void *MemoryMapping_alloc(uint32_t size, int32_t align);
void *MemoryMapping_allocVideoMemory(uint32_t size, int32_t align);
void MemoryMapping_free(void *ptr);
MEMHeapHandle MemoryMapping_MEMFindContainHeap(void *block);
uint32_t MemoryMapping_getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize);
uint32_t MemoryMapping_PhysicalToEffective(uint32_t phyiscalAddress);

2
source/version.h Normal file
View File

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