commit 4e69e59d2a6d89565cda3208270b6d5439fcfcc4 Author: Maschell Date: Sat Jun 30 22:03:44 2018 +0200 First commit of the WUPS version. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a6fedb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/* +*.mod diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d4830d7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,66 @@ +language: cpp +os: linux +sudo: false +dist: trusty +branches: + only: + - master +env: + global: + - DEVKITPRO=/opt/devkitpro + - WUT_ROOT=/opt/devkitpro/wut + - DEVKITPPC=/opt/devkitpro/devkitPPC + - PORTLIBREPOS=$HOME/portlibrepos +cache: + directories: + - "$HOME/.local" + - "$DEVKITPRO" +addons: + apt: + packages: + - p7zip-full +before_install: +- mkdir -p "${PORTLIBREPOS}" +- mkdir -p "${DEVKITPRO}" +- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then wget https://github.com/devkitPro/pacman/releases/download/devkitpro-pacman-1.0.1/devkitpro-pacman.deb + -O /tmp/devkitpro-pacman.deb; fi +- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo dpkg -i /tmp/devkitpro-pacman.deb; + fi +- yes | sudo dkp-pacman -Syu devkitPPC --needed +- yes | sudo dkp-pacman -Syu general-tools --needed +- wget https://github.com/decaf-emu/wut/releases/download/1.0.0-beta/wut.linux64.7z +install: +- 7z x -y $(ls | grep "linux") -o${WUT_ROOT} +- cd $PORTLIBREPOS +- git clone https://github.com/Maschell/WiiUPluginSystem.git +- git clone https://github.com/Maschell/libutils.git -b wut +- cd WiiUPluginSystem +- make && make install +- cd $PORTLIBREPOS +- cd libutils +- mkdir build && cd build +- cmake -DCMAKE_TOOLCHAIN_FILE=$WUT_ROOT/share/wut.toolchain.cmake -DCMAKE_INSTALL_PREFIX=$WUT_ROOT + ../ +- make install +- cd $PORTLIBREPOS +before_script: +- cd $TRAVIS_BUILD_DIR/ +script: +- make -j8 +before_deploy: +- cd $TRAVIS_BUILD_DIR/ +- mkdir -p "wiiu/plugins" +- commit="$(git rev-parse --short=7 HEAD)" +- find -type f -name "*.mod" | xargs -i cp {} wiiu/plugins +- zip -r diibugger_wups_nightly_$commit.zip wiiu +- git config --local user.name "Maschell" +- git config --local user.email "Maschell@gmx.de" +- git tag "DiiBuggerWUPS-$(date +'%Y%m%d%H%M%S')-$(git log --format=%h -1)" +deploy: + provider: releases + skip_cleanup: true + api_key: + secure: p3i7VMXwqTQKZ5DyCJ7Qyp4v24bAhTAOohi4VUCNhDC3iw8D1RTkg07y8WwNKGrOoQmbodDgLlRLbo1wI/8C3qckn5KyDfAP76D89utta6FJHa7BfyM5hwgPMJtbm9gsY7gv8bdlIlOeL5SOsfG632hZ1cPKX9pSYqW2dkVHCh+JriLHDs+VEpzYpjZDxrtYwAWGaOL4vH2LH0/t78oYvDIRDgwOCjX3+ccTjpJsWMxBVy3wjiV1XHjNYL7Nj0j6FHIv9AfBtCgguoxXaBVb5iDmr61fKX2iCh8H17AN7W0SU57AHShgz/Cntuwbi+DWzg3Xzd6vnBHkCQ9osQAqhGUjgZfJHU+pSeo+GaTqYrkINJDq4Y/lFdoO/K9jio1ocoIzr5EFjIdn4ritMFXby7Z5N1Xdoo/oU1Pbqsij8OrFPd+RdzCgCoQ16l4Y1oA39FcSpgxBD2HYwzvYdiSDbHAdDLd4Hpp7tC5IIWMpL040l1nuyBuw7WOi58lW4k4ql94WeOejpJBsG6Sb0Mov+Mg7J0RXYnqBpiuBBguwJMIiGBlRQ2R6+IkxlQU2bSvZMXSjlLN1u49Mkc/FqTCYbWajGsaICpVdW2Gbm2NshADkVT2Sdk+A9DoJnBaU3MRWZfOyViR7xeuV57gruPg24dLb8O6AIZmKWASV6U9exZg= + file: diibugger_wups_nightly_$commit.zip + on: + repo: Maschell/DiiBuggerWUPS 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..dd480be --- /dev/null +++ b/Makefile @@ -0,0 +1,300 @@ +# You probably never need to adjust this Makefile. +# All changes can be done in the makefile.mk + +#--------------------------------------------------------------------------------- +# Clear the implicit built in rules +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- +ifeq ($(strip $(DEVKITPPC)),) +$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=devkitPPC") +endif +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=devkitPRO") +endif + +export PATH := $(DEVKITPPC)/bin:$(PORTLIBS)/bin:$(PATH) +export PORTLIBS := $(DEVKITPRO)/portlibs/ppc +export WUPSDIR := $(DEVKITPRO)/wups +export GCC_VER := $(shell $(DEVKITPPC)/bin/powerpc-eabi-gcc -dumpversion) + +PREFIX := powerpc-eabi- + +export AS := $(PREFIX)as +export CC := $(PREFIX)gcc +export CXX := $(PREFIX)g++ +export LD := $(PREFIX)ld +export AR := $(PREFIX)ar +export OBJCOPY := $(PREFIX)objcopy + +#--------------------------------------------------------------------------------- +# 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 +# INCLUDES is a list of directories containing extra header files +#--------------------------------------------------------------------------------- +TARGET := $(notdir $(CURDIR)) +BUILD := build + +ifeq ($(notdir $(CURDIR)),$(BUILD)) + include ../makefile.mk +else + include makefile.mk +endif + +include $(WUPSDIR)/plugin_makefile.mk + + +#MAP ?= $(TARGET:.mod=.map) + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- + +# -Os: optimise size +# -Wall: generate lots of warnings +# -D__wiiu__: define the symbol __wiiu__ (used in some headers) +# -mcpu=750: enable processor specific compilation +# -meabi: enable eabi specific compilation +# -mhard-float: enable hardware floating point instructions +# -nostartfiles: Do not use the standard system startup files when linking +# -ffunction-sections: split up functions so linker can garbage collect +# -fdata-sections: split up data so linker can garbage collect +COMMON_CFLAGS := -Os -Wall -mcpu=750 -meabi -mhard-float -D__WIIU__ -nostartfiles -ffunction-sections -fdata-sections -Wl,-q $(COMMON_CFLAGS) + +# -x c: compile as c code +# -std=c11: use the c11 standard +CFLAGS := $(COMMON_CFLAGS) -x c -std=gnu11 $(CFLAGS) + +# -x c: compile as c++ code +# -std=gnu++11: use the c++11 standard +CXXFLAGS := $(COMMON_CFLAGS) -x c++ -std=gnu++11 $(CXXFLAGS) + +ifeq ($(DO_LOGGING), 1) + CFLAGS += -D__LOGGING__ + CXXFLAGS += -D__LOGGING__ +endif + +#--------------------------------------------------------------------------------- +# any extra ld flags +#-------------------------------------------------------------------------------- +# --gc-sections: remove unneeded symbols +# -Map: generate a map file +LDFLAGS += -Wl,-Map,$(notdir $@).map,--gc-sections + + +#--------------------------------------------------------------------------------- +Q := @ +MAKEFLAGS += --no-print-directory +#--------------------------------------------------------------------------------- +# any extra libraries we wish to link with the project +#--------------------------------------------------------------------------------- +LIBS += +# +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS += + +NEEDS_WUT := 0 + +ifeq ($(WUT_ENABLE_CPP), 1) + WUT_ENABLE_NEWLIB := 1 + + LDFLAGS += -Wl,-whole-archive,-lwutstdc++,-no-whole-archive + NEEDS_WUT := 1 +endif + +ifeq ($(WUT_ENABLE_NEWLIB), 1) + LDFLAGS += -Wl,-whole-archive,-lwutnewlib,-no-whole-archive + NEEDS_WUT := 1 +endif + +ifeq ($(WUT_DEFAULT_MALLOC), 1) + LDFLAGS += -Wl,-whole-archive,-lwutmalloc,-no-whole-archive + NEEDS_WUT := 1 +endif + +ifeq ($(NEEDS_WUT), 1) + ifeq ($(strip $(WUT_ROOT)),) + $(error "Please set WUT_ROOT in your environment. export WUT_ROOT=wut) + endif + CFLAGS += -D__WUT__ + CXXFLAGS += -D__WUT__ +endif + +#--------------------------------------------------------------------------------- +# 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 PROJECTDIR := $(CURDIR) +export OUTPUT := $(CURDIR)/$(TARGETDIR)/$(TARGET) +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) +export DEPSDIR := $(CURDIR)/$(BUILD) + +#--------------------------------------------------------------------------------- +# automatically build a list of object files for our project +#--------------------------------------------------------------------------------- +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) +TTFFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.ttf))) +PNGFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.png))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) + export REAL_LD := $(CC) +else + export REAL_LD := $(CXX) +endif + +export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \ + $(sFILES:.s=.o) $(SFILES:.S=.o) \ + $(PNGFILES:.png=.png.o) $(addsuffix .o,$(BINFILES)) + +#--------------------------------------------------------------------------------- +# build a list of include paths +#--------------------------------------------------------------------------------- +export INCLUDE_FULL += $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + $(EXTERNAL_INCLUDE) + +#--------------------------------------------------------------------------------- +# build a list of library paths +#--------------------------------------------------------------------------------- +export LIBPATHS_FULL += $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \ + $(EXTERNAL_LIBPATHS) + + +export OUTPUT := $(CURDIR)/$(TARGET) +.PHONY: $(BUILD) clean install + +#--------------------------------------------------------------------------------- +$(BUILD): + @[ -d $@ ] || mkdir -p $@ + @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr $(BUILD) $(OUTPUT).mod $(OUTPUT) + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +THIS_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) + +############################################################################### +# Rule to make everything. +PHONY += all + +all : $(OUTPUT) +############################################################################### +# Special build rules + + +# Rule to make the module file. +$(OUTPUT) : $(OFILES) + @echo "linking ... " $@ + @$(REAL_LD) $(OFILES) $(LDFLAGS) $(LIBS) $(LIBPATHS_FULL) -o $@ + +############################################################################### +# Standard build rules +#--------------------------------------------------------------------------------- +%.a: +#--------------------------------------------------------------------------------- + @echo $(notdir $@) + @rm -f $@ + @$(AR) -rc $@ $^ + +#--------------------------------------------------------------------------------- +%.o: %.cpp + @echo $(notdir $<) + @$(CXX) -MMD -MP -MF $(DEPSDIR)/$*.d $(CXXFLAGS) $(INCLUDE_FULL) -c $< -o $@ $(ERROR_FILTER) + +#--------------------------------------------------------------------------------- +%.o: %.c + @echo $(notdir $<) + @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d $(CFLAGS) $(INCLUDE_FULL) -c $< -o $@ $(ERROR_FILTER) + +#--------------------------------------------------------------------------------- +%.o: %.S + @echo $(notdir $<) + @$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(INCLUDE_FULL) -c $< -o $@ $(ERROR_FILTER) + +#--------------------------------------------------------------------------------- +%.png.o : %.png + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.jpg.o : %.jpg + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.ttf.o : %.ttf + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.bin.o : %.bin + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.wav.o : %.wav + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.mp3.o : %.mp3 + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +#--------------------------------------------------------------------------------- +%.ogg.o : %.ogg + @echo $(notdir $<) + @bin2s -a 32 $< | $(AS) -o $(@) + +############################################################################### +# Assembly listing rules + +# Rule to make assembly listing. +PHONY += list +list : $(LIST) + +# Rule to make the listing file. +%.list : $(TARGET) + $(LOG) + -$Qmkdir -p $(dir $@) + $Q$(OBJDUMP) -d $< > $@ + +############################################################################### +# Clean rule + +# Rule to clean files. +PHONY += clean +clean : + $Qrm -rf $(wildcard $(BUILD) $(BIN)) + +############################################################################### +# Phony targets + +.PHONY : $(PHONY) + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- diff --git a/README.md b/README.md new file mode 100644 index 0000000..4463ebf --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# DiiBugger (WUPS version) [![Build Status](https://api.travis-ci.org/Maschell/DiiBuggerWUPS.svg?branch=master)](https://travis-ci.org/Maschell/DiiBuggerWUPS) + +Allows you to connect to your console and use simple debug operations. +Checkout the CLI client by [jam1garner](https://github.com/jam1garner/diibugger-cli) for usage. + +Once the plugin was loaded, start the `diibugger-cli.py` with python3, and type in `connect [WIIU IP]` to connect to the console. When the running applications changes you need to reconnect. + +# Wii U Plugin System +This is a plugin for the [Wii U Plugin System (WUPS)](https://github.com/Maschell/WiiUPluginSystem/). To be able to use this plugin you have to place the resulting `.mod` file into the following folder: + +``` +sd:/wiiu/plugins +``` +When the file is placed on the SDCard you can load it with [plugin loader](https://github.com/Maschell/WiiUPluginSystem/). + +## Building + +For building you need: +- [wups](https://github.com/Maschell/WiiUPluginSystem) +- [wut](https://github.com/decaf-emu/wut) +- [libutilswut](https://github.com/Maschell/libutils/tree/wut) (WUT version) for common functions. + +Install them (in this order) according to their README's. Don't forget the dependencies of the libs itself. + +## Credits +- Refactoring and porting to a WUPS/wut by Maschell +- Initially created by [Kinnay](https://github.com/Kinnay/DiiBugger) +- CLI client by [jam1garner](https://github.com/jam1garner/diibugger-cli) \ No newline at end of file diff --git a/diibugger-cli.py b/diibugger-cli.py new file mode 100644 index 0000000..413e075 --- /dev/null +++ b/diibugger-cli.py @@ -0,0 +1,578 @@ +import sys, struct, socket, time, os, binascii, time +import disassemble +import threading + +try: + import tabulate +except ModuleNotFoundError: + import pip + print('Installing tabulate') + pip.main(['install','tabulate']) + import tabulate + +class Message: + DSI = 0 + ISI = 1 + Program = 2 + GetStat = 3 + OpenFile = 4 + ReadFile = 5 + CloseFile = 6 + SetPosFile = 7 + GetStatFile = 8 + + Continue = 0 + Step = 1 + StepOver = 2 + + def __init__(self, type, data, arg): + self.type = type + self.data = data + self.arg = arg + +class ExceptionState: + + exceptionNames = [" DSI ", " ISI ", "Program"] + + def __init__(self): + self.filled = False + + def load(self, context, type): + #Convert tuple to list to make it mutable + self.filled = True + self.gpr = list(struct.unpack_from(">32I", context, 8)) + self.cr, self.lr, self.ctr, self.xer = struct.unpack_from(">4I", context, 0x88) + self.srr0, self.srr1, self.ex0, self.ex1 = struct.unpack_from(">4I", context, 0x98) + self.fpr = list(struct.unpack_from(">32d", context, 0xB8)) + self.gqr = list(struct.unpack_from(">8I", context, 0x1BC)) + self.psf = list(struct.unpack_from(">32d", context, 0x1E0)) + + self.exceptionName = self.exceptionNames[type] + + def isBreakPoint(self): + return self.exceptionName == "Program" and self.srr1 & 0x20000 + +class Thread: + + cores = { + 1: "Core 0", + 2: "Core 1", + 4: "Core 2" + } + + def __init__(self, data, offs=0): + self.core = self.cores[struct.unpack_from(">I", data, offs)[0]] + self.priority = struct.unpack_from(">I", data, offs + 4)[0] + self.stackBase = struct.unpack_from(">I", data, offs + 8)[0] + self.stackEnd = struct.unpack_from(">I", data, offs + 12)[0] + self.entryPoint = struct.unpack_from(">I", data, offs + 16)[0] + + namelen = struct.unpack_from(">I", data, offs + 20)[0] + self.name = data[offs + 24 : offs + 24 + namelen].decode("ascii") + +class PyBugger: + def __init__(self): + super().__init__() + self.connected = False + self.breakPoints = [] + + self.basePath = b"" + self.currentHandle = 0x12345678 + self.files = {} + + self.messageHandlers = { + Message.DSI: self.handleException, + Message.ISI: self.handleException, + Message.Program: self.handleException, + Message.GetStat: self.handleGetStat, + Message.OpenFile: self.handleOpenFile, + Message.ReadFile: self.handleReadFile, + Message.CloseFile: self.handleCloseFile, + Message.SetPosFile: self.handleSetPosFile, + Message.GetStatFile: self.handleGetStatFile + } + + self.silent = False + + def handleException(self, msg): + exceptionState.load(msg.data, msg.type) + if not self.silent: + print('+----------------------------------+') + print('|Exception type %s has occured|'%exceptionState.exceptionName) + print('+----------------------------------+') + + def handleGetStat(self, msg): + gamePath = msg.data.decode("ascii") + path = os.path.join(self.basePath, gamePath.strip("/vol")) + print("GetStat: %s" %gamePath) + self.sendFileMessage(os.path.getsize(path)) + + def handleOpenFile(self, msg): + mode = struct.pack(">I", msg.arg).decode("ascii").strip("\x00") + "b" + path = msg.data.decode("ascii") + print("Open: %s" %path) + + f = open(os.path.join(self.basePath, path.strip("/vol")), mode) + self.files[self.currentHandle] = f + self.sendFileMessage(self.currentHandle) + self.currentHandle += 1 + + def handleReadFile(self, msg): + print("Read") + task = Task(blocking=False, cancelable=False) + bufferAddr, size, count, handle = struct.unpack(">IIII", msg.data) + + data = self.files[handle].read(size * count) + task.setInfo("Sending file", len(data)) + + bytesSent = 0 + while bytesSent < len(data): + length = min(len(data) - bytesSent, 0x8000) + self.sendall(b"\x03") + self.sendall(struct.pack(">II", bufferAddr, length)) + self.sendall(data[bytesSent : bytesSent + length]) + bufferAddr += length + bytesSent += length + task.update(bytesSent) + self.sendFileMessage(bytesSent // size) + task.end() + + def handleCloseFile(self, msg): + print("Close") + self.files.pop(msg.arg).close() + self.sendFileMessage() + + def handleSetPosFile(self, msg): + print("SetPos") + handle, pos = struct.unpack(">II", msg.data) + self.files[handle].seek(pos) + self.sendFileMessage() + + def handleGetStatFile(self, msg): + print("GetStatFile") + f = self.files[msg.arg] + pos = f.tell() + f.seek(0, 2) + size = f.tell() + f.seek(pos) + self.sendFileMessage(size) + + def connect(self, host): + self.s = socket.socket() + self.s.connect((host, 1559)) + self.connected = True + self.breakPoints = [] + self.closeRequest = False + + def close(self): + self.sendall(b"\x01") + self.s.close() + self.connected = False + + def updateMessages(self): + self.sendall(b"\x07") + count = struct.unpack(">I", self.recvall(4))[0] + for i in range(count): + type, ptr, length, arg = struct.unpack(">IIII", self.recvall(16)) + data = None + if length: + data = self.recvall(length) + self.messageHandlers[type](Message(type, data, arg)) + + def read(self, addr, num): + self.sendall(b"\x02") + self.sendall(struct.pack(">II", addr, num)) + data = self.recvall(num) + return data + + def write(self, addr, data): + self.sendall(b"\x03") + self.sendall(struct.pack(">II", addr, len(data))) + self.sendall(data) + + def writeCode(self, addr, instr): + self.sendall(b"\x04") + self.sendall(struct.pack(">II", addr, instr)) + + def getThreadList(self): + self.sendall(b"\x05") + length = struct.unpack(">I", self.recvall(4))[0] + data = self.recvall(length) + + offset = 0 + threads = [] + while offset < length: + thread = Thread(data, offset) + threads.append(thread) + offset += 24 + len(thread.name) + return threads + + def toggleBreakPoint(self, addr): + if addr in self.breakPoints: + self.breakPoints.remove(addr) + print('Removed %08X'%addr) + else: + if len(self.breakPoints) >= 10: + return + self.breakPoints.append(addr) + print('Added %08X'%addr) + + self.sendall(b"\x0A") + self.sendall(struct.pack(">I", addr)) + + def continueBreak(self): self.sendCrashMessage(Message.Continue) + def stepBreak(self): self.sendCrashMessage(Message.Step) + def stepOver(self): self.sendCrashMessage(Message.StepOver) + + def sendCrashMessage(self, message): + self.sendMessage(message) + + def sendMessage(self, message, data0=0, data1=0, data2=0): + self.sendall(b"\x06") + self.sendall(struct.pack(">IIII", message, data0, data1, data2)) + + def sendFileMessage(self, data0=0, data1=0, data2=0): + self.sendall(b"\x0F") + self.sendall(struct.pack(">IIII", 0, data0, data1, data2)) + + def getStackTrace(self): + self.sendall(b"\x08") + count = struct.unpack(">I", self.recvall(4))[0] + trace = struct.unpack(">%iI" %count, self.recvall(4 * count)) + return trace + + def pokeExceptionRegisters(self): + self.sendall(b"\x09") + data = struct.pack(">32I32d", *exceptionState.gpr, *exceptionState.fpr) + self.sendall(data) + + def readDirectory(self, path): + self.sendall(b"\x0B") + self.sendall(struct.pack(">I", len(path))) + self.sendall(path.encode("ascii")) + + entries = [] + namelen = struct.unpack(">I", self.recvall(4))[0] + while namelen != 0: + flags = struct.unpack(">I", self.recvall(4))[0] + + size = -1 + if not flags & 0x80000000: + size = struct.unpack(">I", self.recvall(4))[0] + + name = self.recvall(namelen).decode("ascii") + entries.append(DirEntry(flags, size, name)) + + namelen = struct.unpack(">I", self.recvall(4))[0] + return entries + + def dumpFile(self, gamePath, outPath, task): + if task.canceled: + return + + self.sendall(b"\x0C") + self.sendall(struct.pack(">I", len(gamePath))) + self.sendall(gamePath.encode("ascii")) + + length = struct.unpack(">I", self.recvall(4))[0] + task.setInfo("Dumping %s" %gamePath, length) + + with open(outPath, "wb") as f: + bytesDumped = 0 + while bytesDumped < length: + data = self.s.recv(length - bytesDumped) + f.write(data) + bytesDumped += len(data) + task.update(bytesDumped) + + def search(self, startAddress, endAddress, value): + length = int((endAddress - startAddress) / 4) + self.sendall(b"\x11") + self.sendall(struct.pack(">L", startAddress)) + self.sendall(struct.pack(">L", length)) + self.sendall(struct.pack(">L", value)) + location = struct.unpack(">L", self.recvall(4)) + return location + + def loadMods(self, fileBytes): + self.sendall(b"\x12") + self.sendall(struct.pack(">L", len(fileBytes))) + self.sendall(fileBytes) + + def getModuleName(self): + self.sendall(b"\x0D") + length = struct.unpack(">I", self.recvall(4))[0] + return self.recvall(length).decode("ascii") + ".rpx" + + def setPatchFiles(self, fileList, basePath): + self.basePath = basePath + self.sendall(b"\x0E") + + fileBuffer = struct.pack(">I", len(fileList)) + for path in fileList: + fileBuffer += struct.pack(">H", len(path)) + fileBuffer += path.encode("ascii") + + self.sendall(struct.pack(">I", len(fileBuffer))) + self.sendall(fileBuffer) + + def clearPatchFiles(self): + self.sendall(b"\x10") + + def sendall(self, data): + try: + self.s.sendall(data) + except socket.error: + self.connected = False + + def recvall(self, num): + try: + data = b"" + while len(data) < num: + data += self.s.recv(num - len(data)) + except socket.error: + self.connected = False + return b"\x00" * num + return data + +exceptionState = ExceptionState() +bugger = PyBugger() + +while True: + try: + userInput = input("> ").strip() + splitCmd = userInput.split(" ") + cmd = splitCmd[0].lower() + except KeyboardInterrupt: + print("") #Just to prevent issues with early disconnects + except Exception as e: + print(e) + try: + if cmd == "help": + print(" Command list:") + print("-----------------------------------------------------------------") + print("exit") + print(" Closes connection and exits") + print("connect [ip]") + print(" Connects to diibugger at a specified ip address if no ip is") + print(" given, it will use one from ip.txt in the active directory") + print("close") + print(" Closes connection and waits") + print("eval [statement]") + print(" Evalutes a python statement") + print("cmd [command]") + print(" Evaluates a system command") + print("read [address] [length]") + print(" Prints out certain bytes in hex and ascii to the console") + print(" aliases: preview, r") + print("dump [address] [length] [filename]") + print(" Dumps a certain area of memory to file") + print("search [startAddress] [endAddress] [value]") + print(" Search a range of memory for a uin32 value") + print("word [address] [value]") + print(" Writes a uint32 to an address") + print(" aliases: ww, writeword, int") + print("float [address] [value]") + print(" Writes a float to an address") + print("hex [address] [hex]") + print(" Writes bytes to a specified address") + print(" aliases: bytes, w, writebytes") + print("ppc [address] [length]") + print(" Print disassembled code from the specified region") + print("threads") + print(" List thread info") + print("stack") + print(" Prints a stack trace") + print(" aliases: stacktrace, trace") + print("stackdump [stackNum] [filename]") + print(" Dumps entire thread's stack to file (Note: get stacknum from \"threads\")") + print(" aliases: sd") + print("registers (or reg)") + print(" Print registers") + print("update (or u)") + print(" Checks for exceptions") + print(" this is run after every other command as well") + print("breakpoints (or bps)") + print(" List breakpoints") + print("breapoint [address] (or bp)") + print(" Toggle breakpoint") + print("continue (or c)") + print(" Continue past breakpoint") + print("step (or s)") + print(" Step from breakpoint to next line") + elif cmd == "exit": + try: + if bugger.connected: + for i in bugger.breakPoints: + bugger.toggleBreakPoint(i) + bugger.close() + finally: + break + elif cmd == "connect": + bugger.connect(splitCmd[1]) + if bugger.connected: + print("Successfully connected\nCurrent title: "+bugger.getModuleName()) + else: + print("Failed to connect") + elif cmd == "cmd": + os.system(userInput[userInput.find(" ")+1:]) + elif cmd == "eval": + print(eval(userInput[userInput.find(" ")+1:])) + elif not bugger.connected: + print("Diibugger server not connected, use 'connect [ip]' to connect") + elif cmd == "close": + if bugger.connected: + for i in bugger.breakPoints: + bugger.toggleBreakPoint(i) + bugger.close() + elif cmd == "read" or cmd == "preview" or cmd == "r": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + length = 0x30 + if len(splitCmd) >= 3: + length = int(splitCmd[2], 16) + start = address - (address % 0x10) + end = address + length + if end % 0x10 != 0: + end += (0x10 - ((address + length) % 0x10)) + + readBytes = bugger.read(start, end - start) + print(" | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F | 012345678ABCDEF"); + print(" |-------------------------------------------------|----------------") + for i in range(int(len(readBytes) / 0x10)): + thisString = readBytes[i*0x10:(i+1)*0x10].decode('latin1') + for char in ['\n', '\t', '\r', chr(0)]: + thisString = thisString.replace(char, '.') + print("%08X | %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X | %s " % tuple([i*0x10 + start] + list(readBytes[i*0x10:(i+1)*0x10]) + [thisString])) + elif cmd == "dump": + if len(splitCmd) <= 3: + print("Not enough arguments\n\tdump [address] [length] [file]") + else: + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + length = int(splitCmd[2], 16) + filename = "" + for i in splitCmd[3:]: + filename += i + " " + filename = filename.strip().strip('"').strip("'") + with open(filename, 'wb') as f: + f.write(bugger.read(address, length)) + elif cmd == "search": + startAddress = int(splitCmd[1],16) + endAddress = int(splitCmd[2], 16) + value = int(splitCmd[3], 16) + address = bugger.search(startAddress, endAddress, value) + if address == 0: + print("Not found in range") + else: + print("Located at %08X" % address) + elif cmd == "word" or cmd == "ww" or cmd == "writeword" or cmd == "int": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + value = int(splitCmd[2], 16) + bugger.write(address, struct.pack(">L", value)) + elif cmd == "float": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + value = float(splitCmd[2]) + bugger.write(address, struct.pack(">f", value)) + elif cmd == "hex" or cmd == "bytes" or cmd == "w" or cmd == "writebytes": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + bugger.write(address, binascii.unhexlify(splitCmd[2])) + elif cmd == "ppc": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + length = 4 + if len(splitCmd) > 2: + length = int(splitCmd[2], 16) + ppcBytes = bugger.read(address, length) + for i in range(int(len(ppcBytes) / 4)): + value = struct.unpack('>L',ppcBytes[i*4:i*4 + 4])[0] + addr = address + (i*4) + instr = disassemble.disassemble(value, addr) + print("%08X: %08X %s" %(addr, value, instr)) + elif cmd == "stack" or cmd == "stacktrace" or cmd == "trace": + stackTrace = bugger.getStackTrace() + print('') + for address in stackTrace: + print("%X" % address) + elif cmd == "registers" or cmd == "regs": + if exceptionState.filled: + for i in range(4): + for j in range(8): + print("r%2i: %08X" % (i*8 + j, exceptionState.gpr[i*8 + j]), end=' ') + print('') + print('CR:%08X LR:%08X CTR:%08X XER:%08X EX0:%08X EX1:%08X SRR0:%08X SRR1:%08X' % (exceptionState.cr, exceptionState.lr, exceptionState.ctr, exceptionState.xer, exceptionState.ex0, exceptionState.ex1, exceptionState.srr0, exceptionState.srr1)) + else: + print("No exception state") + elif cmd == "update" or cmd == "u": + pass + elif cmd == "threads": + threads = bugger.getThreadList() + table = [] + for i,thread in enumerate(threads): + table.append([i,thread.name,thread.core,'%08X' % thread.stackBase,'%08X' % thread.stackEnd,'%08X' % thread.entryPoint,thread.priority]) + print(tabulate.tabulate(table,["Thread","Name","Core","Stack Start","Stack End","Entrypoint","Priority"])) + elif cmd == "stackdump" or cmd == "sd": + stackNum = int(splitCmd[1],0) + filename = "" + for i in splitCmd[2:]: + filename += i + " " + filename = filename.strip().strip('"').strip("'") + thread = bugger.getThreadList()[stackNum] + with open(filename, 'wb') as f: + f.write(bugger.read(thread.stackEnd, thread.stackBase - thread.stackEnd)) + elif cmd == "breakpoints" or cmd == "bps": + for bp in bugger.breakPoints: + print('%08X'%bp) + elif cmd == "breakpoint" or cmd == "bp": + addressStr = splitCmd[1] + if addressStr[0] == 'r': + address = exceptionState.gpr[int(addressStr[1:])] + else: + address = int(addressStr, 16) + bugger.toggleBreakPoint(address) + elif cmd == "continue" or cmd == "c": + bugger.continueBreak() + elif cmd == "step" or cmd == "s": + bugger.stepBreak() + time.sleep(0.2) + bugger.silent = True + bugger.updateMessages() + bugger.silent = False + print('Stepped to %08X' % exceptionState.srr0) + elif cmd == "stepover" or cmd == "so": + bugger.stepOver() + elif cmd == "load": + filename = userInput[5:] + with open(filename, 'rb') as f: + fileBytes = f.read() + if fileBytes[:4] == b'MODS': + bugger.loadMods(fileBytes) + else: + print("Not a valid mods file") + else: + print("Invalid command") + if bugger.connected: + bugger.updateMessages() + except Exception as e: + print(e) diff --git a/disassemble.py b/disassemble.py new file mode 100644 index 0000000..781442e --- /dev/null +++ b/disassemble.py @@ -0,0 +1,343 @@ + +condition_table_true = ["lt", "gt", "eq"] +condition_table_false = ["ge", "le", "ne"] +trap_condition_table = { + 1: "lgt", + 2: "llt", + 4: "eq", + 5: "lge", + 8: "gt", + 12: "ge", + 16: "lt", + 20: "le", + 31: "u" +} + +spr_table = { + 8: "lr", + 9: "ctr" +} + +def decodeI(value): + return (value >> 2) & 0xFFFFFF, (value >> 1) & 1, value & 1 + +def decodeB(value): + return (value >> 21) & 0x1F, (value >> 16) & 0x1F, (value >> 2) & 0x3FFF, (value >> 1) & 1, value & 1 + +def decodeD(value): + return (value >> 21) & 0x1F, (value >> 16) & 0x1F, value & 0xFFFF + +def decodeX(value): + return (value >> 21) & 0x1F, (value >> 16) & 0x1F, (value >> 11) & 0x1F, (value >> 1) & 0x3FF, value & 1 + +def extend_sign(value, bits=16): + if value & 1 << (bits - 1): + value -= 1 << bits + return value + +def ihex(value): + return "-" * (value < 0) + "0x" + hex(value).lstrip("-0x").rstrip("L").zfill(1).upper() + +def decodeCond(BO, BI): + #TODO: Better condition code + if BO == 20: return "" + if BO & 1: return "?" + if BI > 2: return "?" + if BO == 4: return condition_table_false[BI] + if BO == 12: return condition_table_true[BI] + return "?" + +def loadStore(value, regtype="r"): + D, A, d = decodeD(value) + d = extend_sign(d) + return "%s%i, %s(r%i)" %(regtype, D, ihex(d), A) + +def loadStoreX(D, A, B, pad): + if pad: return "" + return "r%i, %s, r%i" %(D, ("r%i" %A) if A else "0", B) + +def add(D, A, B, Rc): + return "add%s" %("." * Rc), "r%i, r%i, r%i" %(D, A, B) + +def addi(value, addr): + D, A, SIMM = decodeD(value) + SIMM = extend_sign(SIMM) + if A == 0: + return "li", "r%i, %s" %(D, ihex(SIMM)) + return "addi", "r%i, r%i, %s" %(D, A, ihex(SIMM)) + +def addic(value, addr): + D, A, SIMM = decodeD(value) + SIMM = extend_sign(SIMM) + return "addic", "r%i, r%i, %s" %(D, A, ihex(SIMM)) + +def addic_(value, addr): + D, A, SIMM = decodeD(value) + SIMM = extend_sign(SIMM) + return "addic.", "r%i, r%i, %s" %(D, A, ihex(SIMM)) + +def addis(value, addr): + D, A, SIMM = decodeD(value) + SIMM = extend_sign(SIMM) + if A == 0: + return "lis", "r%i, %s" %(D, ihex(SIMM)) + return "addis", "r%i, r%i, %s" %(D, A, ihex(SIMM)) + +def and_(S, A, B, Rc): + return "and%s" % ("." * Rc), "r%i, r%i, r%i" % (A, S, B) + +def b(value, addr): + LI, AA, LK = decodeI(value) + LI = extend_sign(LI, 24) * 4 + if AA: + dst = LI + else: + dst = addr + LI + return "b%s%s" %("l" * LK, "a" * AA), ihex(dst) + +def bc(value, addr): + BO, BI, BD, AA, LK = decodeB(value) + LI = extend_sign(LK, 14) * 4 + instr = "b" + decodeCond(BO, BI) + if LK: instr += "l" + if AA: + instr += "a" + dst = LI + else: + dst = addr + LI + return instr, ihex(dst) + +def bcctr(BO, BI, pad, LK): + if pad: return "" + instr = "b" + decodeCond(BO, BI) + "ctr" + if LK: + instr += "l" + return instr + +def bclr(BO, BI, pad, LK): + if pad: return "" + instr = "b" + decodeCond(BO, BI) + "lr" + if LK: + instr += "l" + return instr + +def cmp(cr, A, B, pad): + if pad: return "" + if cr & 3: + return "" + return "cmp", "cr%i, r%i, r%i" %(cr >> 2, A, B) + +def cmpi(value, addr): + cr, A, SIMM = decodeD(value) + SIMM = extend_sign(SIMM) + if cr & 3: + return "" + return "cmpwi", "cr%i, r%i, %s" %(cr >> 2, A, ihex(SIMM)) + +def cmpl(cr, A, B, pad): + if pad: return "" + if cr & 3: + return "" + return "cmplw", "cr%i, r%i, r%i" %(cr >> 2, A, B) + +def cmpli(value, addr): + cr, A, UIMM = decodeD(value) + if cr & 3: + return "" + return "cmplwi", "cr%i, r%i, %s" %(cr >> 2, A, ihex(UIMM)) + +def cntlzw(S, A, pad, Rc): + if pad: return "" + return "cntlzw%s" %("." * Rc), "r%i, r%i" %(A, S) + +def dcbst(pad1, A, B, pad2): + if pad1 or pad2: return "" + return "dcbst", "r%i, r%i" %(A, B) + +def fmr(D, pad, B, Rc): + if pad: return "" + return "fmr%s" %("." * Rc), "f%i, f%i" %(D, B) + +def fneg(D, pad, B, Rc): + if pad: return "" + return "fneg%s" %("." * Rc), "f%i, f%i" %(D, B) + +def mfspr(D, sprLo, sprHi, pad): + if pad: return "" + sprnum = (sprHi << 5) | sprLo + if sprnum not in spr_table: + spr = "?" + else: + spr = spr_table[sprnum] + return "mf%s" %spr, "r%i" %D + +def mtspr(S, sprLo, sprHi, pad): + if pad: return "" + sprnum = (sprHi << 5) | sprLo + if sprnum not in spr_table: + spr = ihex(sprnum) + else: + spr = spr_table[sprnum] + return "mt%s" %spr, "r%i" %S + +def lbz(value, addr): return "lbz", loadStore(value) +def lfd(value, addr): return "lfd", loadStore(value, "f") +def lfs(value, addr): return "lfs", loadStore(value, "f") +def lmw(value, addr): return "lmw", loadStore(value) +def lwz(value, addr): return "lwz", loadStore(value) +def lwzu(value, addr): return "lwzu", loadStore(value) +def lwarx(D, A, B, pad): return "lwarx", loadStoreX(D, A, B, pad) +def lwzx(D, A, B, pad): return "lwzx", loadStoreX(D, A, B, pad) + +def or_(S, A, B, Rc): + if S == B: + return "mr%s" %("." * Rc), "r%i, r%i" %(A, S) + return "or%s" %("." * Rc), "r%i, r%i, r%i" %(A, S, B) + +def ori(value, addr): + S, A, UIMM = decodeD(value) + if UIMM == 0: + return "nop" + return "ori", "r%s, r%s, %s" %(A, S, ihex(UIMM)) + +def oris(value, addr): + S, A, UIMM = decodeD(value) + return "oris", "r%s, r%s, %s" %(A, S, ihex(UIMM)) + +def rlwinm(value, addr): + S, A, SH, M, Rc = decodeX(value) + MB = M >> 5 + ME = M & 0x1F + dot = "." * Rc + if SH == 0 and MB == 0 and ME == 31: + return "nop" + if MB == 0 and ME == 31 - SH: + return "slwi%s" %dot, "r%i, r%i, %i" %(A, S, SH) + if ME == 31 and SH == 32 - MB: + return "srwi%s" %dot, "r%i, r%i, %i" %(A, S, MB) + if MB == 0 and ME < 31: + return "extlwi%s" %dot, "r%i, r%i, %i,%i" %(A, S, ME + 1, SH) + #extrwi + if MB == 0 and ME == 31: + if SH >= 16: + return "rotlwi%s" %dot, "r%i, r%i, %i" %(A, S, SH) + return "rotrwi%s" %dot, "r%i, r%i, %i" %(A, S, 32 - SH) + if SH == 0 and ME == 31: + return "clrlwi%s" %dot, "r%i, r%i, %i" %(A, S, MB) + if SH == 0 and MB == 0: + return "clrrwi%s" %dot, "r%i, r%i, %i" %(A, S, 31 - ME) + #clrlslwi + return "rlwinm%s" %dot, "r%i, r%i, r%i,r%i,r%i" %(A, S, SH, MB, ME) + +def sc(value, addr): + if value & 0x3FFFFFF != 2: + return "" + return "sc" + +def stb(value, addr): return "stb", loadStore(value) +def stfd(value, addr): return "stfd", loadStore(value, "f") +def stfs(value, addr): return "stfs", loadStore(value, "f") +def stfsu(value, addr): return "stfsu", loadStore(value, "f") +def stmw(value, addr): return "stmw", loadStore(value) +def stw(value, addr): return "stw", loadStore(value) +def stwu(value, addr): return "stwu", loadStore(value) +def stbx(S, A, B, pad): return "stbx", loadStoreX(S, A, B, pad) +def stwx(S, A, B, pad): return "stwx", loadStoreX(S, A, B, pad) +def stwcx(S, A, B, pad): return "stwcx", loadStoreX(S, A, B, pad ^ 1) + +def tw(TO, A, B, pad): + if pad: return "" + if TO == 31 and A == 0 and B == 0: + return "trap" + + if TO not in trap_condition_table: + condition = "?" + else: + condition = trap_condition_table[TO] + return "tw%s" %condition, "r%i, r%i" %(A, B) + +opcode_table_ext1 = { + 16: bclr, + 528: bcctr +} + +opcode_table_ext2 = { + 0: cmp, + 4: tw, + 20: lwarx, + 23: lwzx, + 26: cntlzw, + 28: and_, + 32: cmpl, + 54: dcbst, + 150: stwcx, + 151: stwx, + 215: stbx, + 266: add, + 339: mfspr, + 444: or_, + 467: mtspr +} + +opcode_table_float_ext1 = { + 40: fneg, + 72: fmr +} + +def ext1(value, addr): + DS, A, B, XO, Rc = decodeX(value) + if not XO in opcode_table_ext1: + return "ext1 - %s" %bin(XO) + return opcode_table_ext1[XO](DS, A, B, Rc) + +def ext2(value, addr): + DS, A, B, XO, Rc = decodeX(value) + if not XO in opcode_table_ext2: + return "ext2 - %s" %bin(XO) + return opcode_table_ext2[XO](DS, A, B, Rc) + +def float_ext1(value, addr): + D, A, B, XO, Rc = decodeX(value) + if not XO in opcode_table_float_ext1: + return "float_ext1 - %s" %bin(XO) + return opcode_table_float_ext1[XO](D, A, B, Rc) + +opcode_table = { + 10: cmpli, + 11: cmpi, + 12: addic, + 13: addic_, + 14: addi, + 15: addis, + 16: bc, + 17: sc, + 18: b, + 19: ext1, + 21: rlwinm, + 24: ori, + 25: oris, + 31: ext2, + 32: lwz, + 33: lwzu, + 34: lbz, + 36: stw, + 37: stwu, + 38: stb, + 46: lmw, + 47: stmw, + 48: lfs, + 50: lfd, + 52: stfs, + 53: stfsu, + 54: stfd, + 63: float_ext1 +} + +def disassemble(value, address): + opcode = value >> 26 + if opcode not in opcode_table: + return "???" + instr = opcode_table[opcode](value, address) + if type(instr) == str: + return instr + return instr[0] + " " * (10 - len(instr[0])) + instr[1] \ No newline at end of file diff --git a/makefile.mk b/makefile.mk new file mode 100644 index 0000000..a835ed5 --- /dev/null +++ b/makefile.mk @@ -0,0 +1,66 @@ +# Compiling the projects with libutils logging code? +DO_LOGGING := 1 + +# Links against the wut implementation of newlib, this is useful for using any function +# from the C standard library +WUT_ENABLE_NEWLIB := 0 + +# Links against the wut implementation of stdcpp, this is useful for using any function +# from the C++ standard library. This will enable WUT_ENABLE_NEWLIB if you have not already done so. +WUT_ENABLE_CPP := 0 + +# By default newlib will allocate 90% of the default heap for use with sbrk & malloc, +# if this is unacceptable to you then you should use this as it replaces the newlib +# malloc functions which ones which redirect to the CafeOS default heap functions +# such as MEMAllocFromDefaultHeap. +WUT_DEFAULT_MALLOC := 1 + +# Target filename +TARGET := diibugger.mod + +# Source directories +SOURCES := src/ \ + src/common \ + src/diibugger \ + +# Data directories +DATA := + +# Include directories +INCLUDES := src + +#--------------------------------------------------------------------------------- +# options for code generation and linking +#--------------------------------------------------------------------------------- +# Extra C AND C++ compiler flags +COMMON_CFLAGS := +# Extra C compiler flags +CFLAGS := +# Extra C++ compiler flags +CXXFLAGS := +# Extra linking flags for all linking steps +LDFLAGS := + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(WUPSDIR) $(WUT_ROOT) + +#--------------------------------------------------------------------------------- +# any extra libraries we wish to link with the project +#--------------------------------------------------------------------------------- +LIBS := -lwups -lutilswut -lcoreinit -lnsysnet + +#--------------------------------------------------------------------------------- +# Will be added to the final lib paths +# example: +# -L$C:/library1/lib +#--------------------------------------------------------------------------------- +EXTERNAL_LIBPATHS := + +#--------------------------------------------------------------------------------- +# Will be added to the final include paths +# -IC:/library1/include +#--------------------------------------------------------------------------------- +EXTERNAL_INCLUDE := -I$(WUT_ROOT)/include/libutilswut diff --git a/src/common/diibugger_defs.h b/src/common/diibugger_defs.h new file mode 100644 index 0000000..7cc7cb9 --- /dev/null +++ b/src/common/diibugger_defs.h @@ -0,0 +1,54 @@ +#ifndef DIIBUGGER_DEFS_H +#define DIIBUGGER_DEFS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define STACK_SIZE 0x8000 +#define MESSAGE_COUNT 4 +#define NUM_FILE_HANDLES 4 + +#define TRAP 0x7FE00008 + +#define BREAKPOINT_LIST_SIZE 12 +#define BREAKPOINT_LIST_SIZE_USABLE (BREAKPOINT_LIST_SIZE - 2) + +#define STEP1 (BREAKPOINT_LIST_SIZE-2) +#define STEP2 (BREAKPOINT_LIST_SIZE-1) + +#define SERVER_MESSAGE_DSI 0 +#define SERVER_MESSAGE_ISI 1 +#define SERVER_MESSAGE_PROGRAM 2 +#define SERVER_MESSAGE_GET_STAT 3 +#define SERVER_MESSAGE_OPEN_FILE 4 +#define SERVER_MESSAGE_READ_FILE 5 +#define SERVER_MESSAGE_CLOSE_FILE 6 +#define SERVER_MESSAGE_SET_POS_FILE 7 +#define SERVER_MESSAGE_GET_STAT_FILE 8 +#define SERVER_MESSAGE_WRITE_FILE 9 + +#define CLIENT_MESSAGE_CONTINUE 0 +#define CLIENT_MESSAGE_STEP 1 +#define CLIENT_MESSAGE_STEP_OVER 2 + +#define STEP_STATE_RUNNING 0 +#define STEP_STATE_CONTINUE 1 +#define STEP_STATE_STEPPING 2 + +#define CRASH_STATE_NONE 0 +#define CRASH_STATE_UNRECOVERABLE 1 +#define CRASH_STATE_BREAKPOINT 2 + +struct breakpoint { + uint32_t address; + uint32_t instruction; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* DIIBUGGER_DEFS_H */ diff --git a/src/diibugger/BreakPointManager.cpp b/src/diibugger/BreakPointManager.cpp new file mode 100644 index 0000000..38b5330 --- /dev/null +++ b/src/diibugger/BreakPointManager.cpp @@ -0,0 +1,150 @@ +#include "BreakPointManager.hpp" +#include "utils.h" +#include +#include + +BreakPointManager::BreakPointManager() { + memset(breakpoints,0,sizeof(breakpoints)); +} + +breakpoint * BreakPointManager::GetBreakPoint(uint32_t addr, uint32_t num) { + for (int i = 0; i < num; i++) { + if (this->breakpoints[i].address == addr) { + return &this->breakpoints[i]; + } + } + return NULL; +} + + +breakpoint * BreakPointManager::GetFreeBreakPoint() { + breakpoint *bplist = this->breakpoints; + for (int i = 0; i < BREAKPOINT_LIST_SIZE_USABLE; i++) { + if (bplist[i].address == 0) { + return &bplist[i]; + } + } + return 0; +} + +breakpoint * BreakPointManager::GetBreakPointInRange(uint32_t addr, uint32_t range, breakpoint *prev) { + breakpoint *bplist = this->breakpoints; + + int start = 0; + if (prev) { + start = (prev - bplist) + 1; + } + + for (int i = start; i < BREAKPOINT_LIST_SIZE; i++) { + if (bplist[i].address >= addr && bplist[i].address < addr + range) { + return &bplist[i]; + } + } + return 0; +} + +void BreakPointManager::restoreInstructionForBreakPointsInRange(uint32_t addr, uint32_t range) { + breakpoint *bp = GetBreakPointInRange(addr, range, 0); + while (bp) { + WriteCode(bp->address, bp->instruction); + bp = GetBreakPointInRange(addr, range, bp); + } +} +void BreakPointManager::restoreTRAPForBreakPointsInRange(uint32_t addr, uint32_t range) { + breakpoint * bp = GetBreakPointInRange(addr, range, 0); + while (bp) { + WriteCode(bp->address, TRAP); + bp = GetBreakPointInRange(addr, range, bp); + } +} + +uint32_t BreakPointManager::GetInstruction(uint32_t address) { + breakpoint *bp = GetBreakPoint(address, BREAKPOINT_LIST_SIZE); + if (bp) { + return bp->instruction; + } + return *(uint32_t *)address; +} + + +void BreakPointManager::PredictStepAddresses(OSContext * crashContext, bool stepOver) { + uint32_t currentAddr = crashContext->srr0; + uint32_t instruction = GetInstruction(currentAddr); + + breakpoint *step1 = &breakpoints[STEP1]; + breakpoint *step2 = &breakpoints[STEP2]; + step1->address = currentAddr + 4; + step2->address = 0; + + uint8_t opcode = instruction >> 26; + if (opcode == 19) { + uint16_t XO = (instruction >> 1) & 0x3FF; + bool LK = instruction & 1; + if (!LK || !stepOver) { + if (XO == 16) step2->address = crashContext->lr; //bclr + if (XO == 528) step2->address = crashContext->ctr; //bcctr + } + } + + else if (opcode == 18) { //b + bool AA = instruction & 2; + bool LK = instruction & 1; + uint32_t LI = instruction & 0x3FFFFFC; + if (!LK || !stepOver) { + if (AA) step1->address = LI; + else { + if (LI & 0x2000000) LI -= 0x4000000; + step1->address = currentAddr + LI; + } + } + } + + else if (opcode == 16) { //bc + bool AA = instruction & 2; + bool LK = instruction & 1; + uint32_t BD = instruction & 0xFFFC; + if (!LK || !stepOver) { + if (AA) step2->address = BD; + else { + if (BD & 0x8000) BD -= 0x10000; + step2->address = currentAddr + BD; + } + } + } +} + +void BreakPointManager::RemoveAllBreakPoints() { + for (int i = 0; i < BREAKPOINT_LIST_SIZE_USABLE; i++) { + if (breakpoints[i].address) { + WriteCode(breakpoints[i].address, breakpoints[i].instruction); + breakpoints[i].address = 0; + breakpoints[i].instruction = 0; + } + } +} + +void BreakPointManager::writeTRAPInstructionToSteps() { + breakpoints[STEP1].instruction = *(uint32_t *)(breakpoints[STEP1].address); + WriteCode(breakpoints[STEP1].address, TRAP); + if (breakpoints[STEP2].address) { + breakpoints[STEP2].instruction = *(uint32_t *)(breakpoints[STEP2].address); + WriteCode(breakpoints[STEP2].address, TRAP); + } +} + +void BreakPointManager::RestoreStepInstructions(uint32_t stepSource) { + //Write back the instructions that were replaced for the step + WriteCode(breakpoints[STEP1].address, breakpoints[STEP1].instruction); + breakpoints[STEP1].address = 0; + breakpoints[STEP1].instruction = 0; + if (breakpoints[STEP2].address) { + WriteCode(breakpoints[STEP2].address, breakpoints[STEP2].instruction); + breakpoints[STEP2].address = 0; + breakpoints[STEP2].instruction = 0; + } + + breakpoint *bp = GetBreakPoint(stepSource, BREAKPOINT_LIST_SIZE_USABLE); + if (bp) { + WriteCode(bp->address, TRAP); + } +} diff --git a/src/diibugger/BreakPointManager.hpp b/src/diibugger/BreakPointManager.hpp new file mode 100644 index 0000000..f445ffc --- /dev/null +++ b/src/diibugger/BreakPointManager.hpp @@ -0,0 +1,108 @@ +#ifndef _BREAKPOINT_MANAGER_H_ +#define _BREAKPOINT_MANAGER_H_ + +#include "common/diibugger_defs.h" +#include + +class BreakPointManager { +public: + BreakPointManager(); + + ~BreakPointManager(){ + + } + + /** + \brief Returns a pointer to a breakpoint element for a given address. + + \param addr: Address of the breakpoint. + \param num: end of iteration + + \return Returns the address of the breakpoint data if a breakpoint was set at the given address. + Return NULL if no breakpoint was found at the given address. + **/ + breakpoint * GetBreakPoint(uint32_t addr, uint32_t num); + + /** + \brief Gets a pointer to the next free breakpoint element. + + \return The address of the free breakpoint element that should be filled with information. + Returns NULL if there is no more space for another breakpoint. + **/ + breakpoint * GetFreeBreakPoint(); + + /** + \brief Checks if a address with an given range contains any breakpoints. + This functions is supposed to be used more than one time. + After the initial call pass the previous result until it returns NULL. + + \param addr: start address of the area that should be checked + \param range: size of the range. + \param prev: the previous breakpoint + + \return Return a pointer to a breakpoint element that is in the given range. + Return NULL if there is no (more) breakpoint in the given area. + **/ + + breakpoint * GetBreakPointInRange(uint32_t addr, uint32_t range, breakpoint *prev); + + /** + \brief Restores the instruction for all breakpoints in a given range. + The breakpoint slots will still be occupied, the address will NOT be set to 0. + Use restoreTRAPForBreakPointsInRange with the same arguments to revert it. + + \param addr: start address of the area that should be checked + \param range: size of the range. + **/ + void restoreInstructionForBreakPointsInRange(uint32_t addr, uint32_t range); + + /** + \brief Sets the instruction of all breakpoints in the given range to the TRAP instruction. + The breakpoint slots will still be occupied, the address will NOT be set to 0. + This is supposed to revert the changes of restoreInstructionForBreakPointsInRange. + + \param addr: start address of the area that should be checked + \param range: size of the range. + **/ + void restoreTRAPForBreakPointsInRange(uint32_t addr, uint32_t range); + + /** + \brief Gets the instruction for a given address with the breakpoints in mind. + It's ignoring TRAP instruction, and gets the instruction behind the TRAP + + \return Returns the "real" instruction of a given address. + If a breakpoint is currently set a the given address, the original instruction instead + of the TRAP instruction will be returned. + **/ + uint32_t GetInstruction(uint32_t address); + + /** + \brief Sets the internal step-breakpoints. TODO!!!!!!!!!!!!!!!!!! + + \param crashContext The current crash context + \param stepOver: Set this to true to step over the next instruction, false will step in. + **/ + void PredictStepAddresses(OSContext * crashContext, bool stepOver); + + /** + \brief Removes all breakpoints. + **/ + void RemoveAllBreakPoints(); + + + /** + \brief Writes TRAP instructions to handle steps + **/ + void writeTRAPInstructionToSteps(); + + /** + \brief Restores the step instructions + \param the step source + **/ + void RestoreStepInstructions(uint32_t stepSource); + +private: + breakpoint breakpoints[BREAKPOINT_LIST_SIZE]; +}; + +#endif //_BREAKPOINT_MANAGER_H_ diff --git a/src/diibugger/Diibugger.cpp b/src/diibugger/Diibugger.cpp new file mode 100644 index 0000000..11c35e7 --- /dev/null +++ b/src/diibugger/Diibugger.cpp @@ -0,0 +1,175 @@ +#include "Diibugger.hpp" +#include "handler.h" +#include "utils.h" +#include +#include + +Diibugger * Diibugger::instance = NULL; + +Diibugger::Diibugger() { + FSInit(); + DEBUG_FUNCTION_LINE("FSInit() done\n"); + + this->fileCMDBlock = (FSCmdBlock*) memalign(0x40,sizeof(FSCmdBlock)); + this->fileClient = (FSClient*) memalign(0x40,sizeof(FSClient)); + FSInitCmdBlock(this->fileCMDBlock); + FSAddClient(this->fileClient, -1); + DEBUG_FUNCTION_LINE("FS Stuff done\n"); + + OSInitMessageQueue(&serverQueue, serverMessages, MESSAGE_COUNT); + OSInitMessageQueue(&clientQueue, clientMessages, MESSAGE_COUNT); + + DEBUG_FUNCTION_LINE("Setting the ExceptionCallbacks\n"); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_DSI, DSIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_ISI, ISIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_PROGRAM, ProgramHandler_Fatal); + + memset(&crashContext,0,sizeof(crashContext)); + + stepState = STEP_STATE_RUNNING; + + bpManager = new BreakPointManager(); + + startTCPServer(); +} + +Diibugger::~Diibugger() { + stopTCPServer(); + if(this->fileCMDBlock != NULL) { + free(this->fileCMDBlock); + this->fileCMDBlock = NULL; + } + + if(this->fileClient != NULL) { + FSDelClient(this->fileClient,-1); + free(this->fileClient); + this->fileClient = NULL; + } +} + +OSContext * Diibugger::getCrashContext() { + return &(this->crashContext); +} + +uint8_t Diibugger::getCrashType() { + return crashType; +} + +void Diibugger::cmd_close() { + //Remove all breakpoints + bpManager->RemoveAllBreakPoints(); + + //Make sure we're not stuck in an exception when the + //debugger disconnects without handling it + if (crashState == CRASH_STATE_BREAKPOINT) { + OSMessage message; + message.message = CLIENT_MESSAGE_CONTINUE; + OSSendMessage(&clientQueue, &message, OS_MESSAGE_FLAGS_BLOCKING); + //Wait until execution is resumed before installing the OSFatal crash handler + while (crashState != CRASH_STATE_NONE) { + OSSleepTicks(100000); + } + } + + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_DSI, DSIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_ISI, ISIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_PROGRAM, ProgramHandler_Fatal); +} + +void Diibugger::cmd_read(uint32_t addr, uint32_t num) { + //TODO +} + +void Diibugger::cmd_write(uint32_t addr, uint32_t num) { + //TODO +} + +void Diibugger::cmd_write_code(uint32_t addr, uint32_t instr) { + //Make sure we don't overwrite breakpoint traps + breakpoint *bp = bpManager->GetBreakPoint(addr, BREAKPOINT_LIST_SIZE); + if (bp) { + bp->instruction = instr; + } else { + WriteCode(addr, instr); + } +} + +void Diibugger::cmd_get_thread_list(char * buffer, uint32_t * buffer_size) { + OSThread *currentThread = OSGetCurrentThread(); + OSThread *iterThread = currentThread; + OSThreadLink threadLink; + do { //Loop previous threads + *buffer_size += PushThread(buffer, *buffer_size, iterThread); + OSGetActiveThreadLink(iterThread, &threadLink); + iterThread = threadLink.prev; + } while (iterThread); + + OSGetActiveThreadLink(currentThread, &threadLink); + iterThread = threadLink.next; + while (iterThread) { //Loop next threads + *buffer_size += PushThread(buffer, *buffer_size, iterThread); + OSGetActiveThreadLink(iterThread, &threadLink); + iterThread = threadLink.next; + } +} + +void Diibugger::cmd_push_message(OSMessage * message) { + OSSendMessage(&clientQueue, message, OS_MESSAGE_FLAGS_BLOCKING); +} + +void Diibugger::cmd_get_messages(OSMessage * messages, uint32_t * count) { + OSMessage message; + + while (OSReceiveMessage(&serverQueue, &message, OS_MESSAGE_FLAGS_NONE)) { + memcpy(&messages[*count],&message,sizeof(OSMessage)); + (*count)++; + } +} + +void Diibugger::cmd_get_stack_trace(uint32_t* stacktrace, uint32_t* index) { + uint32_t sp = crashContext.gpr[1]; + while (isValidStackPtr(sp)) { + sp = *(uint32_t *)sp; + if (!isValidStackPtr(sp)) { + break; + } + + stacktrace[*index] = *(uint32_t *)(sp + 4); + (*index)++; + } +} + +void Diibugger::cmd_poke_registers(uint8_t* gpr, uint8_t* fpr) { + memcpy((uint8_t*)&crashContext.gpr,gpr,4*32); + memcpy((uint8_t*)&crashContext.fpr,fpr,8*32); +} + +void Diibugger::cmd_toggle_breakpoint(uint32_t address) { + breakpoint *bp = bpManager->GetBreakPoint(address, BREAKPOINT_LIST_SIZE_USABLE); + if (bp) { + WriteCode(address, bp->instruction); + bp->address = 0; + bp->instruction = 0; + } else { + bp = bpManager->GetFreeBreakPoint(); + bp->address = address; + bp->instruction = *(uint32_t *)address; + WriteCode(address, TRAP); + } +} + +void Diibugger::cmd_get_module_name(char * name, int32_t * length) { + OSDynLoad_GetModuleName((OSDynLoad_Module) -1, name, length); +} + +void Diibugger::cmd_send_file_message(OSMessage * message) { + //OSSendMessage(&fileQueue, message, OS_MESSAGE_BLOCK); +} + +void Diibugger::restoreInstructionForBreakPointsInRange(uint32_t addr, uint32_t range){ + bpManager->restoreInstructionForBreakPointsInRange(addr,range); +} + +void Diibugger::restoreTRAPForBreakPointsInRange(uint32_t addr, uint32_t range){ + bpManager->restoreTRAPForBreakPointsInRange(addr,range); +} diff --git a/src/diibugger/Diibugger.hpp b/src/diibugger/Diibugger.hpp new file mode 100644 index 0000000..9c04624 --- /dev/null +++ b/src/diibugger/Diibugger.hpp @@ -0,0 +1,112 @@ +#ifndef _DIIBUGGER_H_ +#define _DIIBUGGER_H_ + +#include "DiibuggerTCPServer.hpp" +#include "BreakPointManager.hpp" +#include "common/diibugger_defs.h" +#include + +class Diibugger { +public: + static Diibugger *getInstance() { + if(!instance){ + instance = new Diibugger(); + } + return instance; + } + + static void destroyInstance() { + if(instance) { + delete instance; + instance = NULL; + } + } + + void init(); + + void startTCPServer() { + if(tcpServer != NULL) { + return; + } + tcpServer = new DiibuggerTCPServer(1559,28); + } + + void stopTCPServer() { + delete tcpServer; + tcpServer = NULL; + } + + FSClient* getFileClient() { + return fileClient; + } + + FSCmdBlock* getFileBlock() { + return fileCMDBlock; + } + + OSContext * getCrashContext(); + + uint8_t getCrashType(); + + void cmd_close(); + + void cmd_read(uint32_t addr, uint32_t num); + + void cmd_write(uint32_t addr, uint32_t num); + + void cmd_write_code(uint32_t addr, uint32_t instr); + + void cmd_get_thread_list(char * buffer, uint32_t * buffer_size); + + void cmd_push_message(OSMessage * message); + + void cmd_get_messages(OSMessage * messages, uint32_t * count); + + void cmd_get_stack_trace(uint32_t* stacktrace, uint32_t* index); + + void cmd_poke_registers(uint8_t* gpr, uint8_t* fpr); + + void cmd_toggle_breakpoint(uint32_t address); + + void cmd_get_module_name(char * name, int32_t * length); + + void cmd_send_file_message(OSMessage * message); + + void HandleProgram(); + + bool handle_crash(uint32_t type, void * handler, OSContext * context); + + void ReportCrash(uint32_t msg); + + void restoreInstructionForBreakPointsInRange(uint32_t addr, uint32_t range); + + void restoreTRAPForBreakPointsInRange(uint32_t addr, uint32_t range); + +private: + Diibugger(); + + ~Diibugger(); + + OSMessageQueue serverQueue; + OSMessageQueue clientQueue; + OSMessage serverMessages[MESSAGE_COUNT]; + OSMessage clientMessages[MESSAGE_COUNT]; + OSContext crashContext; + uint32_t crashType; + + uint8_t crashState; + + uint8_t stepState; + + uint32_t stepSource; + + FSCmdBlock* fileCMDBlock = NULL; + FSClient* fileClient = NULL; + + static Diibugger *instance; + + DiibuggerTCPServer* tcpServer = NULL; + BreakPointManager* bpManager = NULL; +}; + +#endif //_DIIBUGGER_H_ diff --git a/src/diibugger/DiibuggerTCPServer.cpp b/src/diibugger/DiibuggerTCPServer.cpp new file mode 100644 index 0000000..32d3c93 --- /dev/null +++ b/src/diibugger/DiibuggerTCPServer.cpp @@ -0,0 +1,229 @@ +#include "DiibuggerTCPServer.hpp" +#include +#include +#include + +#include +#include +#include +#include "utils.h" +#include "handler.h" +#include "Diibugger.hpp" + +DiibuggerTCPServer::DiibuggerTCPServer(int32_t port,int32_t priority):TCPServer(port,priority) { + DEBUG_FUNCTION_LINE("Init DiibuggerTCPServer\n"); +} + +DiibuggerTCPServer::~DiibuggerTCPServer() { + +} + +BOOL DiibuggerTCPServer::acceptConnection() { + DEBUG_FUNCTION_LINE("Set debug exceptions\n"); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_DSI, DSIHandler_Debug); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_ISI, ISIHandler_Debug); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_PROGRAM, ProgramHandler_Debug); + DEBUG_FUNCTION_LINE("Let's accept the connection\n"); + + return true; +} + +void DiibuggerTCPServer::onConnectionClosed() { + DEBUG_FUNCTION_LINE("Connection closed\n"); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_DSI, DSIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_ISI, ISIHandler_Fatal); + OSSetExceptionCallbackEx(OS_EXCEPTION_MODE_GLOBAL_ALL_CORES, OS_EXCEPTION_TYPE_PROGRAM, ProgramHandler_Fatal); +} + +BOOL DiibuggerTCPServer::whileLoop() { + int32_t cmd; + volatile int32_t clientfd = getClientFD(); + Diibugger* diibugger = Diibugger::getInstance(); + while (true) { + if(shouldExit()) { + break; + } + + cmd = checkbyte(clientfd); + if (cmd < 0) { + if(socketlasterr() != 6) { + return false; + } + OSSleepTicks(OSMicrosecondsToTicks(1000)); + continue; + } + + if (cmd == 1) { //Close + DEBUG_FUNCTION_LINE("Close!\n"); + diibugger->cmd_close(); + break; + } else if (cmd == 2) { //Read + DEBUG_FUNCTION_LINE("Read!\n"); + uint32_t addr = recvword(clientfd); + uint32_t num = recvword(clientfd); + + // Remove the TRAP instructions. + diibugger->restoreInstructionForBreakPointsInRange(addr,num); + + sendwait(clientfd, (void *)addr, num); + + // Restore the TRAP instructions. + diibugger->restoreTRAPForBreakPointsInRange(addr,num); + + } else if (cmd == 3) { //Write + DEBUG_FUNCTION_LINE("Write!\n"); + uint32_t addr = recvword(clientfd); + uint32_t num = recvword(clientfd); + + //diibugger->cmd_write(addr,num); + recvwait(clientfd, (uint8_t *)addr, num); + } else if (cmd == 4) { //Write code + DEBUG_FUNCTION_LINE("Write code!\n"); + uint32_t addr = recvword(clientfd); + uint32_t instr = recvword(clientfd); + + diibugger->cmd_write_code(addr,instr); + } else if (cmd == 5) { //Get thread list + DEBUG_FUNCTION_LINE("Get thread list!\n"); + //Might need OSDisableInterrupts here? + char buffer[0x1000]; //This should be enough + uint32_t buffer_size = 0; + + diibugger->cmd_get_thread_list(buffer, &buffer_size); + + sendwait(clientfd, &buffer_size, 4); + sendwait(clientfd, buffer, buffer_size); + } else if (cmd == 6) { //Push message + DEBUG_FUNCTION_LINE("Push message \n"); + OSMessage message; + recvwait(clientfd, (uint8_t*)&message, sizeof(OSMessage)); + diibugger->cmd_push_message(&message); + } else if (cmd == 7) { //Get messages + DEBUG_FUNCTION_LINE("Get messages!\n"); + OSMessage messages[10]; + uint32_t count = 0; + + diibugger->cmd_get_messages(messages,&count); + + sendwait(clientfd, &count, 4); + for (uint32_t i = 0; i < count; i++) { + sendwait(clientfd, &messages[i], sizeof(OSMessage)); + if (messages[i].args[0]) { + sendwait(clientfd, (void *)messages[i].args[0], messages[i].args[1]); + } + } + } else if (cmd == 8) { //Get stack trace + DEBUG_FUNCTION_LINE("Get stack trace\n"); + uint32_t index = 0; + uint32_t stackTrace[30]; + + diibugger->cmd_get_stack_trace(stackTrace, &index); + + sendwait(clientfd, &index, 4); + sendwait(clientfd, stackTrace, index * 4); + } else if (cmd == 9) { //Poke registers + DEBUG_FUNCTION_LINE("Poke registers!\n"); + uint8_t gpr[4*32]; + uint8_t fpr[8*32]; + + recvwait(clientfd, (uint8_t*)gpr, 4 * 32); + recvwait(clientfd, (uint8_t*)fpr, 8 * 32); + + diibugger->cmd_poke_registers(gpr,fpr); + } else if (cmd == 10) { //Toggle breakpoint + DEBUG_FUNCTION_LINE("Toggle breakpoint!\n"); + uint32_t address = recvword(clientfd); + diibugger->cmd_toggle_breakpoint(address); + } else if (cmd == 11) { //Read directory + DEBUG_FUNCTION_LINE("Read directory!\n"); + char path[640] = {0}; //512 + 128 + uint32_t pathlen = recvword(clientfd); + if (pathlen < 640) { + recvwait(clientfd, (uint8_t*)path, pathlen); + FSStatus error; + FSDirectoryHandle handle; + FSDirectoryEntry entry; + error = FSOpenDir(diibugger->getFileClient(), diibugger->getFileBlock(), path, &handle, -1); + + while (FSReadDir(diibugger->getFileClient(), diibugger->getFileBlock(), handle, &entry, -1) == 0) { + int32_t namelen = strlen(entry.name); + sendwait(clientfd, &namelen, 4); + sendwait(clientfd, &entry.info.flags, 4); + if (!(entry.info.flags & 0x80000000)) { + sendwait(clientfd, &entry.info.size, 4); + } + sendwait(clientfd, &entry.name, namelen); + } + + error = FSCloseDir(diibugger->getFileClient(), diibugger->getFileBlock(), handle, -1); + } + int32_t terminator = 0; + sendwait(clientfd, &terminator, 4); + } else if (cmd == 12) { //Dump file + DEBUG_FUNCTION_LINE("Dump file!\n"); + char path[640] = {0}; + uint32_t pathlen = recvword(clientfd); + if (pathlen < 640) { + recvwait(clientfd, (uint8_t*)path, pathlen); + + FSStatus error; + FSFileHandle handle; + error = FSOpenFile(diibugger->getFileClient(), diibugger->getFileBlock(), path, "r", &handle, -1); + //CHECK_ERROR(error, "FSOpenFile"); + + FSStat stat; + error = FSGetStatFile(diibugger->getFileClient(), diibugger->getFileBlock(), handle, &stat, -1); + //CHECK_ERROR(error, "FSGetStatFile"); + + uint32_t size = stat.size; + sendwait(clientfd, &stat.size, 4); + + uint8_t *buffer = (uint8_t *)memalign(0x40,0x20000); + + uint32_t read = 0; + while (read < size) { + FSStatus num = FSReadFile(diibugger->getFileClient(), diibugger->getFileBlock(), buffer, 1, 0x20000, handle, 0, -1); + //CHECK_ERROR(num, "FSReadFile"); + read += num; + + sendwait(clientfd, buffer, num); + } + + error = FSCloseFile(diibugger->getFileClient(), diibugger->getFileBlock(), handle, -1); + //CHECK_ERROR(error, "FSCloseFile"); + + free(buffer); + } else { + DEBUG_FUNCTION_LINE("pathlen >= 640"); + } + } else if (cmd == 13) { //Get module name + DEBUG_FUNCTION_LINE("Get module name!\n"); + char name[100] = {0}; + int32_t length = 100; + + diibugger->cmd_get_module_name(name, &length); + + length = strlen(name); + sendwait(clientfd, &length, 4); + sendwait(clientfd, name, length); + } else if (cmd == 14) { //Set patch files + //We don't want this anymore... + diibugger->cmd_close(); + } else if (cmd == 15) { //Send file message + //We don't want this anymore... + diibugger->cmd_close(); + } else if (cmd == 16) { //Clear patch files + //We don't want this anymore... + diibugger->cmd_close(); + } else if (cmd == 17) { //Get persistent id + //uint32_t persistentId = 1337;//diibugger->GetPersistentId(); + //sendwait(clientfd, &persistentId, 4); + diibugger->cmd_close(); + } else { + return false; + } + } + DEBUG_FUNCTION_LINE("End of whileLoop!\n"); + return true; +} + diff --git a/src/diibugger/DiibuggerTCPServer.hpp b/src/diibugger/DiibuggerTCPServer.hpp new file mode 100644 index 0000000..5f6b028 --- /dev/null +++ b/src/diibugger/DiibuggerTCPServer.hpp @@ -0,0 +1,20 @@ +#ifndef _DIIBUGGER_TCPSERVER_H_ +#define _DIIBUGGER_TCPSERVER_H_ + +#include +#include +#include + +class DiibuggerTCPServer: TCPServer { +public: + DiibuggerTCPServer(int32_t port, int32_t priority); + ~DiibuggerTCPServer(); +private: + virtual BOOL whileLoop(); + + virtual BOOL acceptConnection(); + + virtual void onConnectionClosed(); +}; + +#endif //_DIIBUGGER_TCPSERVER_H_ diff --git a/src/diibugger/handler.cpp b/src/diibugger/handler.cpp new file mode 100644 index 0000000..18b4f71 --- /dev/null +++ b/src/diibugger/handler.cpp @@ -0,0 +1,201 @@ +#include +#include +#include "Diibugger.hpp" +#include "diibugger/utils.h" +#include "handler.h" +#include +#include + +bool Diibugger::handle_crash(uint32_t type, void * handler,OSContext * context) { + // This is setting the crash context so we can use it in the client! + memcpy((char *)&crashContext, (const char *)context, sizeof(OSContext)); + crashType = type; + context->srr0 = (uint32_t)handler; + return true; +} + +void FatalCrashHandler() { + OSContext * crashContext = Diibugger::getInstance()->getCrashContext(); + uint8_t crashType = Diibugger::getInstance()->getCrashType(); + char buffer[0x400]; + snprintf(buffer, 0x400, + "An exception of type %i occurred:\n\n" + "r0: %08X r1: %08X r2: %08X r3: %08X r4: %08X\n" + "r5: %08X r6: %08X r7: %08X r8: %08X r9: %08X\n" + "r10:%08X r11:%08X r12:%08X r13:%08X r14:%08X\n" + "r15:%08X r16:%08X r17:%08X r18:%08X r19:%08X\n" + "r20:%08X r21:%08X r22:%08X r23:%08X r24:%08X\n" + "r25:%08X r26:%08X r27:%08X r28:%08X r29:%08X\n" + "r30:%08X r31:%08X\n\n" + "CR: %08X LR: %08X CTR:%08X XER:%08X\n" + "EX0:%08X EX1:%08X SRR0:%08X SRR1:%08X\n", + (unsigned int) crashType, + (unsigned int) crashContext->gpr[0], + (unsigned int) crashContext->gpr[1], + (unsigned int) crashContext->gpr[2], + (unsigned int) crashContext->gpr[3], + (unsigned int) crashContext->gpr[4], + (unsigned int) crashContext->gpr[5], + (unsigned int) crashContext->gpr[6], + (unsigned int) crashContext->gpr[7], + (unsigned int) crashContext->gpr[8], + (unsigned int) crashContext->gpr[9], + (unsigned int) crashContext->gpr[10], + (unsigned int) crashContext->gpr[11], + (unsigned int) crashContext->gpr[12], + (unsigned int) crashContext->gpr[13], + (unsigned int) crashContext->gpr[14], + (unsigned int) crashContext->gpr[15], + (unsigned int) crashContext->gpr[16], + (unsigned int) crashContext->gpr[17], + (unsigned int) crashContext->gpr[18], + (unsigned int) crashContext->gpr[19], + (unsigned int) crashContext->gpr[20], + (unsigned int) crashContext->gpr[21], + (unsigned int) crashContext->gpr[22], + (unsigned int) crashContext->gpr[23], + (unsigned int) crashContext->gpr[24], + (unsigned int) crashContext->gpr[25], + (unsigned int) crashContext->gpr[26], + (unsigned int) crashContext->gpr[27], + (unsigned int) crashContext->gpr[28], + (unsigned int) crashContext->gpr[29], + (unsigned int) crashContext->gpr[30], + (unsigned int) crashContext->gpr[31], + (unsigned int) crashContext->cr, + (unsigned int) crashContext->lr, + (unsigned int) crashContext->ctr, + (unsigned int) crashContext->xer, + (unsigned int) crashContext->__unk1[0], + (unsigned int) crashContext->__unk1[4], + (unsigned int) crashContext->srr0, + (unsigned int) crashContext->srr1 + ); + + OSFatal(buffer); +} + +BOOL DSIHandler_Fatal(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_DSI, (void*)FatalCrashHandler,context); +} +BOOL ISIHandler_Fatal(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_ISI, (void*)FatalCrashHandler,context); +} +BOOL ProgramHandler_Fatal(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_PROGRAM, (void*)FatalCrashHandler,context); +} + +void HandleDSI() { + Diibugger::getInstance()->ReportCrash((uint32_t) SERVER_MESSAGE_DSI); +} + +void HandleISI() { + Diibugger::getInstance()->ReportCrash((uint32_t) SERVER_MESSAGE_ISI); +} + +void HandleProgram() { + Diibugger::getInstance()->HandleProgram(); +} + +void Diibugger::HandleProgram() { + //DEBUG_FUNCTION_LINE("HandleProgram\n"); + //Check if the exception was caused by a breakpoint + if (!(crashContext.srr1 & 0x20000)) { + //DEBUG_FUNCTION_LINE("Was caused by a breakpoint!\n"); + ReportCrash((uint32_t) SERVER_MESSAGE_PROGRAM); + } + + //A breakpoint is done by replacing an instruction by a "trap" instruction + //When execution is continued this instruction still has to be executed + //So we have to put back the original instruction, execute it, and insert + //the breakpoint again + + //We can't simply use the BE and SE bits in the MSR without kernel patches + //However, since they're optional, they might not be implemented on the Wii U + //Patching the kernel is not really worth the effort in this case, so I'm + //simply placing a trap at the next instruction + + //Special case, the twu instruction at the start + uint32_t entryPoint = 0x1005E040; //!TODO!!! + //log_printf("crashContext.srr0 = %08X\n",crashContext.srr0); + if (crashContext.srr0 == (uint32_t)entryPoint + 0x48) { + WriteCode(crashContext.srr0, 0x60000000); //nop + } + + if (stepState == STEP_STATE_RUNNING || stepState == STEP_STATE_STEPPING) { + crashState = CRASH_STATE_BREAKPOINT; + + OSMessage message; + message.message = (void *) SERVER_MESSAGE_PROGRAM; + message.args[0] = (uint32_t)&crashContext; + message.args[1] = sizeof(crashContext); + OSSendMessage(&serverQueue, &message, OS_MESSAGE_FLAGS_BLOCKING); + //DEBUG_FUNCTION_LINE("Added crash context into the serverqueue. Message %08X\n",message.message); + + OSReceiveMessage(&clientQueue, &message, OS_MESSAGE_FLAGS_BLOCKING); + + //DEBUG_FUNCTION_LINE("Client message %08X\n",(uint32_t)message.message); + + if (stepState == STEP_STATE_STEPPING) { + bpManager->RestoreStepInstructions(stepSource); + } + + breakpoint *bp = bpManager->GetBreakPoint(crashContext.srr0, BREAKPOINT_LIST_SIZE_USABLE); + if (bp) { + WriteCode(bp->address, bp->instruction); + } + + //A conditional branch can end up at two places, depending on + //wheter it's taken or not. To work around this, I'm using a + //second, optional address. This is less work than writing code + //that checks the condition registers. + if ((uint32_t)message.message == CLIENT_MESSAGE_STEP_OVER) { + bpManager->PredictStepAddresses(&crashContext, true); + } else { + bpManager->PredictStepAddresses(&crashContext, false); + } + + bpManager->writeTRAPInstructionToSteps(); + + stepSource = crashContext.srr0; + + if ((uint32_t)message.message == CLIENT_MESSAGE_CONTINUE) { + //DEBUG_FUNCTION_LINE("New stepstate = STEP_STATE_CONTINUE\n"); + stepState = STEP_STATE_CONTINUE; + } else { + //DEBUG_FUNCTION_LINE("New stepstate = STEP_STATE_STEPPING\n"); + stepState = STEP_STATE_STEPPING; + } + } else if (stepState == STEP_STATE_CONTINUE) { + //DEBUG_FUNCTION_LINE("Calling RestoreStepInstructions\n"); + bpManager->RestoreStepInstructions(stepSource); + //DEBUG_FUNCTION_LINE("Setting stepState = STEP_STATE_RUNNING\n"); + stepState = STEP_STATE_RUNNING; + //DEBUG_FUNCTION_LINE("Setting crashState = CRASH_STATE_NONE\n"); + crashState = CRASH_STATE_NONE; + } + OSLoadContext(&crashContext); //Resume execution +} + +BOOL DSIHandler_Debug(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_DSI, (void *) HandleDSI,context); +} +BOOL ISIHandler_Debug(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_ISI, (void *) HandleISI,context); +} +BOOL ProgramHandler_Debug(OSContext *context) { + return Diibugger::getInstance()->handle_crash(OS_EXCEPTION_TYPE_PROGRAM, (void *) HandleProgram,context); +} + +void Diibugger::ReportCrash(uint32_t msg) { + crashState = CRASH_STATE_UNRECOVERABLE; + + OSMessage message; + message.message = (void*) msg; + message.args[0] = (uint32_t)&crashContext; + message.args[1] = sizeof(crashContext); + OSSendMessage(&serverQueue, &message, OS_MESSAGE_FLAGS_BLOCKING); + while (true) { + OSSleepTicks(1000000); + } +} diff --git a/src/diibugger/handler.h b/src/diibugger/handler.h new file mode 100644 index 0000000..b89c03c --- /dev/null +++ b/src/diibugger/handler.h @@ -0,0 +1,38 @@ +#ifndef _DIIBUGGER_DEBUGGER_H_ +#define _DIIBUGGER_DEBUGGER_H_ + +#include "common/diibugger_defs.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif +BOOL ProgramHandler_Initialize(OSContext *context); + +BOOL DSIHandler_Debug(OSContext *context); + +BOOL ISIHandler_Debug(OSContext *context); + +BOOL ProgramHandler_Debug(OSContext *context); + +void HandleProgram(); + +void ReportCrash(uint32_t msg); + +void HandleDSI(); + +void HandleISI(); + +BOOL DSIHandler_Fatal(OSContext *context); + +BOOL ISIHandler_Fatal(OSContext *context); + +BOOL ProgramHandler_Fatal(OSContext *context); + +void FatalCrashHandler(); + +#ifdef __cplusplus +} +#endif + +#endif /* _DIIBUGGER_DEBUGGER_H_ */ diff --git a/src/diibugger/utils.cpp b/src/diibugger/utils.cpp new file mode 100644 index 0000000..4be1621 --- /dev/null +++ b/src/diibugger/utils.cpp @@ -0,0 +1,43 @@ +#include +#include + +#include +#include "diibugger/utils.h" +#include +#include + +void WriteCode(uint32_t address, uint32_t instr) { + uint32_t replace_instr = instr; + + ICInvalidateRange(&replace_instr, 4); + DCFlushRange(&replace_instr, 4); + + WUPS_KernelCopyDataFunction((uint32_t)OSEffectiveToPhysical((uint32_t) address), (uint32_t)OSEffectiveToPhysical((uint32_t)&replace_instr), 4); + ICInvalidateRange((void*)(address), 4); + DCFlushRange((void*)(address), 4); + + //DEBUG_FUNCTION_LINE("Did KernelCopyData. %08X = %08X\n",address, *(uint32_t*)address); +} + +bool isValidStackPtr(uint32_t sp) { + return sp >= 0x10000000 && sp < 0x20000000; +} + +uint32_t PushThread(char *buffer, uint32_t offset, OSThread *thread) { + *(uint32_t *)(buffer + offset) = OSGetThreadAffinity(thread); + *(uint32_t *)(buffer + offset + 4) = OSGetThreadPriority(thread); + *(uint32_t *)(buffer + offset + 8) = (uint32_t)thread->stackStart; + *(uint32_t *)(buffer + offset + 12) = (uint32_t)thread->stackEnd; + *(uint32_t *)(buffer + offset + 16) = (uint32_t)thread->entryPoint; + + const char *threadName = OSGetThreadName(thread); + if (threadName) { + uint32_t namelen = strlen(threadName); + *(uint32_t *)(buffer + offset + 20) = namelen; + memcpy(buffer + offset + 24, threadName, namelen); + return 24 + namelen; + } + + *(uint32_t *)(buffer + offset + 20) = 0; + return 24; +} diff --git a/src/diibugger/utils.h b/src/diibugger/utils.h new file mode 100644 index 0000000..a13c7cb --- /dev/null +++ b/src/diibugger/utils.h @@ -0,0 +1,41 @@ +#ifndef _DIIBUGGER_UTILS_H_ +#define _DIIBUGGER_UTILS_H_ + +#include +#include +#include "common/diibugger_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + \brief Writes an instruction to a given address, bypassing any kernel checks. + Caution: if the given address needs to be mappable to physical space via OSEffectiveToPhysical + + \param address: The address where the value will be written. + \param instr: The value that will be written to the given address. +**/ +void WriteCode(uint32_t address, uint32_t instr); + +/** + \brief Checks if the given address is a valid stack pointer + \return Return true if it's a valid stack pointer, false otherwise. +**/ +bool isValidStackPtr(uint32_t sp); + +/** + \brief Pushes threads information into an existing buffer with thread information. + The result will be sent to the client. + + \param buffer: An existing buffer where the result will be stored + \param offset: The offset at where the information of the given thread should be stored + \param thread: A pointer to the thread whose information should be stored into the buffer. +**/ +uint32_t PushThread(char *buffer, uint32_t offset, OSThread *thread); + +#ifdef __cplusplus +} +#endif + +#endif /* _DIIBUGGER_UTILS_H_ */ diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..d7f7672 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +#include "diibugger/DiibuggerTCPServer.hpp" +#include "diibugger/Diibugger.hpp" + +WUPS_FS_ACCESS() + +WUPS_ALLOW_KERNEL() + +// Mandatory plugin information. +WUPS_PLUGIN_NAME("Diibugger"); +WUPS_PLUGIN_DESCRIPTION("Description"); +WUPS_PLUGIN_VERSION("v1.0"); +WUPS_PLUGIN_AUTHOR("Kinnay, jam1garner, Maschell"); +WUPS_PLUGIN_LICENSE("GPL"); + +// Called whenever an application was started. +ON_APPLICATION_START(args){ + if(!args.kernel_access){ + OSFatal("The diibugger plugin needs kernel access!"); + } + + socket_lib_init(); + log_init(); + + DEBUG_FUNCTION_LINE("ON_APPLICATION_START\n"); + + Diibugger::getInstance(); +} + +ON_APP_STATUS_CHANGED(status){ + if(status == WUPS_APP_STATUS_CLOSED){ + Diibugger::destroyInstance(); + } +}