From f162f2189ee8318c6515a6fd8341a357e3806470 Mon Sep 17 00:00:00 2001 From: Maschell Date: Thu, 16 Feb 2023 12:55:26 +0100 Subject: [PATCH] Initial commit --- .clang-format | 67 +++ .github/workflows/ci.yml | 59 +++ .github/workflows/pr.yml | 32 ++ .gitignore | 4 + Dockerfile | 7 + LICENSE | 674 +++++++++++++++++++++++++ Makefile | 143 ++++++ README.md | 92 ++++ src/global_vars.cpp | 4 + src/global_vars.h | 4 + src/imports.cpp | 17 + src/imports.h | 37 ++ src/main.cpp | 50 ++ src/main.h | 11 + src/patches.cpp | 39 ++ src/patches.h | 1 + src/stub/CoreAgent.cpp | 234 +++++++++ src/stub/CoreAgent.h | 8 + src/stub/CoreAgent_GetSetPhys.h | 5 + src/stub/CoreAgent_MemorySetGet.cpp | 29 ++ src/stub/CoreAgent_MemorySetGet.h | 5 + src/stub/EnumToStringUtil.cpp | 149 ++++++ src/stub/EnumToStringUtil.h | 11 + src/stub/GDBDParseUtils.h | 3 + src/stub/GDBDefines.h | 336 ++++++++++++ src/stub/GDBThreadDefines.h | 22 + src/stub/GDBUtils.h | 8 + src/stub/GDB_Commands.cpp | 409 +++++++++++++++ src/stub/GDB_Commands.h | 94 ++++ src/stub/GDB_IO.cpp | 328 ++++++++++++ src/stub/GDB_IO.h | 25 + src/stub/MasterAgent_RegMemReadWrite.h | 5 + src/stub/MasterAgent_ThreadUtils.cpp | 87 ++++ src/stub/MasterAgent_ThreadUtils.h | 5 + src/stub/MasterAgent_Utils.cpp | 39 ++ src/stub/MasterAgent_Utils.h | 3 + src/stub/helper.s | 4 + src/utils/IOUtils.cpp | 70 +++ src/utils/IOUtils.h | 7 + src/utils/kernel.cpp | 80 +++ src/utils/kernel.h | 9 + src/version.h | 2 + 42 files changed, 3218 insertions(+) create mode 100644 .clang-format create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/pr.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 src/global_vars.cpp create mode 100644 src/global_vars.h create mode 100644 src/imports.cpp create mode 100644 src/imports.h create mode 100644 src/main.cpp create mode 100644 src/main.h create mode 100644 src/patches.cpp create mode 100644 src/patches.h create mode 100644 src/stub/CoreAgent.cpp create mode 100644 src/stub/CoreAgent.h create mode 100644 src/stub/CoreAgent_GetSetPhys.h create mode 100644 src/stub/CoreAgent_MemorySetGet.cpp create mode 100644 src/stub/CoreAgent_MemorySetGet.h create mode 100644 src/stub/EnumToStringUtil.cpp create mode 100644 src/stub/EnumToStringUtil.h create mode 100644 src/stub/GDBDParseUtils.h create mode 100644 src/stub/GDBDefines.h create mode 100644 src/stub/GDBThreadDefines.h create mode 100644 src/stub/GDBUtils.h create mode 100644 src/stub/GDB_Commands.cpp create mode 100644 src/stub/GDB_Commands.h create mode 100644 src/stub/GDB_IO.cpp create mode 100644 src/stub/GDB_IO.h create mode 100644 src/stub/MasterAgent_RegMemReadWrite.h create mode 100644 src/stub/MasterAgent_ThreadUtils.cpp create mode 100644 src/stub/MasterAgent_ThreadUtils.h create mode 100644 src/stub/MasterAgent_Utils.cpp create mode 100644 src/stub/MasterAgent_Utils.h create mode 100644 src/stub/helper.s create mode 100644 src/utils/IOUtils.cpp create mode 100644 src/utils/IOUtils.h create mode 100644 src/utils/kernel.cpp create mode 100644 src/utils/kernel.h create mode 100644 src/version.h diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..56cc685 --- /dev/null +++ b/.clang-format @@ -0,0 +1,67 @@ +# Generated from CLion C/C++ Code Style settings +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: Consecutive +AlignConsecutiveMacros: AcrossEmptyLinesAndComments +AlignOperands: Align +AllowAllArgumentsOnNextLine: false +AllowAllConstructorInitializersOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Always +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterReturnType: None +AlwaysBreakTemplateDeclarations: Yes +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: true +BreakBeforeBinaryOperators: None +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +ColumnLimit: 0 +CompactNamespaces: false +ContinuationIndentWidth: 8 +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 4 +KeepEmptyLinesAtTheStartOfBlocks: true +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: All +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PointerAlignment: Right +ReflowComments: false +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +TabWidth: 4 +UseTab: Never diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..04c9cac --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: CI-Release + +on: + push: + branches: + - main + +jobs: + clang-format: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - name: clang-format + run: | + docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src + build-binary: + runs-on: ubuntu-22.04 + needs: clang-format + steps: + - uses: actions/checkout@v3 + - name: create version.h + run: | + git_hash=$(git rev-parse --short "$GITHUB_SHA") + cat < ./src/version.h + #pragma once + #define PLUGIN_VERSION_EXTRA " (nightly-$git_hash)" + EOF + - name: build binary + run: | + docker build . -t builder + docker run --rm -v ${PWD}:/project builder make + - uses: actions/upload-artifact@master + with: + name: binary + path: "*.wps" + deploy-binary: + needs: build-binary + runs-on: ubuntu-22.04 + steps: + - name: Get environment variables + id: get_repository_name + run: | + echo REPOSITORY_NAME=$(echo "$GITHUB_REPOSITORY" | awk -F / '{print $2}' | sed -e "s/:refs//") >> $GITHUB_ENV + echo DATETIME=$(echo $(date '+%Y%m%d-%H%M%S')) >> $GITHUB_ENV + - uses: actions/download-artifact@master + with: + name: binary + - name: zip artifact + run: zip -r ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip *.wps + - name: Create Release + uses: "softprops/action-gh-release@v1" + with: + tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }} + draft: false + prerelease: true + generate_release_notes: true + name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }} + files: | + ./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip \ No newline at end of file diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 0000000..e4cfcc0 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,32 @@ +name: CI-PR + +on: [ pull_request ] + +jobs: + clang-format: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - name: clang-format + run: | + docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src + build-binary: + runs-on: ubuntu-22.04 + needs: clang-format + steps: + - uses: actions/checkout@v3 + - name: create version.h + run: | + git_hash=$(git rev-parse --short "${{ github.event.pull_request.head.sha }}") + cat < ./src/version.h + #pragma once + #define PLUGIN_VERSION_EXTRA " (nightly-$git_hash)" + EOF + - name: build binary + run: | + docker build . -t builder + docker run --rm -v ${PWD}:/project builder make + - uses: actions/upload-artifact@master + with: + name: binary + path: "*.wps" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e80de15 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/* +*.elf +*.wps +.idea/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..661627c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,7 @@ +FROM wiiuenv/devkitppc:20230218 + +COPY --from=wiiuenv/wiiupluginsystem:20230215 /artifacts $DEVKITPRO +COPY --from=wiiuenv/libkernel:20220904 /artifacts $DEVKITPRO +COPY --from=wiiuenv/libwupsbackend:20230217 /artifacts $DEVKITPRO + +WORKDIR project \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ac98f56 --- /dev/null +++ b/Makefile @@ -0,0 +1,143 @@ +#------------------------------------------------------------------------------- +.SUFFIXES: +#------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") +endif + +TOPDIR ?= $(CURDIR) + +include $(DEVKITPRO)/wups/share/wups_rules + +WUT_ROOT := $(DEVKITPRO)/wut +WUMS_ROOT := $(DEVKITPRO)/wums + +#------------------------------------------------------------------------------- +# TARGET is the name of the output +# BUILD is the directory where object files & intermediate files will be placed +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#------------------------------------------------------------------------------- +TARGET := gdbstub +BUILD := build +SOURCES := src src/utils src/stub +DATA := data +INCLUDES := src + +#------------------------------------------------------------------------------- +# options for code generation +#------------------------------------------------------------------------------- +CFLAGS := -Wall -O2 -ffunction-sections \ + $(MACHDEP) + +CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__ -D__WUPS__ + +CXXFLAGS := $(CFLAGS) -std=c++20 + +ASFLAGS := -g $(ARCH) +LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map) -T$(WUMS_ROOT)/share/libkernel.ld -T$(WUPS_ROOT)/share/libwupsbackend.ld $(WUPSSPECS) + +LIBS := -lwups -lwupsbackend -lwut -lkernel + +#------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level +# containing include and lib +#------------------------------------------------------------------------------- +LIBDIRS := $(PORTLIBS) $(WUPS_ROOT) $(WUMS_ROOT) $(WUT_ROOT) $(WUT_ROOT)/usr + +#------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#------------------------------------------------------------------------------- + +export OUTPUT := $(CURDIR)/$(TARGET) +export TOPDIR := $(CURDIR) + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +export DEPSDIR := $(CURDIR)/$(BUILD) + +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#------------------------------------------------------------------------------- + export LD := $(CC) +#------------------------------------------------------------------------------- +else +#------------------------------------------------------------------------------- + export LD := $(CXX) +#------------------------------------------------------------------------------- +endif +#------------------------------------------------------------------------------- + +export OFILES_BIN := $(addsuffix .o,$(BINFILES)) +export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES := $(OFILES_BIN) $(OFILES_SRC) +export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) + +.PHONY: $(BUILD) clean all + +#------------------------------------------------------------------------------- +all: $(BUILD) + +$(BUILD): + @$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD)) + @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +#------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr $(BUILD) $(TARGET).wps $(TARGET).elf + +#------------------------------------------------------------------------------- +else +.PHONY: all + +DEPENDS := $(OFILES:.o=.d) + +#------------------------------------------------------------------------------- +# main targets +#------------------------------------------------------------------------------- +all : $(OUTPUT).wps + +$(OUTPUT).wps : $(OUTPUT).elf +$(OUTPUT).elf : $(OFILES) + +$(OFILES_SRC) : $(HFILES_BIN) + +#------------------------------------------------------------------------------- +# you need a rule like this for each extension you use as binary data +#------------------------------------------------------------------------------- +%.bin.o %_bin.h : %.bin +#------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + +#--------------------------------------------------------------------------------- +%.o: %.s + @echo $(notdir $<) + @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) + + +-include $(DEPENDS) + +#------------------------------------------------------------------------------- +endif +#------------------------------------------------------------------------------- diff --git a/README.md b/README.md new file mode 100644 index 0000000..132a30b --- /dev/null +++ b/README.md @@ -0,0 +1,92 @@ +[![CI-Release](https://github.com/wiiu-env/gdbstub_plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/wiiu-env/gdbstub_plugin/actions/workflows/ci.yml) + +# GDBStub for the Wii U + +This is a plugin which provides a gdbstub for debugging Wii U software, including homebrew. + +It's based on the gdbstub that's inside the `coreinit.rpl` and present on any Wii U. This plugin patches several functions to allow usage of the stub on retail consoles. + +With these patches some bugs have been fixed (e.g. basic `vCont` support and escape packet contents) and support for multiple queries have been added. +Memory access is now done completely via the KernelModule which bypasses the MMU, which allow us to write/read anywhere. + +For research purposes it's planned to reimplement (the important parts of) the `coreinit.rpl` gdbstub step by step. + +## Features +- Hardware breakpoint support (maximum one hw breakpoint is supported at once). +- Support up to 512 software breakpoints at the same time. +- Hardware watchpoints for read/write access of data with 8 byte accuracy (maximum one hw watchpoint is supported at once). +- Stepping to the next instruction (only the for currently active threads) +- Memory/register reading/writing. +- Implemented the optional `qXfer:features:read` and `qXfer:threads:read` query. +- Interrupting the execution at any time via `CTRL+C` +- See the `main.h` for further configuration options via macros. + +## Requirements / Limitations: +- Using [MochaPayload](https://github.com/wiiu-env/MochaPayload) v0.2 or higher or something else that supports the DK_PChar API. If not using mocha, you probably need to adjust the `makeOpenPath` replacement. +- Any homebrew you want to debug needs to be built with [wut](https://github.com/devkitPro/wut) 1.2.0-2 or higher. Official software works too, but you probably won't have any symbols. +- When the gdbstub is loaded, it'll directly start to wait for a connection via TCP. It's recommended to load the plugin when needed via the network instead of placing it permanently on the sd card. For loading plugins at runtime you can use the [wiiload plugin](https://github.com/wiiu-env/wiiload_plugin). +- The console will **not** respond to any other input while waiting for a connection. Please connect to the stub or force-shutdown the console (hold the power button of the **console** for at least 4 seconds) +- The gdbstub will stay loaded and active until the console is shut down. It's possible to change or reload the application. + +## Recommended: +- Using the [USBSerialLogger](https://github.com/wiiu-env/USBSerialLogger) module to have output via serial while debugging. For this you need a USB serial cable with certain chipset. The USBSerialLogger repo for more information. +- Build the homebrew apps with -O0, make sure to add the `-g` compiler flag for creating debug builds with DWARF information. + +## Usage +- Boot your console into a [WiiUPluginLoaderBackend](https://github.com/wiiu-env/WiiUPluginLoaderBackend) compatible environment (e.g. [Aroma](https://github.com/wiiu-env/Aroma)) +- Start the homebrew app you want to debug. +- Load the gdbstub_plugin via wiiload. +- Now the homebrew app will restart and wait for a connection. (When using the usb serial logging it should print `[+-*WAITING FOR DEBUGGER*-+]`) +- Connect to the gdbstub via TCP at port 3000. +- When you don't load any symbol file, you might have to force the endianness via `set endian big` + +Basic settings for gdb: +``` +set arch powerpc:750 +set remotetimeout 30 +set tcp connect-timeout 60 +set print thread-events on +set disassemble-next-line on +set remote hardware-watchpoint-limit 1 +set remote hardware-breakpoint-limit 1 +target remote tcp:192.168.178.123:3000 +``` + +## Building +In order to be able to compile this, you need to have devkitPPC installed +[devkitPPC](https://devkitpro.org/wiki/Getting_Started) with the following +pacman packages installed. + +``` +(sudo) (dkp-)pacman -Syu --needed wiiu-dev +``` + +Make sure the following environment variables are set: + +``` +DEVKITPRO=/opt/devkitpro +DEVKITPPC=/opt/devkitpro/devkitPPC +``` + +Also make sure to +install [wut](https://github.com/wiiu-env/wut), [WiiUPluginSystem](https://github.com/wiiu-env/WiiUPluginSystem), [libkernel](https://github.com/wiiu-env/libkernel) +and [libwupsbackend](https://github.com/wiiu-env/libwupsbackend). + +## Building using the Dockerfile + +It's possible to use a docker image for building. This way you don't need anything installed on your host system. + +``` +# Build docker image (only needed once) +docker build . -t gbdstubplugin-builder + +# make +docker run -it --rm -v ${PWD}:/project gbdstubplugin-builder make + +# make clean +docker run -it --rm -v ${PWD}:/project gbdstubplugin-builder make clean +``` + +## Format the code via docker + +`docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./src -i` \ No newline at end of file diff --git a/src/global_vars.cpp b/src/global_vars.cpp new file mode 100644 index 0000000..3ce84ee --- /dev/null +++ b/src/global_vars.cpp @@ -0,0 +1,4 @@ +#include "global_vars.h" + +bool gHeartbeatDisabled = false; +bool gInitStubs = false; \ No newline at end of file diff --git a/src/global_vars.h b/src/global_vars.h new file mode 100644 index 0000000..f787711 --- /dev/null +++ b/src/global_vars.h @@ -0,0 +1,4 @@ +#pragma once + +extern bool gHeartbeatDisabled; +extern bool gInitStubs; \ No newline at end of file diff --git a/src/imports.cpp b/src/imports.cpp new file mode 100644 index 0000000..0c50f9a --- /dev/null +++ b/src/imports.cpp @@ -0,0 +1,17 @@ +#include "stub/GDBDefines.h" +#include + +auto *gGDBGHSShowDrvrThreadsPtr = (uint32_t *) 0x1004f9bc; +auto *gAppflagsPtr = (uint32_t *) 0x10013c2c; +auto *gIsDebuggerPresentPtr = (uint32_t *) 0x1003aff8; +auto *DAT_100d1378Ptr = (uint32_t *) 0x100d1378; +auto *g100msInTicksPtr = (uint32_t *) 0x100523d8; +auto *gTimerKernelCallbackLastRunPtr = (uint32_t *) 0x100523d0; +auto *DAT_100d1374Ptr = (uint32_t *) 0x100d1374; +auto *gCoreCountPtr = (uint32_t *) 0x1004f9b8; +auto *gGDBStub_main_statePtr = (GDBMainState *) 0x1004f9b4; +auto *gIsDebuggerInitializedOnCore = (uint32_t *) 0x1004f974; +auto *gCoreData = (GDBCoreInfo *) 0x1004fb38; +auto *gCurrentThreadOnCore = (OSThread **) 0x10057c00; +GDBCoreInfo **gGDBCurCoreInfoPtr = (GDBCoreInfo **) 0x1004f9e4; +GDBCoreInfo **gGDBStoppedCoreInfoPtr = (GDBCoreInfo **) 0x1004f9e8; \ No newline at end of file diff --git a/src/imports.h b/src/imports.h new file mode 100644 index 0000000..8dda72e --- /dev/null +++ b/src/imports.h @@ -0,0 +1,37 @@ +#pragma once +#include "stub/GDBDefines.h" +#include +#include + +extern uint32_t *gGDBGHSShowDrvrThreadsPtr; +extern uint32_t *gAppflagsPtr; +extern uint32_t *gIsDebuggerPresentPtr; +extern uint32_t *DAT_100d1378Ptr; +extern uint32_t *DAT_100d1374Ptr; +extern uint32_t *gCoreCountPtr; +extern GDBMainState *gGDBStub_main_statePtr; +extern uint32_t *g100msInTicksPtr; +extern uint32_t *gTimerKernelCallbackLastRunPtr; +extern GDBCoreInfo **gGDBCurCoreInfoPtr; +extern GDBCoreInfo **gGDBStoppedCoreInfoPtr; +extern OSThread **gCurrentThreadOnCore; + +#define gGDBGHSShowDrvrThreads (*gGDBGHSShowDrvrThreadsPtr) +#define gAppflags (*gAppflagsPtr) +#define gIsDebuggerPresent (*gIsDebuggerPresentPtr) +#define DAT_100d1378 (*DAT_100d1378Ptr) +#define DAT_100d1374 (*DAT_100d1374Ptr) +#define gGDBStub_main_state (*gGDBStub_main_statePtr) +#define gCoreCount (*gCoreCountPtr) +#define g100msInTicks (*g100msInTicksPtr) +#define gTimerKernelCallbackLastRun (*gTimerKernelCallbackLastRunPtr) + +#define gGDBCurCoreInfo (*gGDBCurCoreInfoPtr) +#define gGDBStoppedCoreInfo (*gGDBStoppedCoreInfoPtr) + +extern uint32_t *gIsDebuggerInitializedOnCore; +extern GDBCoreInfo *gCoreData; + +extern "C" uint32_t __OSGetAppFlags(); + +#define OSDisableUserHeartbeat ((void (*)(void))(0x101C400 + 0x155b0)) diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..f29ab94 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,50 @@ +#include "main.h" +#include "global_vars.h" +#include "stub/GDB_IO.h" +#include "utils/kernel.h" +#include +#include +#include +#include + +WUPS_PLUGIN_NAME("GDBStub"); +WUPS_PLUGIN_DESCRIPTION("GDBStub"); +WUPS_PLUGIN_VERSION(PLUGIN_VERSION_FULL); +WUPS_PLUGIN_AUTHOR("Maschell, GaryOderNichts"); +WUPS_PLUGIN_LICENSE("GPL"); + +INITIALIZE_PLUGIN() { + gInitStubs = true; + EnableIABRandDABRSupport(); + PluginBackendApiErrorType res; + if ((res = WUPSBackend_InitLibrary()) != PLUGIN_BACKEND_API_ERROR_NONE) { + OSReport("WUPSBackend_InitLibrary failed: %s", WUPSBackend_GetStatusStr(res)); + } +} + +DEINITIALIZE_PLUGIN() { + // The plugin is not loaded the syscalls would point to invalid memory. + // So we have to restore the syscalls before unloading + DisableIABRandDABRSupport(); +} + +ON_APPLICATION_START() { + ResetIOOffsets(); + if (!gHeartbeatDisabled) { + OSReport("Heartbeat not disabled!\n"); + OSRestartGame(0, nullptr); + } +} + +ON_APPLICATION_ENDS() { + gHeartbeatDisabled = false; + bool stubNeedsToBeDisabled = false; + PluginBackendApiErrorType res; + if ((res = WUPSBackend_WillReloadPluginsOnNextLaunch(&stubNeedsToBeDisabled)) == PLUGIN_BACKEND_API_ERROR_NONE) { + if (stubNeedsToBeDisabled) { + gInitStubs = false; + } + } else { + OSReport("gdbstub: WUPSBackend_WillReloadPluginsOnNextLaunch failed: %s", WUPSBackend_GetStatusStr(res)); + } +} diff --git a/src/main.h b/src/main.h new file mode 100644 index 0000000..57accee --- /dev/null +++ b/src/main.h @@ -0,0 +1,11 @@ +#pragma once +#include "version.h" + +#define PLUGIN_VERSION "v0.1" +#define PLUGIN_VERSION_FULL PLUGIN_VERSION PLUGIN_VERSION_EXTRA + +// Uncomment to log incoming and outgoing packet +// #define PACKET_LOGGING + +// Uncomment to add driver threads to the thread list +// #define SHOW_DRIVER_THREADS \ No newline at end of file diff --git a/src/patches.cpp b/src/patches.cpp new file mode 100644 index 0000000..b55dfd3 --- /dev/null +++ b/src/patches.cpp @@ -0,0 +1,39 @@ +#include "global_vars.h" +#include "imports.h" +#include +#include + +DECL_FUNCTION(void, OSPerGameInits) { + real_OSPerGameInits(); + if (gInitStubs && !gHeartbeatDisabled) { + OSDisableUserHeartbeat(); + gHeartbeatDisabled = true; + } +} + +// Hooks into an empty function after the appflags were already set. +DECL_FUNCTION(void, EntryHook) { + if (gInitStubs) { + gAppflags |= 0x01; // Enable the GDBStub! + gAppflags |= 0x80; // We want to use PChar instead of EXI + } +} + +// We have to "hide" the "GDBStub enabled" flag for everything that's using __OSGetAppFlags +DECL_FUNCTION(uint32_t, __OSGetAppFlags) { + auto res = real___OSGetAppFlags(); + if (gInitStubs) { + res = res & ~0x01; + } + return res; +} + +DECL_FUNCTION(int32_t, makeOpenPath, const char *path, char *out) { + strncpy(out, "/dev/iosuhax", 0x20); + return 0; +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(makeOpenPath, (0x3201C400 + (0x02040390 - 0x02000000)), (0x101C400 + (0x02040390 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(OSPerGameInits, (0x3001C400 + 0x020031ec), (0x020031ec - 0xFE3C00), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(EntryHook, (0x3001C400 + 0x020080a8), (0x020080a8 - 0xFE3C00), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(__OSGetAppFlags, (0x3001C400 + 0x02003308), (0x02003308 - 0xFE3C00), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); \ No newline at end of file diff --git a/src/patches.h b/src/patches.h new file mode 100644 index 0000000..7b9637e --- /dev/null +++ b/src/patches.h @@ -0,0 +1 @@ +#pragma once \ No newline at end of file diff --git a/src/stub/CoreAgent.cpp b/src/stub/CoreAgent.cpp new file mode 100644 index 0000000..39a0233 --- /dev/null +++ b/src/stub/CoreAgent.cpp @@ -0,0 +1,234 @@ +#include "CoreAgent.h" +#include "CoreAgent_GetSetPhys.h" +#include "EnumToStringUtil.h" +#include "GDBDefines.h" +#include "GDBThreadDefines.h" +#include "GDBUtils.h" +#include "imports.h" +#include +#include +#include + +static const char exception_print_formats[18][45] = { + "Exception type %d occurred!\n", // 0 + "GPR00 %08X GPR08 %08X GPR16 %08X GPR24 %08X\n", // 1 + "GPR01 %08X GPR09 %08X GPR17 %08X GPR25 %08X\n", // 2 + "GPR02 %08X GPR10 %08X GPR18 %08X GPR26 %08X\n", // 3 + "GPR03 %08X GPR11 %08X GPR19 %08X GPR27 %08X\n", // 4 + "GPR04 %08X GPR12 %08X GPR20 %08X GPR28 %08X\n", // 5 + "GPR05 %08X GPR13 %08X GPR21 %08X GPR29 %08X\n", // 6 + "GPR06 %08X GPR14 %08X GPR22 %08X GPR30 %08X\n", // 7 + "GPR07 %08X GPR15 %08X GPR23 %08X GPR31 %08X\n", // 8 + "LR %08X SRR0 %08x SRR1 %08x\n", // 9 + "DAR %08X DSISR %08X\n", // 10 + "\nSTACK DUMP:", // 11 + " --> ", // 12 + " -->\n", // 13 + "\n", // 14 + "%p", // 15 + "\nCODE DUMP:\n", // 16 + "%p: %08X %08X %08X %08X\n", // 17 +}; + +DECL_FUNCTION(void, __CoreAgent_SaveState, OSExceptionType exceptionType, OSContext *interruptedContext, OSContext *cbContext) { + auto *currentCoreInfo = &gCoreData[OSGetCoreId()]; + currentCoreInfo->exception_level++; + if (currentCoreInfo->exception_level != 1) { + gIsDebuggerPresent = 0; + + CoreAgent_SetCoreState(currentCoreInfo, GDBSTUB_STATE_STOPPING); + + const char *FPAsString = "OFF"; + const char *PRAsString = ""; + if ((interruptedContext->srr1 & MSR_BIT_FP) != 0) { + FPAsString = "ON"; + } + if ((interruptedContext->srr1 & MSR_BIT_PR) != 0) { + PRAsString = " USER"; + } + auto *exceptionAsStr = GDBStub_OSExceptionToString(exceptionType); + OSReport("PANIC %s context:$%08x SRR0:$%08x SRR1:$%08x FP:%s%s\n", + exceptionAsStr, interruptedContext, interruptedContext->srr0, + interruptedContext->srr1, FPAsString, PRAsString); + + OSReport( + "DOUBLE FAULT: __CoreAgent_SaveState(%d %08x) core->exception_level (%d) != 1\n", + exceptionType, + interruptedContext, + currentCoreInfo->exception_level); + + OSReport(exception_print_formats[1], interruptedContext->gpr[0], interruptedContext->gpr[8], interruptedContext->gpr[16], interruptedContext->gpr[24]); + OSReport(exception_print_formats[2], interruptedContext->gpr[1], interruptedContext->gpr[9], interruptedContext->gpr[17], interruptedContext->gpr[25]); + OSReport(exception_print_formats[3], interruptedContext->gpr[2], interruptedContext->gpr[10], interruptedContext->gpr[18], interruptedContext->gpr[26]); + OSReport(exception_print_formats[4], interruptedContext->gpr[3], interruptedContext->gpr[11], interruptedContext->gpr[19], interruptedContext->gpr[27]); + OSReport(exception_print_formats[5], interruptedContext->gpr[4], interruptedContext->gpr[12], interruptedContext->gpr[20], interruptedContext->gpr[28]); + OSReport(exception_print_formats[6], interruptedContext->gpr[5], interruptedContext->gpr[13], interruptedContext->gpr[21], interruptedContext->gpr[29]); + OSReport(exception_print_formats[7], interruptedContext->gpr[6], interruptedContext->gpr[14], interruptedContext->gpr[22], interruptedContext->gpr[30]); + OSReport(exception_print_formats[8], interruptedContext->gpr[7], interruptedContext->gpr[15], interruptedContext->gpr[23], interruptedContext->gpr[31]); + OSReport(exception_print_formats[9], interruptedContext->lr, interruptedContext->srr0, interruptedContext->srr1); + if (exceptionType == OS_EXCEPTION_TYPE_DSI) { + OSReport(exception_print_formats[10], interruptedContext->dsisr, interruptedContext->dar); // this freezes + } + + do { + CoreAgent_SetCoreState(currentCoreInfo, GDBSTUB_STATE_HUNG); + } while (true); + } + CoreAgent_SetCoreState(currentCoreInfo, GDBSTUB_STATE_STOPPING); + currentCoreInfo->stoppedContext = interruptedContext; + GDBStub_MasterCore(); + + currentCoreInfo->stoppedThread = gCurrentThreadOnCore[currentCoreInfo->core]; + if (currentCoreInfo->stoppedThread == (OSThread *) nullptr) { + auto curCore = currentCoreInfo->core; + if (curCore == 0) { + currentCoreInfo->stoppedThread = IDLE_THREAD_CORE_0; + } else if (curCore == 1) { + currentCoreInfo->stoppedThread = IDLE_THREAD_CORE_1; + } else if (curCore == 2) { + currentCoreInfo->stoppedThread = IDLE_THREAD_CORE_2; + } + } else { + if (currentCoreInfo->stoppedThread != (OSThread *) interruptedContext) { + // Check if the interruptedContext is on the stack of the stopped thread. + if (((uint32_t) interruptedContext >= (uint32_t) currentCoreInfo->stoppedThread->stackStart) && + ((uint32_t) interruptedContext < (uint32_t) currentCoreInfo->stoppedThread->stackEnd)) { + } + } + } + currentCoreInfo->currentContext = currentCoreInfo->stoppedContext; + currentCoreInfo->currentThread = currentCoreInfo->stoppedThread; + + FlushFPUContext(); + currentCoreInfo->signal = GDBSIGNAL_SIGTRAP; + currentCoreInfo->OSException = (char) exceptionType; + if (currentCoreInfo->dabr != 0) { + CoreAgent_SetPhyReg32(GDB_REGISTER_DABR, 0); + } + if (currentCoreInfo->iabr != 0) { + CoreAgent_SetPhyReg32(GDB_REGISTER_IABR, 0); + } + bool skipSetCoreData = false; + switch (exceptionType) { + case OS_EXCEPTION_TYPE_DSI: { + auto DSISR = CoreAgent_GetPhyReg32(GDB_REGISTER_DSISR); + if ((currentCoreInfo->dabr != 0) && (DSISR & DSISR_FLAG_DABRMatch) == DSISR_FLAG_DABRMatch) { + currentCoreInfo->signal = GDBSIGNAL_SIGTRAP; + currentCoreInfo->dar = CoreAgent_GetPhyReg32(GDB_REGISTER_DAR); + } else { + currentCoreInfo->signal = GDBSIGNAL_SIGSEGV; + } + break; + } + case OS_EXCEPTION_TYPE_ALIGNMENT: { + currentCoreInfo->signal = GDBSIGNAL_SIGBUS; + break; + } + case OS_EXCEPTION_TYPE_SYSTEM_RESET: + case OS_EXCEPTION_TYPE_MACHINE_CHECK: + case OS_EXCEPTION_TYPE_DECREMENTER: { + currentCoreInfo->signal = GDBSIGNAL_SIGINT; + break; + } + case OS_EXCEPTION_TYPE_TRACE: + case OS_EXCEPTION_TYPE_BREAKPOINT: { + currentCoreInfo->signal = GDBSIGNAL_SIGTRAP; + break; + } + case OS_EXCEPTION_TYPE_ICI: { + currentCoreInfo->signal = GDBSIGNAL_RESUME; + break; + } + case OS_EXCEPTION_TYPE_PROGRAM: { + auto curPC = CoreAgent_PeekWord32((void *) interruptedContext->srr0); + if (curPC == TRAP_INSTRUCTION) { + currentCoreInfo->signal = GDBSIGNAL_BREAKPT; + } else if (curPC == DBGSTR_INSTRUCTION) { + currentCoreInfo->signal = GDBSIGNAL_DBGSTR; + } else if (curPC == DBGMSG_INSTRUCTION) { + currentCoreInfo->signal = GDBSIGNAL_DBGMSG; + } else if (curPC == DBGCTL_INSTRUCTION) { + currentCoreInfo->signal = GDBSIGNAL_DBGCTL; + } else { + currentCoreInfo->signal = GDBSIGNAL_SIGILL; + } + break; + } + case OS_EXCEPTION_TYPE_ISI: + case OS_EXCEPTION_TYPE_EXTERNAL_INTERRUPT: + case OS_EXCEPTION_TYPE_FLOATING_POINT: + case OS_EXCEPTION_TYPE_SYSTEM_CALL: + case OS_EXCEPTION_TYPE_PERFORMANCE_MONITOR: + case OS_EXCEPTION_TYPE_SYSTEM_INTERRUPT: + default: + currentCoreInfo->signal = GDBSIGNAL_SIG0; + skipSetCoreData = true; + break; + } + + if (!skipSetCoreData) { + currentCoreInfo->cachedMSR = interruptedContext->srr1 & 0x87c0ffff; + currentCoreInfo->cachedHID2 = 0; + currentCoreInfo->cachedPC = (currentCoreInfo->currentContext)->srr0; + (currentCoreInfo->currentContext)->srr1 = (currentCoreInfo->currentContext)->srr1 & ~MSR_BIT_SE; + CoreAgent_SetMasterReq(currentCoreInfo, GDBSTUB_REQ_STOPPED); + CoreAgent_SetCoreState(currentCoreInfo, GDBSTUB_STATE_STOPPED); + } + + if (currentCoreInfo->cmd.cmd == GDBSTUB_CMD_SINGLESTEP) { + (currentCoreInfo->currentContext)->srr1 = (currentCoreInfo->currentContext)->srr1 | (uint32_t) currentCoreInfo->stoppedContextExternalIinterruptBit; + CoreAgent_SetCmdDone(currentCoreInfo); + } + CoreAgent_MasterAgentLoop(currentCoreInfo); + do { + CoreAgent_SetCoreState(currentCoreInfo, GDBSTUB_STATE_HUNG); + } while (true); +} + +DECL_FUNCTION(void, CoreAgent_ResumeCore, GDBCoreInfo *curCoreData) { + auto stoppedContext = curCoreData->stoppedContext; + + if (curCoreData->req.ack != curCoreData->reqAckValue) { + return; + } + + CoreAgent_SetCoreState(curCoreData, GDBSTUB_STATE_PROCESSING); + + uint32_t curPCInstruction = CoreAgent_PeekWord32((void *) stoppedContext->srr0); + if (curPCInstruction == TRAP_INSTRUCTION || + curPCInstruction == DBGSTR_INSTRUCTION || + curPCInstruction == DBGMSG_INSTRUCTION || + curPCInstruction == DBGCTL_INSTRUCTION) { + stoppedContext->srr0 = stoppedContext->srr0 + 4; + } + + if (curCoreData->cmd.cmd == GDBSTUB_CMD_CONTINUE) { + CoreAgent_SetCoreState(curCoreData, GDBSTUB_STATE_RUNNING); + curCoreData->stoppedContextExternalIinterruptBit = 0; + stoppedContext->srr1 = stoppedContext->srr1 & ~MSR_BIT_SE; + } else if (curCoreData->cmd.cmd == GDBSTUB_CMD_SINGLESTEP) { + CoreAgent_SetCoreState(curCoreData, GDBSTUB_STATE_SINGLESTEP); + curCoreData->stoppedContextExternalIinterruptBit = ((uint16_t) stoppedContext->srr1) | MSR_BIT_EE; + stoppedContext->srr1 = (stoppedContext->srr1 & ~MSR_BIT_EE) | MSR_BIT_SE; + } + + if (curCoreData->cmd.cmd == GDBSTUB_CMD_CONTINUE) { + CoreAgent_SetCmdDone(curCoreData); + } + curCoreData->exception_level--; + gTimerKernelCallbackLastRun = in_TBLr(); + if (curCoreData->dabr != 0) { + CoreAgent_SetPhyReg32(GDB_REGISTER_DABR, curCoreData->dabr); + } + if (curCoreData->iabr != 0) { + CoreAgent_SetPhyReg32(GDB_REGISTER_IABR, curCoreData->iabr); + } + if (curCoreData->cmd.cmd == GDBSTUB_CMD_CONTINUE) { + __OSSetAndLoadContext(stoppedContext); + return; + } + __OSSetAndLoadContextDebugger(stoppedContext); +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(__CoreAgent_SaveState, (0x3201C400 + (0x02068408 - 0x02000000)), (0x101C400 + (0x02068408 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(CoreAgent_ResumeCore, (0x3201C400 + (0x02067f60 - 0x02000000)), (0x101C400 + (0x02067f60 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); diff --git a/src/stub/CoreAgent.h b/src/stub/CoreAgent.h new file mode 100644 index 0000000..34668e7 --- /dev/null +++ b/src/stub/CoreAgent.h @@ -0,0 +1,8 @@ +#pragma once + +#define __CoreAgent_SaveState ((void (*)(OSExceptionType exceptionType, OSContext * interruptedContext, OSContext * cbContext))(0x101C400 + 0x02068408 - 0x02000000)) +#define CoreAgent_ResumeCore ((void (*)(GDBCoreInfo *))(0x101C400 + 0x02067f60 - 0x02000000)) +#define CoreAgent_SetMasterReq ((void (*)(GDBCoreInfo *, GDBStub_Req))(0x101C400 + 0x02067ac8 - 0x02000000)) +#define CoreAgent_MasterAgentLoop ((void (*)(GDBCoreInfo *))(0x101C400 + 0x020683e0 - 0x02000000)) +#define CoreAgent_SetCoreState ((void (*)(GDBCoreInfo *, GDBStubState))(0x101C400 + 0x020679c8 - 0x02000000)) +#define CoreAgent_SetCmdDone ((void (*)(GDBCoreInfo *))(0x101C400 + 0x02067ab0 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/CoreAgent_GetSetPhys.h b/src/stub/CoreAgent_GetSetPhys.h new file mode 100644 index 0000000..9df07dd --- /dev/null +++ b/src/stub/CoreAgent_GetSetPhys.h @@ -0,0 +1,5 @@ +#pragma once + +#define CoreAgent_GetPhyReg32 ((uint32_t(*)(uint32_t))(0x101C400 + 0x02067b20 - 0x02000000)) +#define CoreAgent_SetPhyReg32 ((uint32_t(*)(uint32_t, uint32_t))(0x101C400 + 0x02067b98 - 0x02000000)) +#define CoreAgent_PeekWord32 ((uint32_t(*)(void *))(0x101C400 + 0x02067cc0 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/CoreAgent_MemorySetGet.cpp b/src/stub/CoreAgent_MemorySetGet.cpp new file mode 100644 index 0000000..8524c2e --- /dev/null +++ b/src/stub/CoreAgent_MemorySetGet.cpp @@ -0,0 +1,29 @@ +#include "CoreAgent_MemorySetGet.h" +#include "utils/kernel.h" +#include +#include +#include +#include +#include + +DECL_FUNCTION(uint32_t, CoreAgent_GetCoreMem, void *addr, uint32_t size, void *outRes) { + if (OSIsAddressValid((uint32_t) addr)) { + KernelWrite((uint32_t) outRes, addr, size); + } else { + memset(outRes, 0, size); + OSReport("CoreAgent_GetCoreMem invalid addr: %08X\n", addr); + } + + return 0; +} + +DECL_FUNCTION(uint32_t, CoreAgent_SetCoreMem, void *addr, uint32_t size, void *srcBuf) { + KernelWrite((uint32_t) addr, srcBuf, size); + ICInvalidateRange(addr, size); + DCFlushRange(addr, size); + + return 0; +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(CoreAgent_GetCoreMem, (0x3201C400 + (0x02067bd4 - 0x02000000)), (0x101C400 + (0x02067bd4 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(CoreAgent_SetCoreMem, (0x3201C400 + (0x02067cf8 - 0x02000000)), (0x101C400 + (0x02067cf8 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); diff --git a/src/stub/CoreAgent_MemorySetGet.h b/src/stub/CoreAgent_MemorySetGet.h new file mode 100644 index 0000000..f425647 --- /dev/null +++ b/src/stub/CoreAgent_MemorySetGet.h @@ -0,0 +1,5 @@ +#pragma once +#include + +#define CoreAgent_GetCoreMem ((uint32_t(*)(void *addr, uint32_t size, void *outRes))(0x101C400 + 0x02067bd4 - 0x02000000)) +#define CoreAgent_SetCoreMem ((uint32_t(*)(void *addr, uint32_t size, void *srcBuf))(0x101C400 + 0x02067cf8 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/EnumToStringUtil.cpp b/src/stub/EnumToStringUtil.cpp new file mode 100644 index 0000000..508a1ef --- /dev/null +++ b/src/stub/EnumToStringUtil.cpp @@ -0,0 +1,149 @@ +#include "EnumToStringUtil.h" + +const char *GDBStub_OSExceptionToString(OSExceptionType type) { + switch (type) { + case OS_EXCEPTION_TYPE_SYSTEM_RESET: + return "SYSTEM_RESET"; + case OS_EXCEPTION_TYPE_MACHINE_CHECK: + return "MACHINE_CHECK"; + case OS_EXCEPTION_TYPE_DSI: + return "DSI "; + case OS_EXCEPTION_TYPE_ISI: + return "ISI "; + case OS_EXCEPTION_TYPE_EXTERNAL_INTERRUPT: + return "EXTERNAL "; + case OS_EXCEPTION_TYPE_ALIGNMENT: + return "ALIGNMENT"; + case OS_EXCEPTION_TYPE_PROGRAM: + return "PROGRAM "; + case OS_EXCEPTION_TYPE_FLOATING_POINT: + return "FP "; + case OS_EXCEPTION_TYPE_DECREMENTER: + return "DECREMENT"; + case OS_EXCEPTION_TYPE_SYSTEM_CALL: + return "SYS_CALL "; + case OS_EXCEPTION_TYPE_TRACE: + return "TRACE "; + case OS_EXCEPTION_TYPE_PERFORMANCE_MONITOR: + return "PERF_MON "; + case OS_EXCEPTION_TYPE_BREAKPOINT: + return "BREAKPTR "; + case OS_EXCEPTION_TYPE_SYSTEM_INTERRUPT: + return "SYS_INTER"; + case OS_EXCEPTION_TYPE_ICI: + return "ICI "; + case 15: + return "NONE*****"; + } + return "UNKNOWN EXCEPTION"; +} + +// Checked +const char *GDBStub_SigToString(GDB_SIGNAL signal) { + switch (signal) { + case GDBSIGNAL_SIG0: + return "GDBSIGNAL_SIG0"; + case GDBSIGNAL_SIGINT: + return "GDBSIGNAL_SIGINT"; + case GDBSIGNAL_SIGQUIT: + return "GDBSIGNAL_SIGQUIT"; + case GDBSIGNAL_SIGILL: + return "GDBSIGNAL_SIGILL"; + case GDBSIGNAL_SIGTRAP: + return "GDBSIGNAL_SIGTRAP"; + case GDBSIGNAL_SIGKILL: + return "GDBSIGNAL_SIGKILL"; + case GDBSIGNAL_SIGBUS: + return "GDBSIGNAL_SIGBUS"; + case GDBSIGNAL_SIGSEGV: + return "GDBSIGNAL_SIGSEGV"; + case GDBSIGNAL_SIGTERM: + return "GDBSIGNAL_SIGTERM"; + case GDBSIGNAL_SIGSTOP: + return "GDBSIGNAL_SIGSTOP"; + case GDBSIGNAL_RESUME: + return "GDBSIGNAL_RESUME"; + case GDBSIGNAL_DBGCTL: + return "GDBSIGNAL_DBGCTL"; + case GDBSIGNAL_DBGMSG: + return "GDBSIGNAL_DBGMSG"; + case GDBSIGNAL_BREAKPT: + return "GDBSIGNAL_BREAKPT"; + case GDBSIGNAL_DBGSTR: + return "GDBSIGNAL_DBGSTR"; + } + return "**INVALID**"; +} + +// Checked +const char *GDBStub_StateToString(GDBStubState state) { + switch (state) { + case GDBSTUB_STATE_INACTIVE: + return "INACTIVE"; + case GDBSTUB_STATE_STOPPED: + return "STOPPED"; + case GDBSTUB_STATE_RUNNING: + return "RUNNING"; + case GDBSTUB_STATE_STOPPING: + return "STOPPING"; + case GDBSTUB_STATE_SINGLESTEP: + return "SINGLESTEP"; + case GDBSTUB_STATE_PROCESSING: + return "PROCESSING"; + case GDBSTUB_STATE_HUNG: + return "HUNG"; + } + return "**INVALID**"; +} + +const char *GDBStub_GDBFlagsToString(GDBStub_GDBFlags flag) { + switch (flag) { + case GDBFLAGS_ZERO: + return " "; + case GDBFLAGS_GDBSTOP: + return "GDBSTOP"; + case GDBFLAGS_GDBSTEP: + return "GDBSTEP"; + case GDBFLAGS_GDBCONT: + return "GDBCONT"; + default: + break; + } + return ""; +} + +const char *GDBStub_CmdToString(GDBStub_CMD cmd) { + switch (cmd) { + case GDBSTUB_CMD_IDLE: + return "IDLE"; + case GDBSTUB_CMD_STOP: + return "STOP"; + case GDBSTUB_CMD_CONTINUE: + return "CONTINUE"; + case GDBSTUB_CMD_SINGLESTEP: + return "SINGLESTEP"; + case GDBSTUB_CMD_GETSYSREG: + return "GETSYSREG"; + case GDBSTUB_CMD_PUTSYSREG: + return "PUTSYSREG"; + case GDBSTUB_CMD_ICINVALIDBLK: + return "ICINVALIDBLK"; + case GDBSTUB_CMD_DCINVALRNG: + return "DCINVALRNG"; + case GDBSTUB_CMD_GETCOREMEM: + return "GETCOREMEM"; + case GDBSTUB_CMD_PUTCOREMEM: + return "PUTCOREMEM"; + } + return "**INVALID**"; +} + +const char *GDBStub_ReqToString(GDBStub_Req req) { + switch (req) { + case GDBSTUB_REQ_STOPPED: + return "STOPPED"; + case GDBSTUB_REQ_FINISHED: + return "FINISHED"; + } + return "**INVALID**"; +} diff --git a/src/stub/EnumToStringUtil.h b/src/stub/EnumToStringUtil.h new file mode 100644 index 0000000..8590d56 --- /dev/null +++ b/src/stub/EnumToStringUtil.h @@ -0,0 +1,11 @@ +#pragma once + +#include "GDBDefines.h" +#include + +const char *GDBStub_OSExceptionToString(OSExceptionType type); +const char *GDBStub_SigToString(GDB_SIGNAL signal); +const char *GDBStub_StateToString(GDBStubState state); +const char *GDBStub_GDBFlagsToString(GDBStub_GDBFlags flag); +const char *GDBStub_CmdToString(GDBStub_CMD cmd); +const char *GDBStub_ReqToString(GDBStub_Req req); diff --git a/src/stub/GDBDParseUtils.h b/src/stub/GDBDParseUtils.h new file mode 100644 index 0000000..f599d1c --- /dev/null +++ b/src/stub/GDBDParseUtils.h @@ -0,0 +1,3 @@ +#pragma once + +#define gdb_getint ((uint32_t(*)(char **))(0x101C400 + 0x0203b628 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/GDBDefines.h b/src/stub/GDBDefines.h new file mode 100644 index 0000000..51e47c7 --- /dev/null +++ b/src/stub/GDBDefines.h @@ -0,0 +1,336 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +typedef enum GDBStub_CMD : uint8_t { + GDBSTUB_CMD_IDLE = 0, + GDBSTUB_CMD_STOP = 1, + GDBSTUB_CMD_CONTINUE = 2, + GDBSTUB_CMD_SINGLESTEP = 3, + GDBSTUB_CMD_GETSYSREG = 4, + GDBSTUB_CMD_PUTSYSREG = 5, + GDBSTUB_CMD_ICINVALIDBLK = 6, + GDBSTUB_CMD_DCINVALRNG = 7, + GDBSTUB_CMD_GETCOREMEM = 8, + GDBSTUB_CMD_PUTCOREMEM = 9 +} GDBStub_CMD; + +typedef enum GDBMainState { + GDBMAINSTATE_LOOP = 0, + GDBMAINSTATE_STEP = 1, + GDBMAINSTATE_RUN = 2, + GDBMAINSTATE_VCONT = 3, + GDBMAINSTATE_MAX_VALUE = 4 +} GDBMainState; + +typedef enum GDBStub_GDBFlags : uint8_t { + GDBFLAGS_ZERO = 0, + GDBFLAGS_GDBSTOP = 1, + GDBFLAGS_GDBSTEP = 2, + GDBFLAGS_INVAL = 3, + GDBFLAGS_GDBCONT = 4 +} GDBStub_GDBFlags; + +typedef enum GDB_SIGNAL : uint16_t { + GDBSIGNAL_SIG0 = 0, + GDBSIGNAL_SIGINT = 2, + GDBSIGNAL_SIGQUIT = 3, + GDBSIGNAL_SIGILL = 4, + GDBSIGNAL_SIGTRAP = 5, + GDBSIGNAL_SIGKILL = 9, + GDBSIGNAL_SIGBUS = 10, + GDBSIGNAL_SIGSEGV = 11, + GDBSIGNAL_SIGTERM = 15, + GDBSIGNAL_SIGSTOP = 17, + GDBSIGNAL_RESUME = 65437, + GDBSIGNAL_DBGCTL = 65445, + GDBSIGNAL_DBGMSG = 65446, + GDBSIGNAL_BREAKPT = 65534, + GDBSIGNAL_DBGSTR = 65535 +} GDB_SIGNAL; + +typedef enum GDBStub_ACCESS { + GDBSTUB_ACCESS_NONE = 0, + GDBSTUB_ACCESS_READ = 1, + GDBSTUB_ACCESS_WRITE = 2 +} GDBStub_ACCESS; + +typedef enum GDBStubState { + GDBSTUB_STATE_INACTIVE = 0, + GDBSTUB_STATE_STOPPED = 1, + GDBSTUB_STATE_RUNNING = 2, + GDBSTUB_STATE_STOPPING = 3, + GDBSTUB_STATE_SINGLESTEP = 4, + GDBSTUB_STATE_PROCESSING = 5, + GDBSTUB_STATE_HUNG = 6 +} GDBStubState; + +typedef enum GDBStub_Req : uint8_t { + GDBSTUB_REQ_STOPPED = 0, + GDBSTUB_REQ_FINISHED = 1 +} GDBStub_Req; + +typedef struct WUT_PACKED CMDStruct { + GDBStub_CMD cmd; + struct WUT_PACKED { + unsigned int ack : 24; + }; +} CMDStruct; +WUT_CHECK_OFFSET(CMDStruct, 0, cmd); +WUT_CHECK_SIZE(CMDStruct, 0x4); + +typedef struct WUT_PACKED REQStruct { + GDBStub_Req req; + struct WUT_PACKED { + unsigned int ack : 24; + }; +} REQStruct; +WUT_CHECK_SIZE(REQStruct, 0x4); + +typedef struct WUT_PACKED GDBCoreInfo { + uint8_t core; + GDBStub_GDBFlags flag; + uint16_t stoppedContextExternalIinterruptBit; + GDB_SIGNAL nextSignal__; + GDB_SIGNAL signal; + GDBStub_ACCESS accessType; + uint32_t accessLevel; + char OSException; + WUT_UNKNOWN_BYTES(3); + int32_t exception_level; + uint32_t numPrintedMessages; + uint32_t totalMessagesInQueue; + OSContext *exceptionContext; + void *exceptionStack; + GDBStubState state; + uint32_t lastStateUpdateTime; + REQStruct req; + uint32_t reqAckValue; + uint32_t req_arg; + uint32_t lastReqSetTime; + uint32_t reqDoneTime; + CMDStruct cmd; + uint32_t cmdAckValue; + uint32_t cmdArg1; + uint32_t cmdArg2; + uint32_t cmdResult; + uint32_t cmdDoneTime; + uint32_t cmdSetAtTime; + OSThread *stoppedThread; + OSContext *stoppedContext; + OSThread *currentThread; + OSContext *currentContext; + uint32_t virtual_ssr0; + uint32_t virtual_ssr1; + uint32_t cachedHID2; + uint32_t cachedMSR; + uint32_t cachedPC; + uint32_t dabr; + uint32_t iabr; + uint32_t dar; +} GDBCoreInfo; +WUT_CHECK_OFFSET(GDBCoreInfo, 0, core); +WUT_CHECK_OFFSET(GDBCoreInfo, 1, flag); +WUT_CHECK_OFFSET(GDBCoreInfo, 2, stoppedContextExternalIinterruptBit); +WUT_CHECK_OFFSET(GDBCoreInfo, 4, nextSignal__); +WUT_CHECK_OFFSET(GDBCoreInfo, 6, signal); +WUT_CHECK_OFFSET(GDBCoreInfo, 8, accessType); +WUT_CHECK_OFFSET(GDBCoreInfo, 12, accessLevel); +WUT_CHECK_OFFSET(GDBCoreInfo, 20, exception_level); +WUT_CHECK_OFFSET(GDBCoreInfo, 24, numPrintedMessages); +WUT_CHECK_OFFSET(GDBCoreInfo, 28, totalMessagesInQueue); +WUT_CHECK_OFFSET(GDBCoreInfo, 32, exceptionContext); +WUT_CHECK_OFFSET(GDBCoreInfo, 36, exceptionStack); +WUT_CHECK_OFFSET(GDBCoreInfo, 40, state); +WUT_CHECK_OFFSET(GDBCoreInfo, 44, lastStateUpdateTime); +WUT_CHECK_OFFSET(GDBCoreInfo, 48, req); +WUT_CHECK_OFFSET(GDBCoreInfo, 52, reqAckValue); +WUT_CHECK_OFFSET(GDBCoreInfo, 56, req_arg); +WUT_CHECK_OFFSET(GDBCoreInfo, 60, lastReqSetTime); +WUT_CHECK_OFFSET(GDBCoreInfo, 64, reqDoneTime); +WUT_CHECK_OFFSET(GDBCoreInfo, 68, cmd); +WUT_CHECK_OFFSET(GDBCoreInfo, 72, cmdAckValue); +WUT_CHECK_OFFSET(GDBCoreInfo, 76, cmdArg1); +WUT_CHECK_OFFSET(GDBCoreInfo, 80, cmdArg2); +WUT_CHECK_OFFSET(GDBCoreInfo, 84, cmdResult); +WUT_CHECK_OFFSET(GDBCoreInfo, 88, cmdDoneTime); +WUT_CHECK_OFFSET(GDBCoreInfo, 92, cmdSetAtTime); +WUT_CHECK_OFFSET(GDBCoreInfo, 96, stoppedThread); +WUT_CHECK_OFFSET(GDBCoreInfo, 100, stoppedContext); +WUT_CHECK_OFFSET(GDBCoreInfo, 104, currentThread); +WUT_CHECK_OFFSET(GDBCoreInfo, 108, currentContext); +WUT_CHECK_OFFSET(GDBCoreInfo, 112, virtual_ssr0); +WUT_CHECK_OFFSET(GDBCoreInfo, 116, virtual_ssr1); +WUT_CHECK_OFFSET(GDBCoreInfo, 120, cachedHID2); +WUT_CHECK_OFFSET(GDBCoreInfo, 124, cachedMSR); +WUT_CHECK_OFFSET(GDBCoreInfo, 128, cachedPC); +WUT_CHECK_OFFSET(GDBCoreInfo, 132, dabr); +WUT_CHECK_OFFSET(GDBCoreInfo, 136, iabr); +WUT_CHECK_OFFSET(GDBCoreInfo, 140, dar); +WUT_CHECK_SIZE(GDBCoreInfo, 144); + +typedef enum DebugQueueType { + STRING = 0, + SET_CMD = 1, + ACK_CMD = 2, + SET_REQ = 3, + ACK_REQ = 4 +} DebugQueueType; + +typedef struct GDBDebugMessageString { + const char *format; + void *args[9]; +} GDBDebugMessageString; +WUT_CHECK_OFFSET(GDBDebugMessageString, 0x0, format); +WUT_CHECK_OFFSET(GDBDebugMessageString, 0x4, args); +WUT_CHECK_SIZE(GDBDebugMessageString, 40); + +typedef struct GDBDebugMessageAckCmd { + GDBStub_CMD cmd; + uint32_t cmdAck; + uint32_t cmdResult; +} GDBDebugMessageAckCmd; +WUT_CHECK_OFFSET(GDBDebugMessageAckCmd, 0x0, cmd); +WUT_CHECK_OFFSET(GDBDebugMessageAckCmd, 0x4, cmdAck); +WUT_CHECK_OFFSET(GDBDebugMessageAckCmd, 0x8, cmdResult); +WUT_CHECK_SIZE(GDBDebugMessageAckCmd, 0xC); + +typedef struct GDBDebugMessageSetReq { + GDBStub_Req req; + uint32_t reqAck; + uint32_t arg; +} GDBDebugMessageSetReq; +WUT_CHECK_OFFSET(GDBDebugMessageSetReq, 0x0, req); +WUT_CHECK_OFFSET(GDBDebugMessageSetReq, 0x4, reqAck); +WUT_CHECK_OFFSET(GDBDebugMessageSetReq, 0x8, arg); +WUT_CHECK_SIZE(GDBDebugMessageSetReq, 0xC); + +typedef struct GDBDebugMessageSetCmd { + uint32_t core; + GDBStub_CMD cmd; + uint32_t cmdCount; + uint32_t arg1; + uint32_t arg2; +} GDBDebugMessageSetCmd; +WUT_CHECK_OFFSET(GDBDebugMessageSetCmd, 0x0, core); +WUT_CHECK_OFFSET(GDBDebugMessageSetCmd, 0x4, cmd); +WUT_CHECK_OFFSET(GDBDebugMessageSetCmd, 0x8, cmdCount); +WUT_CHECK_OFFSET(GDBDebugMessageSetCmd, 0xC, arg1); +WUT_CHECK_OFFSET(GDBDebugMessageSetCmd, 0x10, arg2); +WUT_CHECK_SIZE(GDBDebugMessageSetCmd, 0x14); + +typedef struct GDBDebugMessageAckReq { + uint32_t core; + GDBStub_Req req; + uint32_t reqCount; +} GDBDebugMessageAckReq; +WUT_CHECK_OFFSET(GDBDebugMessageAckReq, 0x0, core); +WUT_CHECK_OFFSET(GDBDebugMessageAckReq, 0x4, req); +WUT_CHECK_OFFSET(GDBDebugMessageAckReq, 0x8, reqCount); +WUT_CHECK_SIZE(GDBDebugMessageAckReq, 0x0C); + +typedef struct debug_queue_msg { + uint64_t timeInTicks; + uint32_t debugMask; + DebugQueueType type; + union { + GDBDebugMessageString dbgStr; + GDBDebugMessageAckCmd dbgAckCmd; + GDBDebugMessageAckReq dbgAckReq; + GDBDebugMessageSetCmd dbgSetCmd; + GDBDebugMessageSetReq dbgSetReq; + WUT_UNKNOWN_BYTES(0x20); + }; + WUT_PADDING_BYTES(8); +} debug_queue_msg; +WUT_CHECK_OFFSET(debug_queue_msg, 0x0, timeInTicks); +WUT_CHECK_OFFSET(debug_queue_msg, 0x8, debugMask); +WUT_CHECK_OFFSET(debug_queue_msg, 0xC, type); +WUT_CHECK_OFFSET(debug_queue_msg, 0x10, dbgStr); +WUT_CHECK_OFFSET(debug_queue_msg, 0x10, dbgAckCmd); +WUT_CHECK_OFFSET(debug_queue_msg, 0x10, dbgAckReq); +WUT_CHECK_OFFSET(debug_queue_msg, 0x10, dbgSetCmd); +WUT_CHECK_OFFSET(debug_queue_msg, 0x10, dbgSetReq); +WUT_CHECK_SIZE(debug_queue_msg, 64); + +typedef enum GDBWatchState : uint8_t { + GDBWATCHSTATE_UNKNOWN = 0, + GDBWATCHSTATE_RWATCH = 5, + GDBWATCHSTATE_WATCH = 6, + GDBWATCHSTATE_AWATCH = 7, + +} GDBWatchState; + +#define MSR_BIT_POW (1 << (31 - 13)) /*0x40000*/ +#define MSR_BIT_RESERVED0 (1 << (31 - 14)) /*0x20000*/ +#define MSR_BIT_ILE (1 << (31 - 15)) /*0x10000*/ +#define MSR_BIT_EE (1 << (31 - 16)) /*0x8000*/ +#define MSR_BIT_PR (1 << (31 - 17)) /*0x4000*/ +#define MSR_BIT_FP (1 << (31 - 18)) /*0x2000*/ +#define MSR_BIT_ME (1 << (31 - 19)) /*0x1000*/ +#define MSR_BIT_FE0 (1 << (31 - 20)) /*0x800*/ +#define MSR_BIT_SE (1 << (31 - 21)) /*0x400*/ +#define MSR_BIT_BE (1 << (31 - 22)) /*0x200*/ +#define MSR_BIT_FE1 (1 << (31 - 23)) /*0x100*/ +#define MSR_BIT_RESERVED1 (1 << (31 - 24)) /*0x80*/ +#define MSR_BIT_IP (1 << (31 - 25)) /*0x40*/ +#define MSR_BIT_IR (1 << (31 - 26)) /*0x20*/ +#define MSR_BIT_DR (1 << (31 - 27)) /*0x10*/ +#define MSR_BIT_RESERVED2 (1 << (31 - 28)) /*8*/ +#define MSR_BIT_PM (1 << (31 - 29)) /*4*/ +#define MSR_BIT_RI (1 << (31 - 30)) /*2 */ +#define MSR_BIT_LE (1 << (31 - 31)) /*1*/ + +#define TRAP_INSTRUCTION 0x7FE00008 +#define DBGSTR_INSTRUCTION 0x7ffff808 +#define DBGMSG_INSTRUCTION 0x7ffef008 +#define DBGCTL_INSTRUCTION 0x7ffe0008 + +#define GDB_REGISTER_R0 0x00 +#define GDB_REGISTER_R1 0x01 +#define GDB_REGISTER_R2 0x02 +#define GDB_REGISTER_R3 0x03 +#define GDB_REGISTER_R4 0x04 +#define GDB_REGISTER_R5 0x05 +#define GDB_REGISTER_R6 0x06 +#define GDB_REGISTER_R7 0x07 +#define GDB_REGISTER_R31 0x1F +#define GDB_REGISTER_F0 0x20 +#define GDB_REGISTER_F31 0x3F +#define GDB_REGISTER_PC 0x40 +#define GDB_REGISTER_MSR 0x41 +#define GDB_REGISTER_CR 0x42 +#define GDB_REGISTER_LR 0x43 +#define GDB_REGISTER_CTR 0x44 +#define GDB_REGISTER_XER 0x45 +#define GDB_REGISTER_FPSCR 0x46 + +#define GDB_REGISTER_DAR 0x6a +#define GDB_REGISTER_DSISR 0x6b + +#define GDB_REGISTER_SRR0 0x70 +#define GDB_REGISTER_SRR1 0x71 +#define GDB_REGISTER_DABR 0x75 +#define GDB_REGISTER_IABR 0x79 + + +#define GDB_REGISTER_HID2 0x9F +#define GDB_REGISTER_PIR 0xD6 +#define GDB_REGISTER_WPAR 0xA5 +#define GDB_REGISTER_PS0 0xA6 +#define GDB_REGISTER_PS31 0xC5 +#define GDB_REGISTER_GQR0 0xC6 +#define GDB_REGISTER_GQR1 0xC7 +#define GDB_REGISTER_GQR2 0xC8 +#define GDB_REGISTER_GQR3 0xC9 +#define GDB_REGISTER_GQR4 0xCA +#define GDB_REGISTER_GQR5 0xCB +#define GDB_REGISTER_GQR6 0xCC +#define GDB_REGISTER_GQR7 0xCD + +#define DSISR_FLAG_ACCESS_RESTRICTED_BY_BAT_OR_PAGE 1 << (31 - 4) +#define DSISR_FLAG_DABRMatch 1 << (31 - 9) \ No newline at end of file diff --git a/src/stub/GDBThreadDefines.h b/src/stub/GDBThreadDefines.h new file mode 100644 index 0000000..7a6a45e --- /dev/null +++ b/src/stub/GDBThreadDefines.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +#define IDLE_THREAD_ID_CORE_0 0x7001 +#define IDLE_THREAD_ID_CORE_1 0x7002 +#define IDLE_THREAD_ID_CORE_2 0x7003 + +#define IDLE_THREAD_CORE_0 ((OSThread *) 0x100) +#define IDLE_THREAD_CORE_1 ((OSThread *) 0x200) +#define IDLE_THREAD_CORE_2 ((OSThread *) 0x300) +#define IDLE_THREAD_LIST_END ((OSThread *) 0x400) +#define END_OF_LIST_THREAD ((OSThread *) 0xFFFFFFFF) + +#define GET_CORE_FROM_IDLE_THREAD(thread) ((uint32_t) thread >> 8 & 3) - 1; + +#define DEFAULT_THREAD_ID 0x8000 + +#define IS_IDLE_THREAD(thread) (((uint32_t) thread & ~0x300) == 0) +#define GET_NEXT_IDLE_THREAD(thread) (OSThread *) (((uint32_t) thread & 0x300) + 0x100) +#define GET_IDLE_THREAD_BY_CORE(coreOfThread) (OSThread *) ((coreOfThread * 0x100) + 0x100); diff --git a/src/stub/GDBUtils.h b/src/stub/GDBUtils.h new file mode 100644 index 0000000..49d39ab --- /dev/null +++ b/src/stub/GDBUtils.h @@ -0,0 +1,8 @@ +#pragma once +#include + +#define GDBStub_MasterCore ((uint32_t(*)(void))(0x101C400 + 0x02036bc8 - 0x02000000)) +#define FlushFPUContext ((void (*)(void))(0x101C400 + 0x0203ee5c - 0x02000000)) +#define __OSSetAndLoadContextDebugger ((void (*)(OSContext *))(0x101C400 + 0x02008188 - 0x02000000)) + +extern "C" uint32_t in_TBLr(); \ No newline at end of file diff --git a/src/stub/GDB_Commands.cpp b/src/stub/GDB_Commands.cpp new file mode 100644 index 0000000..a16c2e3 --- /dev/null +++ b/src/stub/GDB_Commands.cpp @@ -0,0 +1,409 @@ +#include "GDB_Commands.h" +#include "GDBDParseUtils.h" +#include "GDBThreadDefines.h" +#include "GDBUtils.h" +#include "GDB_IO.h" +#include "MasterAgent_RegMemReadWrite.h" +#include "MasterAgent_ThreadUtils.h" +#include "imports.h" +#include "utils/IOUtils.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static char sGDBQueryStringBuffer[100] = {}; + +static char sOutPaginationBuffer[IO_BUFFER_CAPACITY - 4] = {}; + +void qSupported(const char *packet) { + gIsDebuggerPresent = 1; +#ifdef SHOW_DRIVER_THREADS + gGDBGHSShowDrvrThreads = 1; +#endif + DAT_100d1378 = DAT_100d1378 + 1; + gTimerKernelCallbackLastRun = in_TBLr() + g100msInTicks; + MasterAgent_IOInit(); + MasterAgent_IOPutString("PacketSize="); + snprintf(sGDBQueryStringBuffer, sizeof(sGDBQueryStringBuffer), "%x", IO_BUFFER_CAPACITY); + MasterAgent_IOPutString(sGDBQueryStringBuffer); + MasterAgent_IOPutString(";qXfer:features:read+;qXfer:threads:read+;swbreak+;hwbreak+"); + MasterAgent_IOPutString(";COSVer="); + snprintf(sGDBQueryStringBuffer, sizeof(sGDBQueryStringBuffer), "%d", 21301); + MasterAgent_IOPutString(sGDBQueryStringBuffer); + MasterAgent_IOSendEx(false); +} + +void qOffsets(const char *packet) { + OSDynLoad_InternalData *rplIterator = *(reinterpret_cast(0x10081018)); + OSDynLoad_NotifyData *rpl = nullptr; + + for (; rplIterator != nullptr; rplIterator = rplIterator->next) { + if (!rplIterator->notifyData->name || std::string_view(rplIterator->notifyData->name).ends_with("rpx")) { + rpl = rplIterator->notifyData; + break; + } + } + + if (rpl != nullptr) { + MasterAgent_IOInit(); + + snprintf(sGDBQueryStringBuffer, sizeof(sGDBQueryStringBuffer), "TextSeg=%08X;DataSeg=%08X", rpl->textAddr, rpl->dataAddr); + MasterAgent_IOPutString(sGDBQueryStringBuffer); + MasterAgent_IOSendEx(false); + } else { + MasterAgent_PutPacket("", false); + } +} + +static char sLibrariesReadBuffer[IO_BUFFER_CAPACITY] = {}; + +bool qXferLibrariesRead(const char *packet) { + char *charPtr = (char *) packet; + uint32_t read_offset = 0; + uint32_t read_length = 0; + if (charPtr[0] != '\0') { + read_offset = gdb_getint(&charPtr); + charPtr++; + } else { + OSReport("WARNING: qXferLibrariesRead failed to read offset.\n"); + } + if (charPtr[0] != '\0') { + read_length = gdb_getint(&charPtr); + } else { + OSReport("WARNING: qXferLibrariesRead failed to read length.\n"); + } + + if (((read_length * 2) + 1) > (IO_BUFFER_CAPACITY - 4)) { + read_length = ((IO_BUFFER_CAPACITY - 4) / 2) - 1; + } + MasterAgent_IOInit(); + + if (GDBqXfer_libraries_read(read_offset, read_length + 1, sLibrariesReadBuffer) == 0) { + MasterAgent_IOPutString("l"); + DAT_100d1374 = 0; + } else { + MasterAgent_IOPutString("m"); + } + MasterAgent_IOPutStringAsHex(sLibrariesReadBuffer); + MasterAgent_IOSendEx(false); + return true; +} + +bool qXferFeaturesRead(const char *packet) { + auto *annexPtr = (char *) packet; + char *annexEnd = annexPtr; + while (annexEnd[0] != '\0' && annexEnd[0] != ':') { + annexEnd++; + } + annexEnd[0] = '\0'; + auto *charPtr = annexEnd + 1; + if (strncmp(annexPtr, "target.xml", 10) == 0) { + uint32_t read_offset = 0; + uint32_t read_length = 0; + if (charPtr[0] != '\0') { + read_offset = gdb_getint(&charPtr); + charPtr++; + } else { + OSReport("WARNING: qXferFeaturesRead failed to read offset.\n"); + } + if (charPtr[0] != '\0') { + read_length = gdb_getint(&charPtr); + } else { + OSReport("WARNING: qXferFeaturesRead failed to read length.\n"); + } + if (read_length == 0 || read_offset >= GDBTargetXML.size()) { + MasterAgent_PutPacket("l", false); + } else { + auto paginated_str = GDBTargetXML.substr(read_offset, read_length); + memset(sOutPaginationBuffer, 0, sizeof(sOutPaginationBuffer)); + if (paginated_str.size() < sizeof(sOutPaginationBuffer)) { + memcpy(sOutPaginationBuffer, paginated_str.data(), paginated_str.size()); + } else { + OSReport("WARN: qXferFeaturesRead tried to overflow sOutPaginationBuffer!\n"); + } + MasterAgent_IOInit(); + MasterAgent_IOPutString((paginated_str.size() == read_length) ? "m" : "l"); + MasterAgent_IOPutString(sOutPaginationBuffer); + MasterAgent_IOSendEx(false); + } + return true; + } + return false; +} + +void qXferThreadRead(const char *packet) { + auto *charPtr = (char *) packet; + uint32_t read_offset = 0; + uint32_t read_length = 0; + if (charPtr[0] != '\0') { + read_offset = gdb_getint(&charPtr); + charPtr++; + } else { + OSReport("WARNING: qXferThreadRead failed to read offset.\n"); + } + if (charPtr[0] != '\0') { + read_length = gdb_getint(&charPtr); + } else { + OSReport("WARNING: qXferThreadRead failed to read length.\n"); + } + if (read_length == 0) { + MasterAgent_PutPacket("l", false); + return; + } + + int32_t index = 0; + InitThreadInfoBuffer(); + PutStringIntoThreadInfoBuffer(R"( )"); + while (true) { + auto *thread = MasterAgent_GetIndexedThreadID(index); + if (thread == (OSThread *) 0xFFFFFFFF) { + break; + } + + auto threadID = MasterAgent_GetThreadID(thread); + uint32_t core; + const char *threadName; + char threadNameOnStack[0x18]; + + if (thread == IDLE_THREAD_CORE_0) { + core = 0; + threadName = "Idle Core 0"; + } else if (thread == IDLE_THREAD_CORE_1) { + core = 1; + threadName = "Idle Core 1"; + } else if (thread == IDLE_THREAD_CORE_2) { + core = 2; + threadName = "Idle Core 2"; + } else { + core = thread->context.upir; + threadName = thread->name; + if (!threadName) { + snprintf(threadNameOnStack, 0x18, "Thread 0x%8.8x", (uint32_t) thread); + threadName = threadNameOnStack; + } + } + snprintf(sGDBQueryStringBuffer, sizeof(sGDBQueryStringBuffer), R"("); + + PutXMLEscapedStringIntoThreadInfoBuffer(MasterAgent_ThreadExtraInfo(thread)); + + PutStringIntoThreadInfoBuffer(""); + + index++; + } + PutStringIntoThreadInfoBuffer(""); + std::string_view resulBufAsView(GetThreadInfoBuffer()); + if (read_offset >= resulBufAsView.size()) { + MasterAgent_PutPacket("l", false); + } else { + auto paginated_str = resulBufAsView.substr(read_offset, read_length); + memset(sOutPaginationBuffer, 0, sizeof(sOutPaginationBuffer)); + if (paginated_str.size() < sizeof(sOutPaginationBuffer)) { + memcpy(sOutPaginationBuffer, paginated_str.data(), paginated_str.size()); + } else { + OSReport("WARN: qXferThreadRead tried to overflow sOutPaginationBuffer!\n"); + } + MasterAgent_IOInit(); + MasterAgent_IOPutString((paginated_str.size() == read_length) ? "m" : "l"); + MasterAgent_IOPutString(sOutPaginationBuffer); + MasterAgent_IOSendEx(false); + } +} + +void gdb_vpacket(const char *packet) { + auto packetAsString = (char *) packet; + + if (strcmp(packetAsString, "vCont?") == 0) { + MasterAgent_PutPacket("vCont;c;C;s;S;", false); + return; + } + if (strcmp(packetAsString, "vCont;c") == 0) { + gdb_continue("c"); + return; + } + if (strncmp(packetAsString, "vGetRegs;", 9) == 0) { + gdb_vgetregisters(&packetAsString[9]); + return; + } + if (strncmp(packetAsString, "vCont;", 6) != 0) { + MasterAgent_PutPacket("", false); + return; + } + packetAsString = &packetAsString[6]; + for (uint32_t i = 0; i < 3; i++) { + gCoreData[i].flag = GDBFLAGS_GDBSTOP; + gCoreData[i].nextSignal__ = GDBSIGNAL_SIG0; + } + + bool stepDone = false; + + uint32_t result = 0; + while (true) { + if (packetAsString[0] == '\0') { + if (result == 0) { + gGDBStub_main_state = GDBMAINSTATE_VCONT; + } + MasterAgent_SendResult(result); + return; + } + auto packetType = packetAsString[0]; + if (packetType == 'C' || packetType == 'c' || packetType == 'S' || packetType == 's') { + packetAsString++; + GDB_SIGNAL signal = GDBSIGNAL_SIG0; + GDBStub_GDBFlags flag; + + if (packetType == 'C' || packetType == 'S') { + signal = (GDB_SIGNAL) gdb_getint(&packetAsString); + } + + if (packetType == 'C' || packetType == 'c') { + if (!stepDone) { + flag = GDBFLAGS_GDBCONT; + } else { + flag = GDBFLAGS_GDBSTOP; + } + } else { + flag = GDBFLAGS_GDBSTEP; + } + + if (packetAsString[0] == '\0' || packetAsString[0] == ';') { + for (uint32_t i = 0; i < gCoreCount; i++) { + if (gCoreData[i].flag == GDBFLAGS_GDBSTOP) { + gCoreData[i].signal = GDBSIGNAL_RESUME; + if (flag == GDBFLAGS_GDBSTEP) { + stepDone = true; + } + gCoreData[i].flag = flag; + gCoreData[i].nextSignal__ = signal; + } + } + } else if (packetAsString[0] == ':') { + packetAsString++; + auto *thread = gdb_get_pid_tid(&packetAsString); + bool found = false; + for (uint32_t i = 0; i < gCoreCount; i++) { + auto *coreDataForI = &gCoreData[i]; + if (coreDataForI->stoppedThread == thread) { + coreDataForI->signal = GDBSIGNAL_RESUME; + if (flag == GDBFLAGS_GDBSTEP) { + stepDone = true; + } + coreDataForI->flag = flag; + coreDataForI->nextSignal__ = signal; + auto MSR = MasterAgent_GetRegister32(coreDataForI, coreDataForI->stoppedContext, GDB_REGISTER_MSR); + if ((MSR & MSR_BIT_SE) != 0) { + result = MasterAgent_SetRegister32(coreDataForI, coreDataForI->stoppedContext, GDB_REGISTER_MSR, MSR & ~MSR_BIT_SE); + } + found = true; + } + } + + if (!found) { + OSReport("WARN: gdb_vpacket Core which runs thread %08x not found\n", thread); + MasterAgent_SendResult(EPERM); + return; + } + } + } else { + OSReport("WARN: gdb_vpacket invalid packet type. %s\n", packetAsString); + MasterAgent_SendResult(EINVAL); + return; + } + if (packetAsString[0] == ';') { + packetAsString++; + } + } +} + +static bool gdb_sendmemory(const char *packet) { + auto *intPtr = (char *) packet; + auto addr = gdb_getint(&intPtr); + if (intPtr[0] != ',') { + MasterAgent_SendResult(EINVAL); + return true; + } + intPtr++; + auto size = gdb_getint(&intPtr); + MasterAgent_IOInit(); + auto readResult = gdb_mem2hex(addr, size); + if (readResult == 0) { + MasterAgent_IOSendEx(false); + } else { + MasterAgent_SendResult(EIO); + } + + return true; +} + +static void gdb_sendregister(const char *packet) { + auto *intPtr = (char *) (packet); + auto regId = gdb_getint(&intPtr); + if (regId > 0xdb) { + MasterAgent_SendResult(EINVAL); + return; + } + MasterAgent_IOInit(); + if ((regId >= GDB_REGISTER_F0 && regId <= GDB_REGISTER_F31) || + (regId >= GDB_REGISTER_PS0 && regId <= GDB_REGISTER_PS31)) { + auto res = MasterAgent_GetRegister64(gGDBCurCoreInfo, gGDBCurCoreInfo->currentContext, regId); + + MasterAgent_IOPutHex64(res); + } else { + auto res = MasterAgent_GetRegister32(gGDBCurCoreInfo, gGDBCurCoreInfo->currentContext, regId); + MasterAgent_IOPutHex32(res); + } + MasterAgent_IOSendEx(false); +} + +DECL_FUNCTION(void, MasterAgent_ProcessPacket, const char *packet) { +#ifdef PACKET_LOGGING + OSReport("Process packet \"%s\"\n", packet); +#endif + auto prefix = packet[0]; + if (prefix == 'v') { + gdb_vpacket(packet); + return; + } + if (prefix == 'm') { + gdb_sendmemory(&packet[1]); + return; + } else if (prefix == 'p') { + gdb_sendregister(&packet[1]); + return; + } else if (prefix == 'q') { + auto *charPtr = (char *) (&packet[1]); + if (strncmp(charPtr, "Supported:", 10) == 0) { + qSupported(&charPtr[10]); + return; + } else if (strncmp(charPtr, "Xfer:", 5) == 0) { + charPtr = (char *) (&charPtr[5]); + if (strncmp(charPtr, "threads:read::", 14) == 0) { + qXferThreadRead(&charPtr[14]); + return; + } else if (strncmp(charPtr, "features:read:", 14) == 0) { + if (qXferFeaturesRead(&charPtr[14])) { + return; + } + } else if (strncmp(charPtr, "libraries:read::", 16) == 0) { + if (qXferLibrariesRead(&charPtr[16])) { + return; + } + } + } else if (strncmp(charPtr, "Offsets", 7) == 0) { + qOffsets(&charPtr[7]); + return; + } + } + + real_MasterAgent_ProcessPacket(packet); +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_ProcessPacket, (0x3201C400 + (0x0203e4c4 - 0x02000000)), (0x101C400 + (0x0203e4c4 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); \ No newline at end of file diff --git a/src/stub/GDB_Commands.h b/src/stub/GDB_Commands.h new file mode 100644 index 0000000..b7d80b0 --- /dev/null +++ b/src/stub/GDB_Commands.h @@ -0,0 +1,94 @@ +#pragma once +#include + +static constexpr std::string_view GDBTargetXML = R"( + + + powerpc:common + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +)"; + +void qSupported(const char *packet); +void qXferThreadRead(const char *packet); +bool qXferLibrariesRead(const char *packet); +bool qXferFeaturesRead(const char *packet); +void qOffsets(const char *packet); + +#define gdb_continue ((void (*)(const char *packet))(0x101C400 + 0x0203d11c - 0x02000000)) +#define gdb_vgetregisters ((void (*)(const char *packet))(0x101C400 + 0x0203dfb4 - 0x02000000)) +#define gdb_get_pid_tid ((OSThread * (*) (char **input))(0x101C400 + 0x0203d26c - 0x02000000)) +#define GDBqXfer_libraries_read ((uint32_t(*)(uint32_t, int32_t, char *))(0x101C400 + 0x0203d3fc - 0x02000000)) \ No newline at end of file diff --git a/src/stub/GDB_IO.cpp b/src/stub/GDB_IO.cpp new file mode 100644 index 0000000..0685190 --- /dev/null +++ b/src/stub/GDB_IO.cpp @@ -0,0 +1,328 @@ +#include "GDB_IO.h" +#include "GDBUtils.h" +#include "imports.h" + +#include +#include +#include +#include + +static const char *sHexChars = "0123456789abcdef"; +static int32_t gIOOutputOffset = 0; +int32_t gGDBCharsInIOBuffer = 0; +int32_t gGDBCharsOfIOBufferConsumed = 0; +char gIOBuffer[IO_BUFFER_CAPACITY] = {}; +char gIOOutBuffer[IO_BUFFER_CAPACITY] = {}; + +static char sGDBCharUndoGetBuffer = '\0'; + +void ResetIOOffsets() { + gIOOutputOffset = 0; + gGDBCharsInIOBuffer = 0; + gGDBCharsOfIOBufferConsumed = 0; + memset(gIOBuffer, 0, sizeof(gIOBuffer)); + memset(gIOOutBuffer, 0, sizeof(gIOOutBuffer)); + sGDBCharUndoGetBuffer = '\0'; +} + +// 0x02039158 +DECL_FUNCTION(void, MasterAgent_IOInit) { + gIOOutputOffset = 0; +} + +// 0x0203a76c +DECL_FUNCTION(int32_t, MasterAgent_IOCurrentIndex) { + return gIOOutputOffset; +} + +// 0x0203a778 +DECL_FUNCTION(int32_t, MasterAgent_IORemaining) { + return (IO_BUFFER_CAPACITY - 4) - gIOOutputOffset; +} + +// 0x0203a788 +DECL_FUNCTION(void, MasterAgent_IORestoreIndex, int32_t index) { + gIOOutputOffset = index; +} + +// 0x0203a758 +DECL_FUNCTION(char *, MasterAgent_IOCurrentBufferPointer) { + return &gIOOutBuffer[gIOOutputOffset]; +} + +// 0x02039168 +DECL_FUNCTION(void, MasterAgent_IOPutChar, char curChar) { + if ((IO_BUFFER_CAPACITY - 5) < gIOOutputOffset) { + return; + } + + gIOOutBuffer[gIOOutputOffset] = curChar; + gIOOutputOffset++; +} + +// 0x0203a7ec +DECL_FUNCTION(void, MasterAgent_IOPutHex4, uint8_t val) { + if ((IO_BUFFER_CAPACITY - 5) < gIOOutputOffset) { + return; + } + gIOOutBuffer[gIOOutputOffset] = sHexChars[val & 0xf]; + gIOOutputOffset++; +} + +// 0x0203a794 +DECL_FUNCTION(void, MasterAgent_IOPutHex8, uint8_t val) { + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4 - 1)) { + gIOOutBuffer[gIOOutputOffset] = sHexChars[(val >> 4) & 0xf]; + gIOOutBuffer[gIOOutputOffset + 1] = sHexChars[val & 0xf]; + gIOOutputOffset += 2; + } else { + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4)) { + gIOOutBuffer[gIOOutputOffset] = 'f'; + } + } +} + +// 0x0203a884 +DECL_FUNCTION(void, MasterAgent_IOPutHex16, uint16_t value) { + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4 - 3)) { + gIOOutBuffer[gIOOutputOffset] = sHexChars[(value >> 0xc) & 0xf]; + gIOOutBuffer[gIOOutputOffset + 1] = sHexChars[(value >> 0x8) & 0xf]; + gIOOutBuffer[gIOOutputOffset + 2] = sHexChars[(value >> 0x4) & 0xf]; + gIOOutBuffer[gIOOutputOffset + 3] = sHexChars[(value >> 0x0) & 0xf]; + gIOOutputOffset += 4; + } else { + auto offsetCpy = gIOOutputOffset; + while (offsetCpy < (IO_BUFFER_CAPACITY - 4)) { + gIOOutBuffer[offsetCpy] = 'f'; + offsetCpy++; + } + } +} + +// 0x02039190 +DECL_FUNCTION(void, MasterAgent_IOPutHex32, uint32_t value) { + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4 - 7)) { + gIOOutBuffer[gIOOutputOffset] = sHexChars[value >> 0x1c & 0xf]; + gIOOutBuffer[gIOOutputOffset + 1] = sHexChars[value >> 0x18 & 0xf]; + gIOOutBuffer[gIOOutputOffset + 2] = sHexChars[value >> 0x14 & 0xf]; + gIOOutBuffer[gIOOutputOffset + 3] = sHexChars[value >> 0x10 & 0xf]; + gIOOutBuffer[gIOOutputOffset + 4] = sHexChars[value >> 0xc & 0xf]; + gIOOutBuffer[gIOOutputOffset + 5] = sHexChars[value >> 0x8 & 0xf]; + gIOOutBuffer[gIOOutputOffset + 6] = sHexChars[value >> 0x4 & 0xf]; + gIOOutBuffer[gIOOutputOffset + 7] = sHexChars[value >> 0x0 & 0xf]; + gIOOutputOffset += 8; + } else { + auto offsetCpy = gIOOutputOffset; + while (offsetCpy < (IO_BUFFER_CAPACITY - 4)) { + gIOOutBuffer[offsetCpy] = 'f'; + offsetCpy++; + } + } +} + +// 0x0203a81c +DECL_FUNCTION(void, MasterAgent_IOPutStringAsHex, const char *str) { + uint32_t offset = 0; + char curChar = *str; + while (curChar != 0) { + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4 - 1)) { + gIOOutBuffer[gIOOutputOffset] = sHexChars[curChar >> 4]; + gIOOutBuffer[gIOOutputOffset + 1] = sHexChars[curChar & 0xf]; + gIOOutputOffset += 2; + } + offset++; + curChar = str[offset]; + } +} + +void my_MasterAgent_PutPacket(const char *packetStr, bool checkPendingInputFirst); + +DECL_FUNCTION(void, MasterAgent_IOSendEx, bool unknwn1) { + if ((IO_BUFFER_CAPACITY - 4) < gIOOutputOffset) { + return; + } + gIOOutBuffer[gIOOutputOffset] = '\0'; + gIOOutputOffset++; + my_MasterAgent_PutPacket(gIOOutBuffer, unknwn1); +} + +// Checked +DECL_FUNCTION(void, MasterAgent_IOPutString, const char *str) { + uint32_t offset = 0; + auto curChar = str[0]; + while (curChar != '\0') { + auto uVar1 = gIOOutputOffset; + if (gIOOutputOffset < (IO_BUFFER_CAPACITY - 4)) { + uVar1 = gIOOutputOffset + 1; + gIOOutBuffer[gIOOutputOffset] = curChar; + } + offset = offset + 1; + gIOOutputOffset = uVar1; + curChar = str[offset]; + } +} + +extern "C" int32_t DK_PCharReadAsync(uint32_t channel_guess, uint32_t bufferSize, char *buffer); + +// 0x02039250 +DECL_FUNCTION(bool, MasterAgent_IOPendingInput) { + auto masterCore = GDBStub_MasterCore(); + if (OSGetCoreId() == masterCore) { + if (gIsDebuggerInitializedOnCore[masterCore] != 0) { + if ((__OSGetAppFlags() & 0x80) == 0) { + gGDBCharsInIOBuffer = Waikiki_Read(gIOBuffer, IO_BUFFER_CAPACITY); + } else if (gGDBCharsInIOBuffer == gGDBCharsOfIOBufferConsumed) { + gGDBCharsInIOBuffer = DK_PCharReadAsync(1, IO_BUFFER_CAPACITY, gIOBuffer); + } + gGDBCharsOfIOBufferConsumed = 0; + if (gGDBCharsInIOBuffer < 1) { + gGDBCharsInIOBuffer = 0; + return false; + } + return true; + } + } + return false; +} + +// Checked +DECL_FUNCTION(void, MasterAgent_IOUnGetChar, char charToUndo) { + sGDBCharUndoGetBuffer = charToUndo; +} + +// 0x0203936c +DECL_FUNCTION(char, MasterAgent_IOGetChar) { + char result; + + result = sGDBCharUndoGetBuffer; + if (sGDBCharUndoGetBuffer != '\0') { + sGDBCharUndoGetBuffer = '\0'; + return result; + } + if (gGDBCharsInIOBuffer <= gGDBCharsOfIOBufferConsumed) { + while (!my_MasterAgent_IOPendingInput()) { + // wait for input... + } + if (gGDBCharsInIOBuffer <= gGDBCharsOfIOBufferConsumed) { + return -1; + } + } + auto offsetCpy = gGDBCharsOfIOBufferConsumed; + gGDBCharsOfIOBufferConsumed++; + return gIOBuffer[offsetCpy]; +} + +// Doubled capacity to be able to escape every single char, add 4 for the '$' prefix and '#00' checksum suffix +static char sWritePacketBuffer[(IO_BUFFER_CAPACITY * 2) + 4]; + +DECL_FUNCTION(void, MasterAgent_PutPacket, const char *packetStr, bool checkPendingInputFirst) { +#ifdef PACKET_LOGGING + OSReport("Send packet \"%s\"\n", packetStr); +#endif + uint32_t tryCount = 0; + bool ctrl_c_seen = false; + bool checkPendingInput = checkPendingInputFirst; + while (true) { + if (checkPendingInput) { + while (my_MasterAgent_IOPendingInput()) { + auto curChar = my_MasterAgent_IOGetChar(); + if (curChar == '$') { + my_MasterAgent_IOUnGetChar((char) curChar); + return; + } + if (curChar == '\x03') { + ctrl_c_seen = true; + } + } + } + + if (packetStr == nullptr) { + MasterAgent_IOWriteString("$#00"); + } else { + memset(sWritePacketBuffer, 0, sizeof(sWritePacketBuffer)); + auto *outBufferPtr = sWritePacketBuffer; + sWritePacketBuffer[0] = '$'; + outBufferPtr++; + uint32_t checksum = 0; + uint32_t offset = 0; + auto curChar = packetStr[offset]; + while (curChar != '\0') { + if ((curChar == '#' || curChar == '$' || curChar == '}' || curChar == '*')) { + outBufferPtr[0] = '}'; + checksum += '}'; + outBufferPtr[1] = (char) (curChar ^ 0x20); + checksum += (char) (curChar ^ 0x20); + outBufferPtr++; + } else { + outBufferPtr[0] = curChar; + checksum += curChar; + } + offset++; + outBufferPtr++; + curChar = packetStr[offset]; + } + + outBufferPtr[0] = '#'; + outBufferPtr[1] = sHexChars[(checksum & 0xff) >> 4]; + outBufferPtr[2] = sHexChars[checksum & 0xf]; + MasterAgent_IOWriteString(sWritePacketBuffer); + } + + do { + auto curChar = my_MasterAgent_IOGetChar(); + if (((curChar == '+') || (curChar == '-')) || (curChar == '$')) { + if (ctrl_c_seen) { + gCoreData[GDBStub_MasterCore()].signal = GDBSIGNAL_SIGINT; + } + if (curChar == '+') { + return; + } + if (curChar == '-') { + tryCount++; + if (tryCount > 9) { + OSReport("MasterAgent_PutPacket: NACK received 10 times in a row\n"); + return; + } + checkPendingInput = true; + break; + } else { + my_MasterAgent_IOUnGetChar((char) curChar); + return; + } + } + if (curChar == '\x03') { + ctrl_c_seen = true; + } + } while (!my_MasterAgent_IOPendingInput()); + } +} + +DECL_FUNCTION(void, MasterAgent_SendResult, uint32_t result) { + if (result == 0) { + MasterAgent_PutPacket("OK", false); + return; + } + MasterAgent_IOInit(); + my_MasterAgent_IOPutChar(0x45); + my_MasterAgent_IOPutHex8((uint8_t) (result & 0xFF)); + MasterAgent_IOSendEx(false); +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOInit, (0x3201C400 + (0x02039158 - 0x02000000)), (0x101C400 + (0x02039158 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOCurrentIndex, (0x3201C400 + (0x0203a76c - 0x02000000)), (0x101C400 + (0x0203a76c - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IORemaining, (0x3201C400 + (0x0203a778 - 0x02000000)), (0x101C400 + (0x0203a778 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IORestoreIndex, (0x3201C400 + (0x0203a788 - 0x02000000)), (0x101C400 + (0x0203a788 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOCurrentBufferPointer, (0x3201C400 + (0x0203a758 - 0x02000000)), (0x101C400 + (0x0203a758 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutChar, (0x3201C400 + (0x02039168 - 0x02000000)), (0x101C400 + (0x02039168 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutHex4, (0x3201C400 + (0x0203a7ec - 0x02000000)), (0x101C400 + (0x0203a7ec - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutHex8, (0x3201C400 + (0x0203a794 - 0x02000000)), (0x101C400 + (0x0203a794 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutHex16, (0x3201C400 + (0x0203a884 - 0x02000000)), (0x101C400 + (0x0203a884 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutHex32, (0x3201C400 + (0x02039190 - 0x02000000)), (0x101C400 + (0x02039190 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutStringAsHex, (0x3201C400 + (0x0203a81c - 0x02000000)), (0x101C400 + (0x0203a81c - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOSendEx, (0x3201C400 + (0x02039a28 - 0x02000000)), (0x101C400 + (0x02039a28 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPutString, (0x3201C400 + (0x0203b6b4 - 0x02000000)), (0x101C400 + (0x0203b6b4 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOPendingInput, (0x3201C400 + (0x02039250 - 0x02000000)), (0x101C400 + (0x02039250 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOUnGetChar, (0x3201C400 + (0x0203942c - 0x02000000)), (0x101C400 + (0x0203942c - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_IOGetChar, (0x3201C400 + (0x0203936c - 0x02000000)), (0x101C400 + (0x0203936c - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_PutPacket, (0x3201C400 + (0x020394d8 - 0x02000000)), (0x101C400 + (0x020394d8 - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_SendResult, (0x3201C400 + (0x0203bafc - 0x02000000)), (0x101C400 + (0x0203bafc - 0x02000000)), WUPS_FP_TARGET_PROCESS_GAME_AND_MENU); \ No newline at end of file diff --git a/src/stub/GDB_IO.h b/src/stub/GDB_IO.h new file mode 100644 index 0000000..6399796 --- /dev/null +++ b/src/stub/GDB_IO.h @@ -0,0 +1,25 @@ +#pragma once +#include "GDBDefines.h" +#include +#include + +void ResetIOOffsets(); + +// The MasterAgent_MainLoop still has a fixed buffer we need to replace before we +// can increase this value +#define IO_BUFFER_CAPACITY 0x800 + +#define MasterAgent_IOInit ((void (*)(void))(0x101C400 + 0x02039158 - 0x02000000)) +#define MasterAgent_IOPutString ((void (*)(const char *str))(0x101C400 + 0x0203b6b4 - 0x02000000)) +#define MasterAgent_IOSendEx ((void (*)(bool))(0x101C400 + 0x02039a28 - 0x02000000)) +#define MasterAgent_PutPacket ((void (*)(const char *packetStr, bool checkPendingInputFirst))(0x101C400 + 0x020394d8 - 0x02000000)) +#define MasterAgent_IOPutStringAsHex ((void (*)(const char *str))(0x101C400 + 0x0203a81c - 0x02000000)) +#define MasterAgent_SendResult ((void (*)(uint32_t))(0x101C400 + 0x0203bafc - 0x02000000)) +#define MasterAgent_PutPacket ((void (*)(const char *packetStr, bool checkPendingInputFirst))(0x101C400 + 0x020394d8 - 0x02000000)) +#define MasterAgent_IOInit ((void (*)(void))(0x101C400 + 0x02039158 - 0x02000000)) +#define MasterAgent_IOPutString ((void (*)(const char *str))(0x101C400 + 0x0203b6b4 - 0x02000000)) +#define MasterAgent_IOPutHex32 ((void (*)(uint32_t value))(0x101C400 + 0x02039190 - 0x02000000)) +#define MasterAgent_IOWriteString ((void (*)(const char *))(0x101C400 + 0x020394a8 - 0x02000000)) +#define MasterAgent_IOPutHex64 ((void (*)(uint64_t))(0x101C400 + 0x0203b6f8 - 0x02000000)) +#define gdb_mem2hex ((uint32_t(*)(uint32_t addr, uint32_t size))(0x101C400 + 0x0203bcec - 0x02000000)) +#define Waikiki_Read ((int32_t(*)(char *buffer, uint32_t bufferSize))(0x101C400 + 0x0203f2f0 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/MasterAgent_RegMemReadWrite.h b/src/stub/MasterAgent_RegMemReadWrite.h new file mode 100644 index 0000000..914ebc2 --- /dev/null +++ b/src/stub/MasterAgent_RegMemReadWrite.h @@ -0,0 +1,5 @@ +#pragma once + +#define MasterAgent_GetRegister64 ((uint64_t(*)(GDBCoreInfo * curInfo, OSContext * context, uint32_t regId))(0x101C400 + 0x02039e60 - 0x02000000)) +#define MasterAgent_GetRegister32 ((uint32_t(*)(GDBCoreInfo * curInfo, OSContext * context, uint32_t regId))(0x101C400 + 0x02038cf0 - 0x02000000)) +#define MasterAgent_SetRegister32 ((uint32_t(*)(GDBCoreInfo * coreInfo, OSContext * context, uint32_t regId, uint32_t value))(0x101C400 + 0x02039ed0 - 0x02000000)) diff --git a/src/stub/MasterAgent_ThreadUtils.cpp b/src/stub/MasterAgent_ThreadUtils.cpp new file mode 100644 index 0000000..d171cd5 --- /dev/null +++ b/src/stub/MasterAgent_ThreadUtils.cpp @@ -0,0 +1,87 @@ +#include "GDBThreadDefines.h" +#include "GDBUtils.h" +#include "imports.h" +#include +#include +#include +static char sSomeStringBuffer[100] = {}; + +DECL_FUNCTION(const char *, MasterAgent_ThreadExtraInfo, OSThread *thread) { + const char *result; + if (thread == IDLE_THREAD_CORE_0 || thread == IDLE_THREAD_CORE_1 || thread == IDLE_THREAD_CORE_2) { + if (thread == IDLE_THREAD_CORE_0) { + result = "core 0 *running priority = (32:32) name = Idle Core 0"; + } else if (thread == IDLE_THREAD_CORE_1) { + result = "core 1 *running priority = (32:32) name = Idle Core 1"; + } else { + result = "core 2 *running priority = (32:32) name = Idle Core 2"; + } + } else { + GDBStub_MasterCore(); + uint32_t coreOfThread; + + if ((thread->attr & OS_THREAD_ATTRIB_AFFINITY_ANY) == OS_THREAD_ATTRIB_AFFINITY_CPU0) { + coreOfThread = 0; + } else if ((thread->attr & OS_THREAD_ATTRIB_AFFINITY_ANY) == OS_THREAD_ATTRIB_AFFINITY_CPU1) { + coreOfThread = 1; + } else if ((thread->attr & OS_THREAD_ATTRIB_AFFINITY_ANY) == OS_THREAD_ATTRIB_AFFINITY_CPU2) { + coreOfThread = 2; + } else { + coreOfThread = thread->context.upir; + } + + uint32_t threadState; + threadState = thread->state; + + auto *threadStateAsStr = ""; + if (gCoreData[coreOfThread].state == GDBSTUB_STATE_HUNG) { + threadStateAsStr = "HUNG "; + } + if ((gGDBCurCoreInfo != nullptr) && + (thread == gGDBStoppedCoreInfo->stoppedThread)) { + threadStateAsStr = "*"; + } + + auto threadReadyStr = ""; + if ((threadState & OS_THREAD_STATE_READY) != 0) { + threadReadyStr = "ready "; + } + auto threadRunningStr = ""; + if ((threadState & OS_THREAD_STATE_RUNNING) != 0) { + threadRunningStr = "running "; + } + auto threadWaitingStr = ""; + if ((threadState & OS_THREAD_STATE_WAITING) != 0) { + threadWaitingStr = "waiting "; + } + auto threadMoribundStr = ""; + if ((threadState & OS_THREAD_STATE_MORIBUND) != 0) { + threadMoribundStr = "moribund "; + } + auto threadDetachStr = ""; + if ((thread->attr & OS_THREAD_ATTRIB_DETACHED) != 0) { + threadDetachStr = "detach "; + } + char threadNameOnStack[0x18]; + auto *threadName = thread->name; + if (threadName == nullptr) { + snprintf(threadNameOnStack, 0x18, "Thread 0x%8.8x", (uint32_t) thread); + threadName = threadNameOnStack; + } + snprintf(sSomeStringBuffer, 100, "core %d %s%s%s%s%s%spriority = (%d:%d) name = %s", + coreOfThread, + threadStateAsStr, + threadRunningStr, + threadReadyStr, + threadWaitingStr, + threadMoribundStr, + threadDetachStr, + thread->priority, + thread->basePriority, + threadName); + result = sSomeStringBuffer; + } + return result; +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_ThreadExtraInfo, (0x3201C400 + (0x0203a548 - 0x02000000)), (0x101C400 + (0x0203a548 - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); diff --git a/src/stub/MasterAgent_ThreadUtils.h b/src/stub/MasterAgent_ThreadUtils.h new file mode 100644 index 0000000..8441e5c --- /dev/null +++ b/src/stub/MasterAgent_ThreadUtils.h @@ -0,0 +1,5 @@ +#pragma once + +#define MasterAgent_GetIndexedThreadID ((OSThread * (*) (int32_t))(0x101C400 + 0x0203a3e0 - 0x02000000)) +#define MasterAgent_GetThreadID ((uint32_t(*)(OSThread *))(0x101C400 + 0x0203a290 - 0x02000000)) +#define MasterAgent_ThreadExtraInfo ((const char *(*) (OSThread *) )(0x101C400 + 0x0203a548 - 0x02000000)) diff --git a/src/stub/MasterAgent_Utils.cpp b/src/stub/MasterAgent_Utils.cpp new file mode 100644 index 0000000..2d34dc7 --- /dev/null +++ b/src/stub/MasterAgent_Utils.cpp @@ -0,0 +1,39 @@ +#include "MasterAgent_Utils.h" +#include "GDBDefines.h" +#include "GDBUtils.h" +#include "imports.h" +#include "utils/kernel.h" +#include +#include +#include +#include + +DECL_FUNCTION(uint32_t, MasterAgent_PeekWord32, void *addr) { + uint32_t value = 0xbaadf00d; + if (OSIsAddressValid((uint32_t) &value)) { + KernelWrite((uint32_t) &value, addr, 4); + } else { + OSReport("MasterAgent_PeekWord32 invalid addr: %08X\n", addr); + } + return value; +} + +DECL_FUNCTION(uint32_t, MasterAgent_PokeInstr, void *addr, uint32_t newInstruction) { + if (OSIsAddressValid((uint32_t) addr)) { + KernelWriteU32((uint32_t) addr, newInstruction); + for (uint32_t i = 0; i < 3; i++) { + if (gCoreData[i].state == GDBSTUB_STATE_STOPPED) { + if (i != GDBStub_MasterCore()) { + MasterAgent_FlushICBlock(&gCoreData[i], (uint32_t) addr); + } + } + } + } else { + OSReport("MasterAgent_PokeInstr invalid addr: %08X\n", addr); + return EINVAL; + } + return 0; +} + +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_PeekWord32, (0x3201C400 + (0x0203881c - 0x02000000)), (0x101C400 + (0x0203881c - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); +WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MasterAgent_PokeInstr, (0x3201C400 + (0x020389cc - 0x02000000)), (0x101C400 + (0x020389cc - 0x02000000)), WUPS_FP_TARGET_PROCESS_ALL); diff --git a/src/stub/MasterAgent_Utils.h b/src/stub/MasterAgent_Utils.h new file mode 100644 index 0000000..f530292 --- /dev/null +++ b/src/stub/MasterAgent_Utils.h @@ -0,0 +1,3 @@ +#pragma once + +#define MasterAgent_FlushICBlock ((uint32_t(*)(GDBCoreInfo * curCoreInfo, uint32_t addr))(0x101C400 + 0x02038970 - 0x02000000)) \ No newline at end of file diff --git a/src/stub/helper.s b/src/stub/helper.s new file mode 100644 index 0000000..7f5df96 --- /dev/null +++ b/src/stub/helper.s @@ -0,0 +1,4 @@ +.globl in_TBLr +in_TBLr: + mftb %r3,268 + blr diff --git a/src/utils/IOUtils.cpp b/src/utils/IOUtils.cpp new file mode 100644 index 0000000..425053f --- /dev/null +++ b/src/utils/IOUtils.cpp @@ -0,0 +1,70 @@ +#include "IOUtils.h" +#include +#include + +#define THREAD_INFO_BUFFER_CAPACITY 0x10001 +static char sThreadInfoBuffer[THREAD_INFO_BUFFER_CAPACITY] = {}; +static uint32_t sThreadInfoBufferOffset = 0; + +char *GetThreadInfoBuffer() { + sThreadInfoBuffer[sThreadInfoBufferOffset] = '\0'; + return sThreadInfoBuffer; +} +void InitThreadInfoBuffer() { + memset(sThreadInfoBuffer, 0, sizeof(sThreadInfoBuffer)); + sThreadInfoBufferOffset = 0; +} + +bool PutStringIntoThreadInfoBuffer(const char *str) { + uint32_t offset = 0; + while (str[offset] != '\0') { + if (sThreadInfoBufferOffset < (THREAD_INFO_BUFFER_CAPACITY - 2)) { + sThreadInfoBuffer[sThreadInfoBufferOffset] = str[offset]; + sThreadInfoBufferOffset++; + } else { + return false; + } + offset++; + } + return true; +} + +bool PutCharIntoThreadInfoBuffer(char c) { + // we want to keep a null byte at the end + if (sThreadInfoBufferOffset < (THREAD_INFO_BUFFER_CAPACITY - 2)) { + sThreadInfoBuffer[sThreadInfoBufferOffset] = c; + sThreadInfoBufferOffset++; + } else { + return false; + } + return true; +} + +void PutXMLEscapedStringIntoThreadInfoBuffer(const char *str) { + if (str != nullptr) { + const char *curPtr = str; + while (curPtr[0] != '\0') { + switch (curPtr[0]) { + case '<': + PutStringIntoThreadInfoBuffer("<"); + break; + case '>': + PutStringIntoThreadInfoBuffer(">"); + break; + case '&': + PutStringIntoThreadInfoBuffer("&"); + break; + case '"': + PutStringIntoThreadInfoBuffer("""); + break; + case '\'': + PutStringIntoThreadInfoBuffer("'"); + break; + default: + PutCharIntoThreadInfoBuffer(curPtr[0]); + break; + } + curPtr++; + } + } +} diff --git a/src/utils/IOUtils.h b/src/utils/IOUtils.h new file mode 100644 index 0000000..547ed29 --- /dev/null +++ b/src/utils/IOUtils.h @@ -0,0 +1,7 @@ +#pragma once + +char *GetThreadInfoBuffer(); +void InitThreadInfoBuffer(); +bool PutStringIntoThreadInfoBuffer(const char *str); +bool PutCharIntoThreadInfoBuffer(char curChar); +void PutXMLEscapedStringIntoThreadInfoBuffer(const char *str); \ No newline at end of file diff --git a/src/utils/kernel.cpp b/src/utils/kernel.cpp new file mode 100644 index 0000000..851f41e --- /dev/null +++ b/src/utils/kernel.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +void KernelWrite(uint32_t addr, const void *data, uint32_t length) { + uint32_t dst = OSEffectiveToPhysical(addr); + uint32_t src = OSEffectiveToPhysical((uint32_t) data); + if (dst == 0 || src == 0) { + OSReport("Attempted to read/write from 0 (phys). dst %08X src %08X\n", dst, src); + return; + } + KernelCopyData(dst, src, length); + DCFlushRange((void *) addr, length); + ICInvalidateRange((void *) addr, length); +} + +void KernelWriteU32(uint32_t addr, uint32_t value) { + uint32_t dst = OSEffectiveToPhysical(addr); + uint32_t src = OSEffectiveToPhysical((uint32_t) &value); + KernelCopyData(dst, src, 4); + DCFlushRange((void *) addr, 4); + ICInvalidateRange((void *) addr, 4); +} + + +#define KiInitRendezvous ((void (*)(void *)) 0xfff097c4) +#define KiSendICIToOtherCores ((void (*)(uint32_t, uint32_t, uint32_t, uint32_t)) 0xfff052c8) +#define KiWaitRendezvous ((void (*)(void *, uint32_t)) 0xfff097e0) + +void KeSetDABR(uint32_t addr, int32_t allCores, int32_t matchReads, int32_t matchWrite) { + auto maskedAddr = (addr & 0xfffffff8) | 4; + if (matchReads != 0) { + maskedAddr = maskedAddr | 5; + } + if (matchWrite != 0) { + maskedAddr = maskedAddr | 2; + } + + asm volatile( + " mtspr 1013, %0 \n" + : + : "r"(maskedAddr) + :); + + if (allCores != 0) { + register int r13 asm("r13"); + KiInitRendezvous(reinterpret_cast(r13 + -0x72a0)); + KiSendICIToOtherCores(5, maskedAddr, 0, 1); + KiWaitRendezvous(reinterpret_cast(r13 + -0x72a0), 7); + } +} + +void KeSetIABR(uint32_t addr, int32_t allCores) { + auto maskedAddr = (addr & 0xfffffffc) | 3; + + asm volatile( + " mtspr 1010, %0 \n" + : + : "r"(maskedAddr) + :); + + if (allCores != 0) { + register int r13 asm("r13"); + KiInitRendezvous(reinterpret_cast(r13 + -0x7290)); + KiSendICIToOtherCores(10, maskedAddr, 0, 1); + KiWaitRendezvous(reinterpret_cast(r13 + -0x7290), 7); + } +} + +void EnableIABRandDABRSupport() { + KernelPatchSyscall(0x4B, reinterpret_cast(&KeSetDABR)); + KernelPatchSyscall(0x4C, reinterpret_cast(&KeSetIABR)); +} + +void DisableIABRandDABRSupport() { + // Restore original syscalls + KernelPatchSyscall(0x4B, 0xfff036a0); + KernelPatchSyscall(0x4C, 0xfff0370c); +} \ No newline at end of file diff --git a/src/utils/kernel.h b/src/utils/kernel.h new file mode 100644 index 0000000..4b29ebe --- /dev/null +++ b/src/utils/kernel.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +void KernelWrite(uint32_t addr, const void *data, uint32_t length); +void KernelWriteU32(uint32_t addr, uint32_t value); + +void EnableIABRandDABRSupport(); +void DisableIABRandDABRSupport(); \ No newline at end of file diff --git a/src/version.h b/src/version.h new file mode 100644 index 0000000..bfea8ae --- /dev/null +++ b/src/version.h @@ -0,0 +1,2 @@ +#pragma once +#define PLUGIN_VERSION_EXTRA "" \ No newline at end of file