Compare commits

...

63 Commits

Author SHA1 Message Date
Maschell
03ea0aceae Bump version to 0.2.7 2024-05-08 11:22:20 +02:00
Maschell
45efb02d27 Make sure all path checks are case-insensitive 2024-05-08 11:22:20 +02:00
Maschell
60b711cf81 Update Dockerfile 2024-05-06 16:34:44 +02:00
Maschell
884a3561d2 Replace FSWriteFile and FSReadFile only for the game/menu process 2024-04-28 18:20:19 +02:00
Maschell
f9a4b537c8 Skip stat if _DIRENT_HAVE_D_STAT is set 2024-04-28 15:31:48 +02:00
Maschell
835881abfa Add support for FS_LAYER_TYPE_SAVE_REPLACE_FOR_CURRENT_USER 2024-04-28 15:31:48 +02:00
Maschell
d0dfbd6d4e Hotfix for readdir bug in latest newlib version 2024-04-28 15:31:48 +02:00
Maschell
a2c8863cbe Revert "Add support for FS_LAYER_TYPE_SAVE_REPLACE_IGNORE_VOL_SAVE_COMMON"
This reverts commit 71406e2044.
2024-04-28 15:31:48 +02:00
Maschell
0d5bf8c78f Update Dockerfiles to use latest devkitPPC and wut 2024-04-24 18:38:31 +02:00
Maschell
9d0dbda1db Bump version to 0.2.6 2024-04-24 18:38:31 +02:00
Maschell
75854a05e5 Update .gitignore to ignore .zip files 2024-04-24 18:38:31 +02:00
dependabot[bot]
6c2748569d 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-24 18:38:31 +02:00
Maschell
71406e2044 Add support for FS_LAYER_TYPE_SAVE_REPLACE_IGNORE_VOL_SAVE_COMMON 2024-04-24 18:38:31 +02:00
dependabot[bot]
12e102a4a7 Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-17 11:15:45 +01:00
Callum Parsey
0df67fc7d9 Support "wb" mode for opening files
Hachihachi (the Nintendo DS emulator used in Virtual Console) crashes
when its save data is redirected to the SD card. It tries to open the
save-state files in "wb" mode which is currently rejected by the
ContentRedirectionModule. This causes the emulator's `SAVEOpenFile()`
call to fail, and the emulator immediately panics.

I am operating under the assumption that the Wii U's I/O system
doesn't differentiate between text and binary modes, like most other
operating systems. This is evidenced by the fact that the module
already supports "rb" mode and treats it in the same way as "r".
2023-11-17 11:15:25 +01:00
Maschell
f4f50748d7 Remove romfs usage 2023-11-17 11:15:05 +01:00
Maschell
98a137c91f Create dependabot.yml 2023-07-23 10:11:56 +02:00
Maschell
ef29402e54 Bump version 2023-07-19 19:22:17 +02:00
Maschell
473b3bfb94 Update Dockerfile 2023-07-19 16:18:27 +02:00
Maschell
b719da914d Update Dockerfile 2023-07-14 20:41:40 +02:00
Maschell
9e7299b65a Add missing imports 2023-07-14 20:41:40 +02:00
Maschell
96e8ddf97e Fix compiling with latest wut 2023-04-17 14:19:49 +02:00
Maschell
0bfa5be464 Change docker registry to ghcr.io 2023-03-18 16:25:22 +01:00
Maschell
9fc60b3189 Bump version to 0.2.4 2023-01-10 18:15:59 +01:00
Maschell
488df227eb Use the latest libfunctionpatcher version 2023-01-07 10:38:40 +01:00
Maschell
716deafb13 Update the CI to use a non-deprecated release action 2023-01-07 10:26:17 +01:00
Maschell
9f664abc6e Update CI to use actions/checkout@v3 2023-01-07 10:26:17 +01:00
Maschell
8a1c0bdb80 Update Dockerfile to use the latest WUMS version, add dependency to FunctionPatcherModule 2023-01-07 10:26:17 +01:00
Maschell
4300168ea4 Update version string 2022-10-11 15:12:28 +02:00
Maschell
eb0ff82425 Fix CRRemoveFSLayer return value 2022-10-11 14:44:10 +02:00
Maschell
f5266db613 Add support for /vol/aoc redirection 2022-10-10 20:11:57 +02:00
Maschell
8811d7ae0a Improve and fix logging 2022-10-10 20:11:57 +02:00
Maschell
ecd3cc03b2 Add missing FSAInit() call to fix directory merge with parents 2022-10-10 20:11:57 +02:00
Maschell
e46cf2c765 Update version to v0.2.2 2022-10-09 15:45:43 +02:00
Maschell
31045019c1 Improve commit messages for nightlies 2022-10-04 18:49:23 +02:00
Maschell
89c7fc26d8 Prevent calling OSCancelThread for ContentRedirection IO Threads 2022-10-04 18:49:23 +02:00
Maschell
f06f8ecc11 Bump the version 2022-09-19 22:21:40 +02:00
Maschell
ba76c15d1e Log the module version on each application start 2022-09-19 13:19:04 +02:00
Maschell
857461b735 Rewrite of almost everything to fix crashes and lags 2022-09-17 22:38:25 +02:00
Maschell
3be38d6ea9 Add default error value for FSMakeDirWrapper 2022-09-05 20:24:43 +02:00
Maschell
f7358bc380 Fix FSOpenFileWrapper result 2022-09-05 20:24:43 +02:00
Maschell
bfa30678a0 Implement mkdir 2022-09-05 20:24:43 +02:00
Maschell
7669f0f98a Update Dockerfile 2022-09-04 21:51:38 +02:00
Maschell
3cad13da9f Use ubuntu-22.04 instead of ubuntu-18.04 2022-09-04 18:44:06 +02:00
Maschell
18d97f8bd9 Add LICENSE 2022-09-04 18:44:06 +02:00
Maschell
34d9fbeb2f Update CRGetVersion 2022-09-04 18:44:06 +02:00
Maschell
cf51d1f724 Implement support for redirecting FSA function 2022-08-09 16:14:09 +02:00
Maschell
78ccbd0369 Improve setting the CWD for client, at basic error handling 2022-08-09 16:14:09 +02:00
Maschell
031ad15133 Fallback to "/" when no CWD for a given client was found 2022-08-09 16:14:09 +02:00
Maschell
db108068e4 Hook into FSAWriteFileWithPos to log usage, improve existing logging. 2022-08-09 16:14:09 +02:00
Maschell
61381fbb65 Rename void setWorkingDir -> setWorkingDirForFSClient and getFullPathForClient -> getFullPathForFSClient 2022-08-09 16:14:09 +02:00
Maschell
fca2193e40 Fix readdir wrapper 2022-08-08 18:10:19 +02:00
Maschell
eddbc7400e Fill FSStat with more information 2022-08-08 10:15:27 +02:00
Maschell
ce9ebde9ce Minor code cleanup 2022-08-08 10:15:27 +02:00
Maschell
78ca44dbf8 Fix logging the file size on stats wrapper 2022-08-08 10:15:27 +02:00
Maschell
aa58f1745f Return FSError instead of FSStatus in FSWrapper 2022-08-08 10:15:27 +02:00
Maschell
030195238f Remove don't remove extra error flags in FSOpenFileAsync as we end up in FSOpenFileExAsync anyway 2022-08-06 22:47:11 +02:00
Maschell
f420d5edad Add support for FSOpenFileEx(Async) 2022-08-06 22:47:11 +02:00
Maschell
487d1589f5 Add missing const to paths in function replacements 2022-08-06 22:47:11 +02:00
Maschell
72861fcd7f Update Dockerfile to use latest wut version 2022-07-25 13:12:10 -07:00
Maschell
8b7c53f991 Update Dockerfile to use latest WUMS version 2022-05-13 00:29:35 +02:00
Maschell
f3f6fae798 Use the latest libfunctionpatcher 2022-05-08 20:37:13 +02:00
Maschell
8043922311 Use shared_ptr/unique_ptr instead of raw ptr 2022-04-29 15:08:53 +02:00
30 changed files with 3566 additions and 1545 deletions

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

@ -7,17 +7,24 @@ on:
jobs:
clang-format:
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src
docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src
build-binary:
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: create version.h
run: |
git_hash=$(git rev-parse --short "$GITHUB_SHA")
cat <<EOF > ./src/version.h
#pragma once
#define VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary
run: |
docker build . -t builder
@ -28,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
@ -41,25 +48,12 @@ jobs:
- name: zip artifact
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
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/zip
generate_release_notes: true
name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
files: |
./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip

View File

@ -4,17 +4,17 @@ on: [pull_request]
jobs:
clang-format:
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src
docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src
check-build-with-logging:
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: build binary with logging
run: |
docker build . -t builder
@ -22,10 +22,17 @@ jobs:
docker run --rm -v ${PWD}:/project builder make clean
docker run --rm -v ${PWD}:/project builder make DEBUG=1
build-binary:
runs-on: ubuntu-18.04
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: create version.h
run: |
git_hash=$(git rev-parse --short "${{ github.event.pull_request.head.sha }}")
cat <<EOF > ./src/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,8 +1,7 @@
FROM wiiuenv/devkitppc:20220303
FROM ghcr.io/wiiu-env/devkitppc:20240505
COPY --from=wiiuenv/libfunctionpatcher:20220211 /artifacts $DEVKITPRO
COPY --from=wiiuenv/wiiumodulesystem:20220204 /artifacts $DEVKITPRO
COPY --from=wiiuenv/libromfs_wiiu:20220414 /artifacts $DEVKITPRO
COPY --from=wiiuenv/libcontentredirection:20220414 /artifacts $DEVKITPRO
COPY --from=ghcr.io/wiiu-env/libfunctionpatcher:20230621 /artifacts $DEVKITPRO
COPY --from=ghcr.io/wiiu-env/wiiumodulesystem:20240424 /artifacts $DEVKITPRO
COPY --from=ghcr.io/wiiu-env/libcontentredirection:20240428 /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

@ -37,7 +37,7 @@ CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CXXFLAGS := $(CFLAGS) -std=c++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libfunctionpatcher.ld $(WUMSSPECS)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) $(WUMSSPECS)
ifeq ($(DEBUG),1)
CXXFLAGS += -DDEBUG -g
@ -108,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
#-------------------------------------------------------------------------------

View File

@ -35,4 +35,4 @@ docker run -it --rm -v ${PWD}:/project contentredirectionmodule-builder make cle
## Format the code via docker
`docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src -i`
`docker run --rm -v ${PWD}:/src ghcr.io/wiiu-env/clang-format:13.0.0-2 -r ./src -i`

View File

@ -1,9 +1,9 @@
#pragma once
#include "DirInfo.h"
#include <coreinit/filesystem.h>
#include <coreinit/filesystem_fsa.h>
typedef struct FSDirectoryEntryEx {
FSDirectoryEntry realEntry{};
FSADirectoryEntry realEntry{};
bool isMarkedAsDeleted = false;
} FSDirectoryEntryEx;

732
src/FSAReplacements.cpp Normal file
View File

@ -0,0 +1,732 @@
#include "FSAReplacements.h"
#include "FileUtils.h"
#include "utils/logger.h"
#include <coreinit/core.h>
#include <coreinit/thread.h>
#include <malloc.h>
static FSError processFSAShimInThread(FSAShimBuffer *shimBuffer) {
FSError res;
if (gThreadsRunning) {
auto param = (FSShimWrapper *) malloc(sizeof(FSShimWrapper));
if (param == nullptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapper");
OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapper");
}
param->api = FS_SHIM_API_FSA;
param->sync = FS_SHIM_TYPE_SYNC;
param->shim = shimBuffer;
if (OSGetCurrentThread() == gThreadData[OSGetCoreId()].thread) {
res = processShimBufferForFSA(param);
//No need to clean "param", it has been already free'd in processFSAShimBuffer.
} else {
auto message = (FSShimWrapperMessage *) malloc(sizeof(FSShimWrapperMessage));
if (message == nullptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapperMessage");
OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapperMessage");
}
message->param = param;
constexpr int32_t messageSize = sizeof(message->messages) / sizeof(message->messages[0]);
OSInitMessageQueue(&message->messageQueue, message->messages, messageSize);
if (!sendMessageToThread(message)) {
DEBUG_FUNCTION_LINE_ERR("Failed to send message to thread");
OSFatal("ContentRedirectionModule: Failed send message to thread");
}
OSMessage recv;
if (!OSReceiveMessage(&message->messageQueue, &recv, OS_MESSAGE_FLAGS_BLOCKING)) {
DEBUG_FUNCTION_LINE_ERR("Failed to receive message");
OSFatal("ContentRedirectionModule: Failed to receive message");
}
if (recv.args[0] != FS_IO_QUEUE_SYNC_RESULT) {
DEBUG_FUNCTION_LINE_ERR("ContentRedirection: Unexpected message in message queue.");
OSFatal("ContentRedirection: Unexpected message in message queue.");
}
res = (FSError) recv.args[1];
// We only need to clean up "message". "param" has already been free'd by the other thread.
free(message);
}
} else {
res = FS_ERROR_FORCE_REAL_FUNCTION;
DEBUG_FUNCTION_LINE_WARN("Threads are not running yet, skip replacement");
}
return res;
}
DECL_FUNCTION(FSError, FSAOpenFileEx, FSAClientHandle client, const char *path, const char *mode, FSMode createMode, FSOpenFileFlags openFlag, uint32_t preallocSize, FSAFileHandle *handle) {
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_WARN("handle is null.");
return FS_ERROR_INVALID_BUFFER;
}
*handle = -1;
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestOpenFile(shimBuffer, client, path, mode, createMode, openFlag, preallocSize);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestOpenFile failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) handle;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAOpenFileEx" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAOpenFileEx(client, path, mode, createMode, openFlag, preallocSize, handle);
}
DECL_FUNCTION(FSError, FSAOpenFile, FSAClientHandle client, const char *path, const char *mode, FSAFileHandle *handle) {
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_WARN("handle is null.");
return FS_ERROR_INVALID_BUFFER;
}
*handle = -1;
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestOpenFile(shimBuffer, client, path, mode, static_cast<FSMode>(0x660), static_cast<FSOpenFileFlags>(0), 0);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestOpenFile failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) handle;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAOpenFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAOpenFile(client, path, mode, handle);
}
DECL_FUNCTION(FSError, FSACloseFile, FSAClientHandle client, FSAFileHandle handle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestCloseFile(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestCloseFile failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSACloseFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSACloseFile(client, handle);
}
DECL_FUNCTION(FSError, FSAFlushFile, FSAClientHandle client, FSAFileHandle handle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestFlushFile(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestFlushFile failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAFlushFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAFlushFile(client, handle);
}
DECL_FUNCTION(FSError, FSAGetStat, FSAClientHandle client, const char *path, FSAStat *stat) {
if (stat == nullptr) {
DEBUG_FUNCTION_LINE_WARN("stat is null.");
return FS_ERROR_INVALID_BUFFER;
}
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestQueryInfo(shimBuffer, client, path, FSA_QUERY_INFO_STAT);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) stat;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAGetStat" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAGetStat(client, path, stat);
}
DECL_FUNCTION(FSError, FSAGetStatFile, FSAClientHandle client, FSAFileHandle handle, FSAStat *stat) {
if (stat == nullptr) {
DEBUG_FUNCTION_LINE_WARN("stat is null.");
return FS_ERROR_INVALID_BUFFER;
}
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestStatFile(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) stat;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAGetStatFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAGetStatFile(client, handle, stat);
}
DECL_FUNCTION(FSError, FSARemove, FSAClientHandle client, const char *path) {
if (path == nullptr) {
DEBUG_FUNCTION_LINE_WARN("path is null.");
return FS_ERROR_INVALID_PARAM;
}
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestRemove(shimBuffer, client, path);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSARemove" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSARemove(client, path);
}
DECL_FUNCTION(FSError, FSARename, FSAClientHandle client, const char *oldPath, const char *newPath) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestRename(shimBuffer, client, oldPath, newPath);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSARename" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSARename(client, oldPath, newPath);
}
DECL_FUNCTION(FSError, FSASetPosFile, FSAClientHandle client, FSAFileHandle handle, FSAFilePosition pos) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestSetPos(shimBuffer, client, handle, pos);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSASetPosFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSASetPosFile(client, handle, pos);
}
DECL_FUNCTION(FSError, FSATruncateFile, FSAClientHandle client, FSAFileHandle handle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestTruncate(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSATruncateFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSATruncateFile(client, handle);
}
DECL_FUNCTION(FSError, FSAReadFile, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFileHandle handle, uint32_t flags) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestReadFile(shimBuffer, client, buffer, size, count, 0, handle, static_cast<FSAReadFlag>(flags & 0xfffffffe));
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAReadFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAReadFile(client, buffer, size, count, handle, flags);
}
DECL_FUNCTION(FSError, FSAReadFileWithPos, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFilePosition pos, FSAFileHandle handle, uint32_t flags) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestReadFile(shimBuffer, client, buffer, size, count, pos, handle, static_cast<FSAReadFlag>(flags | FSA_READ_FLAG_READ_WITH_POS));
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAReadFileWithPos" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAReadFileWithPos(client, buffer, size, count, pos, handle, flags);
}
DECL_FUNCTION(FSError, FSAWriteFile, FSAClientHandle client, const uint8_t *buffer, uint32_t size, uint32_t count, FSAFileHandle handle, uint32_t flags) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestWriteFile(shimBuffer, client, buffer, size, count, 0, handle, static_cast<FSAWriteFlag>(flags & 0xfffffffe));
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAWriteFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAWriteFile(client, buffer, size, count, handle, flags);
}
DECL_FUNCTION(FSError, FSAWriteFileWithPos, FSAClientHandle client, uint8_t *buffer, uint32_t size, uint32_t count, FSAFilePosition pos, FSAFileHandle handle, uint32_t flags) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestWriteFile(shimBuffer, client, buffer, size, count, pos, handle, static_cast<FSAWriteFlag>(flags | FSA_WRITE_FLAG_READ_WITH_POS));
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAWriteFileWithPos" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAWriteFileWithPos(client, buffer, size, count, pos, handle, flags);
}
DECL_FUNCTION(FSError, FSAGetPosFile, FSAClientHandle client, FSAFileHandle handle, FSAFilePosition *outPos) {
if (outPos == nullptr) {
DEBUG_FUNCTION_LINE_WARN("outPos is null.");
return FS_ERROR_INVALID_BUFFER;
}
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestGetPos(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) outPos;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAGetPosFile" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAGetPosFile(client, handle, outPos);
}
DECL_FUNCTION(FSError, FSAIsEof, FSAClientHandle client, FSAFileHandle handle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestIsEof(shimBuffer, client, handle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAIsEof" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAIsEof(client, handle);
}
DECL_FUNCTION(FSError, FSAFlushMultiQuota, FSAClientHandle client, const char *path) {
DEBUG_FUNCTION_LINE("NOT IMPLEMENTED. path %s", path);
return real_FSAFlushMultiQuota(client, path);
}
DECL_FUNCTION(FSError, FSAFlushQuota, FSAClientHandle client, const char *path) {
DEBUG_FUNCTION_LINE("NOT IMPLEMENTED. path %s", path);
return real_FSAFlushQuota(client, path);
}
DECL_FUNCTION(FSError, FSAChangeMode, FSAClientHandle client, const char *path, FSMode permission) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED path %s permission: %08X", path, permission);
return real_FSAChangeMode(client, path, permission);
}
DECL_FUNCTION(FSError, FSAOpenFileByStat, FSAClientHandle client, FSAStat *stat, const char *mode, const char *path, FSAFileHandle *outFileHandle) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED");
return real_FSAOpenFileByStat(client, stat, mode, path, outFileHandle);
}
DECL_FUNCTION(FSError, FSAAppendFile, FSAClientHandle client, FSAFileHandle fileHandle, uint32_t size, uint32_t count) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED");
return real_FSAAppendFile(client, fileHandle, size, count);
}
DECL_FUNCTION(FSError, FSAAppendFileEx, FSAClientHandle client, FSAFileHandle fileHandle, uint32_t size, uint32_t count, uint32_t flags) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED");
return real_FSAAppendFileEx(client, fileHandle, size, count, flags);
}
DECL_FUNCTION(FSError, FSAOpenDir, FSAClientHandle client, const char *path, FSADirectoryHandle *dirHandle) {
if (dirHandle == nullptr) {
DEBUG_FUNCTION_LINE_WARN("handle is null.");
return FS_ERROR_INVALID_BUFFER;
}
*dirHandle = -1;
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestOpenDir(shimBuffer, client, path);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) dirHandle;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAOpenDir(client, path, dirHandle);
}
DECL_FUNCTION(FSError, FSAReadDir, FSAClientHandle client, FSADirectoryHandle dirHandle, FSADirectoryEntry *directoryEntry) {
if (directoryEntry == nullptr) {
DEBUG_FUNCTION_LINE_WARN("handle is null.");
return FS_ERROR_INVALID_BUFFER;
}
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestReadDir(shimBuffer, client, dirHandle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) directoryEntry;
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAReadDir(client, dirHandle, directoryEntry);
}
DECL_FUNCTION(FSError, FSARewindDir, FSAClientHandle client, FSADirectoryHandle dirHandle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestRewindDir(shimBuffer, client, dirHandle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAOpenDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSARewindDir(client, dirHandle);
}
DECL_FUNCTION(FSError, FSACloseDir, FSAClientHandle client, FSADirectoryHandle dirHandle) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestCloseDir(shimBuffer, client, dirHandle);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSACloseDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSACloseDir(client, dirHandle);
}
DECL_FUNCTION(FSError, FSAMakeDir, FSAClientHandle client, const char *path, FSMode mode) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestMakeDir(shimBuffer, client, path, mode);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAMakeDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAMakeDir(client, path, mode);
}
DECL_FUNCTION(FSError, FSAChangeDir, FSAClientHandle client, const char *path) {
auto *shimBuffer = (FSAShimBuffer *) memalign(0x20, sizeof(FSAShimBuffer));
if (!shimBuffer) {
DEBUG_FUNCTION_LINE_WARN("FS_ERROR_OUT_OF_RESOURCES");
return FS_ERROR_OUT_OF_RESOURCES;
}
auto res = fsaShimPrepareRequestChangeDir(shimBuffer, client, path);
if (res != FS_ERROR_OK) {
free(shimBuffer);
DEBUG_FUNCTION_LINE_WARN("fsaShimPrepareRequestQueryInfo failed");
return res;
}
res = processFSAShimInThread(shimBuffer);
free(shimBuffer);
if (res != FS_ERROR_FORCE_REAL_FUNCTION) {
return res;
}
// Other plugins/modules may override this function as well, so we need to call "real_FSAChangeDir" instead of using
// the existing shimBuffer (which would be more efficient).
return real_FSAChangeDir(client, path);
}
function_replacement_data_t fsa_file_function_replacements[] = {
REPLACE_FUNCTION(FSAOpenFile, LIBRARY_COREINIT, FSAOpenFile),
REPLACE_FUNCTION(FSAOpenFileEx, LIBRARY_COREINIT, FSAOpenFileEx),
REPLACE_FUNCTION(FSACloseFile, LIBRARY_COREINIT, FSACloseFile),
REPLACE_FUNCTION(FSAFlushFile, LIBRARY_COREINIT, FSAFlushFile),
REPLACE_FUNCTION(FSAGetStat, LIBRARY_COREINIT, FSAGetStat),
REPLACE_FUNCTION(FSAGetStatFile, LIBRARY_COREINIT, FSAGetStatFile),
REPLACE_FUNCTION(FSARemove, LIBRARY_COREINIT, FSARemove),
REPLACE_FUNCTION(FSARename, LIBRARY_COREINIT, FSARename),
REPLACE_FUNCTION(FSASetPosFile, LIBRARY_COREINIT, FSASetPosFile),
REPLACE_FUNCTION(FSATruncateFile, LIBRARY_COREINIT, FSATruncateFile),
REPLACE_FUNCTION(FSAReadFile, LIBRARY_COREINIT, FSAReadFile),
REPLACE_FUNCTION(FSAReadFileWithPos, LIBRARY_COREINIT, FSAReadFileWithPos),
REPLACE_FUNCTION(FSAWriteFile, LIBRARY_COREINIT, FSAWriteFile),
REPLACE_FUNCTION(FSAWriteFileWithPos, LIBRARY_COREINIT, FSAWriteFileWithPos),
REPLACE_FUNCTION(FSAGetPosFile, LIBRARY_COREINIT, FSAGetPosFile),
REPLACE_FUNCTION(FSAIsEof, LIBRARY_COREINIT, FSAIsEof),
REPLACE_FUNCTION(FSAFlushMultiQuota, LIBRARY_COREINIT, FSAFlushMultiQuota),
REPLACE_FUNCTION(FSAFlushQuota, LIBRARY_COREINIT, FSAFlushQuota),
REPLACE_FUNCTION(FSAChangeMode, LIBRARY_COREINIT, FSAChangeMode),
REPLACE_FUNCTION(FSAOpenFileByStat, LIBRARY_COREINIT, FSAOpenFileByStat),
REPLACE_FUNCTION(FSAAppendFile, LIBRARY_COREINIT, FSAAppendFile),
REPLACE_FUNCTION(FSAAppendFileEx, LIBRARY_COREINIT, FSAAppendFileEx),
REPLACE_FUNCTION(FSAOpenDir, LIBRARY_COREINIT, FSAOpenDir),
REPLACE_FUNCTION(FSAReadDir, LIBRARY_COREINIT, FSAReadDir),
REPLACE_FUNCTION(FSARewindDir, LIBRARY_COREINIT, FSARewindDir),
REPLACE_FUNCTION(FSACloseDir, LIBRARY_COREINIT, FSACloseDir),
REPLACE_FUNCTION(FSAMakeDir, LIBRARY_COREINIT, FSAMakeDir),
REPLACE_FUNCTION(FSAChangeDir, LIBRARY_COREINIT, FSAChangeDir),
};
uint32_t fsa_file_function_replacements_size = sizeof(fsa_file_function_replacements) / sizeof(function_replacement_data_t);
FSError processShimBufferForFSA(FSShimWrapper *param) {
auto res = doForLayer(param);
if (res == FS_ERROR_FORCE_REAL_FUNCTION) {
if (param->sync == FS_SHIM_TYPE_ASYNC) {
DEBUG_FUNCTION_LINE_ERR("ASYNC FSA API is not supported");
OSFatal("ContentRedirectionModule: ASYNC FSA API is not supported");
}
}
free(param);
return res;
}

15
src/FSAReplacements.h Normal file
View File

@ -0,0 +1,15 @@
#pragma once
#include <function_patcher/function_patching.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
extern function_replacement_data_t fsa_file_function_replacements[];
extern uint32_t fsa_file_function_replacements_size;
#ifdef __cplusplus
}
#endif

View File

@ -1,220 +0,0 @@
#include "FSDirReplacements.h"
#include "FileUtils.h"
#include "IFSWrapper.h"
#include "utils/logger.h"
#include <coreinit/cache.h>
#include <coreinit/filesystem.h>
DECL_FUNCTION(FSStatus, FSOpenDir, FSClient *client, FSCmdBlock *block, char *path, FSDirectoryHandle *handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSOpenDir(client, block, path, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = path](FSErrorFlag realErrorMask) -> FSStatus {
auto res = real_FSOpenDir(c, b, p, h, realErrorMask);
return res;
},
[f = getFullPathForClient(client, path), h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSOpenDirWrapper(f.c_str(), h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSOpenDirAsync, FSClient *client, FSCmdBlock *block, char *path, FSDirectoryHandle *handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSOpenDirAsync(client, block, path, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = path, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSOpenDirAsync(c, b, p, h, realErrorMask, a);
},
[f = getFullPathForClient(client, path), h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSOpenDirWrapper(f.c_str(), h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadDir, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, [[maybe_unused]] FSDirectoryEntry *entry, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("", errorMask);
if (isForceRealFunction(errorMask)) {
return real_FSReadDir(client, block, handle, entry, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, e = entry](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadDir(c, b, h, e, realErrorMask);
},
[h = handle, e = entry](IFSWrapper *layer) -> FSStatus {
return layer->FSReadDirWrapper(h, e);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSDirectoryEntry *entry, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE();
if (isForceRealFunction(errorMask)) {
return real_FSReadDirAsync(client, block, handle, entry, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, e = entry, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadDirAsync(c, b, h, e, realErrorMask, a);
},
[h = handle, e = entry](IFSWrapper *layer) -> FSStatus {
return layer->FSReadDirWrapper(h, e);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSCloseDir, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSCloseDir(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSCloseDir(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSCloseDirWrapper(h);
},
[h = handle, filename = __FILENAME__, func = __FUNCTION__, line = __LINE__](IFSWrapper *layer, FSStatus res) -> FSStatus {
if (layer->isValidDirHandle(h)) {
layer->deleteDirHandle(h);
} else {
DEBUG_FUNCTION_LINE_ERR_LAMBDA(filename, func, line, "Expected to delete dirHandle by %08X but it was not found", h);
}
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Sync result %d", res);
return res;
});
}
DECL_FUNCTION(FSStatus, FSCloseDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE();
if (isForceRealFunction(errorMask)) {
return real_FSCloseDirAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSCloseDirAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSCloseDirWrapper(h);
},
[c = client, b = block, h = handle, a = asyncData, filename = __FILENAME__, func = __FUNCTION__, line = __LINE__](IFSWrapper *layer, FSStatus res) -> FSStatus {
if (layer->isValidDirHandle(h)) {
layer->deleteDirHandle(h);
} else {
DEBUG_FUNCTION_LINE_ERR_LAMBDA(filename, func, line, "Expected to delete dirHandle by %08X but it was not found", h);
}
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Async result %d", res);
return send_result_async(c, b, a, res);
});
}
DECL_FUNCTION(FSStatus, FSRewindDir, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSRewindDir(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRewindDir(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSRewindDirWrapper(h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSRewindDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE();
if (isForceRealFunction(errorMask)) {
return real_FSRewindDirAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRewindDirAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSRewindDirWrapper(h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSMakeDir, FSClient *client, FSCmdBlock *block, char *path, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSMakeDir(client, block, path, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSMakeDir(c, b, p, realErrorMask);
},
[f = getFullPathForClient(client, path)](IFSWrapper *layer) -> FSStatus {
return layer->FSMakeDirWrapper(f.c_str());
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSMakeDirAsync, FSClient *client, FSCmdBlock *block, char *path, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSMakeDirAsync(client, block, path, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSMakeDirAsync(c, b, p, realErrorMask, a);
},
[f = getFullPathForClient(client, path)](IFSWrapper *layer) -> FSStatus {
return layer->FSMakeDirWrapper(f.c_str());
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSChangeDirAsync, FSClient *client, FSCmdBlock *block, const char *path, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("FSChangeDirAsync %s", path);
setWorkingDir(client, path);
return real_FSChangeDirAsync(client, block, path, errorMask, asyncData);
}
function_replacement_data_t fs_dir_function_replacements[] = {
REPLACE_FUNCTION(FSOpenDir, LIBRARY_COREINIT, FSOpenDir),
REPLACE_FUNCTION(FSOpenDirAsync, LIBRARY_COREINIT, FSOpenDirAsync),
REPLACE_FUNCTION(FSReadDir, LIBRARY_COREINIT, FSReadDir),
REPLACE_FUNCTION(FSReadDirAsync, LIBRARY_COREINIT, FSReadDirAsync),
REPLACE_FUNCTION(FSCloseDir, LIBRARY_COREINIT, FSCloseDir),
REPLACE_FUNCTION(FSCloseDirAsync, LIBRARY_COREINIT, FSCloseDirAsync),
REPLACE_FUNCTION(FSRewindDir, LIBRARY_COREINIT, FSRewindDir),
REPLACE_FUNCTION(FSRewindDirAsync, LIBRARY_COREINIT, FSRewindDirAsync),
REPLACE_FUNCTION(FSMakeDir, LIBRARY_COREINIT, FSMakeDir),
REPLACE_FUNCTION(FSMakeDirAsync, LIBRARY_COREINIT, FSMakeDirAsync),
REPLACE_FUNCTION(FSChangeDirAsync, LIBRARY_COREINIT, FSChangeDirAsync),
};
uint32_t fs_dir_function_replacements_size = sizeof(fs_dir_function_replacements) / sizeof(function_replacement_data_t);

View File

@ -1,11 +0,0 @@
#pragma once
#include "IFSWrapper.h"
#include <coreinit/filesystem.h>
#include <function_patcher/function_patching.h>
#include <functional>
#include <string>
extern function_replacement_data_t fs_dir_function_replacements[];
extern uint32_t fs_dir_function_replacements_size;

View File

@ -1,574 +0,0 @@
#include "FSFileReplacements.h"
#include "FileUtils.h"
#include "utils/logger.h"
#include <coreinit/dynload.h>
#include <cstdarg>
DECL_FUNCTION(FSStatus, FSOpenFile, FSClient *client, FSCmdBlock *block, char *path, const char *mode, FSFileHandle *handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSOpenFile(client, block, path, mode, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, m = mode, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSOpenFile(c, b, p, m, h, realErrorMask);
},
[f = getFullPathForClient(client, path), m = mode, h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSOpenFileWrapper(f.c_str(), m, h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSOpenFileAsync, FSClient *client, FSCmdBlock *block, char *path, const char *mode, FSFileHandle *handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSOpenFileAsync(client, block, path, mode, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, m = mode, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSOpenFileAsync(c, b, p, m, h, realErrorMask, a);
},
[p = getFullPathForClient(client, path), m = mode, h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSOpenFileWrapper(p.c_str(), m, h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSCloseFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSCloseFile(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSCloseFile(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSCloseFileWrapper(h);
},
[h = handle, filename = __FILENAME__, func = __FUNCTION__, line = __LINE__](IFSWrapper *layer, FSStatus res) -> FSStatus {
if (layer->isValidFileHandle(h)) {
layer->deleteFileHandle(h);
} else {
DEBUG_FUNCTION_LINE_ERR_LAMBDA(filename, func, line, "Expected to delete fileHandle by handle %08X but it was not found", h);
}
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Sync result %d", res);
return res;
});
}
DECL_FUNCTION(FSStatus, FSCloseFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSCloseFileAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSCloseFileAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSCloseFileWrapper(h);
},
[c = client, b = block, h = handle, a = asyncData, filename = __FILENAME__, func = __FUNCTION__, line = __LINE__](IFSWrapper *layer, FSStatus res) -> FSStatus {
if (layer->isValidFileHandle(h)) {
layer->deleteFileHandle(h);
} else {
DEBUG_FUNCTION_LINE_ERR_LAMBDA(filename, func, line, "Expected to delete fileHandle by handle %08X but it was not found", h);
}
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Async result %d", res);
return send_result_async(c, b, a, res);
});
}
DECL_FUNCTION(FSStatus, FSGetStat, FSClient *client, FSCmdBlock *block, char *path, FSStat *stats, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSGetStat(client, block, path, stats, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, s = stats](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetStat(c, b, p, s, realErrorMask);
},
[p = getFullPathForClient(client, path), s = stats](IFSWrapper *layer) -> FSStatus {
return layer->FSGetStatWrapper(p.c_str(), s);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSGetStatAsync, FSClient *client, FSCmdBlock *block, char *path, FSStat *stats, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSGetStatAsync(client, block, path, stats, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, s = stats, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetStatAsync(c, b, p, s, realErrorMask, a);
},
[p = getFullPathForClient(client, path), s = stats](IFSWrapper *layer) -> FSStatus {
return layer->FSGetStatWrapper(p.c_str(), s);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSGetStatFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSStat *stats, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSGetStatFile(client, block, handle, stats, getRealErrorFlag(errorMask));
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = stats](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetStatFile(c, b, h, s, realErrorMask);
},
[h = handle, s = stats](IFSWrapper *layer) -> FSStatus {
return layer->FSGetStatFileWrapper(h, s);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSGetStatFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSStat *stats, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSGetStatFileAsync(client, block, handle, stats, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = stats, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetStatFileAsync(c, b, h, s, realErrorMask, a);
},
[h = handle, s = stats](IFSWrapper *layer) -> FSStatus {
return layer->FSGetStatFileWrapper(h, s);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadFile, FSClient *client, FSCmdBlock *block, void *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSReadFile(client, block, buffer, size, count, handle, unk1, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = size, co = count, bu = buffer, u = unk1](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadFile(c, b, bu, s, co, h, u, realErrorMask);
},
[b = buffer, s = size, c = count, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSReadFileWrapper(b, s, c, h, u);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadFileAsync, FSClient *client, FSCmdBlock *block, void *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, FSErrorFlag errorMask,
FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSReadFileAsync(client, block, buffer, size, count, handle, unk1, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = size, co = count, bu = buffer, u = unk1, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadFileAsync(c, b, bu, s, co, h, u, realErrorMask, a);
},
[b = buffer, s = size, c = count, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSReadFileWrapper(b, s, c, h, u);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadFileWithPos, FSClient *client, FSCmdBlock *block, void *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, uint32_t unk1, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSReadFileWithPos(client, block, buffer, size, count, pos, handle, unk1, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = size, co = count, p = pos, bu = buffer, u = unk1](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadFileWithPos(c, b, bu, s, co, p, h, u, realErrorMask);
},
[b = buffer, s = size, c = count, p = pos, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSReadFileWithPosWrapper(b, s, c, p, h, u);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSReadFileWithPosAsync, FSClient *client, FSCmdBlock *block, void *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, int32_t unk1, FSErrorFlag errorMask,
FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSReadFileWithPosAsync(client, block, buffer, size, count, pos, handle, unk1, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, s = size, co = count, p = pos, bu = buffer, u = unk1, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSReadFileWithPosAsync(c, b, bu, s, co, p, h, u, realErrorMask, a);
},
[b = buffer, s = size, c = count, p = pos, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSReadFileWithPosWrapper(b, s, c, p, h, u);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSSetPosFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t pos, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSSetPosFile(client, block, handle, pos, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = pos](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSSetPosFile(c, b, h, p, realErrorMask);
},
[h = handle, p = pos](IFSWrapper *layer) -> FSStatus {
return layer->FSSetPosFileWrapper(h, p);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSSetPosFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t pos, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSSetPosFileAsync(client, block, handle, pos, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = pos, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSSetPosFileAsync(c, b, h, p, realErrorMask, a);
},
[h = handle, p = pos](IFSWrapper *layer) -> FSStatus {
return layer->FSSetPosFileWrapper(h, p);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSGetPosFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t *pos, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSGetPosFile(client, block, handle, pos, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = pos](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetPosFile(c, b, h, p, realErrorMask);
},
[h = handle, p = pos](IFSWrapper *layer) -> FSStatus {
return layer->FSGetPosFileWrapper(h, p);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSGetPosFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t *pos, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSGetPosFileAsync(client, block, handle, pos, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, p = pos, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSGetPosFileAsync(c, b, h, p, realErrorMask, a);
},
[h = handle, p = pos](IFSWrapper *layer) -> FSStatus {
return layer->FSGetPosFileWrapper(h, p);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSIsEof, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSIsEof(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSIsEof(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSIsEofWrapper(h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSIsEofAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSIsEofAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSIsEofAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSIsEofWrapper(h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSWriteFile, FSClient *client, FSCmdBlock *block, uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSWriteFile(client, block, buffer, size, count, handle, unk1, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, bu = buffer, s = size, co = count, h = handle, u = unk1](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSWriteFile(c, b, bu, s, co, h, u, realErrorMask);
},
[b = buffer, s = size, c = count, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSWriteFileWrapper(b, s, c, h, u);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSWriteFileAsync, FSClient *client, FSCmdBlock *block, uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, FSErrorFlag errorMask,
FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSWriteFileAsync(client, block, buffer, size, count, handle, unk1, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, bu = buffer, s = size, co = count, h = handle, u = unk1, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSWriteFileAsync(c, b, bu, s, co, h, u, realErrorMask, a);
},
[b = buffer, s = size, c = count, h = handle, u = unk1](IFSWrapper *layer) -> FSStatus {
return layer->FSWriteFileWrapper(b, s, c, h, u);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSTruncateFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSTruncateFile(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSTruncateFile(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSTruncateFileWrapper(h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSTruncateFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSTruncateFileAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSTruncateFileAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSTruncateFileWrapper(h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSRemove, FSClient *client, FSCmdBlock *block, char *path, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSRemove(client, block, path, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRemove(c, b, p, realErrorMask);
},
[p = getFullPathForClient(client, path)](IFSWrapper *layer) -> FSStatus {
return layer->FSRemoveWrapper(p.c_str());
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSRemoveAsync, FSClient *client, FSCmdBlock *block, char *path, [[maybe_unused]] FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s", path);
if (isForceRealFunction(errorMask)) {
return real_FSRemoveAsync(client, block, path, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, p = path, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRemoveAsync(c, b, p, realErrorMask, a);
},
[p = getFullPathForClient(client, path)](IFSWrapper *layer) -> FSStatus {
return layer->FSRemoveWrapper(p.c_str());
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSRename, FSClient *client, FSCmdBlock *block, char *oldPath, char *newPath, FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("%s -> %s", oldPath, newPath);
if (isForceRealFunction(errorMask)) {
return real_FSRename(client, block, oldPath, newPath, getRealErrorFlag(errorMask));
}
return doForLayer(
client,
errorMask,
[c = client, b = block, oP = oldPath, nP = newPath](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRename(c, b, oP, nP, realErrorMask);
},
[oP = getFullPathForClient(client, oldPath), nP = getFullPathForClient(client, newPath)](IFSWrapper *layer) -> FSStatus {
return layer->FSRenameWrapper(oP.c_str(), nP.c_str());
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSRenameAsync,
FSClient *client,
FSCmdBlock *block,
char *oldPath,
char *newPath,
FSErrorFlag errorMask,
FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("%s -> %s", oldPath, newPath);
if (isForceRealFunction(errorMask)) {
return real_FSRenameAsync(client, block, oldPath, newPath, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, oP = oldPath, nP = newPath, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSRenameAsync(c, b, oP, nP, realErrorMask, a);
},
[oP = getFullPathForClient(client, oldPath), nP = getFullPathForClient(client, newPath)](IFSWrapper *layer) -> FSStatus {
return layer->FSRenameWrapper(oP.c_str(), nP.c_str());
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSFlushFile, FSClient *client, FSCmdBlock *block, [[maybe_unused]] FSFileHandle handle, [[maybe_unused]] FSErrorFlag errorMask) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSFlushFile(client, block, handle, errorMask);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSFlushFile(c, b, h, realErrorMask);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSFlushFileWrapper(h);
},
SYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSFlushFileAsync, FSClient *client, FSCmdBlock *block, [[maybe_unused]] FSFileHandle handle, [[maybe_unused]] FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_VERBOSE("");
if (isForceRealFunction(errorMask)) {
return real_FSFlushFileAsync(client, block, handle, getRealErrorFlag(errorMask), asyncData);
}
return doForLayer(
client,
errorMask,
[c = client, b = block, h = handle, a = asyncData](FSErrorFlag realErrorMask) -> FSStatus {
return real_FSFlushFileAsync(c, b, h, realErrorMask, a);
},
[h = handle](IFSWrapper *layer) -> FSStatus {
return layer->FSFlushFileWrapper(h);
},
ASYNC_RESULT_HANDLER);
}
DECL_FUNCTION(FSStatus, FSChangeModeAsync,
FSClient *client,
FSCmdBlock *block,
char *path,
[[maybe_unused]] FSMode mode,
[[maybe_unused]] FSMode modeMask,
[[maybe_unused]] FSErrorFlag errorMask,
FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED FSChangeModeAsync %s mode: %08X", path, mode);
return real_FSChangeModeAsync(client, block, path, mode, modeMask, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSGetFreeSpaceSizeAsync, FSClient *client, FSCmdBlock *block, char *path, [[maybe_unused]] uint64_t *outSize, [[maybe_unused]] FSErrorFlag errorMask, FSAsyncData *asyncData) {
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED FSGetFreeSpaceSizeAsync %s", path);
return real_FSGetFreeSpaceSizeAsync(client, block, path, outSize, errorMask, asyncData);
}
function_replacement_data_t fs_file_function_replacements[] = {
REPLACE_FUNCTION(FSOpenFile, LIBRARY_COREINIT, FSOpenFile),
REPLACE_FUNCTION(FSOpenFileAsync, LIBRARY_COREINIT, FSOpenFileAsync),
REPLACE_FUNCTION(FSCloseFile, LIBRARY_COREINIT, FSCloseFile),
REPLACE_FUNCTION(FSCloseFileAsync, LIBRARY_COREINIT, FSCloseFileAsync),
REPLACE_FUNCTION(FSGetStat, LIBRARY_COREINIT, FSGetStat),
REPLACE_FUNCTION(FSGetStatAsync, LIBRARY_COREINIT, FSGetStatAsync),
REPLACE_FUNCTION(FSGetStatFile, LIBRARY_COREINIT, FSGetStatFile),
REPLACE_FUNCTION(FSGetStatFileAsync, LIBRARY_COREINIT, FSGetStatFileAsync),
REPLACE_FUNCTION(FSReadFile, LIBRARY_COREINIT, FSReadFile),
REPLACE_FUNCTION(FSReadFileAsync, LIBRARY_COREINIT, FSReadFileAsync),
REPLACE_FUNCTION(FSReadFileWithPos, LIBRARY_COREINIT, FSReadFileWithPos),
REPLACE_FUNCTION(FSReadFileWithPosAsync, LIBRARY_COREINIT, FSReadFileWithPosAsync),
REPLACE_FUNCTION(FSSetPosFile, LIBRARY_COREINIT, FSSetPosFile),
REPLACE_FUNCTION(FSSetPosFileAsync, LIBRARY_COREINIT, FSSetPosFileAsync),
REPLACE_FUNCTION(FSGetPosFile, LIBRARY_COREINIT, FSGetPosFile),
REPLACE_FUNCTION(FSGetPosFileAsync, LIBRARY_COREINIT, FSGetPosFileAsync),
REPLACE_FUNCTION(FSIsEof, LIBRARY_COREINIT, FSIsEof),
REPLACE_FUNCTION(FSIsEofAsync, LIBRARY_COREINIT, FSIsEofAsync),
REPLACE_FUNCTION(FSWriteFile, LIBRARY_COREINIT, FSWriteFile),
REPLACE_FUNCTION(FSWriteFileAsync, LIBRARY_COREINIT, FSWriteFileAsync),
REPLACE_FUNCTION(FSTruncateFile, LIBRARY_COREINIT, FSTruncateFile),
REPLACE_FUNCTION(FSTruncateFileAsync, LIBRARY_COREINIT, FSTruncateFileAsync),
REPLACE_FUNCTION(FSRemove, LIBRARY_COREINIT, FSRemove),
REPLACE_FUNCTION(FSRemoveAsync, LIBRARY_COREINIT, FSRemoveAsync),
REPLACE_FUNCTION(FSRename, LIBRARY_COREINIT, FSRename),
REPLACE_FUNCTION(FSRenameAsync, LIBRARY_COREINIT, FSRenameAsync),
REPLACE_FUNCTION(FSFlushFile, LIBRARY_COREINIT, FSFlushFile),
REPLACE_FUNCTION(FSFlushFileAsync, LIBRARY_COREINIT, FSFlushFileAsync),
REPLACE_FUNCTION(FSChangeModeAsync, LIBRARY_COREINIT, FSChangeModeAsync),
//REPLACE_FUNCTION(FSGetFreeSpaceSizeAsync, LIBRARY_COREINIT, FSGetFreeSpaceSizeAsync),
//REPLACE_FUNCTION_VIA_ADDRESS(FSGetFreeSpaceSizeAsync, LIBRARY_COREINIT, 0x0A000000 + 0x0256079c),
};
uint32_t fs_file_function_replacements_size = sizeof(fs_file_function_replacements) / sizeof(function_replacement_data_t);

811
src/FSReplacements.cpp Normal file
View File

@ -0,0 +1,811 @@
#include "FSReplacements.h"
#include "FileUtils.h"
#include "utils/StringTools.h"
#include "utils/logger.h"
#include <coreinit/core.h>
#include <coreinit/thread.h>
FSStatus processFSError(FSError fsError, FSClient *client, FSErrorFlag errorMask) {
auto result = fsError >= 0 ? static_cast<FSStatus>(fsError) : fsaDecodeFsaStatusToFsStatus(fsError);
if (result >= FS_STATUS_OK || result == FS_STATUS_END || result == FS_STATUS_CANCELLED) {
return result;
}
FSErrorFlag errorFlags = FS_ERROR_FLAG_NONE;
bool forceError = false;
switch ((int32_t) result) {
case FS_STATUS_MAX:
errorFlags = FS_ERROR_FLAG_MAX;
break;
case FS_STATUS_ALREADY_OPEN:
errorFlags = FS_ERROR_FLAG_ALREADY_OPEN;
break;
case FS_STATUS_EXISTS:
errorFlags = FS_ERROR_FLAG_EXISTS;
break;
case FS_STATUS_NOT_FOUND:
errorFlags = FS_ERROR_FLAG_NOT_FOUND;
break;
case FS_STATUS_NOT_FILE:
errorFlags = FS_ERROR_FLAG_NOT_FILE;
break;
case FS_STATUS_NOT_DIR:
errorFlags = FS_ERROR_FLAG_NOT_DIR;
break;
case FS_STATUS_ACCESS_ERROR:
errorFlags = FS_ERROR_FLAG_ACCESS_ERROR;
break;
case FS_STATUS_PERMISSION_ERROR:
errorFlags = FS_ERROR_FLAG_PERMISSION_ERROR;
break;
case FS_STATUS_FILE_TOO_BIG:
errorFlags = FS_ERROR_FLAG_FILE_TOO_BIG;
break;
case FS_STATUS_STORAGE_FULL:
errorFlags = FS_ERROR_FLAG_STORAGE_FULL;
break;
case FS_STATUS_JOURNAL_FULL:
errorFlags = FS_ERROR_FLAG_JOURNAL_FULL;
break;
case FS_STATUS_UNSUPPORTED_CMD:
errorFlags = FS_ERROR_FLAG_UNSUPPORTED_CMD;
break;
case FS_STATUS_MEDIA_NOT_READY:
case FS_STATUS_MEDIA_ERROR:
case FS_STATUS_CORRUPTED:
case FS_STATUS_FATAL_ERROR:
forceError = true;
break;
case FS_STATUS_OK:
break;
}
if (forceError || (errorMask != FS_ERROR_FLAG_NONE && (errorFlags & errorMask) == 0)) {
DEBUG_FUNCTION_LINE_ERR("Transit to Fatal Error. Error %s (%d)", FSAGetStatusStr(fsError), fsError);
auto clientBody = fsClientGetBody(client);
fsClientHandleFatalErrorAndBlock(clientBody, clientBody->lastError);
return FS_STATUS_FATAL_ERROR;
}
return result;
}
void handleAsyncRequestsCallback(IOSError err, void *context) {
auto *param = (AsyncParamFS *) context;
auto *client = param->client;
auto *clientBody = fsClientGetBody(client);
auto *block = param->block;
auto *asyncData = &param->asyncData;
auto errorMask = param->errorMask;
auto fsError = __FSAShimDecodeIosErrorToFsaStatus(clientBody->clientHandle, err);
auto fsStatus = processFSError(fsError, client, errorMask);
handleAsyncResult(client, block, asyncData, fsStatus);
}
bool processFSAShimInThread(FSAShimBuffer *shimBuffer, FSClient *client, FSCmdBlock *block, FSErrorFlag errorMask, FSAsyncData *asyncData) {
bool res = false;
if (gThreadsRunning) {
// we **don't** need to free this in this function.
auto param = (FSShimWrapper *) malloc(sizeof(FSShimWrapper));
if (param == nullptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapper");
OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapper");
}
param->api = FS_SHIM_API_FS;
param->sync = FS_SHIM_TYPE_ASYNC;
param->shim = shimBuffer;
param->asyncFS.callback = handleAsyncRequestsCallback;
// The client and block have to valid during the whole fs operation
param->asyncFS.client = client;
param->asyncFS.block = block;
// But we need to copy the asyncData as it might be on the stack.
param->asyncFS.asyncData.param = asyncData->param;
param->asyncFS.asyncData.callback = asyncData->callback;
param->asyncFS.asyncData.ioMsgQueue = asyncData->ioMsgQueue;
// Copy by value
param->asyncFS.errorMask = errorMask;
if (OSGetCurrentThread() == gThreadData[OSGetCoreId()].thread) {
processShimBufferForFS(param);
// because we're doing this in sync, free(param) has already been called at this point.
res = true;
} else {
auto message = (FSShimWrapperMessage *) malloc(sizeof(FSShimWrapperMessage));
if (message == nullptr) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for FSShimWrapperMessage");
OSFatal("ContentRedirectionModule: Failed to allocate memory for FSShimWrapperMessage");
}
message->param = param;
res = sendMessageToThread(message);
// the other thread is call free for us, so we can return early!
}
} else {
DEBUG_FUNCTION_LINE_WARN("Threads are not running yet, skip replacement");
}
return res;
}
DECL_FUNCTION(FSStatus, FSReadFileGeneric, FSClient *client, FSCmdBlock *block, uint8_t *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAReadFlag readFlag, FSErrorFlag errorMask,
FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
// Ensure size * count is not > 32 bit.
auto bytes = uint64_t{size} * uint64_t{count};
if (bytes > 0xFFFFFFFFull) {
DEBUG_FUNCTION_LINE_ERR("FS doesn't support transaction size >= 4GB.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PARAM);
return FS_STATUS_FATAL_ERROR;
}
if (((uint32_t) buffer & 0x3f) != 0) {
DEBUG_FUNCTION_LINE_ERR("buffer must be aligned by FS_IO_BUFFER_ALIGN");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_ALIGNMENT);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestReadFile(shimBuffer, clientBody->clientHandle, buffer, size, count, pos, handle, readFlag) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSReadFileGeneric(client, block, buffer, size, count, pos, handle, readFlag, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSWriteFileGeneric, FSClient *client, FSCmdBlock *block, const uint8_t *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAWriteFlag writeFlag, FSErrorFlag errorMask,
FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
// Ensure size * count is not > 32 bit.
auto bytes = uint64_t{size} * uint64_t{count};
if (bytes > 0xFFFFFFFFull) {
DEBUG_FUNCTION_LINE_ERR("FS doesn't support transaction size >= 4GB.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PARAM);
return FS_STATUS_FATAL_ERROR;
}
if (((uint32_t) buffer & 0x3f) != 0) {
DEBUG_FUNCTION_LINE_ERR("buffer must be aligned by FS_IO_BUFFER_ALIGN");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_ALIGNMENT);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestWriteFile(shimBuffer, clientBody->clientHandle, buffer, size, count, pos, handle, writeFlag) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSWriteFileGeneric(client, block, buffer, size, count, pos, handle, writeFlag, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSOpenFileExAsync, FSClient *client, FSCmdBlock *block, const char *path, const char *mode, FSMode createMode, FSOpenFileFlags openFlag, uint32_t preallocSize, FSFileHandle *handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("handle is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (mode == nullptr) {
DEBUG_FUNCTION_LINE_ERR("mode is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestOpenFile(shimBuffer, clientBody->clientHandle, path, mode, createMode, openFlag, preallocSize) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) handle;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSOpenFileExAsync(client, block, path, mode, createMode, openFlag, preallocSize, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSCloseFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestCloseFile(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSCloseFileAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSGetStatAsync, FSClient *client, FSCmdBlock *block, const char *path, FSStat *stat, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (stat == nullptr) {
DEBUG_FUNCTION_LINE_ERR("stat is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestQueryInfo(shimBuffer, clientBody->clientHandle, path, FSA_QUERY_INFO_STAT) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) stat;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSGetStatAsync(client, block, path, stat, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSGetStatFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSStat *stat, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (stat == nullptr) {
DEBUG_FUNCTION_LINE_ERR("stat is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestStatFile(shimBuffer, clientBody->clientHandle, handle) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) stat;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSGetStatFileAsync(client, block, handle, stat, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSSetPosFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSAFilePosition pos, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestSetPos(shimBuffer, clientBody->clientHandle, handle, pos) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSSetPosFileAsync(client, block, handle, pos, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSGetPosFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, const FSAFilePosition *pos, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (pos == nullptr) {
DEBUG_FUNCTION_LINE_ERR("pos is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestGetPos(shimBuffer, clientBody->clientHandle, handle) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) pos;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSGetPosFileAsync(client, block, handle, pos, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSIsEofAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestIsEof(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSIsEofAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSTruncateFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestTruncate(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSTruncateFileAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSRemoveAsync, FSClient *client, FSCmdBlock *block, const char *path, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestRemove(shimBuffer, clientBody->clientHandle, path) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSRemoveAsync(client, block, path, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSRenameAsync, FSClient *client, FSCmdBlock *block, const char *oldPath, const char *newPath, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (oldPath == nullptr || newPath == nullptr) {
DEBUG_FUNCTION_LINE_ERR("oldPath or newPath is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestRename(shimBuffer, clientBody->clientHandle, oldPath, newPath) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSRenameAsync(client, block, oldPath, newPath, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSFlushFileAsync, FSClient *client, FSCmdBlock *block, FSFileHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestFlushFile(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSFlushFileAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSChangeModeAsync, FSClient *client, FSCmdBlock *block, const char *path, FSMode mode, FSMode modeMask, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestChangeMode(shimBuffer, clientBody->clientHandle, path, mode, modeMask) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSChangeModeAsync(client, block, path, mode, modeMask, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSOpenDirAsync, FSClient *client, FSCmdBlock *block, const char *path, FSDirectoryHandle *handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("handle is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestOpenDir(shimBuffer, clientBody->clientHandle, path) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) handle;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSOpenDirAsync(client, block, path, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSReadDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSDirectoryEntry *entry, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (entry == nullptr) {
DEBUG_FUNCTION_LINE_ERR("entry is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_BUFFER);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestReadDir(shimBuffer, clientBody->clientHandle, handle) == 0) {
// Hacky solution to pass the pointer into the other thread.
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
auto *hackyBuffer = (uint32_t *) &shimBuffer->response;
hackyBuffer[1] = (uint32_t) entry;
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSReadDirAsync(client, block, handle, entry, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSCloseDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestCloseDir(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSCloseDirAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSRewindDirAsync, FSClient *client, FSCmdBlock *block, FSDirectoryHandle handle, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (fsaShimPrepareRequestRewindDir(shimBuffer, clientBody->clientHandle, handle) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSRewindDirAsync(client, block, handle, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSMakeDirAsync, FSClient *client, FSCmdBlock *block, const char *path, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestMakeDir(shimBuffer, clientBody->clientHandle, path, static_cast<FSMode>(0x660)) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSMakeDirAsync(client, block, path, errorMask, asyncData);
}
DECL_FUNCTION(FSStatus, FSChangeDirAsync, FSClient *client, FSCmdBlock *block, const char *path, FSErrorFlag errorMask, FSAsyncData *asyncData) {
auto *clientBody = fsClientGetBody(client);
auto *shimBuffer = (FSAShimBuffer *) fsCmdBlockGetBody(block);
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("path is null.");
fsClientHandleFatalError(clientBody, FS_ERROR_INVALID_PATH);
return FS_STATUS_FATAL_ERROR;
}
if (fsaShimPrepareRequestChangeDir(shimBuffer, clientBody->clientHandle, path) == 0) {
if (processFSAShimInThread(shimBuffer, client, block, errorMask, asyncData)) {
return FS_STATUS_OK;
}
}
return real_FSChangeDirAsync(client, block, path, errorMask, asyncData);
}
function_replacement_data_t fs_file_function_replacements[] = {
REPLACE_FUNCTION(FSOpenFileExAsync, LIBRARY_COREINIT, FSOpenFileExAsync),
REPLACE_FUNCTION(FSCloseFileAsync, LIBRARY_COREINIT, FSCloseFileAsync),
REPLACE_FUNCTION(FSGetStatAsync, LIBRARY_COREINIT, FSGetStatAsync),
REPLACE_FUNCTION(FSGetStatFileAsync, LIBRARY_COREINIT, FSGetStatFileAsync),
REPLACE_FUNCTION_VIA_ADDRESS_FOR_PROCESS(FSReadFileGeneric, 0x3201C400 + 0x4ecc0, 0x101C400 + 0x4ecc0, FP_TARGET_PROCESS_GAME_AND_MENU),
REPLACE_FUNCTION(FSSetPosFileAsync, LIBRARY_COREINIT, FSSetPosFileAsync),
REPLACE_FUNCTION(FSGetPosFileAsync, LIBRARY_COREINIT, FSGetPosFileAsync),
REPLACE_FUNCTION(FSIsEofAsync, LIBRARY_COREINIT, FSIsEofAsync),
REPLACE_FUNCTION_VIA_ADDRESS_FOR_PROCESS(FSWriteFileGeneric, 0x3201C400 + 0x4eec0, 0x101C400 + 0x4eec0, FP_TARGET_PROCESS_GAME_AND_MENU),
REPLACE_FUNCTION(FSTruncateFileAsync, LIBRARY_COREINIT, FSTruncateFileAsync),
REPLACE_FUNCTION(FSRemoveAsync, LIBRARY_COREINIT, FSRemoveAsync),
REPLACE_FUNCTION(FSRenameAsync, LIBRARY_COREINIT, FSRenameAsync),
REPLACE_FUNCTION(FSFlushFileAsync, LIBRARY_COREINIT, FSFlushFileAsync),
REPLACE_FUNCTION(FSChangeModeAsync, LIBRARY_COREINIT, FSChangeModeAsync),
REPLACE_FUNCTION(FSOpenDirAsync, LIBRARY_COREINIT, FSOpenDirAsync),
REPLACE_FUNCTION(FSReadDirAsync, LIBRARY_COREINIT, FSReadDirAsync),
REPLACE_FUNCTION(FSCloseDirAsync, LIBRARY_COREINIT, FSCloseDirAsync),
REPLACE_FUNCTION(FSRewindDirAsync, LIBRARY_COREINIT, FSRewindDirAsync),
REPLACE_FUNCTION(FSMakeDirAsync, LIBRARY_COREINIT, FSMakeDirAsync),
REPLACE_FUNCTION(FSChangeDirAsync, LIBRARY_COREINIT, FSChangeDirAsync),
};
uint32_t fs_file_function_replacements_size = sizeof(fs_file_function_replacements) / sizeof(function_replacement_data_t);
FSError processShimBufferForFS(FSShimWrapper *param) {
FSError result = doForLayer(param);
FSStatus fsResult = FS_STATUS_MEDIA_ERROR;
if (result == FS_ERROR_FORCE_REAL_FUNCTION) {
if (param->sync == FS_SHIM_TYPE_SYNC) {
fsResult = FS_STATUS_MEDIA_ERROR;
DEBUG_FUNCTION_LINE_ERR("SYNC FS API is not supported");
OSFatal("ContentRedirectionModule: SYNC FS API is not supported");
} else if (param->sync == FS_SHIM_TYPE_ASYNC) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
switch ((FSACommandEnum) param->shim->command) {
case FSA_COMMAND_READ_FILE: {
auto *request = &param->shim->request.readFile;
fsResult = real_FSReadFileGeneric(param->asyncFS.client, param->asyncFS.block, request->buffer, request->size, request->count, request->pos, request->handle, request->readFlags, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSReadFileGeneric. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_WRITE_FILE: {
auto *request = &param->shim->request.writeFile;
fsResult = real_FSWriteFileGeneric(param->asyncFS.client, param->asyncFS.block, request->buffer, request->size, request->count, request->pos, request->handle, request->writeFlags, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSWriteFileGeneric. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_OPEN_FILE: {
auto *request = &param->shim->request.openFile;
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *handlePtr = (FSFileHandle *) hackyBuffer[1];
fsResult = real_FSOpenFileExAsync(param->asyncFS.client, param->asyncFS.block, request->path, request->mode, static_cast<FSMode>(request->unk0x290), static_cast<FSOpenFileFlags>(request->unk0x294), request->unk0x298, handlePtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSOpenFileExAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_CLOSE_FILE: {
auto *request = &param->shim->request.closeFile;
fsResult = real_FSCloseFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSCloseFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_SET_POS_FILE: {
auto *request = &param->shim->request.setPosFile;
fsResult = real_FSSetPosFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, request->pos, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSSetPosFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_GET_POS_FILE: {
auto *request = &param->shim->request.getPosFile;
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *posPtr = (FSAFilePosition *) hackyBuffer[1];
fsResult = real_FSGetPosFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, posPtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSGetPosFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_STAT_FILE: {
auto *request = &param->shim->request.statFile;
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *statPtr = (FSStat *) hackyBuffer[1];
fsResult = real_FSGetStatFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, statPtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSGetStatFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_GET_INFO_BY_QUERY: {
auto *request = &param->shim->request.getInfoByQuery;
if (request->type == FSA_QUERY_INFO_STAT) {
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *statPtr = (FSStat *) hackyBuffer[1];
fsResult = real_FSGetStatAsync(param->asyncFS.client, param->asyncFS.block, request->path, statPtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSGetStatAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
} else {
DEBUG_FUNCTION_LINE_ERR("Missing real implementation for FSA_COMMAND_GET_INFO_BY_QUERY type %08X", request->type);
}
break;
}
case FSA_COMMAND_IS_EOF: {
auto *request = &param->shim->request.isEof;
fsResult = real_FSIsEofAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSIsEofAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_TRUNCATE_FILE: {
auto *request = &param->shim->request.truncateFile;
fsResult = real_FSTruncateFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSTruncateFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_REMOVE: {
auto *request = &param->shim->request.remove;
fsResult = real_FSRemoveAsync(param->asyncFS.client, param->asyncFS.block, request->path, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSRemoveAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_RENAME: {
auto *request = &param->shim->request.rename;
fsResult = real_FSRenameAsync(param->asyncFS.client, param->asyncFS.block, request->oldPath, request->newPath, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSRenameAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_FLUSH_FILE: {
auto *request = &param->shim->request.flushFile;
fsResult = real_FSFlushFileAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSFlushFileAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_CHANGE_MODE: {
auto *request = &param->shim->request.changeMode;
fsResult = real_FSChangeModeAsync(param->asyncFS.client, param->asyncFS.block, request->path, (FSMode) request->mode1, (FSMode) request->mode2, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSChangeModeAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_OPEN_DIR: {
auto *request = &param->shim->request.openDir;
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *handlePtr = (FSDirectoryHandle *) hackyBuffer[1];
fsResult = real_FSOpenDirAsync(param->asyncFS.client, param->asyncFS.block, request->path, handlePtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSOpenDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_READ_DIR: {
auto *request = &param->shim->request.readDir;
// Hacky solution. We stored the pointer from the user in the response to use it at this point.
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *entryPtr = (FSDirectoryEntry *) hackyBuffer[1];
fsResult = real_FSReadDirAsync(param->asyncFS.client, param->asyncFS.block, request->handle, entryPtr, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSReadDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_CLOSE_DIR: {
auto *request = &param->shim->request.closeDir;
fsResult = real_FSCloseDirAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSCloseDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_REWIND_DIR: {
auto *request = &param->shim->request.rewindDir;
fsResult = real_FSRewindDirAsync(param->asyncFS.client, param->asyncFS.block, request->handle, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSRewindDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_MAKE_DIR: {
auto *request = &param->shim->request.makeDir;
fsResult = real_FSMakeDirAsync(param->asyncFS.client, param->asyncFS.block, request->path, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSMakeDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
case FSA_COMMAND_CHANGE_DIR: {
auto *request = &param->shim->request.changeDir;
fsResult = real_FSChangeDirAsync(param->asyncFS.client, param->asyncFS.block, request->path, param->asyncFS.errorMask, &param->asyncFS.asyncData);
if (fsResult != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("Failed to submit real_FSChangeDirAsync. Return was %d. Fake actual async result to FS_STATUS_MEDIA_ERROR instead", fsResult);
handleAsyncResult(param->asyncFS.client, param->asyncFS.block, &param->asyncFS.asyncData, FS_STATUS_MEDIA_ERROR);
}
break;
}
default: {
DEBUG_FUNCTION_LINE_ERR("Missing real implementation for command %08X", param->shim->command);
fsResult = FS_STATUS_FATAL_ERROR;
}
}
#pragma GCC diagnostic pop
}
}
free(param);
if (fsResult != FS_STATUS_OK) {
result = FS_ERROR_MEDIA_ERROR;
}
return result;
}

View File

@ -10,9 +10,6 @@ extern "C" {
extern function_replacement_data_t fs_file_function_replacements[];
extern uint32_t fs_file_function_replacements_size;
extern function_replacement_data_t test_function_replacements[];
extern uint32_t test_function_replacements_size;
#ifdef __cplusplus
}
#endif

View File

@ -2,36 +2,40 @@
#include "FileUtils.h"
#include "utils/StringTools.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <algorithm>
#include <coreinit/cache.h>
#include <coreinit/debug.h>
#include <coreinit/filesystem_fsa.h>
#include <cstdio>
#include <filesystem>
#include <sys/dirent.h>
#include <sys/fcntl.h>
#include <sys/unistd.h>
FSStatus FSWrapper::FSOpenDirWrapper(const char *path, FSDirectoryHandle *handle) {
FSError FSWrapper::FSOpenDirWrapper(const char *path, FSDirectoryHandle *handle) {
if (path == nullptr) {
return FS_ERROR_INVALID_PARAM;
}
if (!IsPathToReplace(path)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] handle was nullptr", getName().c_str());
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_PARAM;
}
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
auto *dirHandle = getNewDirHandle();
if (dirHandle != nullptr) {
auto dirHandle = getNewDirHandle();
if (dirHandle) {
DIR *dir;
auto newPath = GetNewPath(path);
if ((dir = opendir(newPath.c_str()))) {
dirHandle->dir = dir;
dirHandle->handle = (((uint32_t) dirHandle) & 0x0FFFFFFF) | 0x30000000;
dirHandle->handle = (((uint32_t) dirHandle.get()) & 0x0FFFFFFF) | 0x30000000;
*handle = dirHandle->handle;
dirHandle->path[0] = '\0';
@ -42,31 +46,44 @@ FSStatus FSWrapper::FSOpenDirWrapper(const char *path, FSDirectoryHandle *handle
OSMemoryBarrier();
}
} else {
delete dirHandle;
result = FS_STATUS_NOT_FOUND;
auto err = errno;
if (err == ENOENT) {
DEBUG_FUNCTION_LINE("[%s] Open dir %s (%s) failed. FS_ERROR_NOT_FOUND", getName().c_str(), path, newPath.c_str());
return FS_ERROR_NOT_FOUND;
}
DEBUG_FUNCTION_LINE_ERR("[%s] Open dir %s (%s) failed. errno %d", getName().c_str(), path, newPath.c_str(), err);
if (err == EACCES) {
return FS_ERROR_PERMISSION_ERROR;
} else if (err == ENOTDIR) {
return FS_ERROR_NOT_DIR;
} else if (err == ENFILE || err == EMFILE) {
return FS_ERROR_MAX_DIRS;
}
return FS_ERROR_MEDIA_ERROR;
}
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc dir handle", getName().c_str());
result = FS_STATUS_MAX;
result = FS_ERROR_MAX_DIRS;
}
return result;
}
FSStatus FSWrapper::FSReadDirWrapper(FSDirectoryHandle handle, FSDirectoryEntry *entry) {
FSError FSWrapper::FSReadDirWrapper(FSDirectoryHandle handle, FSDirectoryEntry *entry) {
if (!isValidDirHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *dirHandle = getDirFromHandle(handle);
auto dirHandle = getDirFromHandle(handle);
DIR *dir = dirHandle->dir;
FSStatus result = FS_STATUS_END;
FSError result = FS_ERROR_END_OF_DIR;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] readdir %08X (handle %08X)", getName().c_str(), dir, handle);
do {
errno = 0;
struct dirent *entry_ = readdir(dir);
if (entry_) {
if (SkipDeletedFilesInReadDir() && std::string_view(entry_->d_name).starts_with(deletePrefix)) {
if (SkipDeletedFilesInReadDir() && starts_with_case_insensitive(entry_->d_name, deletePrefix)) {
DEBUG_FUNCTION_LINE_ERR("Skip file file name %s because of the prefix", entry_->d_name);
continue;
}
@ -81,160 +98,217 @@ FSStatus FSWrapper::FSReadDirWrapper(FSDirectoryHandle handle, FSDirectoryEntry
if (strcmp(entry_->d_name, ".") == 0 || strcmp(entry_->d_name, "..") == 0) {
entry->info.size = 0;
} else {
#ifdef _DIRENT_HAVE_D_STAT
translate_stat(&entry_->d_stat, &entry->info);
#else
struct stat sb {};
auto strLen = strlen(dirHandle->path) + 1 + strlen(entry_->d_name) + 1;
char path[strLen];
snprintf(path, sizeof(path), "%s/%s", dirHandle->path, entry_->d_name);
if (stat(path, &sb) >= 0) {
entry->info.size = sb.st_size;
entry->info.flags = (FSStatFlags) 0;
entry->info.owner = sb.st_uid;
entry->info.group = sb.st_gid;
auto path = string_format("%s/%s", dirHandle->path, entry_->d_name);
std::replace(path.begin(), path.end(), '\\', '/');
uint32_t length = path.size();
//! clear path of double slashes
for (uint32_t i = 1; i < length; ++i) {
if (path[i - 1] == '/' && path[i] == '/') {
path.erase(i, 1);
i--;
length--;
}
}
if (stat(path.c_str(), &sb) >= 0) {
translate_stat(&sb, &entry->info);
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to stat file (%s) in read dir %08X (dir handle %08X)", getName().c_str(), path.c_str(), dir, handle);
result = FS_ERROR_MEDIA_ERROR;
break;
}
#endif
}
}
result = FS_STATUS_OK;
result = FS_ERROR_OK;
} else {
auto err = errno;
if (err != 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to read dir %08X (handle %08X). errno %d (%s)", getName().c_str(), dir, handle, err, strerror(err));
result = FS_ERROR_MEDIA_ERROR;
}
}
break;
} while (true);
return result;
}
FSStatus FSWrapper::FSCloseDirWrapper(FSDirectoryHandle handle) {
FSError FSWrapper::FSCloseDirWrapper(FSDirectoryHandle handle) {
if (!isValidDirHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *dirHandle = getDirFromHandle(handle);
auto dirHandle = getDirFromHandle(handle);
DIR *dir = dirHandle->dir;
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] closedir %08X (handle %08X)", getName().c_str(), dir, handle);
if (closedir(dir) != 0) {
if (closedir(dir) < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close dir %08X (handle %08X)", getName().c_str(), dir, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
}
dirHandle->dir = nullptr;
return result;
}
FSStatus FSWrapper::FSRewindDirWrapper(FSDirectoryHandle handle) {
FSError FSWrapper::FSRewindDirWrapper(FSDirectoryHandle handle) {
if (!isValidDirHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *dirHandle = getDirFromHandle(handle);
auto dirHandle = getDirFromHandle(handle);
DIR *dir = dirHandle->dir;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] rewindir %08X (handle %08X)", getName().c_str(), dir, handle);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] rewinddir %08X (handle %08X)", getName().c_str(), dir, handle);
rewinddir(dir);
return FS_STATUS_OK;
return FS_ERROR_OK;
}
FSStatus FSWrapper::FSMakeDirWrapper(const char *path) {
FSError FSWrapper::FSMakeDirWrapper(const char *path) {
if (!IsPathToReplace(path)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to create dir %s but layer is not writeable", getName().c_str(), path);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_PERMISSION_ERROR;
}
DEBUG_FUNCTION_LINE_ERR("NOT IMPLEMENTED MAKE DIR");
return FS_STATUS_FATAL_ERROR;
auto newPath = GetNewPath(path);
auto res = mkdir(newPath.c_str(), 0000660);
if (res < 0) {
auto err = errno;
if (err == EACCES) {
return FS_ERROR_PERMISSION_ERROR;
} else if (err == EEXIST) {
return FS_ERROR_ALREADY_EXISTS;
} else if (err == ENOTDIR) {
return FS_ERROR_NOT_DIR;
} else if (err == ENOENT) {
return FS_ERROR_NOT_FOUND;
}
return FS_ERROR_MEDIA_ERROR;
}
return FS_ERROR_OK;
}
FSStatus FSWrapper::FSOpenFileWrapper(const char *path, const char *mode, FSFileHandle *handle) {
FSError FSWrapper::FSOpenFileWrapper(const char *path, const char *mode, FSFileHandle *handle) {
if (!IsPathToReplace(path)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (path == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] path was nullptr", getName().c_str());
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_PARAM;
}
if (mode == nullptr || handle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] mode or handle was nullptr", getName().c_str());
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_PARAM;
}
auto newPath = GetNewPath(path);
if (pCheckIfDeleted && CheckFileShouldBeIgnored(newPath)) {
return static_cast<FSStatus>((FS_STATUS_NOT_FOUND & 0x0000FFFF) | FS_STATUS_FORCE_NO_FALLBACK);
return static_cast<FSError>((FS_ERROR_NOT_FOUND & FS_ERROR_REAL_MASK) | FS_ERROR_FORCE_NO_FALLBACK);
}
auto result = FS_STATUS_OK;
auto result = FS_ERROR_OK;
int _mode;
// Map flags to open modes
if (!IsFileModeAllowed(mode)) {
OSReport("## WARN ## [%s] Given mode is not allowed %s", getName().c_str(), mode);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Given mode is not allowed %s", getName().c_str(), mode);
return FS_STATUS_ACCESS_ERROR;
DEBUG_FUNCTION_LINE("[%s] Given mode is not allowed %s", getName().c_str(), mode);
return FS_ERROR_ACCESS_ERROR;
}
if (strcmp(mode, "r") == 0 || strcmp(mode, "rb") == 0) {
_mode = 0x000;
_mode = O_RDONLY;
} else if (strcmp(mode, "r+") == 0) {
_mode = 0x002;
} else if (strcmp(mode, "w") == 0) {
_mode = 0x601;
_mode = O_RDWR;
} else if (strcmp(mode, "w") == 0 || strcmp(mode, "wb") == 0) {
_mode = O_WRONLY | O_CREAT | O_TRUNC;
} else if (strcmp(mode, "w+") == 0) {
_mode = 0x602;
_mode = O_RDWR | O_CREAT | O_TRUNC;
} else if (strcmp(mode, "a") == 0) {
_mode = 0x209;
_mode = O_WRONLY | O_CREAT | O_APPEND;
} else if (strcmp(mode, "a+") == 0) {
_mode = 0x20A;
_mode = O_RDWR | O_CREAT | O_APPEND;
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] mode \"%s\" was allowed but is unsupported", getName().c_str(), mode);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
}
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Open %s (as %s) mode %s,", getName().c_str(), path, newPath.c_str(), mode);
int32_t fd = open(newPath.c_str(), _mode);
if (fd >= 0) {
auto *fileHandle = getNewFileHandle();
auto fileHandle = getNewFileHandle();
if (fileHandle) {
std::lock_guard<std::mutex> lock(openFilesMutex);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Opened %s (as %s) mode %s, fd %d (%08X)", getName().c_str(), path, newPath.c_str(), mode, fd, handle);
fileHandle->handle = (((uint32_t) fileHandle) & 0x0FFFFFFF) | 0x30000000;
fileHandle->handle = (((uint32_t) fileHandle.get()) & 0x0FFFFFFF) | 0x30000000;
*handle = fileHandle->handle;
fileHandle->fd = fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Opened %s (as %s) mode %s (%08X), fd %d (%08X)", getName().c_str(), path, newPath.c_str(), mode, _mode, fd, fileHandle->handle);
openFiles.push_back(fileHandle);
OSMemoryBarrier();
} else {
close(fd);
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc new fileHandle", getName().c_str());
result = FS_STATUS_MAX;
result = FS_ERROR_MAX_FILES;
}
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] File not found %s (%s)", getName().c_str(), path, newPath.c_str());
result = FS_STATUS_NOT_FOUND;
auto err = errno;
if (err == ENOENT) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] File not found %s (%s)", getName().c_str(), path, newPath.c_str());
result = FS_ERROR_NOT_FOUND;
} else {
DEBUG_FUNCTION_LINE("[%s] Open file %s (%s) failed. errno %d ", getName().c_str(), path, newPath.c_str(), err);
if (err == EACCES) {
return FS_ERROR_PERMISSION_ERROR;
} else if (err == ENOENT) {
result = FS_ERROR_NOT_FOUND;
} else if (err == EEXIST) {
result = FS_ERROR_ALREADY_EXISTS;
} else if (err == EISDIR) {
result = FS_ERROR_NOT_FILE;
} else if (err == ENOTDIR) {
result = FS_ERROR_NOT_DIR;
} else if (err == ENFILE || err == EMFILE) {
result = FS_ERROR_MAX_FILES;
} else {
result = FS_ERROR_MEDIA_ERROR;
}
}
}
return result;
}
FSStatus FSWrapper::FSCloseFileWrapper(FSFileHandle handle) {
FSError FSWrapper::FSCloseFileWrapper(FSFileHandle handle) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Close %d (handle %08X)", getName().c_str(), real_fd, handle);
if (close(real_fd) != 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close %d (handle %08X) ", getName().c_str(), real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
}
fileHandle->fd = -1;
return result;
@ -243,126 +317,113 @@ FSStatus FSWrapper::FSCloseFileWrapper(FSFileHandle handle) {
bool FSWrapper::CheckFileShouldBeIgnored(std::string &path) {
auto asPath = std::filesystem::path(path);
if (std::string(asPath.filename().c_str()).starts_with(deletePrefix)) {
DEBUG_FUNCTION_LINE_VERBOSE("Ignore %s, filename starts with %s", path.c_str(), deletePrefix.c_str());
if (starts_with_case_insensitive(asPath.filename().c_str(), deletePrefix)) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Ignore %s, filename starts with %s", getName().c_str(), path.c_str(), deletePrefix.c_str());
return true;
}
auto newDelPath = asPath.replace_filename(deletePrefix + asPath.filename().c_str());
struct stat buf {};
if (stat(newDelPath.c_str(), &buf) == 0) {
DEBUG_FUNCTION_LINE_VERBOSE("Ignore %s, file %s exists", path.c_str(), newDelPath.c_str());
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Ignore %s, file %s exists", getName().c_str(), path.c_str(), newDelPath.c_str());
return true;
}
return false;
}
FSStatus FSWrapper::FSGetStatWrapper(const char *path, FSStat *stats) {
FSError FSWrapper::FSGetStatWrapper(const char *path, FSStat *stats) {
if (path == nullptr || stats == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] path was or stats nullptr", getName().c_str());
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_PARAM;
}
if (!IsPathToReplace(path)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto newPath = GetNewPath(path);
struct stat path_stat {};
if (pCheckIfDeleted && CheckFileShouldBeIgnored(newPath)) {
return static_cast<FSStatus>((FS_STATUS_NOT_FOUND & 0x0000FFFF) | FS_STATUS_FORCE_NO_FALLBACK);
return static_cast<FSError>((FS_ERROR_NOT_FOUND & FS_ERROR_REAL_MASK) | FS_ERROR_FORCE_NO_FALLBACK);
}
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] stat of %s (%s)", getName().c_str(), path, newPath.c_str());
if (stat(newPath.c_str(), &path_stat) < 0) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Path %s (%s) not found ", getName().c_str(), path, newPath.c_str());
result = FS_STATUS_NOT_FOUND;
result = FS_ERROR_NOT_FOUND;
} else {
memset(&(stats->flags), 0, sizeof(stats->flags));
if (S_ISDIR(path_stat.st_mode)) {
stats->flags = (FSStatFlags) ((uint32_t) FS_STAT_DIRECTORY);
} else {
stats->size = path_stat.st_size;
stats->mode = (FSMode) FS_MODE_READ_OWNER;
stats->flags = (FSStatFlags) 0;
stats->owner = path_stat.st_uid;
stats->group = path_stat.st_gid;
}
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Stats file for %s (%s), size %016llX", getName().c_str(), path, newPath.c_str(), stats->size);
translate_stat(&path_stat, stats);
}
return result;
}
FSStatus FSWrapper::FSGetStatFileWrapper(FSFileHandle handle, FSStat *stats) {
FSError FSWrapper::FSGetStatFileWrapper(FSFileHandle handle, FSStat *stats) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
struct stat path_stat {};
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] fstat of fd %d (FSFileHandle %08X)", getName().c_str(), real_fd, handle);
if (fstat(real_fd, &path_stat) < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] fstat of fd %d (FSFileHandle %08X) failed", getName().c_str(), real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
} else {
memset(&(stats->flags), 0, sizeof(stats->flags));
stats->size = path_stat.st_size;
stats->mode = (FSMode) FS_MODE_READ_OWNER;
stats->flags = (FSStatFlags) 0;
stats->owner = path_stat.st_uid;
stats->group = path_stat.st_gid;
translate_stat(&path_stat, stats);
}
return result;
}
FSStatus FSWrapper::FSReadFileWrapper(void *buffer, uint32_t size, uint32_t count, FSFileHandle handle, [[maybe_unused]] uint32_t unk1) {
FSError FSWrapper::FSReadFileWrapper(void *buffer, uint32_t size, uint32_t count, FSFileHandle handle, [[maybe_unused]] uint32_t unk1) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (size * count == 0) {
return FS_STATUS_OK;
return FS_ERROR_OK;
}
if (buffer == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] buffer is null but size * count is not 0 (It's: %d)", getName().c_str(), size * count);
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_BUFFER;
}
auto *fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
auto fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Read %u bytes of fd %08X (FSFileHandle %08X) to buffer %08X", getName().c_str(), size * count, real_fd, handle, buffer);
int32_t read = readIntoBuffer(real_fd, buffer, size, count);
int64_t read = readIntoBuffer(real_fd, buffer, size, count);
FSStatus result;
FSError result;
if (read < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] read %u bytes of fd %d (FSFileHandle %08X) failed", getName().c_str(), size * count, real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
DEBUG_FUNCTION_LINE_ERR("[%s] Read %u bytes of fd %d (FSFileHandle %08X) failed", getName().c_str(), size * count, real_fd, handle);
auto err = errno;
if (err == EBADF || err == EROFS) {
return FS_ERROR_ACCESS_ERROR;
}
result = FS_ERROR_MEDIA_ERROR;
} else {
result = static_cast<FSStatus>((uint32_t) (read & 0xFFFFFFFF) / size);
result = static_cast<FSError>(((uint32_t) read) / size);
}
return result;
}
FSStatus FSWrapper::FSReadFileWithPosWrapper(void *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, int32_t unk1) {
FSError FSWrapper::FSReadFileWithPosWrapper(void *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, int32_t unk1) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Read from with position.", getName().c_str());
FSStatus result;
if ((result = this->FSSetPosFileWrapper(handle, pos)) != FS_STATUS_OK) {
FSError result;
if ((result = this->FSSetPosFileWrapper(handle, pos)) != FS_ERROR_OK) {
return result;
}
@ -371,20 +432,24 @@ FSStatus FSWrapper::FSReadFileWithPosWrapper(void *buffer, uint32_t size, uint32
return result;
}
FSStatus FSWrapper::FSSetPosFileWrapper(FSFileHandle handle, uint32_t pos) {
FSError FSWrapper::FSSetPosFileWrapper(FSFileHandle handle, uint32_t pos) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
int real_fd = fileHandle->fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %d (FSFileHandle %08X) to get current position for truncation", getName().c_str(), real_fd, handle);
if (lseek(real_fd, (off_t) pos, SEEK_SET) != pos) {
DEBUG_FUNCTION_LINE_ERR("[%s] lseek fd %d (FSFileHandle %08X) to position %u failed", getName().c_str(), real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %d (FSFileHandle %08X) SEEK_SET to position %08X", getName().c_str(), real_fd, handle, pos);
off_t newPos;
if ((newPos = lseek(real_fd, (off_t) pos, SEEK_SET)) != pos) {
DEBUG_FUNCTION_LINE_ERR("[%s] lseek fd %d (FSFileHandle %08X) to position %08X failed", getName().c_str(), real_fd, handle, pos);
if (newPos < 0) {
// TODO: read errno
}
result = FS_ERROR_MEDIA_ERROR;
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] pos set to %u for fd %d (FSFileHandle %08X)", getName().c_str(), pos, real_fd, handle);
}
@ -392,13 +457,13 @@ FSStatus FSWrapper::FSSetPosFileWrapper(FSFileHandle handle, uint32_t pos) {
return result;
}
FSStatus FSWrapper::FSGetPosFileWrapper(FSFileHandle handle, uint32_t *pos) {
FSError FSWrapper::FSGetPosFileWrapper(FSFileHandle handle, uint32_t *pos) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
int real_fd = fileHandle->fd;
@ -406,86 +471,88 @@ FSStatus FSWrapper::FSGetPosFileWrapper(FSFileHandle handle, uint32_t *pos) {
off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR);
if (currentPos == -1) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position (res: %lld) of fd (handle %08X) to check EoF", getName().c_str(), currentPos, real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
} else {
*pos = currentPos;
}
return result;
}
FSStatus FSWrapper::FSIsEofWrapper(FSFileHandle handle) {
FSError FSWrapper::FSIsEofWrapper(FSFileHandle handle) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
FSStatus result;
FSError result;
int real_fd = fileHandle->fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for truncation", getName().c_str(), real_fd, handle);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for EOF detection", getName().c_str(), real_fd, handle);
off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get end position for truncation", getName().c_str(), real_fd, handle);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get end position for EOF detection", getName().c_str(), real_fd, handle);
off_t endPos = lseek(real_fd, (off_t) 0, SEEK_END);
if (currentPos == -1 || endPos == -1) {
// TODO: check errno
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position (res: %lld) or endPos (res: %lld) of fd (handle %08X) to check EoF", getName().c_str(), currentPos, endPos, real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
} else if (currentPos == endPos) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] FSIsEof END for %d\n", getName().c_str(), real_fd);
result = FS_STATUS_END;
result = FS_ERROR_END_OF_FILE;
} else {
lseek(real_fd, currentPos, SEEK_CUR);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] FSIsEof OK for %d\n", getName().c_str(), real_fd);
result = FS_STATUS_OK;
result = FS_ERROR_OK;
}
return result;
}
FSStatus FSWrapper::FSTruncateFileWrapper(FSFileHandle handle) {
FSError FSWrapper::FSTruncateFileWrapper(FSFileHandle handle) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to truncate fd %d (handle %08X) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
int real_fd = fileHandle->fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] lseek fd %08X (FSFileHandle %08X) to get current position for truncation", getName().c_str(), real_fd, handle);
off_t currentPos = lseek(real_fd, (off_t) 0, SEEK_CUR);
if (currentPos == -1) {
// TODO check errno
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to get current position of fd (handle %08X) to truncate file", getName().c_str(), real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Truncate fd %08X (FSFileHandle %08X) to %lld bytes ", getName().c_str(), real_fd, handle, currentPos);
if (ftruncate(real_fd, currentPos) < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] ftruncate failed for fd %08X (FSFileHandle %08X) errno %d", getName().c_str(), real_fd, handle, errno);
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
}
}
return result;
}
FSStatus FSWrapper::FSWriteFileWrapper(uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, [[maybe_unused]] uint32_t unk1) {
FSError FSWrapper::FSWriteFileWrapper(const uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, [[maybe_unused]] uint32_t unk1) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to write to fd %d (handle %08X) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
}
auto *fileHandle = getFileFromHandle(handle);
auto fileHandle = getFileFromHandle(handle);
FSStatus result;
FSError result;
int real_fd = fileHandle->fd;
@ -495,53 +562,53 @@ FSStatus FSWrapper::FSWriteFileWrapper(uint8_t *buffer, uint32_t size, uint32_t
auto err = errno;
DEBUG_FUNCTION_LINE_ERR("[%s] Write failed %u bytes to fd %08X (FSFileHandle %08X) from buffer %08X errno %d", getName().c_str(), count * size, real_fd, handle, buffer, err);
if (err == EFBIG) {
result = FS_STATUS_FILE_TOO_BIG;
result = FS_ERROR_FILE_TOO_BIG;
} else if (err == EACCES) {
result = FS_STATUS_ACCESS_ERROR;
result = FS_ERROR_ACCESS_ERROR;
} else {
result = FS_STATUS_MEDIA_ERROR;
result = FS_ERROR_MEDIA_ERROR;
}
} else {
result = static_cast<FSStatus>((uint32_t) (writeRes & 0xFFFFFFFF) / size);
result = static_cast<FSError>(((uint32_t) writeRes) / size);
}
return result;
}
FSStatus FSWrapper::FSRemoveWrapper(const char *path) {
FSError FSWrapper::FSRemoveWrapper(const char *path) {
if (!IsPathToReplace(path)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to remove %s but layer is not writeable", getName().c_str(), path);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_PERMISSION_ERROR;
}
auto newPath = GetNewPath(path);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Remove %s (%s)", getName().c_str(), path, newPath.c_str());
if (remove(newPath.c_str()) < 0) {
auto err = errno;
DEBUG_FUNCTION_LINE_ERR("[%s] rename failed %s (%s) errno %d", getName().c_str(), path, newPath.c_str(), err);
DEBUG_FUNCTION_LINE_ERR("[%s] Rename failed %s (%s) errno %d", getName().c_str(), path, newPath.c_str(), err);
if (err == ENOTDIR) {
return FS_STATUS_NOT_DIR;
return FS_ERROR_NOT_DIR;
} else if (err == EACCES) {
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
} else if (err == EISDIR) {
return FS_STATUS_NOT_FILE;
return FS_ERROR_NOT_FILE;
} else if (err == EPERM) {
return FS_STATUS_PERMISSION_ERROR;
return FS_ERROR_PERMISSION_ERROR;
}
return FS_STATUS_MEDIA_ERROR;
return FS_ERROR_MEDIA_ERROR;
}
return FS_STATUS_OK;
return FS_ERROR_OK;
}
FSStatus FSWrapper::FSRenameWrapper(const char *oldPath, const char *newPath) {
FSError FSWrapper::FSRenameWrapper(const char *oldPath, const char *newPath) {
if (!IsPathToReplace(oldPath) || !IsPathToReplace(newPath)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to rename %s to %s but layer is not writeable", getName().c_str(), oldPath, newPath);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_PERMISSION_ERROR;
}
auto oldPathRedirect = GetNewPath(oldPath);
auto newPathRedirect = GetNewPath(newPath);
@ -550,36 +617,41 @@ FSStatus FSWrapper::FSRenameWrapper(const char *oldPath, const char *newPath) {
auto err = errno;
DEBUG_FUNCTION_LINE_ERR("[%s] Rename failed %s (%s) -> %s (%s). errno %d", getName().c_str(), oldPath, oldPathRedirect.c_str(), newPath, newPathRedirect.c_str(), err);
if (err == ENOTDIR) {
return FS_STATUS_NOT_DIR;
return FS_ERROR_NOT_DIR;
} else if (err == EACCES) {
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
} else if (err == EISDIR) {
return FS_STATUS_NOT_FILE;
return FS_ERROR_NOT_FILE;
} else if (err == EPERM) {
return FS_STATUS_PERMISSION_ERROR;
return FS_ERROR_PERMISSION_ERROR;
}
return FS_STATUS_MEDIA_ERROR;
return FS_ERROR_MEDIA_ERROR;
}
return FS_STATUS_OK;
return FS_ERROR_OK;
}
FSStatus FSWrapper::FSFlushFileWrapper(FSFileHandle handle) {
FSError FSWrapper::FSFlushFileWrapper(FSFileHandle handle) {
if (!isValidFileHandle(handle)) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
if (!pIsWriteable) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Tried to fsync fd %d (handle %08X)) but layer is not writeable", getName().c_str(), getFileFromHandle(handle)->fd, handle);
return FS_STATUS_ACCESS_ERROR;
return FS_ERROR_ACCESS_ERROR;
}
auto *fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
auto fileHandle = getFileFromHandle(handle);
int real_fd = fileHandle->fd;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] fsync fd %08X (FSFileHandle %08X)", real_fd, handle);
FSStatus result = FS_STATUS_OK;
FSError result = FS_ERROR_OK;
if (fsync(real_fd) < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] fsync failed for fd %08X (FSFileHandle %08X)", getName().c_str(), real_fd, handle);
result = FS_STATUS_MEDIA_ERROR;
auto err = errno;
if (err == EBADF) {
result = FS_ERROR_INVALID_FILEHANDLE;
} else {
result = FS_ERROR_MEDIA_ERROR;
}
}
return result;
}
@ -591,6 +663,7 @@ bool FSWrapper::IsFileModeAllowed(const char *mode) {
if (pIsWriteable && (strcmp(mode, "r+") == 0 ||
strcmp(mode, "w") == 0 ||
strcmp(mode, "wb") == 0 ||
strcmp(mode, "w+") == 0 ||
strcmp(mode, "a") == 0 ||
strcmp(mode, "a+") == 0)) {
@ -600,15 +673,16 @@ bool FSWrapper::IsFileModeAllowed(const char *mode) {
return false;
}
bool FSWrapper::IsPathToReplace(const std::string_view &path) {
return path.starts_with(pPathToReplace);
return starts_with_case_insensitive(path, pPathToReplace);
}
std::string FSWrapper::GetNewPath(const std::string_view &path) {
auto subStr = path.substr(this->pPathToReplace.length());
auto res = string_format("%s%.*s", this->pReplacePathWith.c_str(), int(subStr.length()), subStr.data());
std::replace(res.begin(), res.end(), '/', '/');
std::replace(res.begin(), res.end(), '\\', '/');
uint32_t length = res.size();
@ -627,23 +701,23 @@ std::string FSWrapper::GetNewPath(const std::string_view &path) {
bool FSWrapper::isValidFileHandle(FSFileHandle handle) {
std::lock_guard<std::mutex> lock(openFilesMutex);
return std::ranges::any_of(openFiles, [handle](FileInfo *val) { return val->handle == handle; });
return std::ranges::any_of(openFiles, [handle](auto &cur) { return cur->handle == handle; });
}
bool FSWrapper::isValidDirHandle(FSDirectoryHandle handle) {
std::lock_guard<std::mutex> lock(openDirsMutex);
return std::ranges::any_of(openDirs, [handle](DirInfo *val) { return val->handle == handle; });
return std::ranges::any_of(openDirs, [handle](auto &cur) { return cur->handle == handle; });
}
FileInfo *FSWrapper::getNewFileHandle() {
return new (std::nothrow) FileInfo;
std::shared_ptr<FileInfo> FSWrapper::getNewFileHandle() {
return make_shared_nothrow<FileInfo>();
}
DirInfo *FSWrapper::getNewDirHandle() {
return new (std::nothrow) DirInfo;
std::shared_ptr<DirInfo> FSWrapper::getNewDirHandle() {
return make_shared_nothrow<DirInfo>();
}
FileInfo *FSWrapper::getFileFromHandle(FSFileHandle handle) {
std::shared_ptr<FileInfo> FSWrapper::getFileFromHandle(FSFileHandle handle) {
std::lock_guard<std::mutex> lock(openFilesMutex);
for (auto &file : openFiles) {
if (file->handle == handle) {
@ -651,11 +725,11 @@ FileInfo *FSWrapper::getFileFromHandle(FSFileHandle handle) {
}
}
DEBUG_FUNCTION_LINE_ERR("[%s] FileInfo for handle %08X was not found. isValidFileHandle check missing?", getName().c_str(), handle);
OSFatal("Failed to find file handle");
OSFatal("ContentRedirectionModule: Failed to find file handle");
return nullptr;
}
DirInfo *FSWrapper::getDirFromHandle(FSDirectoryHandle handle) {
std::shared_ptr<DirInfo> FSWrapper::getDirFromHandle(FSDirectoryHandle handle) {
std::lock_guard<std::mutex> lock(openDirsMutex);
for (auto &dir : openDirs) {
if (dir->handle == handle) {
@ -663,48 +737,18 @@ DirInfo *FSWrapper::getDirFromHandle(FSDirectoryHandle handle) {
}
}
DEBUG_FUNCTION_LINE_ERR("[%s] DirInfo for handle %08X was not found. isValidDirHandle check missing?", getName().c_str(), handle);
OSFatal("Failed to find dir handle");
OSFatal("ContentRedirectionModule: Failed to find dir handle");
return nullptr;
}
void FSWrapper::deleteDirHandle(FSDirectoryHandle handle) {
std::lock_guard<std::mutex> lock(openDirsMutex);
bool found = false;
int count = 0;
DirInfo *info;
for (auto &val : openDirs) {
if ((FSDirectoryHandle) val->handle == handle) {
found = true;
info = val;
break;
}
count++;
}
if (found) {
openDirs.erase(openDirs.begin() + count);
delete info;
} else {
if (!remove_locked_first_if(openDirsMutex, openDirs, [handle](auto &cur) { return (FSFileHandle) cur->handle == handle; })) {
DEBUG_FUNCTION_LINE_ERR("[%s] Delete failed because the handle %08X was not found", getName().c_str(), handle);
}
}
void FSWrapper::deleteFileHandle(FSFileHandle handle) {
std::lock_guard<std::mutex> lock(openFilesMutex);
bool found = false;
auto count = 0;
FileInfo *info;
for (auto &val : openFiles) {
if ((FSFileHandle) val->handle == handle) {
found = true;
info = val;
break;
}
count++;
}
if (found) {
openFiles.erase(openFiles.begin() + count);
delete info;
} else {
if (!remove_locked_first_if(openFilesMutex, openFiles, [handle](auto &cur) { return (FSFileHandle) cur->handle == handle; })) {
DEBUG_FUNCTION_LINE_ERR("[%s] Delete failed because the handle %08X was not found", getName().c_str(), handle);
}
}

View File

@ -22,84 +22,82 @@ public:
std::replace(pReplacePathWith.begin(), pReplacePathWith.end(), '\\', '/');
}
~FSWrapper() override {
if (!openFiles.empty()) {
DEBUG_FUNCTION_LINE_ERR("Clean leaked fileInfos");
for (auto &file : openFiles) {
delete file;
}
{
std::lock_guard<std::mutex> lockFiles(openFilesMutex);
openFiles.clear();
}
if (!openDirs.empty()) {
DEBUG_FUNCTION_LINE_ERR("Clean leaked dirInfos");
for (auto &dir : openDirs) {
delete dir;
}
{
std::lock_guard<std::mutex> lockDirs(openDirsMutex);
openDirs.clear();
}
}
FSStatus FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) override;
FSError FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) override;
FSStatus FSReadDirWrapper(FSDirectoryHandle handle,
FSDirectoryEntry *entry) override;
FSError FSReadDirWrapper(FSDirectoryHandle handle,
FSDirectoryEntry *entry) override;
FSStatus FSCloseDirWrapper(FSDirectoryHandle handle) override;
FSError FSCloseDirWrapper(FSDirectoryHandle handle) override;
FSStatus FSMakeDirWrapper(const char *path) override;
FSError FSMakeDirWrapper(const char *path) override;
FSStatus FSRewindDirWrapper(FSDirectoryHandle handle) override;
FSError FSRewindDirWrapper(FSDirectoryHandle handle) override;
FSStatus FSOpenFileWrapper(const char *path,
const char *mode,
FSFileHandle *handle) override;
FSError FSOpenFileWrapper(const char *path,
const char *mode,
FSFileHandle *handle) override;
FSStatus FSCloseFileWrapper(FSFileHandle handle) override;
FSError FSCloseFileWrapper(FSFileHandle handle) override;
FSStatus FSGetStatWrapper(const char *path, FSStat *stats) override;
FSError FSGetStatWrapper(const char *path, FSStat *stats) override;
FSStatus FSGetStatFileWrapper(FSFileHandle handle,
FSStat *stats) override;
FSError FSGetStatFileWrapper(FSFileHandle handle,
FSStat *stats) override;
FSStatus FSReadFileWrapper(void *buffer,
FSError FSReadFileWrapper(void *buffer,
uint32_t size,
uint32_t count,
FSFileHandle handle,
uint32_t unk1) override;
FSError FSReadFileWithPosWrapper(void *buffer,
uint32_t size,
uint32_t count,
uint32_t pos,
FSFileHandle handle,
int32_t unk1) override;
FSError FSSetPosFileWrapper(FSFileHandle handle,
uint32_t pos) override;
FSError FSGetPosFileWrapper(FSFileHandle handle,
uint32_t *pos) override;
FSError FSIsEofWrapper(FSFileHandle handle) override;
FSError FSTruncateFileWrapper(FSFileHandle handle) override;
FSError FSWriteFileWrapper(const uint8_t *buffer,
uint32_t size,
uint32_t count,
FSFileHandle handle,
uint32_t unk1) override;
FSStatus FSReadFileWithPosWrapper(void *buffer,
uint32_t size,
uint32_t count,
uint32_t pos,
FSFileHandle handle,
int32_t unk1) override;
FSError FSRemoveWrapper(const char *path) override;
FSStatus FSSetPosFileWrapper(FSFileHandle handle,
uint32_t pos) override;
FSError FSRenameWrapper(const char *oldPath,
const char *newPath) override;
FSStatus FSGetPosFileWrapper(FSFileHandle handle,
uint32_t *pos) override;
FSError FSFlushFileWrapper(FSFileHandle handle) override;
FSStatus FSIsEofWrapper(FSFileHandle handle) override;
FSStatus FSTruncateFileWrapper(FSFileHandle handle) override;
FSStatus FSWriteFileWrapper(uint8_t *buffer,
uint32_t size,
uint32_t count,
FSFileHandle handle,
uint32_t unk1) override;
FSStatus FSRemoveWrapper(const char *path) override;
FSStatus FSRenameWrapper(const char *oldPath,
const char *newPath) override;
FSStatus FSFlushFileWrapper(FSFileHandle handle) override;
uint32_t getLayerId() override {
return (uint32_t) this;
}
protected:
virtual bool IsFileModeAllowed(const char *mode);
@ -108,8 +106,8 @@ protected:
std::string GetNewPath(const std::string_view &path);
DirInfo *getDirFromHandle(FSDirectoryHandle handle);
FileInfo *getFileFromHandle(FSFileHandle handle);
std::shared_ptr<DirInfo> getDirFromHandle(FSDirectoryHandle handle);
std::shared_ptr<FileInfo> getFileFromHandle(FSFileHandle handle);
bool isValidDirHandle(FSDirectoryHandle handle) override;
bool isValidFileHandle(FSFileHandle handle) override;
@ -119,8 +117,8 @@ protected:
virtual bool CheckFileShouldBeIgnored(std::string &path);
virtual FileInfo *getNewFileHandle();
virtual DirInfo *getNewDirHandle();
virtual std::shared_ptr<FileInfo> getNewFileHandle();
virtual std::shared_ptr<DirInfo> getNewDirHandle();
virtual bool SkipDeletedFilesInReadDir();
@ -134,6 +132,6 @@ private:
bool pIsWriteable = false;
std::mutex openFilesMutex;
std::mutex openDirsMutex;
std::vector<FileInfo *> openFiles;
std::vector<DirInfo *> openDirs;
std::vector<std::shared_ptr<FileInfo>> openFiles;
std::vector<std::shared_ptr<DirInfo>> openDirs;
};

View File

@ -1,35 +1,43 @@
#include "FSWrapperMergeDirsWithParent.h"
#include "utils/StringTools.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <coreinit/cache.h>
#include <coreinit/debug.h>
#include <coreinit/filesystem.h>
#include <filesystem>
FSStatus FSWrapperMergeDirsWithParent::FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) {
FSError FSWrapperMergeDirsWithParent::FSOpenDirWrapper(const char *path,
FSADirectoryHandle *handle) {
if (handle == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] handle was NULL", getName().c_str());
return FS_ERROR_INVALID_PARAM;
}
auto res = FSWrapper::FSOpenDirWrapper(path, handle);
if (res == FS_STATUS_OK) {
if (handle == nullptr || !isValidDirHandle(*handle)) {
if (res == FS_ERROR_OK) {
if (!isValidDirHandle(*handle)) {
FSWrapper::FSCloseDirWrapper(*handle);
DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), *handle);
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_DIRHANDLE;
}
auto *dirHandle = getDirExFromHandle(*handle);
auto dirHandle = getDirExFromHandle(*handle);
if (dirHandle != nullptr) {
dirHandle->readResultCapacity = 0;
dirHandle->readResultNumberOfEntries = 0;
dirHandle->realDirHandle = 0;
if (pFSClient && pCmdBlock) {
FSDirectoryHandle realHandle = 0;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call real_FSOpenDir for %s with error_flag %08X", getName().c_str(), path, (uint32_t) this);
// Call FSOpen with "this" as errorFlag call FSOpen for "parent" layers only.
if (FSOpenDir(pFSClient, pCmdBlock, path, &realHandle, (FSErrorFlag) (uint32_t) this) == FS_STATUS_OK) {
if (clientHandle) {
FSADirectoryHandle realHandle = 0;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSAOpenDir with %s for parent layer", getName().c_str(), path);
FSError err;
if ((err = FSAOpenDir(clientHandle, path, &realHandle)) == FS_ERROR_OK) {
dirHandle->realDirHandle = realHandle;
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Failed to open real dir %s", getName().c_str(), path);
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to open real dir %s. %s (%d)", getName().c_str(), path, FSAGetStatusStr(err), err);
}
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Global FSClient or FSCmdBlock were null", getName().c_str());
DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str());
}
OSMemoryBarrier();
}
@ -41,21 +49,21 @@ bool FSWrapperMergeDirsWithParent::SkipDeletedFilesInReadDir() {
return false;
}
FSStatus FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSDirectoryHandle handle, FSDirectoryEntry *entry) {
FSError FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSADirectoryHandle handle, FSADirectoryEntry *entry) {
do {
auto res = FSWrapper::FSReadDirWrapper(handle, entry);
if (res == FS_STATUS_OK || res == FS_STATUS_END) {
if (res == FS_ERROR_OK || res == FS_ERROR_END_OF_DIR) {
if (!isValidDirHandle(handle)) {
DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle);
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_DIRHANDLE;
}
auto *dirHandle = getDirExFromHandle(handle);
if (res == FS_STATUS_OK) {
auto dirHandle = getDirExFromHandle(handle);
if (res == FS_ERROR_OK) {
if (dirHandle->readResultCapacity == 0) {
dirHandle->readResult = (FSDirectoryEntryEx *) malloc(sizeof(FSDirectoryEntryEx));
if (dirHandle->readResult == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc memory for %08X (handle %08X)", getName().c_str(), dirHandle, handle);
OSFatal("Failed to alloc memory for read result");
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc memory for %08X (handle %08X)", getName().c_str(), dirHandle.get(), handle);
OSFatal("ContentRedirectionModule: Failed to alloc memory for read result");
}
dirHandle->readResultCapacity = 1;
}
@ -65,18 +73,18 @@ FSStatus FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSDirectoryHandle handle
dirHandle->readResult = (FSDirectoryEntryEx *) realloc(dirHandle->readResult, newCapacity * sizeof(FSDirectoryEntryEx));
dirHandle->readResultCapacity = newCapacity;
if (dirHandle->readResult == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to realloc memory for %08X (handle %08X)", getName().c_str(), dirHandle, handle);
OSFatal("Failed to alloc memory for read result");
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to realloc memory for %08X (handle %08X)", getName().c_str(), dirHandle.get(), handle);
OSFatal("ContentRedirectionModule: Failed to alloc memory for read result");
}
}
memcpy(&dirHandle->readResult[dirHandle->readResultNumberOfEntries].realEntry, entry, sizeof(FSDirectoryEntry));
memcpy(&dirHandle->readResult[dirHandle->readResultNumberOfEntries].realEntry, entry, sizeof(FSADirectoryEntry));
dirHandle->readResultNumberOfEntries++;
/**
* Read the next entry if this enntry starts with deletePrefix. We keep the entry but mark it as deleted.
* Read the next entry if this entry starts with deletePrefix. We keep the entry but mark it as deleted.
*/
if (std::string_view(entry->name).starts_with(deletePrefix)) {
if (starts_with_case_insensitive(entry->name, deletePrefix)) {
dirHandle->readResult[dirHandle->readResultNumberOfEntries].isMarkedAsDeleted = true;
OSMemoryBarrier();
@ -85,22 +93,22 @@ FSStatus FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSDirectoryHandle handle
OSMemoryBarrier();
} else if (res == FS_STATUS_END) {
} else if (res == FS_ERROR_END_OF_DIR) {
// Read the real directory.
if (dirHandle->realDirHandle != 0) {
if (pFSClient && pCmdBlock) {
FSDirectoryEntry realDirEntry;
FSStatus readDirResult;
if (clientHandle) {
FSADirectoryEntry realDirEntry;
FSError readDirResult;
while (true) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call real_FSReadDir for %08X with error_flag %08X", getName().c_str(), dirHandle->realDirHandle, (uint32_t) this);
readDirResult = FSReadDir(pFSClient, pCmdBlock, dirHandle->realDirHandle, &realDirEntry, (FSErrorFlag) (uint32_t) this);
if (readDirResult == FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSReadDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle);
readDirResult = FSAReadDir(clientHandle, dirHandle->realDirHandle, &realDirEntry);
if (readDirResult == FS_ERROR_OK) {
bool found = false;
auto nameDeleted = deletePrefix + realDirEntry.name;
for (int i = 0; i < dirHandle->readResultNumberOfEntries; i++) {
auto curResult = &dirHandle->readResult[i];
// Don't return file that are "deleted"
// Don't return files that are "deleted"
if (strcmp(curResult->realEntry.name, nameDeleted.c_str()) == 0) {
found = true;
break;
@ -113,21 +121,21 @@ FSStatus FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSDirectoryHandle handle
}
// If it's new we can use it :)
if (!found) {
memcpy(entry, &realDirEntry, sizeof(FSDirectoryEntry));
res = FS_STATUS_OK;
memcpy(entry, &realDirEntry, sizeof(FSADirectoryEntry));
res = FS_ERROR_OK;
break;
}
} else if (readDirResult == FS_STATUS_END) {
res = FS_STATUS_END;
} else if (readDirResult == FS_ERROR_END_OF_DIR) {
res = FS_ERROR_END_OF_DIR;
break;
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] real_FSReadDir returned an unexpected error: %08X", getName().c_str(), readDirResult);
res = FS_STATUS_END;
DEBUG_FUNCTION_LINE_ERR("[%s] real_FSReadDir returned an unexpected error: %s (%d)", getName().c_str(), FSAGetStatusStr(readDirResult), readDirResult);
res = FS_ERROR_END_OF_DIR;
break;
}
}
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Global FSClient or FSCmdBlock were null", getName().c_str());
DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str());
}
}
} else {
@ -138,28 +146,30 @@ FSStatus FSWrapperMergeDirsWithParent::FSReadDirWrapper(FSDirectoryHandle handle
} while (true);
}
FSStatus FSWrapperMergeDirsWithParent::FSCloseDirWrapper(FSDirectoryHandle handle) {
FSError FSWrapperMergeDirsWithParent::FSCloseDirWrapper(FSADirectoryHandle handle) {
auto res = FSWrapper::FSCloseDirWrapper(handle);
if (res == FS_STATUS_OK) {
if (res == FS_ERROR_OK) {
if (!isValidDirHandle(handle)) {
DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle);
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_DIRHANDLE;
}
auto *dirHandle = getDirExFromHandle(handle);
auto dirHandle = getDirExFromHandle(handle);
if (dirHandle->realDirHandle != 0) {
if (pFSClient && pCmdBlock) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSCloseDir for %08X with error_flag %08X (this)", getName().c_str(), dirHandle->realDirHandle, (uint32_t) this);
auto realResult = FSCloseDir(pFSClient, pCmdBlock, dirHandle->realDirHandle, (FSErrorFlag) (uint32_t) this);
if (realResult == FS_STATUS_OK) {
if (clientHandle) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSCloseDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle);
auto realResult = FSACloseDir(clientHandle, dirHandle->realDirHandle);
if (realResult == FS_ERROR_OK) {
dirHandle->realDirHandle = 0;
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close realDirHandle %d: res %d", getName().c_str(), dirHandle->realDirHandle, realResult);
return realResult;
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to close realDirHandle %d: res %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(realResult), realResult);
return realResult == FS_ERROR_CANCELLED ? FS_ERROR_CANCELLED : FS_ERROR_MEDIA_ERROR;
}
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Global FSClient or FSCmdBlock were null", getName().c_str());
DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str());
}
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str());
}
if (dirHandle->readResult != nullptr) {
@ -174,14 +184,14 @@ FSStatus FSWrapperMergeDirsWithParent::FSCloseDirWrapper(FSDirectoryHandle handl
return res;
}
FSStatus FSWrapperMergeDirsWithParent::FSRewindDirWrapper(FSDirectoryHandle handle) {
FSError FSWrapperMergeDirsWithParent::FSRewindDirWrapper(FSADirectoryHandle handle) {
auto res = FSWrapper::FSRewindDirWrapper(handle);
if (res == FS_STATUS_OK) {
if (res == FS_ERROR_OK) {
if (!isValidDirHandle(handle)) {
DEBUG_FUNCTION_LINE_ERR("[%s] No valid dir handle %08X", getName().c_str(), handle);
return FS_STATUS_FATAL_ERROR;
return FS_ERROR_INVALID_DIRHANDLE;
}
auto *dirHandle = getDirExFromHandle(handle);
auto dirHandle = getDirExFromHandle(handle);
if (dirHandle->readResult != nullptr) {
dirHandle->readResultNumberOfEntries = 0;
#pragma GCC diagnostic push
@ -191,16 +201,19 @@ FSStatus FSWrapperMergeDirsWithParent::FSRewindDirWrapper(FSDirectoryHandle hand
}
if (dirHandle->realDirHandle != 0) {
if (pFSClient && pCmdBlock) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call real_FSRewindDir for %08X with error_flag %08X (this)", getName().c_str(), dirHandle->realDirHandle, (uint32_t) this);
if (FSRewindDir(pFSClient, pCmdBlock, dirHandle->realDirHandle, (FSErrorFlag) (uint32_t) this) == FS_STATUS_OK) {
if (clientHandle) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call FSARewindDir with %08X for parent layer", getName().c_str(), dirHandle->realDirHandle);
FSError err;
if ((err = FSARewindDir(clientHandle, dirHandle->realDirHandle)) == FS_ERROR_OK) {
dirHandle->realDirHandle = 0;
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to rewind dir for realDirHandle %08X", getName().c_str(), dirHandle->realDirHandle);
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to rewind dir for realDirHandle %08X. %s (%d)", getName().c_str(), dirHandle->realDirHandle, FSAGetStatusStr(err), err);
}
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Global FSClient or FSCmdBlock were null", getName().c_str());
DEBUG_FUNCTION_LINE_ERR("[%s] clientHandle was null", getName().c_str());
}
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] dirHandle->realDirHandle was 0", getName().c_str());
}
OSMemoryBarrier();
}
@ -215,43 +228,34 @@ FSWrapperMergeDirsWithParent::FSWrapperMergeDirsWithParent(const std::string &na
replaceWithPath,
fallbackOnError,
false) {
pFSClient = new (std::nothrow) FSClient;
pCmdBlock = new (std::nothrow) FSCmdBlock;
if (pFSClient == nullptr || pCmdBlock == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to alloc client or cmdBlock", name.c_str());
freeFSClient();
FSAInit();
this->clientHandle = FSAAddClient(nullptr);
if (clientHandle < 0) {
DEBUG_FUNCTION_LINE_ERR("[%s] FSAClientHandle failed: %s (%d)", name.c_str(), FSAGetStatusStr(static_cast<FSError>(clientHandle)), clientHandle);
clientHandle = 0;
}
if (FSAddClient(pFSClient, FS_ERROR_FLAG_ALL) != FS_STATUS_OK) {
DEBUG_FUNCTION_LINE_ERR("[%s] Failed to addClient");
freeFSClient();
}
FSInitCmdBlock(pCmdBlock);
}
FSWrapperMergeDirsWithParent::~FSWrapperMergeDirsWithParent() {
freeFSClient();
}
void FSWrapperMergeDirsWithParent::freeFSClient() {
if (pFSClient) {
FSDelClient(pFSClient, FS_ERROR_FLAG_ALL);
if (clientHandle) {
FSError res;
if ((res = FSADelClient(clientHandle)) != FS_ERROR_OK) {
DEBUG_FUNCTION_LINE_ERR("[%s] FSADelClient failed: %s (%d)", FSAGetStatusStr(res), res);
}
clientHandle = 0;
}
delete pFSClient;
delete pCmdBlock;
pFSClient = nullptr;
pCmdBlock = nullptr;
}
DirInfoEx *FSWrapperMergeDirsWithParent::getDirExFromHandle(FSDirectoryHandle handle) {
auto *dir = getDirFromHandle(handle);
auto res = dynamic_cast<DirInfoEx *>(dir);
if (res == nullptr) {
DEBUG_FUNCTION_LINE_ERR("[%s] dynamic_cast<DirInfoEx *>(%08X)", getName().c_str(), handle);
OSFatal("dynamic_cast<DirInfoEx *> failed");
std::shared_ptr<DirInfoEx> FSWrapperMergeDirsWithParent::getDirExFromHandle(FSADirectoryHandle handle) {
auto dir = std::dynamic_pointer_cast<DirInfoEx>(getDirFromHandle(handle));
if (!dir) {
DEBUG_FUNCTION_LINE_ERR("[%s] dynamic_pointer_cast<DirInfoEx *>(%08X) failed", getName().c_str(), handle);
OSFatal("ContentRedirectionModule: dynamic_pointer_cast<DirInfoEx *> failed");
}
return res;
return dir;
}
DirInfo *FSWrapperMergeDirsWithParent::getNewDirHandle() {
return new (std::nothrow) DirInfoEx;
std::shared_ptr<DirInfo> FSWrapperMergeDirsWithParent::getNewDirHandle() {
return make_shared_nothrow<DirInfoEx>();
}

View File

@ -13,24 +13,26 @@ public:
~FSWrapperMergeDirsWithParent() override;
FSStatus FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) override;
FSError FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) override;
FSStatus FSReadDirWrapper(FSDirectoryHandle handle,
FSDirectoryEntry *entry) override;
FSError FSReadDirWrapper(FSDirectoryHandle handle,
FSDirectoryEntry *entry) override;
FSStatus FSCloseDirWrapper(FSDirectoryHandle handle) override;
FSError FSCloseDirWrapper(FSDirectoryHandle handle) override;
FSStatus FSRewindDirWrapper(FSDirectoryHandle handle) override;
FSError FSRewindDirWrapper(FSDirectoryHandle handle) override;
DirInfo *getNewDirHandle() override;
std::shared_ptr<DirInfo> getNewDirHandle() override;
bool SkipDeletedFilesInReadDir() override;
private:
void freeFSClient();
FSClient *pFSClient;
FSCmdBlock *pCmdBlock;
uint32_t getLayerId() override {
return (uint32_t) clientHandle;
}
DirInfoEx *getDirExFromHandle(FSDirectoryHandle handle);
private:
FSAClientHandle clientHandle;
std::shared_ptr<DirInfoEx> getDirExFromHandle(FSDirectoryHandle handle);
};

View File

@ -5,26 +5,29 @@
#include "utils/logger.h"
#include "utils/utils.h"
#include <coreinit/cache.h>
#include <coreinit/filesystem_fsa.h>
#include <coreinit/thread.h>
#include <malloc.h>
#include <map>
#include <unistd.h>
#include <wums.h>
std::mutex workingDirMutex;
std::map<FSClient *, std::string> workingDirs;
std::map<FSAClientHandle, std::string> workingDirs;
std::mutex fsLayerMutex;
std::vector<IFSWrapper *> fsLayers;
std::vector<std::unique_ptr<IFSWrapper>> fsLayers;
std::string getFullPathGeneric(FSAClientHandle client, const char *path, std::mutex &mutex, std::map<FSAClientHandle, std::string> &map) {
std::lock_guard<std::mutex> workingDirLock(mutex);
std::string getFullPathForClient(FSClient *pClient, char *path) {
std::string res;
if (path[0] != '/' && path[0] != '\\') {
if (workingDirs.count(pClient) > 0) {
res = string_format("%s%s", workingDirs.at(pClient).c_str(), path);
} else {
DEBUG_FUNCTION_LINE_ERR("Failed to find working dir for client");
if (map.count(client) == 0) {
DEBUG_FUNCTION_LINE_WARN("No working dir found for client %08X, fallback to \"/\"", client);
workingDirs[client] = "/";
}
res = string_format("%s%s", map.at(client).c_str(), path);
} else {
res = path;
}
@ -34,140 +37,326 @@ std::string getFullPathForClient(FSClient *pClient, char *path) {
return res;
}
void setWorkingDir(FSClient *client, const char *path) {
std::lock_guard<std::mutex> workingDirLock(workingDirMutex);
void setWorkingDirGeneric(FSAClientHandle client, const char *path, std::mutex &mutex, std::map<FSAClientHandle, std::string> &map) {
if (!path) {
DEBUG_FUNCTION_LINE_WARN("Path was NULL");
return;
}
workingDirs[client] = path;
std::lock_guard<std::mutex> workingDirLock(mutex);
std::string cwd(path);
if (cwd.empty() || cwd.back() != '/') {
cwd.push_back('/');
}
map[client] = cwd;
OSMemoryBarrier();
}
std::string getFullPath(FSAClientHandle pClient, const char *path) {
return getFullPathGeneric(pClient, path, workingDirMutex, workingDirs);
}
void setWorkingDir(FSAClientHandle client, const char *path) {
setWorkingDirGeneric(client, path, workingDirMutex, workingDirs);
}
void clearFSLayer() {
{
std::lock_guard<std::mutex> workingDirLock(workingDirMutex);
workingDirs.clear();
}
{
std::lock_guard<std::mutex> layerlock(fsLayerMutex);
for (auto &layer : fsLayers) {
delete layer;
}
std::lock_guard<std::mutex> layerLock(fsLayerMutex);
fsLayers.clear();
}
}
// FUN_0204cc20
#define fsClientHandleFatalErrorAndBlock ((void (*)(FSClientBody *, uint32_t))(0x101C400 + 0x4cc20))
FSStatus doForLayer(FSClient *client,
FSErrorFlag errorMask,
const std::function<FSStatus(FSErrorFlag errorMask)> &real_function,
const std::function<FSStatus(IFSWrapper *layer)> &layer_callback,
const std::function<FSStatus(IFSWrapper *layer, FSStatus)> &result_handler) {
FSErrorFlag realErrorMask = errorMask;
bool sendMessageToThread(FSShimWrapperMessage *param) {
auto *curThread = &gThreadData[OSGetCoreId()];
if (curThread->setup) {
OSMessage send;
send.message = param;
send.args[0] = FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND;
auto res = OSSendMessage(&curThread->queue, &send, OS_MESSAGE_FLAGS_NONE);
if (!res) {
DEBUG_FUNCTION_LINE_ERR("Message Queue for ContentRedirection IO Thread is full");
OSFatal("ContentRedirectionModule: Message Queue for ContentRedirection IO Thread is full");
}
return res;
} else {
DEBUG_FUNCTION_LINE_ERR("Thread not setup");
OSFatal("ContentRedirectionModule: Thread not setup");
}
return false;
}
FSError doForLayer(FSShimWrapper *param) {
std::lock_guard<std::mutex> lock(fsLayerMutex);
if (!fsLayers.empty()) {
uint32_t startIndex = fsLayers.size();
for (uint32_t i = fsLayers.size(); i > 0; i--) {
if ((uint32_t) fsLayers[i - 1] == errorMask) {
startIndex = i - 1;
realErrorMask = FS_ERROR_FLAG_ALL;
if ((uint32_t) fsLayers[i - 1]->getLayerId() == param->shim->clientHandle) {
startIndex = i - 1;
break;
}
}
if (startIndex > 0) {
for (uint32_t i = startIndex; i > 0; i--) {
auto layer = fsLayers[i - 1];
auto &layer = fsLayers[i - 1];
if (!layer->isActive()) {
continue;
}
auto result = layer_callback(layer);
if (result != FS_STATUS_FORCE_PARENT_LAYER) {
if (result < FS_STATUS_OK && result != FS_STATUS_END && result != FS_STATUS_CANCELLED) {
if (layer->fallbackOnError()) {
// Only fallback if FS_STATUS_FORCE_NO_FALLBACK flag is not set.
if (static_cast<FSStatus>(result & 0xFFFF0000) != FS_STATUS_FORCE_NO_FALLBACK) {
continue;
auto layerResult = FS_ERROR_FORCE_PARENT_LAYER;
auto command = (FSACommandEnum) param->shim->command;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
switch (command) {
case FSA_COMMAND_OPEN_DIR: {
auto *request = &param->shim->request.openDir;
auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] OpenDir: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str());
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *handlePtr = (FSDirectoryHandle *) hackyBuffer[1];
layerResult = layer->FSOpenDirWrapper(fullPath.c_str(), handlePtr);
break;
}
case FSA_COMMAND_READ_DIR: {
auto *request = &param->shim->request.readDir;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadDir: %08X", layer->getName().c_str(), request->handle);
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *dirEntryPtr = (FSADirectoryEntry *) hackyBuffer[1];
layerResult = layer->FSReadDirWrapper(request->handle, dirEntryPtr);
break;
}
case FSA_COMMAND_CLOSE_DIR: {
auto *request = &param->shim->request.closeDir;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] CloseDir: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSCloseDirWrapper(request->handle);
if (layerResult != FS_ERROR_FORCE_REAL_FUNCTION && layerResult != FS_ERROR_FORCE_PARENT_LAYER) {
if (layer->isValidDirHandle(request->handle)) {
layer->deleteDirHandle(request->handle);
} else {
// Remove FS_STATUS_FORCE_NO_FALLBACK flag.
result = static_cast<FSStatus>((result & 0x0000FFFF) | 0xFFFF0000);
DEBUG_FUNCTION_LINE_ERR("[%s] Expected to delete dirHandle by %08X but it was not found", layer->getName().c_str(), request->handle);
}
}
break;
}
case FSA_COMMAND_REWIND_DIR: {
auto *request = &param->shim->request.rewindDir;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] RewindDir: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSRewindDirWrapper(request->handle);
break;
}
case FSA_COMMAND_MAKE_DIR: {
auto *request = &param->shim->request.makeDir;
auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] MakeDir: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str());
layerResult = layer->FSMakeDirWrapper(fullPath.c_str());
break;
}
case FSA_COMMAND_OPEN_FILE: {
auto *request = &param->shim->request.openFile;
auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path);
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *handlePtr = (FSFileHandle *) hackyBuffer[1];
DEBUG_FUNCTION_LINE_VERBOSE("[%s] OpenFile: path %s (full path: %s) mode %s", layer->getName().c_str(), request->path, fullPath.c_str(), request->mode);
layerResult = layer->FSOpenFileWrapper(fullPath.c_str(), request->mode, handlePtr);
break;
}
case FSA_COMMAND_CLOSE_FILE: {
auto *request = &param->shim->request.closeFile;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] CloseFile: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSCloseFileWrapper(request->handle);
if (layerResult != FS_ERROR_FORCE_REAL_FUNCTION && layerResult != FS_ERROR_FORCE_PARENT_LAYER) {
if (layer->isValidFileHandle(request->handle)) {
layer->deleteFileHandle(request->handle);
} else {
DEBUG_FUNCTION_LINE_ERR("[%s] Expected to delete fileHandle by handle %08X but it was not found", layer->getName().c_str(), request->handle);
}
}
break;
}
case FSA_COMMAND_GET_INFO_BY_QUERY: {
auto *request = &param->shim->request.getInfoByQuery;
if (request->type == FSA_QUERY_INFO_STAT) {
auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetStat: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str());
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *statPtr = (FSStat *) hackyBuffer[1];
layerResult = layer->FSGetStatWrapper(fullPath.c_str(), statPtr);
}
break;
}
case FSA_COMMAND_STAT_FILE: {
auto *request = &param->shim->request.statFile;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetStatFile: %08X", layer->getName().c_str(), request->handle);
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *statPtr = (FSStat *) hackyBuffer[1];
layerResult = layer->FSGetStatFileWrapper(request->handle, statPtr);
break;
}
case FSA_COMMAND_READ_FILE: {
auto *request = &param->shim->request.readFile;
if (request->readFlags == FSA_READ_FLAG_NONE) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadFile: buffer %08X size %08X count %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->handle);
layerResult = layer->FSReadFileWrapper(request->buffer, request->size, request->count, request->handle, 0);
} else if (request->readFlags == FSA_READ_FLAG_READ_WITH_POS) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] ReadFileWithPos: buffer %08X size %08X count %08X pos %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->pos, request->handle);
layerResult = layer->FSReadFileWithPosWrapper(request->buffer, request->size, request->count, request->pos, request->handle, 0);
}
break;
}
case FSA_COMMAND_SET_POS_FILE: {
auto *request = &param->shim->request.setPosFile;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] SetPosFile: %08X %08X", layer->getName().c_str(), request->handle, request->pos);
layerResult = layer->FSSetPosFileWrapper(request->handle, request->pos);
break;
}
case FSA_COMMAND_GET_POS_FILE: {
auto *request = &param->shim->request.getPosFile;
// Hacky solution:
auto *hackyBuffer = (uint32_t *) &param->shim->response;
auto *posPtr = (FSAFilePosition *) hackyBuffer[1];
DEBUG_FUNCTION_LINE_VERBOSE("[%s] GetPosFile: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSGetPosFileWrapper(request->handle, posPtr);
break;
}
case FSA_COMMAND_IS_EOF: {
auto *request = &param->shim->request.isEof;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] IsEof: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSIsEofWrapper(request->handle);
break;
}
case FSA_COMMAND_TRUNCATE_FILE: {
auto *request = &param->shim->request.truncateFile;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] TruncateFile: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSTruncateFileWrapper(request->handle);
break;
}
case FSA_COMMAND_WRITE_FILE: {
auto *request = &param->shim->request.writeFile;
if (request->writeFlags == FSA_WRITE_FLAG_NONE) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] WriteFile: buffer %08X size %08X count %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->handle);
layerResult = layer->FSWriteFileWrapper(request->buffer, request->size, request->count, request->handle, 0);
} else if (request->writeFlags == FSA_WRITE_FLAG_READ_WITH_POS) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] WriteFileWithPos: buffer %08X size %08X count %08X pos %08X handle %08X", layer->getName().c_str(), request->buffer, request->size, request->count, request->pos, request->handle);
layerResult = layer->FSWriteFileWithPosWrapper(request->buffer, request->size, request->count, request->pos, request->handle, 0);
}
break;
}
case FSA_COMMAND_REMOVE: {
auto *request = &param->shim->request.remove;
auto fullPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->path);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Remove: %s (full path: %s)", layer->getName().c_str(), request->path, fullPath.c_str());
layerResult = layer->FSRemoveWrapper(fullPath.c_str());
break;
}
case FSA_COMMAND_RENAME: {
auto *request = &param->shim->request.rename;
auto fullOldPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->oldPath);
auto fullNewPath = getFullPath((FSAClientHandle) param->shim->clientHandle, request->newPath);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Rename: %s -> %s (full path: %s -> %s)", layer->getName().c_str(), request->oldPath, request->newPath, fullOldPath.c_str(), fullNewPath.c_str());
layerResult = layer->FSRenameWrapper(fullOldPath.c_str(), fullNewPath.c_str());
break;
}
case FSA_COMMAND_FLUSH_FILE: {
auto *request = &param->shim->request.flushFile;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] FlushFile: %08X", layer->getName().c_str(), request->handle);
layerResult = layer->FSFlushFileWrapper(request->handle);
break;
}
case FSA_COMMAND_CHANGE_DIR: {
auto *request = &param->shim->request.changeDir;
DEBUG_FUNCTION_LINE_VERBOSE("[%s] ChangeDir: %s", layer->getName().c_str(), request->path);
setWorkingDir((FSAClientHandle) param->shim->clientHandle, request->path);
// We still want to call the original function.
layerResult = FS_ERROR_FORCE_PARENT_LAYER;
break;
}
case FSA_COMMAND_GET_CWD: {
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_GET_CWD hook not implemented");
break;
}
case FSA_COMMAND_APPEND_FILE: {
auto *request = &param->shim->request.appendFile;
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_APPEND_FILE hook not implemented for handle %08X", request->handle);
break;
}
case FSA_COMMAND_FLUSH_MULTI_QUOTA: {
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_FLUSH_MULTI_QUOTA hook not implemented");
break;
}
case FSA_COMMAND_OPEN_FILE_BY_STAT: {
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_OPEN_FILE_BY_STAT hook not implemented");
break;
}
case FSA_COMMAND_CHANGE_OWNER: {
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_CHANGE_OWNER hook not implemented");
break;
}
case FSA_COMMAND_CHANGE_MODE: {
DEBUG_FUNCTION_LINE_WARN("FSA_COMMAND_CHANGE_OWNER hook not implemented");
break;
}
default: {
break;
}
}
#pragma GCC diagnostic pop
if (layerResult != FS_ERROR_FORCE_PARENT_LAYER) {
auto maskedResult = (FSError) ((layerResult & FS_ERROR_REAL_MASK) | FS_ERROR_EXTRA_MASK);
auto result = layerResult >= 0 ? layerResult : maskedResult;
if (result < FS_ERROR_OK && result != FS_ERROR_END_OF_FILE && result != FS_ERROR_END_OF_DIR && result != FS_ERROR_CANCELLED) {
if (layer->fallbackOnError()) {
// Only fallback if FS_ERROR_FORCE_NO_FALLBACK flag is not set.
if (static_cast<FSError>(layerResult & FS_ERROR_EXTRA_MASK) != FS_ERROR_FORCE_NO_FALLBACK) {
continue;
}
}
}
if (param->sync == FS_SHIM_TYPE_SYNC) {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Return with result %08X %s", layer->getName().c_str(), result, result <= 0 ? FSAGetStatusStr(result) : "");
return result;
} else if (param->sync == FS_SHIM_TYPE_ASYNC) {
// convert to IOSError
auto err = (IOSError) result;
if (result == FS_ERROR_INVALID_BUFFER) {
err = IOS_ERROR_ACCESS;
} else if (result == FS_ERROR_INVALID_CLIENTHANDLE) {
err = IOS_ERROR_INVALID;
} else if (result == FS_ERROR_BUSY) {
err = IOS_ERROR_QFULL;
}
if (result >= FS_STATUS_OK || result == FS_STATUS_END || result == FS_STATUS_CANCELLED) {
DEBUG_FUNCTION_LINE_VERBOSE("Returned %08X by %s", result, layer->getName().c_str());
return result_handler(layer, result);
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call async callback :) with result %08X %s", layer->getName().c_str(), err, result <= 0 ? FSAGetStatusStr(result) : "");
param->asyncFS.callback(err, &param->asyncFS);
return FS_ERROR_OK;
} else {
// This should never happen.
DEBUG_FUNCTION_LINE_ERR("Unknown sync type.");
OSFatal("ContentRedirectionModule: Unknown sync type.");
}
FSErrorFlag errorFlags = FS_ERROR_FLAG_NONE;
bool forceError = false;
switch ((int) result) {
case FS_STATUS_MAX:
errorFlags = FS_ERROR_FLAG_MAX;
break;
case FS_STATUS_ALREADY_OPEN:
errorFlags = FS_ERROR_FLAG_ALREADY_OPEN;
break;
case FS_STATUS_EXISTS:
errorFlags = FS_ERROR_FLAG_EXISTS;
break;
case FS_STATUS_NOT_FOUND:
errorFlags = FS_ERROR_FLAG_NOT_FOUND;
break;
case FS_STATUS_NOT_FILE:
errorFlags = FS_ERROR_FLAG_NOT_FILE;
break;
case FS_STATUS_NOT_DIR:
errorFlags = FS_ERROR_FLAG_NOT_DIR;
break;
case FS_STATUS_ACCESS_ERROR:
errorFlags = FS_ERROR_FLAG_ACCESS_ERROR;
break;
case FS_STATUS_PERMISSION_ERROR:
errorFlags = FS_ERROR_FLAG_PERMISSION_ERROR;
break;
case FS_STATUS_FILE_TOO_BIG:
errorFlags = FS_ERROR_FLAG_FILE_TOO_BIG;
break;
case FS_STATUS_STORAGE_FULL:
errorFlags = FS_ERROR_FLAG_STORAGE_FULL;
break;
case FS_STATUS_JOURNAL_FULL:
errorFlags = FS_ERROR_FLAG_JOURNAL_FULL;
break;
case FS_STATUS_UNSUPPORTED_CMD:
errorFlags = FS_ERROR_FLAG_UNSUPPORTED_CMD;
break;
case FS_STATUS_MEDIA_NOT_READY:
case FS_STATUS_MEDIA_ERROR:
case FS_STATUS_CORRUPTED:
case FS_STATUS_FATAL_ERROR:
forceError = true;
break;
case FS_STATUS_OK:
break;
}
if (forceError || (realErrorMask != FS_ERROR_FLAG_NONE && (errorFlags & realErrorMask) == 0)) {
DEBUG_FUNCTION_LINE_ERR("Transit to Fatal Error");
auto clientBody = fsClientGetBody(client);
fsClientHandleFatalErrorAndBlock(clientBody, clientBody->lastError);
return FS_STATUS_FATAL_ERROR;
}
DEBUG_FUNCTION_LINE_VERBOSE("%08X Returned %08X by %s ", errorMask, result, layer->getName().c_str());
return result_handler(layer, result);
} else {
DEBUG_FUNCTION_LINE_VERBOSE("[%s] Call parent layer / real function", layer->getName().c_str());
}
}
}
}
auto mask = static_cast<FSErrorFlag>((realErrorMask & FS_ERROR_FLAG_REAL_MASK) | FS_ERROR_FLAG_FORCE_REAL);
return real_function(mask);
return FS_ERROR_FORCE_REAL_FUNCTION;
}
FSCmdBlockBody *fsCmdBlockGetBody(FSCmdBlock *cmdBlock) {
@ -189,16 +378,14 @@ FSClientBody *fsClientGetBody(FSClient *client) {
return body;
}
FSStatus send_result_async(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus status) {
FSStatus handleAsyncResult(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus status) {
if (asyncData->callback != nullptr) {
if (asyncData->ioMsgQueue != nullptr) {
DEBUG_FUNCTION_LINE_ERR("callback and ioMsgQueue both set.");
return FS_STATUS_FATAL_ERROR;
OSFatal("ContentRedirectionModule: callback and ioMsgQueue both set.");
}
// userCallbacks are called in the DefaultAppIOQueue.
asyncData->ioMsgQueue = OSGetDefaultAppIOQueue();
//DEBUG_FUNCTION_LINE("Force to OSGetDefaultAppIOQueue (%08X)", asyncData->ioMsgQueue);
}
if (asyncData->ioMsgQueue != nullptr) {
@ -215,6 +402,7 @@ FSStatus send_result_async(FSClient *client, FSCmdBlock *block, FSAsyncData *asy
result->block = block;
result->status = status;
OSMemoryBarrier();
while (!OSSendMessage(asyncData->ioMsgQueue, (OSMessage *) &(result->ioMsg), OS_MESSAGE_FLAGS_NONE)) {
DEBUG_FUNCTION_LINE_ERR("Failed to send message");
}
@ -233,6 +421,7 @@ int64_t readIntoBuffer(int32_t handle, void *buffer, size_t size, size_t count)
int32_t curResult;
int64_t totalSize = 0;
while (sizeToRead > 0) {
curResult = read(handle, newBuffer, sizeToRead);
if (curResult < 0) {
DEBUG_FUNCTION_LINE_ERR("Reading %08X bytes from handle %08X failed. result %08X errno: %d ", size * count, handle, curResult, errno);
@ -248,9 +437,9 @@ int64_t readIntoBuffer(int32_t handle, void *buffer, size_t size, size_t count)
return totalSize;
}
int64_t writeFromBuffer(int32_t handle, void *buffer, size_t size, size_t count) {
int64_t writeFromBuffer(int32_t handle, const void *buffer, size_t size, size_t count) {
auto sizeToWrite = size * count;
void *ptr = buffer;
auto *ptr = buffer;
int32_t curResult;
int64_t totalSize = 0;
while (sizeToWrite > 0) {
@ -267,4 +456,130 @@ int64_t writeFromBuffer(int32_t handle, void *buffer, size_t size, size_t count)
sizeToWrite -= curResult;
}
return totalSize;
}
FSIOThreadData gThreadData[3];
bool gThreadsRunning = false;
static int32_t fsIOthreadCallback([[maybe_unused]] int argc, const char **argv) {
auto *magic = ((FSIOThreadData *) argv);
DEBUG_FUNCTION_LINE_VERBOSE("Hello from IO Thread for core: %d", OSGetCoreId());
constexpr int32_t messageSize = sizeof(magic->messages) / sizeof(magic->messages[0]);
OSInitMessageQueue(&magic->queue, magic->messages, messageSize);
OSMessage recv;
while (OSReceiveMessage(&magic->queue, &recv, OS_MESSAGE_FLAGS_BLOCKING)) {
if (recv.args[0] == FS_IO_QUEUE_COMMAND_STOP) {
DEBUG_FUNCTION_LINE_VERBOSE("Received break command! Stop thread");
break;
} else if (recv.args[0] == FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND) {
auto *message = (FSShimWrapperMessage *) recv.message;
auto *param = (FSShimWrapper *) message->param;
FSError res = FS_ERROR_MEDIA_ERROR;
auto syncType = param->sync;
if (param->api == FS_SHIM_API_FS) {
res = processShimBufferForFS(param);
} else if (param->api == FS_SHIM_API_FSA) {
res = processShimBufferForFSA(param);
} else {
DEBUG_FUNCTION_LINE_ERR("Incompatible API type %d", param->api);
OSFatal("ContentRedirectionModule: Incompatible API type");
}
// param is free'd at this point!!!
if (syncType == FS_SHIM_TYPE_SYNC) {
// For sync messages we can't (and don't need to) free "message", because it contains the queue we're about to use.
// But this is not a problem because it's sync anyway.
OSMessage send;
send.args[0] = FS_IO_QUEUE_SYNC_RESULT;
send.args[1] = (uint32_t) res;
if (!OSSendMessage(&message->messageQueue, &send, OS_MESSAGE_FLAGS_NONE)) {
DEBUG_FUNCTION_LINE_ERR("Failed to send message");
OSFatal("ContentRedirectionModule: Failed to send message");
}
} else if (syncType == FS_SHIM_TYPE_ASYNC) {
// If it's async we need to clean up "message" :)
free(message);
}
}
}
return 0;
}
void startFSIOThreads() {
int32_t threadAttributes[] = {OS_THREAD_ATTRIB_AFFINITY_CPU0, OS_THREAD_ATTRIB_AFFINITY_CPU1, OS_THREAD_ATTRIB_AFFINITY_CPU2};
auto stackSize = 16 * 1024;
int coreId = 0;
for (int core : threadAttributes) {
auto *threadData = &gThreadData[coreId];
memset(threadData, 0, sizeof(*threadData));
threadData->setup = false;
threadData->thread = (OSThread *) memalign(8, sizeof(OSThread));
if (!threadData->thread) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate threadData");
OSFatal("ContentRedirectionModule: Failed to allocate IO Thread");
continue;
}
threadData->stack = (uint8_t *) memalign(0x20, stackSize);
if (!threadData->thread) {
free(threadData->thread);
DEBUG_FUNCTION_LINE_ERR("Failed to allocate threadData stack");
OSFatal("ContentRedirectionModule: Failed to allocate IO Thread stack");
continue;
}
OSMemoryBarrier();
if (!OSCreateThread(threadData->thread, &fsIOthreadCallback, 1, (char *) threadData, reinterpret_cast<void *>((uint32_t) threadData->stack + stackSize), stackSize, 0, core)) {
free(threadData->thread);
free(threadData->stack);
threadData->setup = false;
DEBUG_FUNCTION_LINE_ERR("failed to create threadData");
OSFatal("ContentRedirectionModule: Failed to create threadData");
}
strncpy(threadData->threadName, string_format("ContentRedirection IO Thread %d", coreId).c_str(), sizeof(threadData->threadName) - 1);
OSSetThreadName(threadData->thread, threadData->threadName);
OSResumeThread(threadData->thread);
threadData->setup = true;
coreId++;
}
gThreadsRunning = true;
OSMemoryBarrier();
}
void stopFSIOThreads() {
if (!gThreadsRunning) {
return;
}
for (auto &gThread : gThreadData) {
auto *thread = &gThread;
if (!thread->setup) {
continue;
}
OSMessage message;
message.args[0] = FS_IO_QUEUE_COMMAND_STOP;
OSSendMessage(&thread->queue, &message, OS_MESSAGE_FLAGS_NONE);
if (OSIsThreadSuspended(thread->thread)) {
OSResumeThread(thread->thread);
}
OSJoinThread(thread->thread, nullptr);
if (thread->stack) {
free(thread->stack);
thread->stack = nullptr;
}
if (thread->thread) {
free(thread->thread);
thread->thread = nullptr;
}
}
gThreadsRunning = false;
}

View File

@ -1,84 +1,110 @@
#pragma once
#include "IFSWrapper.h"
#include "utils/logger.h"
#include <coreinit/core.h>
#include <coreinit/filesystem.h>
#include <coreinit/filesystem_fsa.h>
#include <functional>
#include <mutex>
#include <romfs_dev.h>
#include <string>
struct FSIOThreadData {
OSThread *thread;
void *stack;
OSMessageQueue queue;
OSMessage messages[0x10];
bool setup;
char threadName[0x50];
};
struct AsyncParamFS {
FSClient *client;
FSCmdBlock *block;
FSErrorFlag errorMask;
FSAsyncData asyncData;
IOSAsyncCallbackFn callback;
};
typedef enum FSShimSyncType {
FS_SHIM_TYPE_SYNC = 1,
FS_SHIM_TYPE_ASYNC = 2
} FSShimSyncType;
typedef enum FSShimApiType {
FS_SHIM_API_FS = 1,
FS_SHIM_API_FSA = 2
} FSShimApiType;
struct FSShimWrapper {
FSAShimBuffer *shim;
AsyncParamFS asyncFS;
FSShimSyncType sync;
FSShimApiType api;
};
struct FSShimWrapperMessage {
FSShimWrapper *param;
OSMessageQueue messageQueue;
OSMessage messages[0x1];
};
#define FS_IO_QUEUE_COMMAND_STOP 0x13371337
#define FS_IO_QUEUE_COMMAND_PROCESS_FS_COMMAND 0x42424242
#define FS_IO_QUEUE_SYNC_RESULT 0x43434343
extern bool gThreadsRunning;
extern FSIOThreadData gThreadData[3];
extern std::mutex fsLayerMutex;
extern std::vector<IFSWrapper *> fsLayers;
extern std::vector<std::unique_ptr<IFSWrapper>> fsLayers;
#define SYNC_RESULT_HANDLER [filename = __FILENAME__, func = __FUNCTION__, line = __LINE__]([[maybe_unused]] IFSWrapper *layer, FSStatus res) -> FSStatus { \
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Sync result was %d", res); \
return res; \
}
#define fsaShimPrepareRequestReadFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, uint8_t * buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAReadFlag readFlags))(0x101C400 + 0x436cc))
#define fsaShimPrepareRequestWriteFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const uint8_t *buffer, uint32_t size, uint32_t count, uint32_t pos, FSFileHandle handle, FSAWriteFlag writeFlags))(0x101C400 + 0x437f4))
#define fsaShimPrepareRequestOpenFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, const char *mode, FSMode createMode, FSOpenFileFlags openFlag, uint32_t preallocSize))(0x101C400 + 0x43588))
#define fsaShimPrepareRequestCloseFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43a00))
#define fsaShimPrepareRequestStatFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43998))
#define fsaShimPrepareRequestQueryInfo ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSAQueryInfoType type))(0x101C400 + 0x44118))
#define fsaShimPrepareRequestSetPos ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle, FSAFilePosition position))(0x101C400 + 0x43930))
#define fsaShimPrepareRequestGetPos ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x438fc))
#define fsaShimPrepareRequestIsEof ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43964))
#define fsaShimPrepareRequestTruncate ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x43a34))
#define fsaShimPrepareRequestRemove ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *))(0x101C400 + 0x43aa8))
#define fsaShimPrepareRequestRename ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *, const char *))(0x101C400 + 0x43bc0))
#define fsaShimPrepareRequestFlushFile ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSFileHandle handle))(0x101C400 + 0x439cc))
#define fsaShimPrepareRequestChangeMode ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSMode mode, FSMode modeMask))(0x101C400 + 0x43ff4))
#define ASYNC_RESULT_HANDLER [c = client, b = block, a = asyncData, filename = __FILENAME__, func = __FUNCTION__, line = __LINE__]([[maybe_unused]] IFSWrapper *layer, FSStatus res) -> FSStatus { \
DEBUG_FUNCTION_LINE_VERBOSE_EX(filename, func, line, "Async result was %d", res); \
return send_result_async(c, b, a, res); \
}
#define fsaShimPrepareRequestOpenDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path))(0x101C400 + 0x43458))
#define fsaShimPrepareRequestReadDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x434ec))
#define fsaShimPrepareRequestCloseDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x43554))
#define fsaShimPrepareRequestRewindDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, FSDirectoryHandle handle))(0x101C400 + 0x43520))
#define fsaShimPrepareRequestMakeDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path, FSMode mode))(0x101C400 + 0x43314))
#define fsaShimPrepareRequestChangeDir ((FSError(*)(FSAShimBuffer * shim, IOSHandle clientHandle, const char *path))(0x101C400 + 0x43258))
#define FS_ERROR_FLAG_EXTRA_MASK (FSErrorFlag) 0xFFFF0000
#define FS_ERROR_FLAG_REAL_MASK (FSErrorFlag) 0x0000FFFF
#define FS_ERROR_FLAG_FORCE_REAL (FSErrorFlag) 0xFEDC0000
#define fsaDecodeFsaStatusToFsStatus ((FSStatus(*)(FSError))(0x101C400 + 0x4b148))
#define fsClientHandleFatalError ((void (*)(FSClientBody *, uint32_t))(0x101C400 + 0x4b34c))
#define fsClientHandleFatalErrorAndBlock ((void (*)(FSClientBody *, uint32_t))(0x101C400 + 0x4cc20))
static inline FSErrorFlag getRealErrorFlag(FSErrorFlag flag) {
auto res = flag & FS_ERROR_FLAG_REAL_MASK;
if (res == 0x0000FFFF) {
return FS_ERROR_FLAG_ALL;
}
return static_cast<FSErrorFlag>(res);
}
extern "C" FSError __FSAShimDecodeIosErrorToFsaStatus(IOSHandle handle, IOSError err);
static inline FSErrorFlag isForceRealFunction(FSErrorFlag flag) {
return static_cast<FSErrorFlag>((flag & FS_ERROR_FLAG_EXTRA_MASK) == FS_ERROR_FLAG_FORCE_REAL);
}
bool sendMessageToThread(FSShimWrapperMessage *param);
void clearFSLayer();
struct WUT_PACKED FSCmdBlockBody { //! FSAsyncResult object used for this command.
FSError doForLayer(FSShimWrapper *param);
WUT_UNKNOWN_BYTES(0x96C);
FSAsyncResult asyncResult;
};
WUT_CHECK_OFFSET(FSCmdBlockBody, 0x96C, asyncResult);
WUT_CHECK_SIZE(FSCmdBlockBody, 0x96C + 0x28);
FSError processShimBufferForFS(FSShimWrapper *param);
struct WUT_PACKED FSClientBody {
WUT_UNKNOWN_BYTES(0x1448);
void *fsm;
WUT_UNKNOWN_BYTES(0x15E8 - 0x1448 - 0x04);
uint32_t lastError;
BOOL isLastErrorWithoutVolume;
WUT_UNKNOWN_BYTES(0x161C - 0x15E8 - 0x4 - 0x4);
FSClient *client;
};
WUT_CHECK_OFFSET(FSClientBody, 0x1448, fsm);
WUT_CHECK_OFFSET(FSClientBody, 0x15E8, lastError);
WUT_CHECK_OFFSET(FSClientBody, 0x15EC, isLastErrorWithoutVolume);
WUT_CHECK_OFFSET(FSClientBody, 0x161C, client);
WUT_CHECK_SIZE(FSClientBody, 0x161C + 0x4);
std::string getFullPathForClient(FSClient *pClient, char *path);
void setWorkingDir(FSClient *client, const char *path);
FSStatus doForLayer(FSClient *client,
FSErrorFlag errorMask,
const std::function<FSStatus(FSErrorFlag errorMask)> &real_function,
const std::function<FSStatus(IFSWrapper *layer)> &layer_callback,
const std::function<FSStatus(IFSWrapper *layer, FSStatus)> &result_handler);
FSError processShimBufferForFSA(FSShimWrapper *param);
FSCmdBlockBody *fsCmdBlockGetBody(FSCmdBlock *cmdBlock);
FSClientBody *fsClientGetBody(FSClient *client);
FSStatus send_result_async(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus result);
FSStatus handleAsyncResult(FSClient *client, FSCmdBlock *block, FSAsyncData *asyncData, FSStatus status);
int64_t readIntoBuffer(int32_t handle, void *buffer, size_t size, size_t count);
int64_t writeFromBuffer(int32_t handle, void *buffer, size_t size, size_t count);
int64_t writeFromBuffer(int32_t handle, const void *buffer, size_t size, size_t count);
int32_t CreateSubfolder(const char *fullpath);
void startFSIOThreads();
void stopFSIOThreads();

View File

@ -1,10 +1,13 @@
#pragma once
#include <coreinit/filesystem.h>
#include <coreinit/filesystem_fsa.h>
#include <functional>
#include <string>
#define FS_STATUS_FORCE_PARENT_LAYER (FSStatus) 0xFFFF0000
#define FS_STATUS_FORCE_NO_FALLBACK (FSStatus) 0xFFFE0000
#define FS_ERROR_EXTRA_MASK 0xFFF00000
#define FS_ERROR_REAL_MASK 0x000FFFFF
#define FS_ERROR_FORCE_PARENT_LAYER (FSError) 0xFFE00000
#define FS_ERROR_FORCE_NO_FALLBACK (FSError) 0xFFD00000
#define FS_ERROR_FORCE_REAL_FUNCTION (FSError) 0xFFC00000
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
@ -12,104 +15,113 @@
class IFSWrapper {
public:
virtual ~IFSWrapper() = default;
virtual FSStatus FSOpenDirWrapper(const char *path,
FSDirectoryHandle *handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSOpenDirWrapper(const char *path,
FSADirectoryHandle *handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSReadDirWrapper(FSDirectoryHandle handle,
FSDirectoryEntry *entry) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSReadDirWrapper(FSADirectoryHandle handle,
FSADirectoryEntry *entry) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSCloseDirWrapper(FSDirectoryHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSCloseDirWrapper(FSADirectoryHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSRewindDirWrapper(FSDirectoryHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSRewindDirWrapper(FSADirectoryHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSMakeDirWrapper(const char *path) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSMakeDirWrapper(const char *path) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSOpenFileWrapper(const char *path,
const char *mode,
FSFileHandle *handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSOpenFileWrapper(const char *path,
const char *mode,
FSAFileHandle *handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSCloseFileWrapper(FSFileHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSCloseFileWrapper(FSAFileHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSGetStatWrapper(const char *path,
FSStat *stats) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSGetStatWrapper(const char *path,
FSAStat *stats) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSGetStatFileWrapper(FSFileHandle handle,
FSStat *stats) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSGetStatFileWrapper(FSAFileHandle handle,
FSAStat *stats) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSReadFileWrapper(void *buffer,
virtual FSError FSReadFileWrapper(void *buffer,
uint32_t size,
uint32_t count,
FSAFileHandle handle,
uint32_t unk1) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSReadFileWithPosWrapper(void *buffer,
uint32_t size,
uint32_t count,
uint32_t pos,
FSAFileHandle handle,
int32_t unk1) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSSetPosFileWrapper(FSAFileHandle handle,
uint32_t pos) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSGetPosFileWrapper(FSAFileHandle handle,
uint32_t *pos) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSIsEofWrapper(FSAFileHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSTruncateFileWrapper(FSAFileHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSError FSWriteFileWrapper(const uint8_t *buffer,
uint32_t size,
uint32_t count,
FSFileHandle handle,
FSAFileHandle handle,
uint32_t unk1) {
return FS_STATUS_FORCE_PARENT_LAYER;
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSReadFileWithPosWrapper(void *buffer,
virtual FSError FSWriteFileWithPosWrapper(const uint8_t *buffer,
uint32_t size,
uint32_t count,
uint32_t pos,
FSFileHandle handle,
int32_t unk1) {
return FS_STATUS_FORCE_PARENT_LAYER;
FSAFilePosition pos,
FSAFileHandle handle,
uint32_t unk1) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSSetPosFileWrapper(FSFileHandle handle,
uint32_t pos) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSRemoveWrapper(const char *path) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSGetPosFileWrapper(FSFileHandle handle,
uint32_t *pos) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSRenameWrapper(const char *oldPath,
const char *newPath) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual FSStatus FSIsEofWrapper(FSFileHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
}
virtual FSStatus FSTruncateFileWrapper(FSFileHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
}
virtual FSStatus FSWriteFileWrapper(uint8_t *buffer,
uint32_t size,
uint32_t count,
FSFileHandle handle,
uint32_t unk1) {
return FS_STATUS_FORCE_PARENT_LAYER;
}
virtual FSStatus FSRemoveWrapper(const char *path) {
return FS_STATUS_FORCE_PARENT_LAYER;
}
virtual FSStatus FSRenameWrapper(const char *oldPath,
const char *newPath) {
return FS_STATUS_FORCE_PARENT_LAYER;
}
virtual FSStatus FSFlushFileWrapper(FSFileHandle handle) {
return FS_STATUS_FORCE_PARENT_LAYER;
virtual FSError FSFlushFileWrapper(FSAFileHandle handle) {
return FS_ERROR_FORCE_PARENT_LAYER;
}
virtual bool fallbackOnError() {
@ -128,13 +140,19 @@ public:
return pName;
}
virtual bool isValidDirHandle(FSDirectoryHandle handle) = 0;
virtual bool isValidDirHandle(FSADirectoryHandle handle) = 0;
virtual bool isValidFileHandle(FSFileHandle handle) = 0;
virtual bool isValidFileHandle(FSAFileHandle handle) = 0;
virtual void deleteDirHandle(FSDirectoryHandle handle) = 0;
virtual void deleteDirHandle(FSADirectoryHandle handle) = 0;
virtual void deleteFileHandle(FSFileHandle handle) = 0;
virtual void deleteFileHandle(FSAFileHandle handle) = 0;
virtual uint32_t getLayerId() = 0;
virtual uint32_t getHandle() {
return (uint32_t) this;
}
private:
bool pIsActive = true;

View File

@ -2,24 +2,130 @@
#include "FSWrapperMergeDirsWithParent.h"
#include "FileUtils.h"
#include "IFSWrapper.h"
#include "malloc.h"
#include "utils/StringTools.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <content_redirection/redirection.h>
#include <coreinit/debug.h>
#include <coreinit/dynload.h>
#include <mutex>
#include <nn/act.h>
#include <wums/exports.h>
struct AOCTitle {
WUT_UNKNOWN_BYTES(0x68);
};
WUT_CHECK_SIZE(AOCTitle, 0x68);
bool getAOCPath(std::string &outStr) {
int32_t (*AOC_Initialize)() = nullptr;
int32_t (*AOC_Finalize)() = nullptr;
int32_t (*AOC_ListTitle)(uint32_t * titleCountOut, AOCTitle * titleList, uint32_t maxCount, void *workBuffer, uint32_t workBufferSize) = nullptr;
int32_t (*AOC_OpenTitle)(char *pathOut, AOCTitle *aocTitleInfo, void *workBuffer, uint32_t workBufferSize) = nullptr;
int32_t (*AOC_CalculateWorkBufferSize)(uint32_t count) = nullptr;
int32_t (*AOC_CloseTitle)(AOCTitle * aocTitleInfo) = nullptr;
AOCTitle title{};
char aocPath[256];
aocPath[0] = '\0';
uint32_t outCount = 0;
uint32_t workBufferSize = 0;
void *workBuffer = nullptr;
bool result = false;
OSDynLoad_Module aoc_handle;
if (OSDynLoad_Acquire("nn_aoc.rpl", &aoc_handle) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_Acquire failed");
return false;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_Initialize", reinterpret_cast<void **>(&AOC_Initialize)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_Finalize", reinterpret_cast<void **>(&AOC_Finalize)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_OpenTitle", reinterpret_cast<void **>(&AOC_OpenTitle)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_ListTitle", reinterpret_cast<void **>(&AOC_ListTitle)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_CalculateWorkBufferSize", reinterpret_cast<void **>(&AOC_CalculateWorkBufferSize)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
if (OSDynLoad_FindExport(aoc_handle, OS_DYNLOAD_EXPORT_FUNC, "AOC_CloseTitle", reinterpret_cast<void **>(&AOC_CloseTitle)) != OS_DYNLOAD_OK) {
DEBUG_FUNCTION_LINE_WARN("OSDynLoad_FindExport failed");
goto end;
}
AOC_Initialize();
workBufferSize = AOC_CalculateWorkBufferSize(1);
workBuffer = memalign(0x40, workBufferSize);
if (!workBuffer) {
DEBUG_FUNCTION_LINE_WARN("Failed to alloc workBuffer");
goto end;
}
if (AOC_ListTitle(&outCount, &title, 1, workBuffer, workBufferSize) < 0) {
DEBUG_FUNCTION_LINE_WARN("AOC_ListTitle failed");
goto end;
}
if (AOC_OpenTitle(aocPath, &title, workBuffer, workBufferSize) < 0) {
DEBUG_FUNCTION_LINE_WARN("AOC_OpenTitle failed");
goto end;
}
result = true;
outStr = aocPath;
AOC_CloseTitle(&title);
end:
free(workBuffer);
AOC_Finalize();
OSDynLoad_Release(aoc_handle);
return result;
}
ContentRedirectionApiErrorType CRAddFSLayer(CRLayerHandle *handle, const char *layerName, const char *replacementDir, FSLayerType layerType) {
if (!handle || layerName == nullptr || replacementDir == nullptr) {
DEBUG_FUNCTION_LINE_ERR("CONTENT_REDIRECTION_API_ERROR_INVALID_ARG");
DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_INVALID_ARG");
return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG;
}
IFSWrapper *ptr;
std::unique_ptr<IFSWrapper> ptr;
if (layerType == FS_LAYER_TYPE_CONTENT_REPLACE) {
ptr = new (std::nothrow) FSWrapper(layerName, "/vol/content", replacementDir, false, false);
DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/content\" to \"%s\", mode: \"replace\"", replacementDir);
ptr = make_unique_nothrow<FSWrapper>(layerName, "/vol/content", replacementDir, false, false);
} else if (layerType == FS_LAYER_TYPE_CONTENT_MERGE) {
ptr = new (std::nothrow) FSWrapperMergeDirsWithParent(layerName, "/vol/content", replacementDir, true);
DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/content\" to \"%s\", mode: \"merge\"", replacementDir);
ptr = make_unique_nothrow<FSWrapperMergeDirsWithParent>(layerName, "/vol/content", replacementDir, true);
} else if (layerType == FS_LAYER_TYPE_AOC_MERGE || layerType == FS_LAYER_TYPE_AOC_REPLACE) {
std::string targetPath;
if (!getAOCPath(targetPath)) {
DEBUG_FUNCTION_LINE_ERR("(%s) Failed to get the AOC path. Not redirecting /vol/aoc", layerName);
return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG;
}
DEBUG_FUNCTION_LINE_INFO("Redirecting \"%s\" to \"%s\", mode: \"%s\"", targetPath.c_str(), replacementDir, layerType == FS_LAYER_TYPE_AOC_MERGE ? "merge" : "replace");
if (layerType == FS_LAYER_TYPE_AOC_MERGE) {
ptr = make_unique_nothrow<FSWrapperMergeDirsWithParent>(layerName, targetPath.c_str(), replacementDir, true);
} else {
ptr = make_unique_nothrow<FSWrapper>(layerName, targetPath.c_str(), replacementDir, false, false);
}
} else if (layerType == FS_LAYER_TYPE_SAVE_REPLACE) {
ptr = new (std::nothrow) FSWrapper(layerName, "/vol/save", replacementDir, false, true);
DEBUG_FUNCTION_LINE_INFO("Redirecting \"/vol/save\" to \"%s\", mode: \"replace\"", replacementDir);
ptr = make_unique_nothrow<FSWrapper>(layerName, "/vol/save", replacementDir, false, true);
} else if (layerType == FS_LAYER_TYPE_SAVE_REPLACE_FOR_CURRENT_USER) {
nn::act::Initialize();
nn::act::PersistentId persistentId = nn::act::GetPersistentId();
nn::act::Finalize();
std::string user = string_format("/vol/save/%08X", 0x80000000 | persistentId);
DEBUG_FUNCTION_LINE_INFO("Redirecting \"%s\" to \"%s\", mode: \"replace\"", user.c_str(), replacementDir);
ptr = make_unique_nothrow<FSWrapper>(layerName, user, replacementDir, false, true);
} else {
DEBUG_FUNCTION_LINE_ERR("CONTENT_REDIRECTION_API_ERROR_UNKNOWN_LAYER_DIR_TYPE: %s %s %d", layerName, replacementDir, layerType);
return CONTENT_REDIRECTION_API_ERROR_UNKNOWN_FS_LAYER_TYPE;
@ -27,8 +133,8 @@ ContentRedirectionApiErrorType CRAddFSLayer(CRLayerHandle *handle, const char *l
if (ptr) {
DEBUG_FUNCTION_LINE_VERBOSE("Added new layer (%s). Replacement dir: %s Type:%d", layerName, replacementDir, layerType);
std::lock_guard<std::mutex> lock(fsLayerMutex);
fsLayers.push_back(ptr);
*handle = (CRLayerHandle) ptr;
*handle = (CRLayerHandle) ptr->getHandle();
fsLayers.push_back(std::move(ptr));
return CONTENT_REDIRECTION_API_ERROR_NONE;
}
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory");
@ -36,48 +142,32 @@ ContentRedirectionApiErrorType CRAddFSLayer(CRLayerHandle *handle, const char *l
}
ContentRedirectionApiErrorType CRRemoveFSLayer(CRLayerHandle handle) {
std::lock_guard<std::mutex> lock(fsLayerMutex);
auto count = 0;
auto found = false;
IFSWrapper *layer;
for (auto &cur : fsLayers) {
if ((CRLayerHandle) cur == handle) {
found = true;
layer = cur;
break;
}
count++;
}
if (!found) {
DEBUG_FUNCTION_LINE_ERR("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle);
if (!remove_locked_first_if(fsLayerMutex, fsLayers, [handle](auto &cur) { return (CRLayerHandle) cur->getHandle() == handle; })) {
DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle);
return CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND;
}
fsLayers.erase(fsLayers.begin() + count);
delete layer;
return CONTENT_REDIRECTION_API_ERROR_NONE;
}
ContentRedirectionApiErrorType CRSetActive(CRLayerHandle handle, bool active) {
std::lock_guard<std::mutex> lock(fsLayerMutex);
auto found = false;
IFSWrapper *layer;
for (auto &cur : fsLayers) {
if ((CRLayerHandle) cur == handle) {
found = true;
layer = cur;
break;
if ((CRLayerHandle) cur->getHandle() == handle) {
cur->setActive(active);
return CONTENT_REDIRECTION_API_ERROR_NONE;
}
}
if (!found) {
DEBUG_FUNCTION_LINE_ERR("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle);
return CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND;
}
layer->setActive(active);
return CONTENT_REDIRECTION_API_ERROR_NONE;
DEBUG_FUNCTION_LINE_WARN("CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND for handle %08X", handle);
return CONTENT_REDIRECTION_API_ERROR_LAYER_NOT_FOUND;
}
uint32_t CRGetVersion() {
return CONTENT_REDIRECT_MODULE_VERSION;
ContentRedirectionApiErrorType CRGetVersion(ContentRedirectionVersion *outVersion) {
if (outVersion == nullptr) {
return CONTENT_REDIRECTION_API_ERROR_INVALID_ARG;
}
*outVersion = 1;
return CONTENT_REDIRECTION_API_ERROR_NONE;
}
int CRAddDevice(const devoptab_t *device) {

View File

@ -1,27 +1,65 @@
#include "FSDirReplacements.h"
#include "FSFileReplacements.h"
#include "FSAReplacements.h"
#include "FSReplacements.h"
#include "FileUtils.h"
#include "utils/StringTools.h"
#include "utils/logger.h"
#include "version.h"
#include <wums.h>
WUMS_MODULE_EXPORT_NAME("homebrew_content_redirection");
WUMS_USE_WUT_DEVOPTAB();
WUMS_DEPENDS_ON(homebrew_functionpatcher);
#define VERSION "v0.2.7"
DECL_FUNCTION(void, OSCancelThread, OSThread *thread) {
if (thread == gThreadData[0].thread || thread == gThreadData[1].thread || thread == gThreadData[2].thread) {
DEBUG_FUNCTION_LINE_INFO("Prevent calling OSCancelThread for ContentRedirection IO Threads");
return;
}
real_OSCancelThread(thread);
}
function_replacement_data_t OSCancelThreadReplacement = REPLACE_FUNCTION(OSCancelThread, LIBRARY_COREINIT, OSCancelThread);
WUMS_INITIALIZE() {
initLogging();
DEBUG_FUNCTION_LINE("Patch functions");
// we only patch static functions, we don't need re-patch them at every launch
FunctionPatcherPatchFunction(fs_file_function_replacements, fs_file_function_replacements_size);
FunctionPatcherPatchFunction(fs_dir_function_replacements, fs_dir_function_replacements_size);
if (FunctionPatcher_InitLibrary() != FUNCTION_PATCHER_RESULT_SUCCESS) {
OSFatal("homebrew_content_redirection: FunctionPatcher_InitLibrary failed");
}
bool wasPatched;
for (uint32_t i = 0; i < fs_file_function_replacements_size; i++) {
wasPatched = false;
if (FunctionPatcher_AddFunctionPatch(&fs_file_function_replacements[i], nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) {
OSFatal("homebrew_content_redirection: Failed to patch function");
}
}
for (uint32_t i = 0; i < fsa_file_function_replacements_size; i++) {
wasPatched = false;
if (FunctionPatcher_AddFunctionPatch(&fsa_file_function_replacements[i], nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) {
OSFatal("homebrew_content_redirection: Failed to patch function");
}
}
wasPatched = false;
if (FunctionPatcher_AddFunctionPatch(&OSCancelThreadReplacement, nullptr, &wasPatched) != FUNCTION_PATCHER_RESULT_SUCCESS || !wasPatched) {
OSFatal("homebrew_content_redirection: Failed to patch OSCancelThreadReplacement");
}
DEBUG_FUNCTION_LINE("Patch functions finished");
deinitLogging();
}
WUMS_APPLICATION_STARTS() {
OSReport("Running ContentRedirectionModule " VERSION VERSION_EXTRA "\n");
initLogging();
startFSIOThreads();
}
WUMS_APPLICATION_ENDS() {
clearFSLayer();
stopFSIOThreads();
deinitLogging();
}
}

View File

@ -11,4 +11,14 @@ std::string string_format(const std::string &format, Args... args) {
auto buf = std::make_unique<char[]>(size);
std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
}
static inline bool starts_with_case_insensitive(std::string_view str, std::string_view prefix) {
if (str.size() < prefix.size())
return false;
return std::equal(prefix.begin(), prefix.end(), str.begin(),
[](char a, char b) {
return std::tolower(a) == std::tolower(b);
});
}

View File

@ -38,6 +38,8 @@ extern "C" {
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##WARN ## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##INFO ## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS);
@ -52,6 +54,8 @@ extern "C" {
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##ERROR## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##WARN ## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##INFO ## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, OSReport, "##ERROR## ", "\n", FMT, ##ARGS);

View File

@ -1,5 +1,8 @@
#include "utils/logger.h"
#include <coreinit/filesystem.h>
#include <cstdio>
#include <string.h>
#include <sys/stat.h>
#include <whb/log.h>
#define PRINTF_BUFFER_LENGTH 2048
@ -36,4 +39,39 @@ void dumpHex(const void *data, size_t size) {
}
}
}
}
}
FSMode translate_permission_mode(mode_t mode) {
// Convert normal Unix octal permission bits into CafeOS hexadecimal permission bits
return (FSMode) (((mode & S_IRWXU) << 2) | ((mode & S_IRWXG) << 1) | (mode & S_IRWXO));
}
FSTime translate_time(time_t timeValue) {
// FSTime stats at 1980-01-01, time_t starts at 1970-01-01
auto EPOCH_DIFF_SECS_WII_U_FS_TIME = 315532800; //EPOCH_DIFF_SECS(WIIU_FSTIME_EPOCH_YEAR)
auto adjustedTimeValue = timeValue - EPOCH_DIFF_SECS_WII_U_FS_TIME;
// FSTime is in microseconds, time_t is in seconds
return adjustedTimeValue * 1000000;
}
void translate_stat(struct stat *posStat, FSStat *fsStat) {
memset(fsStat, 0, sizeof(FSStat));
fsStat->size = posStat->st_size;
fsStat->mode = translate_permission_mode(posStat->st_mode);
fsStat->flags = static_cast<FSStatFlags>(0x1C000000); // These bits are always set
if (S_ISDIR(posStat->st_mode)) {
fsStat->flags = static_cast<FSStatFlags>(fsStat->flags | FS_STAT_DIRECTORY);
} else if (S_ISREG(posStat->st_mode)) {
fsStat->flags = static_cast<FSStatFlags>(fsStat->flags | FS_STAT_FILE);
fsStat->allocSize = posStat->st_size;
fsStat->quotaSize = posStat->st_size;
}
fsStat->modified = translate_time(posStat->st_atime);
fsStat->created = translate_time(posStat->st_ctime);
fsStat->entryId = posStat->st_ino;
fsStat->owner = posStat->st_uid;
fsStat->group = posStat->st_gid;
}

View File

@ -1,38 +1,35 @@
#pragma once
#include <malloc.h>
#include <memory>
#include <mutex>
#include <vector>
#ifdef __cplusplus
extern "C" {
#endif
template<class T, class... Args>
std::unique_ptr<T> make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
#define LIMIT(x, min, max) \
({ \
typeof(x) _x = x; \
typeof(min) _min = min; \
typeof(max) _max = max; \
(((_x) < (_min)) ? (_min) : ((_x) > (_max)) ? (_max) \
: (_x)); \
})
template<class T, class... Args>
std::shared_ptr<T> make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
#define DegToRad(a) ((a) *0.01745329252f)
#define RadToDeg(a) ((a) *57.29577951f)
#define ALIGN4(x) (((x) + 3) & ~3)
#define ALIGN32(x) (((x) + 31) & ~31)
template<typename T, class Allocator, class Predicate>
bool remove_locked_first_if(std::mutex &mutex, std::vector<T, Allocator> &list, Predicate pred) {
std::lock_guard<std::mutex> lock(mutex);
auto it = list.begin();
while (it != list.end()) {
if (pred(*it)) {
list.erase(it);
return true;
}
it++;
}
return false;
}
// those work only in powers of 2
#define ROUNDDOWN(val, align) ((val) & ~(align - 1))
#define ROUNDUP(val, align) ROUNDDOWN(((val) + (align - 1)), align)
#define le16(i) ((((uint16_t) ((i) &0xFF)) << 8) | ((uint16_t) (((i) &0xFF00) >> 8)))
#define le32(i) ((((uint32_t) le16((i) &0xFFFF)) << 16) | ((uint32_t) le16(((i) &0xFFFF0000) >> 16)))
#define le64(i) ((((uint64_t) le32((i) &0xFFFFFFFFLL)) << 32) | ((uint64_t) le32(((i) &0xFFFFFFFF00000000LL) >> 32)))
//Needs to have log_init() called beforehand.
void dumpHex(const void *data, size_t size);
#ifdef __cplusplus
}
#endif
void translate_stat(struct stat *posStat, FSStat *fsStat);

2
src/version.h Normal file
View File

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