[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs     diff=csharp\n\n# Standard to msysgit\n*.doc\t diff=astextplain\n*.DOC\t diff=astextplain\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n*.dot  diff=astextplain\n*.DOT  diff=astextplain\n*.pdf  diff=astextplain\n*.PDF\t diff=astextplain\n*.rtf\t diff=astextplain\n*.RTF\t diff=astextplain\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build hiyaCFW\n\non:\n  push:\n    branches: [\"*\"]\n    paths-ignore:\n      - 'README.md'\n  pull_request:\n    branches: [\"*\"]\n    paths-ignore:\n      - 'README.md'\n  release:\n    types: [created]\n  workflow_dispatch:\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    container: devkitpro/devkitarm:20241104\n    name: Build with Docker using devkitARM\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v4\n        with:\n          submodules: recursive\n      - name: Install tools\n        run: |\n          sudo apt-get update\n          sudo apt-get install p7zip-full python -y\n      - name: Silence all git safe directory warnings\n        run: |\n          git config --system --add safe.directory '*'\n          git fetch --prune --unshallow --tags\n      - name: Build\n        id: build\n        run: |\n          make\n      - name: Pack 7z for nightly\n        if: ${{ !startsWith(github.ref, 'refs/tags') }}\n        run: |\n          mkdir hiyaCFW\n          cp hiya.dsi hiyaCFW\n          7z a hiyaCFW.7z hiyaCFW\n      - name: Pack 7z for release\n        if: ${{ startsWith(github.ref, 'refs/tags') }}\n        run: |\n          mkdir \"for SDNAND SD card\"\n          cp hiya.dsi \"for SDNAND SD card\"\n          7z a template.7z \"for SDNAND SD card\"\n          mv template.7z hiyaCFW.7z\n      - name: Publish build to GH Actions\n        uses: actions/upload-artifact@main\n        with:\n          path: hiyaCFW.7z\n          name: build\n\n  # Only run this for non-PR jobs.\n  publish_build:\n    runs-on: ubuntu-latest\n    name: Publish build to release\n    if: ${{ success() && !startsWith(github.ref, 'refs/pull') }}\n    needs: build\n    steps:\n      - name: Download artifacts\n        uses: actions/download-artifact@main\n        with:\n          name: build\n          path: build\n      - name: Upload to ${{ github.repository }} release\n        if: ${{ startsWith(github.ref, 'refs/tags') }}\n        run: |\n          ID=$(jq --raw-output '.release.id' $GITHUB_EVENT_PATH)\n\n          for file in ${{ github.workspace }}/build/*; do\n            AUTH_HEADER=\"Authorization: token ${{ secrets.GITHUB_TOKEN }}\"\n            CONTENT_LENGTH=\"Content-Length: $(stat -c%s $file)\"\n            CONTENT_TYPE=\"Content-Type: application/7z-x-compressed\"\n            UPLOAD_URL=\"https://uploads.github.com/repos/${{ github.repository }}/releases/$ID/assets?name=$(basename $file)\"\n\n            curl -XPOST -H \"$AUTH_HEADER\" -H \"$CONTENT_LENGTH\" -H \"$CONTENT_TYPE\" --upload-file \"$file\" \"$UPLOAD_URL\"\n          done\n"
  },
  {
    "path": ".gitignore",
    "content": "*/build\n*.nds\n*.dsi\n*.cia\n*.elf\ndata/*\n*.DS_Store\n.vscode\narm9/include/version.h\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"libs/libslim\"]\n\tpath = libs/libslim\n\turl = https://github.com/DS-Homebrew/libslim.git\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#---------------------------------------------------------------------------------\n.SECONDARY:\n\nifeq ($(strip $(DEVKITARM)),)\n$(error \"Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM\")\nendif\n\nifneq (,$(shell which python3))\nPYTHON\t:= python3\nelse ifneq (,$(shell which python2))\nPYTHON\t:= python2\nelse ifneq (,$(shell which python))\nPYTHON\t:= python\nelse\n$(error \"Python not found in PATH, please install it.\")\nendif\n\nexport TARGET\t:=\t$(shell basename $(CURDIR))\nexport TOPDIR\t:=\t$(CURDIR)\n\n# specify a directory which contains the nitro filesystem\n# this is relative to the Makefile\nNITRO_FILES\t:=\n\n# These set the information text in the nds file\nGAME_ICON\t:= icon.bmp\nGAME_TITLE\t:= hiyaCFW\nGAME_SUBTITLE1\t:= CFW for Nintendo DSi\nGAME_SUBTITLE2\t:= made by Apache Thunder\n\ninclude $(DEVKITARM)/ds_rules\n\n.PHONY: bootloader checkarm7 checkarm9 clean libslim\n\n#---------------------------------------------------------------------------------\n# main targets\n#---------------------------------------------------------------------------------\nall: libslim bootloader checkarm7 checkarm9 $(TARGET).nds\n\n#---------------------------------------------------------------------------------\nbootloader:\n\t$(MAKE) -C bootloader \"EXTRA_CFLAGS= -DNO_DLDI\"\n\n#---------------------------------------------------------------------------------\ncheckarm7:\n\t$(MAKE) -C arm7\n\t\n#---------------------------------------------------------------------------------\ncheckarm9:\n\t$(MAKE) -C arm9\n\n#---------------------------------------------------------------------------------\n$(TARGET).nds\t: $(NITRO_FILES) arm7/$(TARGET).elf arm9/$(TARGET).elf\n\tndstool\t-c $(TARGET).nds -7 arm7/$(TARGET).elf -9 arm9/$(TARGET).elf -r9 00080002 \\\n\t\t\t-b $(GAME_ICON) \"$(GAME_TITLE);$(GAME_SUBTITLE1);$(GAME_SUBTITLE2)\" \\\n\t\t\t-g HIYA 01 \"HIYACFW\" -z 80040000 -u 00030004 $(_ADDFILES)\n\t$(PYTHON) fix_ndsheader.py $(TARGET).nds\n\tcp $(TARGET).nds hiya.dsi\n\n#---------------------------------------------------------------------------------\narm7/$(TARGET).elf:\n\t$(MAKE) -C arm7\n\t\n#---------------------------------------------------------------------------------\narm9/$(TARGET).elf:\n\t$(MAKE) -C arm9\n\n#---------------------------------------------------------------------------------\nclean:\n\t@echo clean ...\n\t@$(MAKE) -C arm9 clean\n\t@$(MAKE) -C arm7 clean\n\t@$(MAKE) -C bootloader clean\n\t@$(MAKE) -C libs/libslim clean\n\t@rm -f $(TARGET).nds $(TARGET).nds.orig.nds hiya.dsi\n\nlibslim:\n\t$(MAKE) -C libs/libslim/libslim\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"https://github.com/RocketRobz/hiyaCFW/blob/master/logo/logo.png\"><br>\n  <a href=\"https://gbatemp.net/threads/release-hiyacfw-worlds-first-nintendo-dsi-cfw.502631/\">\n   <img src=\"https://img.shields.io/badge/GBAtemp-Thread-blue.svg\" alt=\"GBAtemp Thread\">\n  </a>\n  <a href=\"https://discord.gg/fCzqcWteC4\">\n   <img src=\"https://img.shields.io/badge/Discord%20Server-%23other--nds--homebrew-green.svg\" alt=\"Discord Server\">\n  </a>\n  <a href=\"https://github.com/RocketRobz/hiyaCFW/actions?query=workflow%3A%22Build+hiyaCFW%22\">\n    <img src=\"https://github.com/RocketRobz/hiyaCFW/workflows/Build%20hiyaCFW/badge.svg\" alt=\"Build status on GitHub Actions\">\n  </a>\n</p>\n\nHiyaCFW is the world's FIRST Nintendo DSi CFW, made by the talented folks over on our Discord server.\n\n# Features\n\n- Run custom DSiWare\n- NAND to SD card redirection\n- Run NAND backups from any console\n- Replace the system menu with **TW**i**L**ight Menu++\n- Run blocked flashcards (such as R4 Ultra)\n- Remove region-locking\n- Change the NAND region (Not compatible with CHN and KOR NANDs)\n- Run 3DS-exclusive DSiWare (such as WarioWare Touched)\n- Custom splash screens\n\n# Compiling\n\nIn order to compile this on your own, you will need [devkitPro](https://devkitpro.org/)'s toolchains with the devkitARM, plus the necessary tools and libraries. `dkp-pacman` is included for easy installation of all components:\n\n```\n $ dkp-pacman -Syu devkitARM general-tools dstools ndstool libnds\n```\n\nOnce everything is downloaded and installed, `git clone` this repository, navigate to the folder, and run `make` to compile HiyaCFW. If there is an error, let us know.\n\n# Credits\n- Apache Thunder, NoCash, StuckPixel, Shutterbug2000, and Gericom.\n- Drenn: .bmp loading code from GameYob, for custom splash screens.\n- Pk11: .gif loading code for animated splash screens.\n- Rocket Robz: Logo graphic, settings screen, support for region-changing and any NAND backup.\n- devkitPro: For the majority of the base code like nds-bootloader which this loader uses.\n"
  },
  {
    "path": "arm7/Makefile",
    "content": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#---------------------------------------------------------------------------------\nifeq ($(strip $(DEVKITARM)),)\n$(error \"Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM\")\nendif\n\ninclude $(DEVKITARM)/ds_rules\n\n#---------------------------------------------------------------------------------\n# BUILD is the directory where object files & intermediate files will be placed\n# SOURCES is a list of directories containing source code\n# INCLUDES is a list of directories containing extra header files\n# DATA is a list of directories containing binary files\n# all directories are relative to this makefile\n#---------------------------------------------------------------------------------\nBUILD\t\t:=\tbuild\nSOURCES\t\t:=\tsource\nINCLUDES\t:=\tinclude build\nDATA\t\t:=\n\n#---------------------------------------------------------------------------------\n# options for code generation\n#---------------------------------------------------------------------------------\nARCH\t:=\t-march=armv4t -mthumb -mthumb-interwork\n\nCFLAGS\t:=\t-g -Wall -O2\\\n\t\t-mcpu=arm7tdmi -mtune=arm7tdmi -fomit-frame-pointer\\\n\t\t-ffast-math \\\n\t\t$(ARCH)\n\nCFLAGS\t+=\t$(INCLUDE) -DARM7\nCXXFLAGS\t:=\t$(CFLAGS) -fno-rtti -fno-exceptions -fno-rtti\n\n\nASFLAGS\t:=\t-g $(ARCH)\nLDFLAGS\t=\t-specs=ds_arm7.specs -g $(ARCH) -Wl,--nmagic -Wl,-Map,$(notdir $*).map\n\nLIBS\t:=\t-lnds7\n\n#---------------------------------------------------------------------------------\n# list of directories containing libraries, this must be the top level containing\n# include and lib\n#---------------------------------------------------------------------------------\nLIBDIRS\t:=\t$(LIBNDS)\n\n\n#---------------------------------------------------------------------------------\n# no real need to edit anything past this point unless you need to add additional\n# rules for different file extensions\n#---------------------------------------------------------------------------------\nifneq ($(BUILD),$(notdir $(CURDIR)))\n#---------------------------------------------------------------------------------\n\nexport ARM7ELF\t:=\t$(CURDIR)/$(TARGET).elf\nexport DEPSDIR\t:=\t$(CURDIR)/$(BUILD)\n\nexport VPATH\t:=\t$(foreach dir,$(SOURCES),$(CURDIR)/$(dir))\n\nCFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))\nCPPFILES\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))\nSFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))\nBINFILES\t:=\t$(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))\n\nexport OFILES\t:=\t$(addsuffix .o,$(BINFILES)) \\\n\t\t\t\t\t$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)\n\nexport INCLUDE\t:=\t$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \\\n\t\t\t\t\t$(foreach dir,$(LIBDIRS),-I$(dir)/include) \\\n\t\t\t\t\t-I$(CURDIR)/$(BUILD)\n\nexport LIBPATHS\t:=\t$(foreach dir,$(LIBDIRS),-L$(dir)/lib)\n\n#---------------------------------------------------------------------------------\n# use CXX for linking C++ projects, CC for standard C\n#---------------------------------------------------------------------------------\nifeq ($(strip $(CPPFILES)),)\n#---------------------------------------------------------------------------------\n\texport LD\t:=\t$(CC)\n#---------------------------------------------------------------------------------\nelse\n#---------------------------------------------------------------------------------\n\texport LD\t:=\t$(CXX)\n#---------------------------------------------------------------------------------\nendif\n#---------------------------------------------------------------------------------\n\n.PHONY: $(BUILD) clean\n\n#---------------------------------------------------------------------------------\n$(BUILD):\n\t@[ -d $@ ] || mkdir -p $@\n\t@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile\n\n#---------------------------------------------------------------------------------\nclean:\n\t@echo clean ...\n\t@rm -fr $(BUILD) *.elf\n\n#---------------------------------------------------------------------------------\nelse\n\nDEPENDS\t:=\t$(OFILES:.o=.d)\n\n#---------------------------------------------------------------------------------\n# main targets\n#---------------------------------------------------------------------------------\n$(ARM7ELF)\t:\t$(OFILES)\n\t@echo linking $(notdir $@)\n\t@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@\n\n#---------------------------------------------------------------------------------\n# you need a rule like this for each extension you use as binary data\n#---------------------------------------------------------------------------------\n%.bin.o\t:\t%.bin\n#---------------------------------------------------------------------------------\n\t@echo $(notdir $<)\n\t@$(bin2o)\n\n-include $(DEPENDS)\n\n#---------------------------------------------------------------------------------------\nendif\n#---------------------------------------------------------------------------------------\n"
  },
  {
    "path": "arm7/source/main.c",
    "content": "/*---------------------------------------------------------------------------------\n\ndefault ARM7 core\n\nCopyright (C) 2005 - 2010\n\tMichael Noland (joat)\n\tJason Rogers (dovoto)\n\tDave Murphy (WinterMute)\n\nThis software is provided 'as-is', without any express or implied\nwarranty.  In no event will the authors be held liable for any\ndamages arising from the use of this software.\n\nPermission is granted to anyone to use this software for any\npurpose, including commercial applications, and to alter it and\nredistribute it freely, subject to the following restrictions:\n\n1.\tThe origin of this software must not be misrepresented; you\n\tmust not claim that you wrote the original software. If you use\n\tthis software in a product, an acknowledgment in the product\n\tdocumentation would be appreciated but is not required.\n\n2.\tAltered source versions must be plainly marked as such, and\n\tmust not be misrepresented as being the original software.\n\n3.\tThis notice may not be removed or altered from any source\n\tdistribution.\n\n---------------------------------------------------------------------------------*/\n#include <nds.h>\n\n#define SD_IRQ_STATUS (*(vu32*)0x400481C)\n\nvoid VcountHandler() { inputGetAndSend(); }\n\nint main(void) {\n\n\tirqInit();\n\n\treadUserSettings();\n\n\tinitClockIRQ();\n\n\tfifoInit();\n\n\tSetYtrigger(80);\n\n\tinstallSystemFIFO();\n\n\tfifoSendValue32(FIFO_USER_01, SD_IRQ_STATUS);\n\tfifoSendValue32(FIFO_USER_02, i2cReadRegister(0x4A, 0x70));\n\n\tirqSet(IRQ_VCOUNT, VcountHandler);\n\n\tirqEnable( IRQ_VBLANK | IRQ_VCOUNT | IRQ_NETWORK );\n\n\twhile (1) {\n\t\t/* if (*(u32*)0x02FFFD0C == 0x54534453) { // 'SDST'\n\t\t\tfifoSendValue32(FIFO_USER_01, SD_IRQ_STATUS);\n\t\t\t*(u32*)0x02FFFD0C = 0;\n\t\t} */\n\t\tif(fifoCheckValue32(FIFO_USER_04)) {\n\t\t\tif(fifoCheckValue32(FIFO_USER_03)) {\n\t\t\t\ti2cWriteRegister(0x4A, 0x70, 0x01);\t// Bootflag = Warmboot/SkipHealthSafety\n\t\t\t}\n\t\t\t// After writing i2c, set FIFO_USER_04 back to 0 so arm7 doesn't repeatedly run i2c code.\n\t\t\tfifoSendValue32(FIFO_USER_04, 0);\n\t\t}\n\t\tswiWaitForVBlank();\n\t}\n}\n\n"
  },
  {
    "path": "arm9/Makefile",
    "content": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#---------------------------------------------------------------------------------\nifeq ($(strip $(DEVKITARM)),)\n$(error \"Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM\")\nendif\n\nexport LIBSLIM\t:=\t$(CURDIR)/../libs/libslim/libslim\n\ninclude $(DEVKITARM)/ds_rules\n\n#---------------------------------------------------------------------------------\n\n# If on a tagged commit, use the tag instead of the commit\nifneq ($(shell echo $(shell git tag -l --points-at HEAD) | head -c 1),)\nGIT_VER := $(shell git tag -l --points-at HEAD)\nelse\nGIT_VER := $(shell git describe --tags --match v[0-9]* --abbrev=7 | sed 's/-[0-9]*-g/-/')\nendif\n\n# Ensure version.h exists\nifeq (,$(wildcard include/version.h))\n$(shell mkdir -p include)\n$(shell touch include/version.h)\nendif\n\n# Print new version if changed\nifeq (,$(findstring $(GIT_VER), $(shell cat include/version.h)))\n$(shell printf \"#ifndef VERSION_HPP\\n#define VERSION_HPP\\n\\n#define VER_NUMBER \\\"$(GIT_VER)\\\"\\n\\n#endif\\n\" > include/version.h)\nendif\n\n#---------------------------------------------------------------------------------\n# BUILD is the directory where object files & intermediate files will be placed\n# SOURCES is a list of directories containing source code\n# INCLUDES is a list of directories containing extra header files\n# DATA is a list of directories containing binary files\n# GRAPHICS is a list of directories containing image files to be converted with grit\n# all directories are relative to this makefile\n#---------------------------------------------------------------------------------\nBUILD\t\t:=\tbuild\nSOURCES\t\t:=\tsource\nINCLUDES\t:=\tinclude\nDATA\t\t:=\t../data\nGRAPHICS\t:=\tgraphics\n\n#---------------------------------------------------------------------------------\n# options for code generation\n#---------------------------------------------------------------------------------\nARCH\t:=\t-mthumb -mthumb-interwork\n\nCFLAGS\t:=\t-g -Wall -O2\\\n\t\t\t-march=armv5te -mtune=arm946e-s -fomit-frame-pointer\\\n\t\t\t-ffast-math \\\n\t\t\t$(ARCH)\n\nCFLAGS\t+=\t$(INCLUDE) -DARM9\nCXXFLAGS\t:=\t$(CFLAGS) -fno-rtti -fno-exceptions\n\nASFLAGS\t:=\t-g $(ARCH) -march=armv5te -mtune=arm946e-s\n\nLDFLAGS\t=\t-specs=../ds_arm9_hiya.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)\n\n#---------------------------------------------------------------------------------\n# any extra libraries we wish to link with the project\n#---------------------------------------------------------------------------------\nLIBS\t:=\t-lslim -lnds9\n\n#---------------------------------------------------------------------------------\n# list of directories containing libraries, this must be the top level containing\n# include and lib\n#---------------------------------------------------------------------------------\nLIBDIRS\t:=\t$(LIBSLIM) $(LIBNDS)\n\n#---------------------------------------------------------------------------------\n# no real need to edit anything past this point unless you need to add additional\n# rules for different file extensions\n#---------------------------------------------------------------------------------\nifneq ($(BUILD),$(notdir $(CURDIR)))\n#---------------------------------------------------------------------------------\n\nexport ARM9ELF\t:=\t$(CURDIR)/$(TARGET).elf\nexport DEPSDIR\t:=\t$(CURDIR)/$(BUILD)\n\nexport VPATH\t:=\t$(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \\\n\t\t\t\t\t$(foreach dir,$(DATA),$(CURDIR)/$(dir)) \\\n\t\t\t\t\t$(foreach dir,$(GRAPHICS),$(CURDIR)/$(dir))\n\nCFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))\nCPPFILES\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))\nSFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))\nBINFILES\t:=\t$(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))\nBMPFILES\t:=\t$(foreach dir,$(GRAPHICS),$(notdir $(wildcard $(dir)/*.bmp)))\n\n#---------------------------------------------------------------------------------\n# use CXX for linking C++ projects, CC for standard C\n#---------------------------------------------------------------------------------\nifeq ($(strip $(CPPFILES)),)\n#---------------------------------------------------------------------------------\n\texport LD\t:=\t$(CC)\n#---------------------------------------------------------------------------------\nelse\n#---------------------------------------------------------------------------------\n\texport LD\t:=\t$(CXX)\n#---------------------------------------------------------------------------------\nendif\n#---------------------------------------------------------------------------------\n\nexport OFILES\t:=\t$(addsuffix .o,$(BINFILES)) \\\n\t\t\t\t\t$(BMPFILES:.bmp=.o) \\\n\t\t\t\t\t$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)\n\nexport INCLUDE\t:=\t$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \\\n\t\t\t\t\t$(foreach dir,$(LIBDIRS),-I$(dir)/include) \\\n\t\t\t\t\t-I$(CURDIR)/$(BUILD)\n\nexport LIBPATHS\t:=\t$(foreach dir,$(LIBDIRS),-L$(dir)/lib)\n\n.PHONY: $(BUILD) clean\n\n#---------------------------------------------------------------------------------\n$(BUILD):\n\t@[ -d $@ ] || mkdir -p $@\n\t@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile\n\n#---------------------------------------------------------------------------------\nclean:\n\t@echo clean ...\n\t@rm -fr $(BUILD) *.elf *.nds* *.bin\n\n#---------------------------------------------------------------------------------\nelse\n\n#---------------------------------------------------------------------------------\n# main targets\n#---------------------------------------------------------------------------------\n$(ARM9ELF)\t:\t$(OFILES)\n\t@echo linking $(notdir $@)\n\t@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@\n\n#---------------------------------------------------------------------------------\n# you need a rule like this for each extension you use as binary data\n#---------------------------------------------------------------------------------\n%.bin.o\t:\t%.bin\n#---------------------------------------------------------------------------------\n\t@echo $(notdir $<)\n\t@$(bin2o)\n\n#---------------------------------------------------------------------------------\n%.s %.h\t: %.bmp\n#---------------------------------------------------------------------------------\n\tgrit $< -gb -gB8 -gzl -gT! -fts -o$*\n\n-include $(DEPSDIR)/*.d\n\n#---------------------------------------------------------------------------------------\nendif\n#---------------------------------------------------------------------------------------\n"
  },
  {
    "path": "arm9/ds_arm9_hiya.mem",
    "content": "/*--------------------------------------------------------------------------------\n\tThis Source Code Form is subject to the terms of the Mozilla Public License,\n\tv. 2.0. If a copy of the MPL was not distributed with this file, You can\n\tobtain one at https://mozilla.org/MPL/2.0/.\n--------------------------------------------------------------------------------*/\nMEMORY {\n\tewram\t: ORIGIN = 0x02004000, LENGTH = 3M + 512K - 0x4000\n\tdtcm\t: ORIGIN = 0x0b000000, LENGTH = 16K\n\tvectors\t: ORIGIN = 0x01000000, LENGTH = 256\n\titcm\t: ORIGIN = 0x01000100, LENGTH = 32K - 256\n}\n"
  },
  {
    "path": "arm9/ds_arm9_hiya.specs",
    "content": "%rename link                old_link\n\n*link:\n%(old_link) -T ../ds_arm9_hiya.mem%s -T ds_arm9.ld%s --gc-sections\n\n*startfile:\nds_arm9_crt0%O%s crti%O%s crtbegin%O%s\n\n"
  },
  {
    "path": "arm9/source/bios_decompress_callback.c",
    "content": "/*\n    NitroHax -- Cheat tool for the Nintendo DS\n    Copyright (C) 2008  Michael \"Chishm\" Chisholm\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"bios_decompress_callback.h\"\n\nstatic int getSizeBiosCallback (uint8 * source, uint16 * dest, uint32 r2)\n{\n\t(void)dest;\n\t(void)r2;\n\treturn *((int*)source);\n}\n\nstatic uint8 readByteBiosCallback (uint8 * source)\n{\n\treturn *source;\n}\n\nTDecompressionStream decompressBiosCallback =\n{\n  getSizeBiosCallback,\n  (void*)0,\n  readByteBiosCallback\n} ;\n\n\n"
  },
  {
    "path": "arm9/source/bios_decompress_callback.h",
    "content": "/*\n    NitroHax -- Cheat tool for the Nintendo DS\n    Copyright (C) 2008  Michael \"Chishm\" Chisholm\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BIOS_DECOMPRESS_CALLBACK_H\n#define BIOS_DECOMPRESS_CALLBACK_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <nds/bios.h>\n#include <nds/ndstypes.h>\n\nextern TDecompressionStream decompressBiosCallback;\n\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // BIOS_DECOMPRESS_CALLBACK_H\n\n"
  },
  {
    "path": "arm9/source/dsi_only.cpp",
    "content": "#include <nds.h>\n#include \"dsiOnly_top.h\"\n#include \"dsiOnly_bot.h\"\n\nstatic void dsiOnly_setBrightness(u8 screen, s8 bright) {\n\tu16 mode = 1 << 14;\n\n\tif (bright < 0) {\n\t\tmode = 2 << 14;\n\t\tbright = -bright;\n\t}\n\tif (bright > 31) {\n\t\tbright = 31;\n\t}\n\t*(vu16*)(0x0400006C + (0x1000 * screen)) = bright + mode;\n}\n\nvoid dsiOnly(void) {\n\tif (isDSiMode()) return;\t// Proceed running on DSi\n\n\tdsiOnly_setBrightness(0, 31);\n\tdsiOnly_setBrightness(1, 31);\n\n\tvideoSetMode(MODE_4_2D);\n\tvideoSetModeSub(MODE_4_2D);\n\n\tvramSetBankA(VRAM_A_MAIN_BG);\n\tvramSetBankB(VRAM_B_MAIN_BG);\n\tvramSetBankC(VRAM_C_SUB_BG);\n\tvramSetBankD(VRAM_D_LCD);\n\n\t// Display DSi Only screen\n\tint bg3 = bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 1, 0);\n\tdecompress(dsiOnly_topBitmap, bgGetGfxPtr(bg3), LZ77Vram);\n\tfor (int i = 0; i < 16; i++) {\n\t\tBG_PALETTE[i] = dsiOnly_topPal[i];\n\t}\n\n\tint bg3sub = bgInitSub(3, BgType_Bmp8, BgSize_B8_256x256, 1, 0);\n\tdecompress(dsiOnly_botBitmap, bgGetGfxPtr(bg3sub), LZ77Vram);\n\tfor (int i = 0; i < 16; i++) {\n\t\tBG_PALETTE_SUB[i] = dsiOnly_botPal[i];\n\t}\n\n\tdsiOnly_setBrightness(0, 0);\n\tdsiOnly_setBrightness(1, 0);\n\n\twhile (1) {\n\t\tswiWaitForVBlank();\n\t}\n}"
  },
  {
    "path": "arm9/source/fileOperations.cpp",
    "content": "#include \"fileOperations.h\"\n#include <nds.h>\n#include <slim.h>\n#include <stdio.h>\n#include <dirent.h>\n#include <vector>\n\nusing namespace std;\n\noff_t getFileSize(const char *fileName)\n{\n\tFILE* fp = fopen(fileName, \"rb\");\n\toff_t fsize = 0;\n\tif (fp) {\n\t\tfseek(fp, 0, SEEK_END);\n\t\tfsize = ftell(fp);\t\t\t// Get source file's size\n\t\tfseek(fp, 0, SEEK_SET);\n\t\tfclose(fp);\n\t}\n\n\treturn fsize;\n}\n"
  },
  {
    "path": "arm9/source/fileOperations.h",
    "content": "#include <nds.h>\n\n#ifndef FILE_COPY\n#define FILE_COPY\n\nextern off_t getFileSize(const char *fileName);\n\n#endif // FILE_COPY"
  },
  {
    "path": "arm9/source/gif.cpp",
    "content": "#include \"gif.hpp\"\n#include \"lzw.hpp\"\n#include \"tonccpy.h\"\n\n#include <stdio.h>\n\nstd::vector<Gif *> Gif::_animating;\n\nvoid Gif::timerHandler(void) {\n\tfor (auto gif : _animating) {\n\t\tgif->displayFrame();\n\t}\n}\n\nvoid Gif::displayFrame(void) {\n\tif (_paused || ++_currentDelayProgress < _currentDelay)\n\t\treturn;\n\n\t_currentDelayProgress = 0;\n\t_waitingForInput = false;\n\n\tif (_currentFrame >= _frames.size()) {\n\t\t_currentFrame = 0;\n\t\t_currentLoop++;\n\t}\n\n\tif (_currentLoop > _loopCount) {\n\t\t_finished = true;\n\t\t_paused = true;\n\t\t_currentLoop = 0;\n\t\treturn;\n\t}\n\n\tFrame &frame = _frames[_currentFrame++];\n\n\tif (frame.hasGCE) {\n\t\t_currentDelay = frame.gce.delay;\n\t\tif (frame.gce.delay == 0) {\n\t\t\t_finished = true;\n\t\t\t_paused = true;\n\t\t} else if (frame.gce.userInputFlag) {\n\t\t\t_waitingForInput = true;\n\t\t}\n\t}\n\n\tstd::vector<u16> &colorTable = frame.descriptor.lctFlag ? frame.lct : _gct;\n\n\ttonccpy(_top ? BG_PALETTE : BG_PALETTE_SUB, colorTable.data(), colorTable.size() * 2);\n\n\t// Disposal method 2 = fill with bg color\n\tif (frame.gce.disposalMethod == 2)\n\t\ttoncset(_top ? BG_GFX : BG_GFX_SUB, header.bgColor, 256 * 192);\n\n\tif(_compressed) { // Was left compressed to be able to fit\n\t\tint x = 0, y = 0;\n\t\tu8 *dst = (u8*)(_top ? BG_GFX : BG_GFX_SUB) + (frame.descriptor.y + y + (192 - header.height) / 2) * 256 + frame.descriptor.x + (256 - header.width) / 2;\n\t\tu8 row[frame.descriptor.w];\n\t\tauto flush_fn = [&dst, &row, &x, &y, &frame](std::vector<u8>::const_iterator begin, std::vector<u8>::const_iterator end) {\n\t\t\tfor (; begin != end; ++begin) {\n\t\t\t\tif (!frame.gce.transparentColorFlag || *begin != frame.gce.transparentColor)\n\t\t\t\t\trow[x] = *begin;\n\t\t\t\telse\n\t\t\t\t\trow[x] = *(dst + x);\n\t\t\t\tx++;\n\t\t\t\tif (x >= frame.descriptor.w) {\n\t\t\t\t\ttonccpy(dst, row, frame.descriptor.w);\n\t\t\t\t\ty++;\n\t\t\t\t\tx = 0;\n\t\t\t\t\tdst += 256;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tLZWReader reader(frame.image.lzwMinimumCodeSize, flush_fn);\n\t\treader.decode(frame.image.imageData.begin(), frame.image.imageData.end());\n\t} else { // Already decompressed, just copy\n\t\tauto it = frame.image.imageData.begin();\n\t\tfor(int y = 0; y < frame.descriptor.h; y++) {\n\t\t\tu8 *dst = (u8*)(_top ? BG_GFX : BG_GFX_SUB) + (frame.descriptor.y + y + (192 - header.height) / 2) * 256 + frame.descriptor.x + (256 - header.width) / 2;\n\t\t\tu8 row[frame.descriptor.w];\n\t\t\tfor(int x = 0; x < frame.descriptor.w; x++, it++) {\n\t\t\t\tif (!frame.gce.transparentColorFlag || *it != frame.gce.transparentColor)\n\t\t\t\t\trow[x] = *it;\n\t\t\t\telse\n\t\t\t\t\trow[x] = *(dst + x);\n\t\t\t}\n\t\t\ttonccpy(dst, row, frame.descriptor.w);\n\t\t}\n\t}\n}\n\nbool Gif::load(const char *path, bool top, bool animate, bool forceDecompress) {\n\t_top = top;\n\n\tFILE *file = fopen(path, \"rb\");\n\tif (!file)\n\t\treturn false;\n\n\tif(forceDecompress) {\n\t\t_compressed = false;\n\t} else {\n\t\tfseek(file, 0, SEEK_END);\n\t\t_compressed = ftell(file) > (/*dsiFeatures()*/true ? 1 << 20 : 1 << 18); // Decompress files bigger than 1MiB (256KiB in DS Mode) while drawing\n\t\tfseek(file, 0, SEEK_SET);\n\t}\n\n\t// Reserve space for 2,000 frames\n\t_frames.reserve(2000);\n\n\t// Read header\n\tfread(&header, 1, sizeof(header), file);\n\n\t// Check that this is a GIF\n\tif (memcmp(header.signature, \"GIF87a\", sizeof(header.signature)) != 0 && memcmp(header.signature, \"GIF89a\", sizeof(header.signature)) != 0) {\n\t\tfclose(file);\n\t\treturn false;\n\t}\n\n\t// Load global color table\n\tif (header.gctFlag) {\n\t\tint numColors = (2 << header.gctSize);\n\n\t\t_gct = std::vector<u16>(numColors);\n\t\tfor (int i = 0; i < numColors; i++) {\n\t\t\tconst u8 r = fgetc(file);\n\t\t\tconst u8 g = fgetc(file);\n\t\t\tconst u8 b = fgetc(file);\n\n\t\t\tconst u16 green = (g >> 2) << 5;\n\t\t\t_gct[i] = r >> 3 | (b >> 3) << 10;\n\t\t\tif (green & BIT(5)) {\n\t\t\t\t_gct[i] |= BIT(15);\n\t\t\t}\n\t\t\tfor (int gBit = 6; gBit <= 10; gBit++) {\n\t\t\t\tif (green & BIT(gBit)) {\n\t\t\t\t\t_gct[i] |= BIT(gBit-1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set default loop count to 0, uninitialized default is 0xFFFF so it's infinite\n\t_loopCount = 0;\n\n\tFrame frame;\n\twhile (1) {\n\t\tswitch (fgetc(file)) {\n\t\t\tcase 0x21: { // Extension\n\t\t\t\tswitch (fgetc(file)) {\n\t\t\t\t\tcase 0xF9: { // Graphics Control\n\t\t\t\t\t\tframe.hasGCE = true;\n\t\t\t\t\t\tfread(&frame.gce, 1, fgetc(file), file);\n\t\t\t\t\t\tif(frame.gce.delay < 2) // If delay is less then 2, change it to 10\n\t\t\t\t\t\t\tframe.gce.delay = 10;\n\t\t\t\t\t\tfgetc(file); // Terminator\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} case 0x01: { // Plain text\n\t\t\t\t\t\t// Unsupported for now, I can't even find a text GIF to test with\n\t\t\t\t\t\t// frame.hasText = true;\n\t\t\t\t\t\t// fread(&frame.textDescriptor, 1, sizeof(frame.textDescriptor), file);\n\t\t\t\t\t\tfseek(file, 12, SEEK_CUR);\n\t\t\t\t\t\twhile (u8 size = fgetc(file)) {\n\t\t\t\t\t\t\t// char temp[size + 1];\n\t\t\t\t\t\t\t// fread(temp, 1, size, file);\n\t\t\t\t\t\t\t// frame.text += temp;\n\t\t\t\t\t\t\tfseek(file, size, SEEK_CUR);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// _frames.push_back(frame);\n\t\t\t\t\t\t// frame = Frame();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} case 0xFF: { // Application extension\n\t\t\t\t\t\tif (fgetc(file) == 0xB) {\n\t\t\t\t\t\t\tchar buffer[0xC] = {0};\n\t\t\t\t\t\t\tfread(buffer, 1, 0xB, file);\n\t\t\t\t\t\t\tif (strcmp(buffer, \"NETSCAPE2.0\") == 0) { // Check for Netscape loop count\n\t\t\t\t\t\t\t\tfseek(file, 2, SEEK_CUR);\n\t\t\t\t\t\t\t\tfread(&_loopCount, 1, sizeof(_loopCount), file);\n\t\t\t\t\t\t\t\tif(_loopCount == 0) // If loop count 0 is specified, loop forever\n\t\t\t\t\t\t\t\t\t_loopCount = 0xFFFF;\n\t\t\t\t\t\t\t\tfgetc(file); //terminator\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} case 0xFE: { // Comment\n\t\t\t\t\t\t// Skip comments and unsupported application extionsions\n\t\t\t\t\t\twhile (u8 size = fgetc(file)) {\n\t\t\t\t\t\t\tfseek(file, size, SEEK_CUR);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} case 0x2C: { // Image desriptor\n\t\t\t\tframe.hasImage = true;\n\t\t\t\tfread(&frame.descriptor, 1, sizeof(frame.descriptor), file);\n\t\t\t\tif (frame.descriptor.lctFlag) {\n\t\t\t\t\tint numColors = 2 << frame.descriptor.lctSize;\n\t\t\t\t\tframe.lct = std::vector<u16>(numColors);\n\t\t\t\t\tfor (int i = 0; i < numColors; i++) {\n\t\t\t\t\t\tconst u8 r = fgetc(file);\n\t\t\t\t\t\tconst u8 g = fgetc(file);\n\t\t\t\t\t\tconst u8 b = fgetc(file);\n\n\t\t\t\t\t\tconst u16 green = (g >> 2) << 5;\n\t\t\t\t\t\tframe.lct[i] = r >> 3 | (b >> 3) << 10;\n\t\t\t\t\t\tif (green & BIT(5)) {\n\t\t\t\t\t\t\tframe.lct[i] |= BIT(15);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int gBit = 6; gBit <= 10; gBit++) {\n\t\t\t\t\t\t\tif (green & BIT(gBit)) {\n\t\t\t\t\t\t\t\tframe.lct[i] |= BIT(gBit-1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tframe.image.lzwMinimumCodeSize = fgetc(file);\n\t\t\t\tif(_compressed) { // Leave compressed to fit more in RAM\n\t\t\t\t\twhile (u8 size = fgetc(file)) {\n\t\t\t\t\t\tsize_t end = frame.image.imageData.size();\n\t\t\t\t\t\tframe.image.imageData.resize(end + size);\n\t\t\t\t\t\tfread(frame.image.imageData.data() + end, 1, size, file);\n\t\t\t\t\t}\n\t\t\t\t} else { // Decompress now for faster draw\n\t\t\t\t\tframe.image.imageData = std::vector<u8>(frame.descriptor.w * frame.descriptor.h);\n\t\t\t\t\tauto it = frame.image.imageData.begin();\n\t\t\t\t\tauto flush_fn = [&it, &frame](std::vector<u8>::const_iterator begin, std::vector<u8>::const_iterator end) {\n\t\t\t\t\t\tstd::copy(begin, end, it);\n\t\t\t\t\t\tit += std::distance(begin, end);\n\t\t\t\t\t};\n\t\t\t\t\tLZWReader reader(frame.image.lzwMinimumCodeSize, flush_fn);\n\n\t\t\t\t\twhile (u8 size = fgetc(file)) {\n\t\t\t\t\t\tstd::vector<u8> buffer(size);\n\t\t\t\t\t\tfread(buffer.data(), 1, size, file);\n\t\t\t\t\t\treader.decode(buffer.begin(), buffer.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_frames.push_back(frame);\n\t\t\t\tframe = Frame();\n\t\t\t\tbreak;\n\t\t\t} case 0x3B: { // Trailer\n\t\t\t\tgoto breakWhile;\n\t\t\t}\n\t\t}\n\t}\n\tbreakWhile:\n\n\tfclose(file);\n\n\t_paused = false;\n\t_finished = loopForever();\n\t_frames.shrink_to_fit();\n\tif(animate)\n\t\t_animating.push_back(this);\n\n\treturn true;\n}\n"
  },
  {
    "path": "arm9/source/gif.hpp",
    "content": "#ifndef GIF_HPP\n#define GIF_HPP\n\n#include <nds/ndstypes.h>\n#include <vector>\n#include <cstddef>\n\ntypedef unsigned int uint;\n\nclass Gif {\n\tstruct Header {\n\t\tchar signature[6];\n\t\tu16 width;\n\t\tu16 height;\n\t\tu8 gctSize: 3;\n\t\tu8 sortFlag: 1;\n\t\tu8 colorResolution: 3;\n\t\tu8 gctFlag: 1;\n\t\tu8 bgColor;\n\t\tu8 pixelAspectRatio;\n\t} __attribute__ ((__packed__)) header;\n\tstatic_assert(sizeof(Header) == 13);\n\n\tstruct Frame {\n\t\tstruct GraphicsControlExtension {\n\t\t\tu8 transparentColorFlag: 1;\n\t\t\tu8 userInputFlag: 1;\n\t\t\tu8 disposalMethod: 3;\n\t\t\tu8 reserved: 3;\n\t\t\tu16 delay; // In hundreths (1/100) of a second\n\t\t\tu8 transparentColor;\n\t\t} __attribute__ ((__packed__)) gce;\n\t\tstatic_assert(sizeof(GraphicsControlExtension) == 4);\n\n\t\t// Unsupported for now\n\t\t// struct PlainText {\n\t\t// \tu16 gridX;\n\t\t// \tu16 gridY;\n\t\t// \tu16 gridW;\n\t\t// \tu16 gridH;\n\t\t// \tu8 charW;\n\t\t// \tu8 charH;\n\t\t// \tu8 forgroundIndex;\n\t\t// \tu8 backgroundIndex;\n\t\t// } __attribute__ ((__packed__)) textDescriptor;\n\t\t// static_assert(sizeof(PlainText) == 12);\n\n\t\tstruct Descriptor {\n\t\t\tu16 x;\n\t\t\tu16 y;\n\t\t\tu16 w;\n\t\t\tu16 h;\n\t\t\tu8 lctSize: 3;\n\t\t\tu8 reserved: 2;\n\t\t\tu8 sortFlag: 1;\n\t\t\tu8 interlaceFlag: 1;\n\t\t\tu8 lctFlag: 1;\n\t\t} __attribute__ ((__packed__)) descriptor;\n\t\tstatic_assert(sizeof(Descriptor) == 9);\n\n\t\tstruct Image {\n\t\t\tu8 lzwMinimumCodeSize;\n\t\t\tstd::vector<u8> imageData;\n\t\t} image;\n\n\t\tstd::vector<u16> lct; // In DS format\n\t\t// std::string text;\n\t\tbool hasGCE = false;\n\t\t// bool hasText = false;\n\t\tbool hasImage = false;\n\t};\n\n\tstd::vector<Frame> _frames;\n\tstd::vector<u16> _gct; // In DS format\n\tu16 _loopCount = 0xFFFF;\n\tbool _top = false;\n\tbool _compressed = false;\n\n\t// Animation vairables\n\tstatic std::vector<Gif *> _animating;\n\tuint _currentFrame = 0;\n\tuint _currentDelay = 0;\n\tuint _currentDelayProgress = 0;\n\tu16 _currentLoop = 0;\n\tbool _paused = true;\n\tbool _finished = true;\n\n\tbool _waitingForInput = false;\n\n\tstatic void animate(bool top);\n\n\tvoid displayFrame(void);\n\npublic:\n\tstatic void timerHandler(void);\n\n\tGif() {}\n\tGif(const char *path, bool top, bool animate, bool forceDecompress) { load(path, top, animate, forceDecompress); }\n\t~Gif() {}\n\n\tbool load(const char *path, bool top, bool animate, bool forceDecompress);\n\n\tFrame &frame(int frame) { return _frames[frame]; }\n\tstd::vector<u16> gct() { return _gct; }\n\n\tbool paused() { return _paused; }\n\tvoid pause() { _paused = true; }\n\tvoid unpause() { _paused = false; }\n\tvoid toggle() { _paused = !_paused; }\n\n\tbool loopForever(void) { return _loopCount == 0xFFFF; }\n\tbool waitingForInput(void) { return _waitingForInput; }\n\tvoid resume(void) { _waitingForInput = false; _currentDelayProgress = _currentDelay; }\n\tbool finished(void) { return _finished; }\n\n\tint currentFrame(void) { return _currentFrame; }\n};\n\n#endif\n"
  },
  {
    "path": "arm9/source/inifile.cpp",
    "content": "/*\n    inifile.cpp\n    Copyright (C) 2007 Acekard, www.acekard.com\n    Copyright (C) 2007-2009 somebody\n    Copyright (C) 2009 yellow wood goblin\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <cstdio>\n#include <cstdlib>\n#include \"inifile.h\"\n#include \"stringtool.h\"\n\nstatic bool freadLine(FILE* f,std::string& str)\n{\n  str.clear();\n__read:\n  char p=0;\n\n  size_t readed=fread(&p,1,1,f);\n  if(0==readed)\n  {\n    str=\"\";\n    return false;\n  }\n  if('\\n'==p||'\\r'==p)\n  {\n    str=\"\";\n    return true;\n  }\n\n  while(p!='\\n'&&p!='\\r'&&readed)\n  {\n    str+=p;\n    readed=fread(&p,1,1,f);\n  }\n\n  if(str.empty()||\"\"==str)\n  {\n    goto __read;\n  }\n\n  return true;\n}\n\nstatic void trimString(std::string& str)\n{\n  size_t first=str.find_first_not_of(\" \\t\"),last;\n  if(first==str.npos)\n  {\n    str=\"\";\n  }\n  else\n  {\n    last=str.find_last_not_of(\" \\t\");\n    if(first>0||(last+1)<str.length()) str=str.substr(first,last-first+1);\n  }\n}\n\nCIniFile::CIniFile()\n{\n  m_bLastResult=false;\n  m_bModified=false;\n  m_bReadOnly=false;\n}\n\nCIniFile::CIniFile(const std::string& filename)\n{\n  m_sFileName=filename;\n  m_bLastResult=false;\n  m_bModified=false;\n  m_bReadOnly=false;\n  LoadIniFile(m_sFileName);\n}\n\nCIniFile::~CIniFile()\n{\n  if(m_FileContainer.size()>0)\n  {\n    m_FileContainer.clear();\n  }\n}\n\nvoid CIniFile::SetString(const std::string& Section,const std::string& Item,const std::string& Value)\n{\n  if(GetFileString(Section,Item)!=Value)\n  {\n    SetFileString(Section,Item,Value);\n    m_bModified=true;\n  }\n}\n\nvoid CIniFile::SetInt(const std::string& Section,const std::string& Item,int Value)\n{\n  std::string strtemp=formatString(\"%d\",Value);\n\n  if(GetFileString(Section,Item)!=strtemp)\n  {\n    SetFileString(Section,Item,strtemp);\n    m_bModified=true;\n  }\n}\n\nstd::string CIniFile::GetString(const std::string& Section,const std::string& Item)\n{\n  return GetFileString(Section,Item);\n}\n\nstd::string CIniFile::GetString(const std::string& Section,const std::string& Item,const std::string& DefaultValue)\n{\n  std::string temp=GetString(Section,Item);\n  if(!m_bLastResult)\n  {\n    SetString(Section,Item,DefaultValue);\n    temp=DefaultValue;\n  }\n  return temp;\n}\n\nvoid CIniFile::GetStringVector(const std::string& Section,const std::string& Item,std::vector< std::string >& strings,char delimiter)\n{\n  std::string strValue=GetFileString(Section,Item);\n  strings.clear();\n  size_t pos;\n  while((pos=strValue.find(delimiter),strValue.npos!=pos))\n  {\n    const std::string string=strValue.substr(0,pos);\n    if(string.length())\n    {\n      strings.push_back(string);\n    }\n    strValue=strValue.substr(pos+1,strValue.npos);\n  }\n  if(strValue.length())\n  {\n    strings.push_back(strValue);\n  }\n}\n\nvoid CIniFile::SetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter)\n{\n  std::string strValue;\n  for(size_t ii=0;ii<strings.size();++ii)\n  {\n    if(ii) strValue+=delimiter;\n    strValue+=strings[ii];\n  }\n  SetString(Section,Item,strValue);\n}\n\nint CIniFile::GetInt(const std::string& Section,const std::string& Item)\n{\n  std::string value=GetFileString(Section,Item);\n  if(value.size()>2&&'0'==value[0]&&('x'==value[1]||'X'==value[1]))\n    return strtol(value.c_str(),NULL,16);\n  else\n    return strtol(value.c_str(),NULL,10);\n}\n\nint CIniFile::GetInt(const std::string& Section,const std::string& Item,int DefaultValue)\n{\n  int temp;\n  temp=GetInt(Section,Item);\n  if(!m_bLastResult)\n  {\n    SetInt(Section,Item,DefaultValue);\n    temp=DefaultValue;\n  }\n  return temp;\n}\n\nbool CIniFile::LoadIniFile(const std::string& FileName)\n{\n  //dbg_printf(\"load %s\\n\",FileName.c_str());\n  if(FileName!=\"\") m_sFileName=FileName;\n\n  FILE* f=fopen(FileName.c_str(),\"rb\");\n\n  if(NULL==f) return false;\n\n  //check for utf8 bom.\n  char bom[3];\n  if(fread(bom,3,1,f)==1&&bom[0]==0xef&&bom[1]==0xbb&&bom[2]==0xbf) ;\n  else fseek(f,0,SEEK_SET);\n\n  std::string strline(\"\");\n  m_FileContainer.clear();\n\n  while(freadLine(f,strline))\n  {\n    trimString(strline);\n    if(strline!=\"\"&&';'!=strline[0]&&'/'!=strline[0]&&'!'!=strline[0]) m_FileContainer.push_back(strline);\n  }\n\n  fclose(f);\n\n  m_bLastResult=false;\n  m_bModified=false;\n\n  return true;\n}\n\nbool CIniFile::SaveIniFileModified(const std::string& FileName)\n{\n  if(m_bModified==true)\n  {\n    return SaveIniFile(FileName);\n  }\n\n  return true;\n}\n\nbool CIniFile::SaveIniFile(const std::string& FileName)\n{\n  if(FileName!=\"\")\n    m_sFileName=FileName;\n\n  FILE* f=fopen(m_sFileName.c_str(),\"wb\");\n  if(NULL==f)\n  {\n    return false;\n  }\n\n  for(size_t ii=0;ii<m_FileContainer.size();ii++)\n  {\n    std::string& strline=m_FileContainer[ii];\n    size_t notSpace=strline.find_first_not_of(' ');\n    strline=strline.substr(notSpace);\n    if(strline.find('[')==0&&ii>0)\n    {\n      if(!m_FileContainer[ii-1].empty()&&m_FileContainer[ii-1]!=\"\")\n        fwrite(\"\\r\\n\",1,2,f);\n    }\n    if(!strline.empty()&&strline!=\"\")\n    {\n      fwrite(strline.c_str(),1,strline.length(),f);\n      fwrite(\"\\r\\n\",1,2,f);\n    }\n  }\n\n  fclose(f);\n\n  m_bModified=false;\n\n  return true;\n}\n\nstd::string CIniFile::GetFileString(const std::string& Section,const std::string& Item)\n{\n  std::string strline;\n  std::string strSection;\n  std::string strItem;\n  std::string strValue;\n\n  size_t ii=0;\n  size_t iFileLines=m_FileContainer.size();\n\n  if(m_bReadOnly)\n  {\n    cSectionCache::iterator it=m_Cache.find(Section);\n    if((it!=m_Cache.end())) ii=it->second;\n  }\n\n  m_bLastResult=false;\n\n  if(iFileLines>=0)\n  {\n    while(ii<iFileLines)\n    {\n      strline=m_FileContainer[ii++];\n\n      size_t rBracketPos=0;\n      if('['==strline[0]) rBracketPos=strline.find(']');\n      if(rBracketPos>0&&rBracketPos!=std::string::npos)\n      {\n        strSection=strline.substr(1,rBracketPos-1);\n        if(m_bReadOnly) m_Cache.insert(std::make_pair(strSection,ii-1));\n        if(strSection==Section)\n        {\n          while(ii<iFileLines)\n          {\n            strline=m_FileContainer[ii++];\n            size_t equalsignPos=strline.find('=');\n            if(equalsignPos!=strline.npos)\n            {\n              size_t last=equalsignPos?strline.find_last_not_of(\" \\t\",equalsignPos-1):strline.npos;\n              if(last==strline.npos) strItem=\"\";\n              else strItem=strline.substr(0,last+1);\n\n              if(strItem==Item)\n              {\n                size_t first=strline.find_first_not_of(\" \\t\",equalsignPos+1);\n                if(first==strline.npos) strValue=\"\";\n                else strValue=strline.substr(first);\n                m_bLastResult=true;\n                return strValue;\n              }\n            }\n            else if('['==strline[0])\n            {\n              break;\n            }\n          }\n          break;\n        }\n      }\n    }\n  }\n  return std::string(\"\");\n}\n\nvoid CIniFile::SetFileString(const std::string& Section,const std::string& Item,const std::string& Value)\n{\n  std::string strline;\n  std::string strSection;\n  std::string strItem;\n\n  if(m_bReadOnly) return;\n\n  size_t ii=0;\n  size_t iFileLines=m_FileContainer.size();\n\n  while(ii<iFileLines)\n  {\n    strline=m_FileContainer[ii++];\n\n    size_t rBracketPos=0;\n    if('['==strline[0]) rBracketPos=strline.find(']');\n    if(rBracketPos>0&&rBracketPos!=std::string::npos)\n    {\n      strSection=strline.substr(1,rBracketPos-1);\n      if(strSection==Section)\n      {\n        while(ii<iFileLines)\n        {\n          strline=m_FileContainer[ii++];\n          size_t equalsignPos=strline.find('=');\n          if(equalsignPos!=strline.npos)\n          {\n              size_t last=equalsignPos?strline.find_last_not_of(\" \\t\",equalsignPos-1):strline.npos;\n              if(last==strline.npos) strItem=\"\";\n              else strItem=strline.substr(0,last+1);\n\n              if(Item==strItem)\n              {\n                ReplaceLine(ii-1,Item+\" = \"+Value);\n                return;\n              }\n          }\n          else if('['==strline[0])\n          {\n            InsertLine(ii-1,Item+\" = \"+Value);\n            return;\n          }\n        }\n        InsertLine(ii,Item+\" = \"+Value);\n        return;\n      }\n    }\n  }\n\n  InsertLine(ii,\"[\"+Section+\"]\");\n  InsertLine(ii+1,Item+\" = \"+Value);\n  return;\n}\n\n\n\nbool CIniFile::InsertLine(size_t line,const std::string& str)\n{\n  m_FileContainer.insert(m_FileContainer.begin()+line,str);\n  return true;\n}\n\nbool CIniFile::ReplaceLine(size_t line,const std::string& str)\n{\n  m_FileContainer[line]=str;\n  return true;\n}\n"
  },
  {
    "path": "arm9/source/inifile.h",
    "content": "/*\n    inifile.h\n    Copyright (C) 2007 Acekard, www.acekard.com\n    Copyright (C) 2007-2009 somebody\n    Copyright (C) 2009-2010 yellow wood goblin\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef _INIFILE_H_\n#define _INIFILE_H_\n\n#include <string>\n#include <vector>\n#include <map>\n\nclass CIniFile\n{\n  public:\n    CIniFile();\n    CIniFile(const std::string& filename);\n    virtual ~CIniFile();\n\n  public:\n    bool LoadIniFile(const std::string& FileName);\n    bool SaveIniFile(const std::string& FileName);\n    bool SaveIniFileModified(const std::string& FileName);\n\n    std::string GetString(const std::string& Section,const std::string& Item,const std::string& DefaultValue);\n    void SetString(const std::string& Section,const std::string& Item,const std::string& Value);\n    int GetInt(const std::string& Section,const std::string& Item,int DefaultValue);\n    void SetInt(const std::string& Section,const std::string& Item,int Value);\n    void GetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter=',');\n    void SetStringVector(const std::string& Section,const std::string& Item,std::vector<std::string>& strings,char delimiter=',');\n  protected:\n    std::string m_sFileName;\n    typedef std::vector<std::string> cStringArray;\n    cStringArray m_FileContainer;\n    bool m_bLastResult;\n    bool m_bModified;\n    bool m_bReadOnly;\n    typedef std::map<std::string,size_t> cSectionCache;\n    cSectionCache m_Cache;\n\n    bool InsertLine(size_t line,const std::string& str);\n    bool ReplaceLine(size_t line,const std::string& str);\n\n    void SetFileString(const std::string& Section,const std::string& Item,const std::string& Value);\n    std::string GetFileString(const std::string& Section,const std::string& Item);\n\n    std::string GetString(const std::string& Section,const std::string& Item);\n    int GetInt(const std::string& Section,const std::string& Item);\n};\n\n#endif // _INIFILE_H_\n"
  },
  {
    "path": "arm9/source/lzw.cpp",
    "content": "#include \"lzw.hpp\"\n\nu16 LZWReader::readLSB(std::vector<u8>::iterator &begin, const std::vector<u8>::iterator &end) {\n\twhile (nBits < width) {\n\t\tif (begin == end) {\n\t\t\terr = true;\n\t\t\treturn 0;\n\t\t}\n\t\tu8 x = *(begin++);\n\t\tbits |= x << nBits;\n\t\tnBits += 8;\n\t}\n\tu16 code = bits & ((1 << width) - 1);\n\tbits >>= width;\n\tnBits -= width;\n\treturn code;\n}\n\nbool LZWReader::decode(std::vector<u8>::iterator begin, std::vector<u8>::iterator end) {\n\to = 0;\n\terr = false;\n\t// Loop over the code stream, converting codes into decompressed bytes.\n\twhile (begin != end) {\n\t\tu16 code = readLSB(begin, end);\n\t\tif (err) {\n\t\t\tflush();\n\t\t\treturn false;\n\t\t}\n\n\t\tif (code < clear) { // Literal\n\t\t\toutput[o++] = code;\n\t\t\tif (last != DECODER_INVALID_CODE) {\n\t\t\t\t// Save what the hi code expands to.\n\t\t\t\tsuffix[hi] = code;\n\t\t\t\tprefix[hi] = last;\n\t\t\t}\n\t\t} else if (code == clear) { // Clear\n\t\t\twidth = 1 + litWidth;\n\t\t\thi = eof;\n\t\t\toverflow = 1 << width;\n\t\t\tlast = DECODER_INVALID_CODE;\n\t\t\tcontinue;\n\t\t} else if (code == eof) { // End\n\t\t\tflush();\n\t\t\treturn true;\n\t\t} else if (code <= hi) {\n\t\t\tu16 c = code;\n\t\t\tuint i = output.size() - 1;\n\t\t\tif (code == hi && last != DECODER_INVALID_CODE) {\n\t\t\t\t// code == hi is a special case which expands to the last expansion\n\t\t\t\t// followed by the head of the last expansion. To find the head, we walk\n\t\t\t\t// the prefix chain until we find a literal code.\n\t\t\t\tc = last;\n\t\t\t\twhile (c >= clear)\n\t\t\t\t\tc = prefix[c];\n\t\t\t\toutput[i] = c;\n\t\t\t\ti--;\n\t\t\t\tc = last;\n\t\t\t}\n\t\t\t// Copy the suffix chain into output and then write that to w.\n\t\t\twhile (c >= clear) {\n\t\t\t\toutput[i] = suffix[c];\n\t\t\t\ti--;\n\t\t\t\tc = prefix[c];\n\t\t\t}\n\t\t\toutput[i] = c;\n\t\t\tstd::copy(output.begin() + i, output.end(), output.begin() + o);\n\t\t\to += std::distance(output.begin() + i, output.end());\n\t\t\tif (last != DECODER_INVALID_CODE) {\n\t\t\t\t// Save what the hi code expands to\n\t\t\t\tsuffix[hi] = c;\n\t\t\t\tprefix[hi] = last;\n\t\t\t}\n\t\t} else { // Error\n\t\t\tflush();\n\t\t\treturn false;\n\t\t}\n\n\t\tlast = code;\n\t\thi++;\n\t\tif (hi >= overflow) {\n\t\t\tif (hi > overflow) {\n\t\t\t\tflush();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (width == MAX_WIDTH) {\n\t\t\t\tlast = DECODER_INVALID_CODE;\n\t\t\t\t// Undo the d.hi++ a few lines above, so that (1) we maintain\n\t\t\t\t// the invariant that d.hi < d.overflow, and (2) d.hi does not\n\t\t\t\t// eventually overflow a uint16.\n\t\t\t\thi--;\n\t\t\t} else {\n\t\t\t\twidth++;\n\t\t\t\toverflow = 1 << width;\n\t\t\t}\n\t\t}\n\t\tif (o >= FLUSH_BUFFER) {\n\t\t\tflush();\n\t\t}\n\t}\n\n\tflush();\n\treturn true;\n}\n\nLZWReader::LZWReader(int minCodeSize, std::function<void(u8_itr, u8_itr)> flushFunction) : litWidth(minCodeSize), flushFn(flushFunction) {\n\twidth = 1 + litWidth;\n\tclear = 1 << litWidth;\n\teof = clear + 1;\n\thi = clear + 1;\n\toverflow = 1 << width;\n\tlast = DECODER_INVALID_CODE;\n\n\tsuffix = std::vector<u8>(1 << MAX_WIDTH);\n\tprefix = std::vector<u16>(1 << MAX_WIDTH);\n\toutput = std::vector<u8>(2 * (1 << MAX_WIDTH));\n}\n\nvoid LZWReader::flush(void) {\n\tif (flushFn && o > 0) {\n\t\tflushFn(output.begin(), output.begin() + o);\n\t}\n\to = 0;\n}\n"
  },
  {
    "path": "arm9/source/lzw.hpp",
    "content": "#ifndef LZW_HPP\n#define LZW_HPP\n\n#include <nds.h>\n#include <functional>\n#include <vector>\n\ntypedef unsigned int uint;\ntypedef std::vector<u8>::const_iterator u8_itr;\n\nclass LZWReader {\n\tconstexpr static u16 MAX_WIDTH = 12;\n\tconstexpr static u16 DECODER_INVALID_CODE = 0xFFFF;\n\tconstexpr static u16 FLUSH_BUFFER = 1 << MAX_WIDTH;\n\n\tint litWidth;\n\tstd::function<void(u8_itr, u8_itr)> flushFn;\n\tu32 bits = 0;\n\tuint nBits = 0;\n\tuint width;\n\tbool err = false;\n\n\tu16 clear, eof, hi, overflow, last;\n\n\tstd::vector<u8> suffix;\n\tstd::vector<u16> prefix;\n\n\tstd::vector<u8> output;\n\tint o = 0;\n\t// std::vector<u8> toRead;\n\n\tu16 readLSB(std::vector<u8>::iterator &it, const std::vector<u8>::iterator &end);\n\n\tint read(std::vector<u8> &buffer);\n\n\tvoid flush(void);\n\npublic:\n\tLZWReader(int minCodeSize, std::function<void(u8_itr, u8_itr)> flushFunction);\n\n\tbool decode(std::vector<u8>::iterator begin, std::vector<u8>::iterator end);\n};\n\n#endif\n"
  },
  {
    "path": "arm9/source/main.cpp",
    "content": "#include <dirent.h>\n#include <nds.h>\n#include <slim.h>\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"bios_decompress_callback.h\"\n#include \"fileOperations.h\"\n#include \"gif.hpp\"\n#include \"inifile.h\"\n#include \"nds_loader_arm9.h\"\n#include \"tonccpy.h\"\n#include \"version.h\"\n\n#include \"topLoad.h\"\n#include \"subLoad.h\"\n// #include \"topError.h\"\n// #include \"subError.h\"\n\n#define CONSOLE_SCREEN_WIDTH 32\n#define CONSOLE_SCREEN_HEIGHT 24\n\n#define SETTINGS_INI_PATH \"sd:/hiya/settings.ini\"\n\n#define TMD_SIZE 0x208\n\nstatic char tmdBuffer[TMD_SIZE];\n\nbool splash = true;\nbool dsiSplash = false;\nbool titleAutoboot = false;\nbool eraseUnlaunch = true;\n\nbool splashFound[2] = {false};\nbool splashBmp[2] = {false};\nbool rgb565BmpDisplayMode = false;\nu16* dsImageBuffer[2];\n\nGif gif[2];\n\nvoid hBlankHandler() {\n\tint scanline = REG_VCOUNT;\n\tif (scanline > 192) {\n\t\treturn;\n\t} else if (scanline == 192) {\n\t\tif (splashBmp[0]) {\n\t\t\tdmaCopyWordsAsynch(0, dsImageBuffer[0], BG_PALETTE_SUB, 256*2);\n\t\t}\n\t\tif (splashBmp[1]) {\n\t\t\tdmaCopyWordsAsynch(1, dsImageBuffer[1], BG_PALETTE, 256*2);\n\t\t}\n\t} else {\n\t\tscanline++;\n\t\tif (splashBmp[0]) {\n\t\t\tdmaCopyWordsAsynch(0, dsImageBuffer[0]+(scanline*256), BG_PALETTE_SUB, 256*2);\n\t\t}\n\t\tif (splashBmp[1]) {\n\t\t\tdmaCopyWordsAsynch(1, dsImageBuffer[1]+(scanline*256), BG_PALETTE, 256*2);\n\t\t}\n\t}\n}\n\nbool loadBMP(bool top) {\n\tFILE* file = fopen((top ? \"sd:/hiya/splashtop.bmp\" : \"sd:/hiya/splashbottom.bmp\"), \"rb\");\n\tif (!file)\n\t\treturn false;\n\n\t// Read width & height\n\tfseek(file, 0x12, SEEK_SET);\n\tu32 width, height;\n\tfread(&width, 1, sizeof(width), file);\n\tfread(&height, 1, sizeof(height), file);\n\n\tif (width > 256 || height > 192) {\n\t\tfclose(file);\n\t\treturn false;\n\t}\n\n\tif (rgb565BmpDisplayMode) {\n\t\tdsImageBuffer[top] = new u16[256*192];\n\t\ttoncset(dsImageBuffer[top], 0, 256*192);\n\t}\n\n\tfseek(file, 0xE, SEEK_SET);\n\tu8 headerSize = fgetc(file);\n\tbool rgb565 = false;\n\tif(headerSize == 0x38) {\n\t\t// Check the upper byte green mask for if it's got 5 or 6 bits\n\t\tfseek(file, 0x2C, SEEK_CUR);\n\t\trgb565 = fgetc(file) == 0x07;\n\t\tfseek(file, headerSize - 0x2E, SEEK_CUR);\n\t} else {\n\t\tfseek(file, headerSize - 1, SEEK_CUR);\n\t}\n\tu16 *bmpImageBuffer = new u16[width * height];\n\tfread(bmpImageBuffer, 2, width * height, file);\n\tu16 *src = bmpImageBuffer;\n\tif (rgb565BmpDisplayMode) {\n\t\tu16 *dst = dsImageBuffer[top] + ((191 - ((192 - height) / 2)) * 256) + (256 - width) / 2;\n\t\tif (rgb565) {\n\t\t\tfor (uint y = 0; y < height; y++, dst -= 256) {\n\t\t\t\tfor (uint x = 0; x < width; x++) {\n\t\t\t\t\tu16 val = *(src++);\n\t\t\t\t\tconst u16 green = ((val) & (0x3F << 5));\n\t\t\t\t\tu16 color = ((val >> 11) & 0x1F) | (val & 0x1F) << 10;\n\t\t\t\t\tif (green & BIT(5)) {\n\t\t\t\t\t\tcolor |= BIT(15);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int g = 6; g <= 10; g++) {\n\t\t\t\t\t\tif (green & BIT(g)) {\n\t\t\t\t\t\t\tcolor |= BIT(g-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t*(dst + x) = color;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (uint y = 0; y < height; y++, dst -= 256) {\n\t\t\t\tfor (uint x = 0; x < width; x++) {\n\t\t\t\t\tu16 val = *(src++);\n\t\t\t\t\t*(dst + x) = ((val >> 10) & 0x1F) | ((val) & (0x1F << 5)) | (val & 0x1F) << 10;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tu16 *dst = (top ? BG_GFX : BG_GFX_SUB) + ((191 - ((192 - height) / 2)) * 256) + (256 - width) / 2;\n\t\tfor (uint y = 0; y < height; y++, dst -= 256) {\n\t\t\tfor (uint x = 0; x < width; x++) {\n\t\t\t\tu16 val = *(src++);\n\t\t\t\t*(dst + x) = ((val >> (rgb565 ? 11 : 10)) & 0x1F) | ((val >> (rgb565 ? 1 : 0)) & (0x1F << 5)) | (val & 0x1F) << 10 | BIT(15);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] bmpImageBuffer;\n\tfclose(file);\n\n\tif (rgb565BmpDisplayMode) {\n\t\tu8* dsImageBuffer8 = new u8[256*192];\n\t\tfor (int i = 0; i < 256*192; i++) {\n\t\t\tdsImageBuffer8[i] = i;\n\t\t}\n\n\t\tdmaCopyWords(3, dsImageBuffer8, top ? BG_GFX : BG_GFX_SUB, 256*192);\n\t\tdelete[] dsImageBuffer8;\n\t}\n\treturn true;\n}\n\nvoid bootSplashInit() {\n\t// Initialize bitmap background\n\tvideoSetMode(MODE_3_2D);\n\tvideoSetModeSub(MODE_3_2D);\n\tvramSetBankA(VRAM_A_MAIN_BG);\n\tvramSetBankC(VRAM_C_SUB_BG);\n\t// Clear these to prevent messing up the main BG\n\tvramSetBankH(VRAM_H_LCD);\n\tvramSetBankG(VRAM_G_LCD);\n\n\tif (splashFound[true] && splashBmp[true] && !splashBmp[false])\n\t\tbgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);\n\telse\n\t\tbgInit(3, BgType_Bmp8, BgSize_B8_256x256, 0, 0);\n\n\tif (splashFound[false] && !splashBmp[true] && splashBmp[false])\n\t\tbgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);\n\telse\n\t\tbgInitSub(3, BgType_Bmp8, BgSize_B8_256x256, 0, 0);\n\n\t// Clear backgrounds\n\ttoncset16(BG_PALETTE, 0, 256);\n\ttoncset16(BG_PALETTE_SUB, 0, 256);\n\ttoncset16(BG_GFX, 0, 256 * 256 * 2);\n\ttoncset16(BG_GFX_SUB, 0, 256 * 256 * 2);\n}\n\nvoid loadScreen() {\n\tbootSplashInit();\n\n\trgb565BmpDisplayMode = ((!splashFound[true] || splashBmp[true]) && (!splashFound[false] || splashBmp[false]));\n\n\t// Display Load Screen\n\tif (splashBmp[true]) {\n\t\tloadBMP(true);\n\t} else if (!splashFound[true]) {\n\t\ttonccpy(BG_PALETTE, topLoadPal, topLoadPalLen);\n\t\tswiDecompressLZSSVram((void*)topLoadBitmap, BG_GFX, 0, &decompressBiosCallback);\n\t}\n\tif (splashBmp[false]) {\n\t\tloadBMP(false);\n\t} else if (!splashFound[false]) {\n\t\ttonccpy(BG_PALETTE_SUB, subLoadPal, subLoadPalLen);\n\t\tswiDecompressLZSSVram((void*)subLoadBitmap, BG_GFX_SUB, 0, &decompressBiosCallback);\n\t}\n\n\tif ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {\n\t\tirqSet(IRQ_HBLANK, hBlankHandler);\n\t\tirqEnable(IRQ_HBLANK);\n\t}\n}\n\nint cursorPosition = 0;\n\nvoid loadSettings(void) {\n\t// GUI\n\tCIniFile settingsini(SETTINGS_INI_PATH);\n\n\tsplash = settingsini.GetInt(\"HIYA-CFW\", \"SPLASH\", 0);\n\tdsiSplash = settingsini.GetInt(\"HIYA-CFW\", \"DSI_SPLASH\", 0);\n\ttitleAutoboot = settingsini.GetInt(\"HIYA-CFW\", \"TITLE_AUTOBOOT\", 0);\n\teraseUnlaunch = settingsini.GetInt(\"HIYA-CFW\", \"ERASE_UNLAUNCH\", 1);\n}\n\nvoid saveSettings(void) {\n\t// GUI\n\tCIniFile settingsini(SETTINGS_INI_PATH);\n\n\tsettingsini.SetInt(\"HIYA-CFW\", \"SPLASH\", splash);\n\tsettingsini.SetInt(\"HIYA-CFW\", \"DSI_SPLASH\", dsiSplash);\n\tsettingsini.SetInt(\"HIYA-CFW\", \"TITLE_AUTOBOOT\", titleAutoboot);\n\tsettingsini.SaveIniFile(SETTINGS_INI_PATH);\n}\n\nvoid setupConsole() {\n\t// Subscreen as a console\n\tvideoSetMode(MODE_0_2D);\n\tvramSetBankG(VRAM_G_MAIN_BG);\n\tvideoSetModeSub(MODE_0_2D);\n\tvramSetBankH(VRAM_H_SUB_BG);\n}\n\nint main( int argc, char **argv) {\n\textern void dsiOnly(void);\n\tdsiOnly();\n\n\t// defaultExceptionHandler();\n\n\t/* scanKeys();\n\tif ((keysHeld() & KEY_RIGHT) && (keysHeld() & KEY_A)) {\n\t\tsetupConsole();\n\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\n\t\tiprintf(\"Please remove the SD Card and\\n\");\n\t\tiprintf(\"insert the SD Card containing\\n\");\n\t\tiprintf(\"hiyaCFW, then press A\\n\");\n\t\tiprintf(\"to continue.\");\n\n\t\t// Prevent accidential presses\n\t\tfor (int i = 0; i < 60; i++) {\n\t\t\tswiWaitForVBlank();\n\t\t}\n\n\t\twhile (1) {\n\t\t\tscanKeys();\n\t\t\tif (keysHeld() & KEY_A) break;\n\t\t\tswiWaitForVBlank();\n\t\t}\n\n\t\tfor (int i = 0; i < 24; i++) {\n\t\t\tswiWaitForVBlank();\n\t\t}\n\t}\n\n\t*(u32*)0x0CFFFD0C = 0x54534453; // 'SDST'\n\twhile (*(u32*)0x0CFFFD0C != 0) { swiDelay(100); } */\n\n\tu32 sdIrqStatus = fifoGetValue32(FIFO_USER_01);\n\tif ((sdIrqStatus & BIT(5)) != 0 && (sdIrqStatus & BIT(7)) == 0) {\n\t\tsetupConsole();\n\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\n\t\tiprintf(\"The SD card is write-locked.\\n\");\n\t\tiprintf(\"Please turn off the POWER,\\n\");\n\t\tiprintf(\"remove the SD card, move the\\n\");\n\t\tiprintf(\"write-lock switch up, re-insert\\n\");\n\t\tiprintf(\"the SD card, then try again.\");\n\n\t\twhile (1)\n\t\t\tswiWaitForVBlank();\n\t}\n\n\tif (!fatInitDefault()) {\n\t\t/* bootSplashInit();\n\n\t\t// Display Error Screen\n\t\tswiDecompressLZSSVram((void*)topErrorBitmap, BG_GFX, 0, &decompressBiosCallback);\n\t\tswiDecompressLZSSVram((void*)subErrorBitmap, BG_GFX_SUB, 0, &decompressBiosCallback);\n\t\ttonccpy(&BG_PALETTE[0], topErrorPal, topErrorPalLen);\n\t\ttonccpy(&BG_PALETTE_SUB[0], subErrorPal, subErrorPalLen); */\n\n\t\tsetupConsole();\n\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\n\t\tiprintf(\"FAT init failed!\");\n\n\t\twhile (1)\n\t\t\tswiWaitForVBlank();\n\t}\n\n\tif ((access(\"sd:/\", F_OK) != 0) && (access(\"fat:/\", F_OK) == 0)) {\n\t\tsetupConsole();\n\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\n\t\tiprintf(\"hiyaCFW is not compatible\\n\");\n\t\tiprintf(\"with flashcards!\");\n\n\t\twhile (1)\n\t\t\tswiWaitForVBlank();\n\t}\n\n\tu8 oldRegion = 0;\n\tu8 regionChar = 0;\n\tFILE* f_hwinfoS = fopen(\"sd:/sys/HWINFO_S.dat\", \"rb\");\n\tif (f_hwinfoS) {\n\t\tfseek(f_hwinfoS, 0x90, SEEK_SET);\n\t\tfread(&oldRegion, 1, 1, f_hwinfoS);\n\t\tfseek(f_hwinfoS, 0xA0, SEEK_SET);\n\t\tfread(&regionChar, 1, 1, f_hwinfoS);\n\t\tfclose(f_hwinfoS);\n\t} else {\n\t\tsetupConsole();\n\t\tconsoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);\n\t\tconsoleClear();\n\t\tiprintf(\"Error!\\n\");\n\t\tiprintf(\"\\n\");\n\t\tiprintf(\"HWINFO_S.dat not found!\");\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\n\t\twhile (1)\n\t\t\tswiWaitForVBlank();\n\t}\n\n\tu8 newRegion = oldRegion;\n\tif (regionChar == 'C') {\n\t\tif (newRegion != 4) newRegion = 4;\n\t} else if (regionChar == 'K') {\n\t\tif (newRegion != 5) newRegion = 5;\n\t} else {\n\t\tif (newRegion >= 4) newRegion = 0;\n\t}\n\n\tloadSettings();\n\n\tbool gotoSettings = (access(SETTINGS_INI_PATH, F_OK) != 0);\n\n\tscanKeys();\n\n\tif (keysHeld() & KEY_SELECT) gotoSettings = true;\n\n\tif (gotoSettings) {\n\t\tsetupConsole();\n\n\t\tint optionCount = 2;\n\t\tint optionShift = 0;\n\t\tif (regionChar != 'C' && regionChar != 'K') {\n\t\t\toptionCount++; // Display region setting\n\t\t\toptionShift++;\n\t\t}\n\n\t\tint pressed = 0;\n\t\tbool menuprinted = true;\n\n\t\twhile (1) {\n\t\t\tif (menuprinted) {\n\t\t\t\tconsoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);\n\t\t\t\tconsoleClear();\n\n\t\t\t\tiprintf (\"\\x1B[46m\");\n\n\t\t\t\tiprintf(\"hiyaCFW %s%cconfiguration\\n\", VER_NUMBER, sizeof(VER_NUMBER) > 11 ? '\\n' : ' ');\n\t\t\t\tiprintf(\"Press A to select, START to save\");\n\t\t\t\tiprintf(\"\\n\");\n\n\t\t\t\tiprintf (\"\\x1B[47m\");\n\n\t\t\t\tif (optionCount > 2) {\n\t\t\t\t\tif (cursorPosition == 0) iprintf (\"\\x1B[41m\");\n\t\t\t\t\telse iprintf (\"\\x1B[47m\");\n\n\t\t\t\t\tiprintf(\" Region: \");\n\t\t\t\t\tswitch (newRegion) {\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tiprintf(\"JPN(x), USA( ),\\n         EUR( ), AUS( )\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tiprintf(\"JPN( ), USA(x),\\n         EUR( ), AUS( )\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tiprintf(\"JPN( ), USA( ),\\n         EUR(x), AUS( )\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\tiprintf(\"JPN( ), USA( ),\\n         EUR( ), AUS(x)\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tiprintf(\"\\n\\n\");\n\t\t\t\t}\n\n\t\t\t\tif (cursorPosition == 0+optionShift) iprintf (\"\\x1B[41m\");\n\t\t\t\telse iprintf (\"\\x1B[47m\");\n\n\t\t\t\tiprintf(\" Splash: \");\n\t\t\t\tif (splash)\n\t\t\t\t\tiprintf(\"Off( ), On(x)\");\n\t\t\t\telse\n\t\t\t\t\tiprintf(\"Off(x), On( )\");\n\t\t\t\tiprintf(\"\\n\\n\");\n\n\t\t\t\tif (cursorPosition == 1+optionShift) iprintf (\"\\x1B[41m\");\n\t\t\t\telse iprintf (\"\\x1B[47m\");\n\n\t\t\t\tif (dsiSplash)\n\t\t\t\t\tiprintf(\" (x)\");\n\t\t\t\telse\n\t\t\t\t\tiprintf(\" ( )\");\n\t\t\t\tiprintf(\" DSi Splash/H&S screen\\n\");\n\n\t\t\t\tif (cursorPosition == 2+optionShift) iprintf (\"\\x1B[41m\");\n\t\t\t\telse iprintf (\"\\x1B[47m\");\n\n\t\t\t\tif (titleAutoboot)\n\t\t\t\t\tiprintf(\" (x)\");\n\t\t\t\telse\n\t\t\t\t\tiprintf(\" ( )\");\n\t\t\t\tiprintf(\" Autoboot title\\n\");\n\n\t\t\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\t\t\tconsoleClear();\n\n\t\t\t\tiprintf(\"\\n\");\n\t\t\t\tif ((cursorPosition == 0) && (optionCount > 2)) {\n\t\t\t\t\tiprintf(\" Change the SDNAND region.\\n\");\n\t\t\t\t\tiprintf(\" \\n\");\n\t\t\t\t\tiprintf(\" Changing from the original\\n\");\n\t\t\t\t\tiprintf(\" will break apps such as DSi\\n\");\n\t\t\t\t\tiprintf(\" Shop and 3DS Transfer Tool.\\n\");\n\t\t\t\t\tif (regionChar == 'J') {\n\t\t\t\t\t\tiprintf(\" \\n\");\n\t\t\t\t\t\tiprintf(\" System settings will be reset.\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tiprintf(\" \\n\");\n\t\t\t\t\tiprintf(\" Original region: \");\n\t\t\t\t\tif (regionChar == 'J') {\n\t\t\t\t\t\tiprintf(\"JPN\");\n\t\t\t\t\t} else if (regionChar == 'E') {\n\t\t\t\t\t\tiprintf(\"USA\");\n\t\t\t\t\t} else if (regionChar == 'P') {\n\t\t\t\t\t\tiprintf(\"EUR\");\n\t\t\t\t\t} else if (regionChar == 'U') {\n\t\t\t\t\t\tiprintf(\"AUS\");\n\t\t\t\t\t}\n\t\t\t\t} else if (cursorPosition == 0+optionShift) {\n\t\t\t\t\tiprintf(\" Enable splash screen.\");\n\t\t\t\t} else if (cursorPosition == 1+optionShift) {\n\t\t\t\t\tiprintf(\" Enable showing the DSi Splash/\\n\");\n\t\t\t\t\tiprintf(\" Health & Safety screen.\");\n\t\t\t\t} else if (cursorPosition == 2+optionShift) {\n\t\t\t\t\tiprintf(\" Load title contained in\\n\");\n\t\t\t\t\tiprintf(\" sd:/hiya/autoboot.bin\\n\");\n\t\t\t\t\tiprintf(\" instead of the DSi Menu.\");\n\t\t\t\t}\n\n\t\t\t\tmenuprinted = false;\n\t\t\t}\n\n\t\t\tdo {\n\t\t\t\tscanKeys();\n\t\t\t\tpressed = keysDownRepeat();\n\t\t\t\tswiWaitForVBlank();\n\t\t\t} while (!pressed);\n\n\t\t\tif (pressed & KEY_L) {\n\t\t\t\t// Debug code\n\t\t\t\tFILE* ResetData = fopen(\"sd:/hiya/ResetData_extract.bin\",\"wb\");\n\t\t\t\tfwrite((void*)0x02000000,1,0x800,ResetData);\n\t\t\t\tfclose(ResetData);\n\t\t\t\tfor (int i = 0; i < 30; i++) swiWaitForVBlank();\n\t\t\t}\n\n\t\t\tif (pressed & KEY_A) {\n\t\t\t\tif (optionCount > 2) {\n\t\t\t\t\tswitch (cursorPosition){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tnewRegion++;\n\t\t\t\t\t\t\tif (newRegion == 4) newRegion = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsplash = !splash;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tdsiSplash = !dsiSplash;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\ttitleAutoboot = !titleAutoboot;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch (cursorPosition){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsplash = !splash;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tdsiSplash = !dsiSplash;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\ttitleAutoboot = !titleAutoboot;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmenuprinted = true;\n\t\t\t}\n\n\t\t\tif (pressed & KEY_UP) {\n\t\t\t\tcursorPosition--;\n\t\t\t\tmenuprinted = true;\n\t\t\t} else if (pressed & KEY_DOWN) {\n\t\t\t\tcursorPosition++;\n\t\t\t\tmenuprinted = true;\n\t\t\t}\n\n\t\t\tif (cursorPosition < 0) cursorPosition = optionCount;\n\t\t\tif (cursorPosition > optionCount) cursorPosition = 0;\n\n\t\t\tif (pressed & KEY_START) {\n\t\t\t\tsaveSettings();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (newRegion != oldRegion) {\n\t\tFILE* f_hwinfoS = fopen(\"sd:/sys/HWINFO_S.dat\", \"rb+\");\n\t\tif (f_hwinfoS) {\n\t\t\tu32 supportedLangBitmask = 0x01; // JPN: Japanese\n\t\t\tif (newRegion == 5) { // KOR\n\t\t\t\tsupportedLangBitmask = 0x80; // Korean\n\t\t\t} else if (newRegion == 4) { // CHN\n\t\t\t\tsupportedLangBitmask = 0x40; // Chinese\n\t\t\t} else if (newRegion == 3) { // AUS\n\t\t\t\tsupportedLangBitmask = 0x02; // English\n\t\t\t} else if (newRegion == 2) { // EUR\n\t\t\t\tsupportedLangBitmask = 0x3E; // English, French, German, Italian, Spanish\n\t\t\t} else if (newRegion == 1) { // USA\n\t\t\t\tsupportedLangBitmask = 0x26; // English, French, Spanish\n\t\t\t}\n\t\t\tfseek(f_hwinfoS, 0x88, SEEK_SET);\n\t\t\tfwrite(&supportedLangBitmask, sizeof(u32), 1, f_hwinfoS);\n\t\t\tfseek(f_hwinfoS, 0x90, SEEK_SET);\n\t\t\tfwrite(&newRegion, 1, 1, f_hwinfoS);\n\t\t\tfclose(f_hwinfoS);\n\t\t\tif (regionChar == 'J') {\n\t\t\t\t// Reset system settings to work around touch inputs not working\n\t\t\t\tremove(\"sd:/shared1/TWLCFG0.dat\");\n\t\t\t\tremove(\"sd:/shared1/TWLCFG1.dat\");\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create dummy file\n\t// Check the free space\n\tstruct statvfs st;\n\tstatvfs(\"sd:/\", &st);\n\tu32 freeSpace = st.f_bsize * st.f_bfree;\n\tu64 realFreeSpace = st.f_bsize * st.f_bfree;\n\n\t// If the free space is bigger than 2GiB (using a u32 so always 0 - 4GiB)\n\t// or the free space is less than 20MiB (and the actual free space is over 4GiB)\n\tif(freeSpace > (2u << 30) || (freeSpace < (20u << 20) && realFreeSpace > (4u << 30))) {\n\t\tconsoleDemoInit();\n\t\tsize_t oldSize = 0;\n\t\t// Check old dummy file size to see if it can just be removed\n\t\tFILE *file = fopen(\"sd:/hiya/dummy.bin\", \"rb\");\n\t\tif(file) {\n\t\t\tfseek(file, 0, SEEK_END);\n\t\t\toldSize = ftell(file);\n\t\t\tfclose(file);\n\t\t}\n\n\t\t// Check that dummy file is still needed\n\t\tif((freeSpace + oldSize) > (2u << 30) || (freeSpace + oldSize) < (20u << 20)) {\n\t\t\t// Make sure hiya directory exists and make the file\n\t\t\tmkdir(\"sd:/hiya\", 0777);\n\t\t\tiprintf(\"Making new dummy file...   \");\n\n\t\t\t// Make sure the file exists\n\t\t\tfile = fopen(\"sd:/hiya/dummy.bin\", \"wb\");\n\t\t\tif(file)\n\t\t\t\tfclose(file);\n\n\t\t\t// If free space is less than 20MiB, add free space + 2GiB + 10MiB\n\t\t\t// otherwise add free space - 2GiB + 10MiB\n\t\t\ttruncate(\"sd:/hiya/dummy.bin\", (freeSpace < (20u << 20) ? (freeSpace + (2 << 30)) : (freeSpace - (2 << 30))) + (10 << 20));\n\t\t\tiprintf(\"Done!\\n\");\n\t\t} else {\n\t\t\tiprintf(\"Removing old dummy file... \");\n\t\t\tremove(\"sd:/hiya/dummy.bin\");\n\t\t\tiprintf(\"Done!\\n\");\n\t\t}\n\t}\n\n\tif (!gotoSettings && (*(u32*)0x02000300 == 0x434E4C54 || fifoGetValue32(FIFO_USER_02) == 0x01)) {\n\t\t// if \"CNLT\" is found in RAM, or if warmboot flag is set, then don't show splash\n\t\tsplash = false;\n\t}\n\n\tif ((*(u32*)0x02000300 == 0x434E4C54) && (*(u32*)0x02000310 != 0x00000000)) {\n\t\t// if \"CNLT\" is found, and a title is set to launch, then don't autoboot title in \"autoboot.bin\"\n\t\ttitleAutoboot = false;\n\t}\n\n\tif (titleAutoboot) {\n\t\tFILE* ResetData = fopen(\"sd:/hiya/autoboot.bin\",\"rb\");\n\t\tif (ResetData) {\n\t\t\tfread((void*)0x02000300,1,0x20,ResetData);\n\t\t\tdsiSplash = false;\t// Disable DSi splash, so that DSi Menu doesn't appear\n\t\t\tfclose(ResetData);\n\t\t}\n\t}\n\n\tif (splash) {\n\t\tif (gif[true].load(\"sd:/hiya/splashtop.gif\", true, true, false)) {\n\t\t\tsplashFound[true] = true;\n\t\t\tsplashBmp[true] = false;\n\t\t} else if (access(\"sd:/hiya/splashtop.bmp\", F_OK) == 0) {\n\t\t\tsplashFound[true] = true;\n\t\t\tsplashBmp[true] = true;\n\t\t}\n\n\t\tif (gif[false].load(\"sd:/hiya/splashbottom.gif\", false, true, false)) {\n\t\t\tsplashFound[false] = true;\n\t\t\tsplashBmp[false] = false;\n\t\t} else if (access(\"sd:/hiya/splashtop.bmp\", F_OK) == 0) {\n\t\t\tsplashFound[false] = true;\n\t\t\tsplashBmp[false] = true;\n\t\t}\n\n\t\tloadScreen();\n\n\t\tif (rgb565BmpDisplayMode) {\n\t\t\tfor (int i = 0; i < 60 * 3; i++)\n\t\t\t\tswiWaitForVBlank();\n\t\t} else {\n\t\t\ttimerStart(0, ClockDivider_1024, TIMER_FREQ_1024(100), Gif::timerHandler);\n\n\t\t\t// If both GIFs will loop forever (or are not loaded)\n\t\t\t// then show for 3s\n\t\t\tif (gif[true].loopForever() && gif[false].loopForever()) {\n\t\t\t\tfor (int i = 0; i < 60 * 3; i++)\n\t\t\t\t\tswiWaitForVBlank();\n\t\t\t} else {\n\t\t\t\twhile (!(gif[true].finished() && gif[false].finished())) {\n\t\t\t\t\tswiWaitForVBlank();\n\t\t\t\t\tscanKeys();\n\t\t\t\t\tu16 down = keysDown();\n\n\t\t\t\t\tfor (auto &g : gif) {\n\t\t\t\t\t\tif (g.waitingForInput() && down)\n\t\t\t\t\t\t\tg.resume();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimerStop(0);\n\t\t}\n\t}\n\n\tif (!dsiSplash) {\n\t\tfifoSendValue32(FIFO_USER_03, 1);\n\t\t// Tell Arm7 to check FIFO_USER_03 code\n\t\tfifoSendValue32(FIFO_USER_04, 1);\n\t\t// Small delay to ensure arm7 has time to write i2c stuff\n\t\tfor (int i = 0; i < 1*3; i++) { swiWaitForVBlank(); }\n\t} else {\n\t\tfifoSendValue32(FIFO_USER_04, 1);\n\t}\n\n\tchar tmdpath[256];\n\tsnprintf (tmdpath, sizeof(tmdpath), \"sd:/title/00030017/484e41%x/content/title.tmd\", regionChar);\n\n\tFILE* f_tmd = fopen(tmdpath, \"rb\");\n\tif (f_tmd) {\n\t\tif ((getFileSize(tmdpath) > TMD_SIZE) && eraseUnlaunch) {\n\t\t\t// Read big .tmd file at the correct size\n\t\t\tf_tmd = fopen(tmdpath, \"rb\");\n\t\t\tfread(tmdBuffer, 1, TMD_SIZE, f_tmd);\n\t\t\tfclose(f_tmd);\n\n\t\t\t// Write correct sized .tmd file\n\t\t\tf_tmd = fopen(tmdpath, \"wb\");\n\t\t\tfwrite(tmdBuffer, 1, TMD_SIZE, f_tmd);\n\t\t\tfclose(f_tmd);\n\t\t}\n\t\tint err = runNdsFile(\"sd:/hiya/BOOTLOADER.NDS\", 0, NULL);\n\t\tif ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {\n\t\t\twhile (dmaBusy(0) || dmaBusy(1));\n\t\t\tirqDisable(IRQ_HBLANK);\n\t\t}\n\t\tsetupConsole();\n\t\tconsoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);\n\t\tconsoleClear();\n\t\tiprintf (\"Start failed. Error %i\\n\", err);\n\t\tif (err == 1) printf (\"bootloader.nds not found!\");\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\t} else {\n\t\tif ((splashFound[true] || splashFound[false]) && rgb565BmpDisplayMode) {\n\t\t\twhile (dmaBusy(0) || dmaBusy(1));\n\t\t\tirqDisable(IRQ_HBLANK);\n\t\t}\n\t\tsetupConsole();\n\t\tconsoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 15, 0, true, true);\n\t\tconsoleClear();\n\t\tiprintf(\"Error!\\n\");\n\t\tiprintf(\"\\n\");\n\t\tiprintf(\"Launcher's title.tmd was\\n\");\n\t\tiprintf(\"not found!\");\n\t\tconsoleInit(NULL, 1, BgType_Text4bpp, BgSize_T_256x256, 15, 0, false, true);\n\t\tconsoleClear();\n\t}\n\n\twhile (1)\n\t\tswiWaitForVBlank();\n}\n\n"
  },
  {
    "path": "arm9/source/nds_loader_arm9.c",
    "content": "/*-----------------------------------------------------------------\n Copyright (C) 2005 - 2010\n\tMichael \"Chishm\" Chisholm\n\tDave \"WinterMute\" Murphy\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n------------------------------------------------------------------*/\n#include <string.h>\n#include <nds.h>\n#include <sys/stat.h>\n#include <limits.h>\n\n#include <unistd.h>\n#include <slim.h>\n\n#include \"load_bin.h\"\n\n#include \"nds_loader_arm9.h\"\n#define LCDC_BANK_C (u16*)0x06840000\n#define STORED_FILE_CLUSTER (*(((u32*)LCDC_BANK_C) + 1))\n#define INIT_DISC (*(((u32*)LCDC_BANK_C) + 2))\n\n#define STORED_FILE_CLUSTER_OFFSET 4 \n#define INIT_DISC_OFFSET 8\n#define ARG_START_OFFSET 16\n#define ARG_SIZE_OFFSET 20\n#define HAVE_DSISD_OFFSET 28\n#define DSIMODE_OFFSET 32\n\ntypedef signed int addr_t;\ntypedef unsigned char data_t;\n\n#define FIX_ALL\t0x01\n#define FIX_GLUE\t0x02\n#define FIX_GOT\t0x04\n#define FIX_BSS\t0x08\n\nstatic addr_t readAddr (data_t *mem, addr_t offset) {\n\treturn ((addr_t*)mem)[offset/sizeof(addr_t)];\n}\n\nstatic void writeAddr (data_t *mem, addr_t offset, addr_t value) {\n\t((addr_t*)mem)[offset/sizeof(addr_t)] = value;\n}\n\nstatic void vramcpy (void* dst, const void* src, int len)\n{\n\tu16* dst16 = (u16*)dst;\n\tu16* src16 = (u16*)src;\n\t\n\tfor ( ; len > 0; len -= 2) {\n\t\t*dst16++ = *src16++;\n\t}\n}\t\n\nint runNds (const void* loader, u32 loaderSize, u32 cluster, bool initDisc, int argc, const char** argv)\n{\n\tchar* argStart;\n\tu16* argData;\n\tu16 argTempVal = 0;\n\tint argSize;\n\tconst char* argChar;\n\n\tirqDisable(IRQ_ALL);\n\n\t// Direct CPU access to VRAM bank C\n\tVRAM_C_CR = VRAM_ENABLE | VRAM_C_LCD;\n\t// Load the loader/patcher into the correct address\n\tvramcpy (LCDC_BANK_C, loader, loaderSize);\n\n\t// Set the parameters for the loader\n\t// STORED_FILE_CLUSTER = cluster;\n\twriteAddr ((data_t*) LCDC_BANK_C, STORED_FILE_CLUSTER_OFFSET, cluster);\n\t// INIT_DISC = initDisc;\n\twriteAddr ((data_t*) LCDC_BANK_C, INIT_DISC_OFFSET, initDisc);\n\n\twriteAddr ((data_t*) LCDC_BANK_C, DSIMODE_OFFSET, isDSiMode());\n\tif(argv[0][0]=='s' && argv[0][1]=='d') {\n\t\twriteAddr ((data_t*) LCDC_BANK_C, HAVE_DSISD_OFFSET, 1);\n\t}\n\n\t// Give arguments to loader\n\targStart = (char*)LCDC_BANK_C + readAddr((data_t*)LCDC_BANK_C, ARG_START_OFFSET);\n\targStart = (char*)(((int)argStart + 3) & ~3);\t// Align to word\n\targData = (u16*)argStart;\n\targSize = 0;\n\t\n\tfor (; argc > 0 && *argv; ++argv, --argc) \n\t{\n\t\tfor (argChar = *argv; *argChar != 0; ++argChar, ++argSize) \n\t\t{\n\t\t\tif (argSize & 1) \n\t\t\t{\n\t\t\t\targTempVal |= (*argChar) << 8;\n\t\t\t\t*argData = argTempVal;\n\t\t\t\t++argData;\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\targTempVal = *argChar;\n\t\t\t}\n\t\t}\n\t\tif (argSize & 1)\n\t\t{\n\t\t\t*argData = argTempVal;\n\t\t\t++argData;\n\t\t}\n\t\targTempVal = 0;\n\t\t++argSize;\n\t}\n\t*argData = argTempVal;\n\t\n\twriteAddr ((data_t*) LCDC_BANK_C, ARG_START_OFFSET, (addr_t)argStart - (addr_t)LCDC_BANK_C);\n\twriteAddr ((data_t*) LCDC_BANK_C, ARG_SIZE_OFFSET, argSize);\n\n\tirqDisable(IRQ_ALL);\n\n\t// Give the VRAM to the ARM7\n\tVRAM_C_CR = VRAM_ENABLE | VRAM_C_ARM7_0x06000000;\n\t// Reset into a passme loop\n\tREG_EXMEMCNT |= ARM7_OWNS_ROM | ARM7_OWNS_CARD;\n\t\n\t*((vu32*)0x02FFFFFC) = 0;\n\t*((vu32*)0x02FFFE04) = (u32)0xE59FF018;\n\t*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;\n\n\tresetARM7(0x06000000);\n\n\tswiSoftReset(); \n\treturn true;\n}\n\nint runNdsFile (const char* filename, int argc, const char** argv)  {\n\n\tstruct stat st;\n\tchar filePath[PATH_MAX];\n\tint pathLen;\n\tconst char* args[1];\n\n\tif (stat (filename, &st) < 0) {\n\t\treturn 1;\n\t}\n\n\tif (argc <= 0 || !argv) {\n\t\t// Construct a command line if we weren't supplied with one\n\t\tif (!getcwd (filePath, PATH_MAX)) {\n\t\t\treturn 2;\n\t\t}\n\t\tpathLen = strlen (filePath);\n\t\tstrcpy (filePath + pathLen, filename);\n\t\targs[0] = filePath;\n\t\targv = args;\n\t}\n\n\treturn runNds (load_bin, load_bin_size, st.st_ino, true, argc, argv);\n}\n\n"
  },
  {
    "path": "arm9/source/nds_loader_arm9.h",
    "content": "/*-----------------------------------------------------------------\n Copyright (C) 2005 - 2010\n\tMichael \"Chishm\" Chisholm\n\tDave \"WinterMute\" Murphy\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n------------------------------------------------------------------*/\n\n#ifndef NDS_LOADER_ARM9_H\n#define NDS_LOADER_ARM9_H\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define LOAD_DEFAULT_NDS 0\n\nint runNds (const void* loader, u32 loaderSize, u32 cluster, bool initDisc, int argc, const char** argv);\n\nint runNdsFile (const char* filename, int argc, const char** argv);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // NDS_LOADER_ARM7_H\n"
  },
  {
    "path": "arm9/source/stringtool.cpp",
    "content": "/*---------------------------------------------------------------------------------\n\n\nCopyright (C) 2007 Acekard, www.acekard.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\n---------------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n\n\n#include \"stringtool.h\"\n#include <cstdarg>\n#include <cstdio>\n#include <malloc.h>\n\nstd::string formatString( const char* fmt, ... )\n{\n    const char * f = fmt;\n    va_list argList;\n    va_start(argList, fmt);\n    char * ptempStr = NULL;\n    size_t max_len = vasiprintf( &ptempStr, f, argList);\n    std::string str( ptempStr );\n    str.resize( max_len );\n    free( ptempStr );\n    va_end(argList);\n    return str;\n}\n"
  },
  {
    "path": "arm9/source/stringtool.h",
    "content": "/*---------------------------------------------------------------------------------\n\n\nCopyright (C) 2007 Acekard, www.acekard.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\n---------------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n\n\n#ifndef _STRINGTOOL_H_\n#define _STRINGTOOL_H_\n\n#include <string>\n\nstd::string formatString( const char* fmt, ... );\n\n\n\n#endif//_STRINGTOOL_H_\n"
  },
  {
    "path": "arm9/source/tonccpy.c",
    "content": "#include \"tonccpy.h\"\n//# tonccpy.c\n\n//! VRAM-safe cpy.\n/*! This version mimics memcpy in functionality, with \n    the benefit of working for VRAM as well. It is also \n    slightly faster than the original memcpy, but faster \n    implementations can be made.\n    \\param dst  Destination pointer.\n    \\param src  Source pointer.\n    \\param size Fill-length in bytes.\n    \\note   The pointers and size need not be word-aligned.\n*/\nvoid tonccpy(void *dst, const void *src, uint size)\n{\n    if(size==0 || dst==NULL || src==NULL)\n        return;\n\n    uint count;\n    u16 *dst16;     // hword destination\n    u8  *src8;      // byte source\n\n    // Ideal case: copy by 4x words. Leaves tail for later.\n    if( ((u32)src|(u32)dst)%4==0 && size>=4)\n    {\n        u32 *src32= (u32*)src, *dst32= (u32*)dst;\n\n        count= size/4;\n        uint tmp= count&3;\n        count /= 4;\n\n        // Duff's Device, good friend!\n        switch(tmp) {\n            do {    *dst32++ = *src32++;\n        case 3:     *dst32++ = *src32++;\n        case 2:     *dst32++ = *src32++;\n        case 1:     *dst32++ = *src32++;\n        case 0:     ; } while(count--);\n        }\n\n        // Check for tail\n        size &= 3;\n        if(size == 0)\n            return;\n\n        src8= (u8*)src32;\n        dst16= (u16*)dst32;\n    }\n    else        // Unaligned.\n    {\n        uint dstOfs= (u32)dst&1;\n        src8= (u8*)src;\n        dst16= (u16*)(dst-dstOfs);\n\n        // Head: 1 byte.\n        if(dstOfs != 0)\n        {\n            *dst16= (*dst16 & 0xFF) | *src8++<<8;\n            dst16++;\n            if(--size==0)\n                return;\n        }\n    }\n\n    // Unaligned main: copy by 2x byte.\n    count= size/2;\n    while(count--)\n    {\n        *dst16++ = src8[0] | src8[1]<<8;\n        src8 += 2;\n    }\n\n    // Tail: 1 byte.\n    if(size&1)\n        *dst16= (*dst16 &~ 0xFF) | *src8;\n}\n//# toncset.c\n\n//! VRAM-safe memset, internal routine.\n/*! This version mimics memset in functionality, with \n    the benefit of working for VRAM as well. It is also \n    slightly faster than the original memset.\n    \\param dst  Destination pointer.\n    \\param fill Word to fill with.\n    \\param size Fill-length in bytes.\n    \\note   The \\a dst pointer and \\a size need not be \n        word-aligned. In the case of unaligned fills, \\a fill \n        will be masked off to match the situation.\n*/\nvoid __toncset(void *dst, u32 fill, uint size)\n{\n    if(size==0 || dst==NULL)\n        return;\n\n    uint left= (u32)dst&3;\n    u32 *dst32= (u32*)(dst-left);\n    u32 count, mask;\n\n    // Unaligned head.\n    if(left != 0)\n    {\n        // Adjust for very small stint.\n        if(left+size<4)\n        {\n            mask= BIT_MASK(size*8)<<(left*8);   \n            *dst32= (*dst32 &~ mask) | (fill & mask);\n            return;\n        }\n\n        mask= BIT_MASK(left*8);\n        *dst32= (*dst32 & mask) | (fill&~mask);\n        dst32++;\n        size -= 4-left;\n    }\n\n    // Main stint.\n    count= size/4;\n    uint tmp= count&3;\n    count /= 4;\n\n    switch(tmp) {\n        do {    *dst32++ = fill;\n    case 3:     *dst32++ = fill;\n    case 2:     *dst32++ = fill;\n    case 1:     *dst32++ = fill;\n    case 0:     ; } while(count--);\n    }\n\n    // Tail\n    size &= 3;\n    if(size)\n    {\n        mask= BIT_MASK(size*8);\n        *dst32= (*dst32 &~ mask) | (fill & mask);\n    }\n}"
  },
  {
    "path": "arm9/source/tonccpy.h",
    "content": "//# Stuff you may not have yet.\n\n#ifndef TONCCPY_H\n#define TONCCPY_H\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <nds.h>\n\ntypedef unsigned int uint;\n#define BIT_MASK(len)       ( (1<<(len))-1 )\nstatic inline u32 quad8(u8 x)   {   x |= x<<8; return x | x<<16;    }\n\n\n//# Declarations and inlines.\n\nvoid tonccpy(void *dst, const void *src, uint size);\n\nvoid __toncset(void *dst, u32 fill, uint size);\nstatic inline void toncset(void *dst, u8 src, uint size);\nstatic inline void toncset16(void *dst, u16 src, uint size);\nstatic inline void toncset32(void *dst, u32 src, uint size);\n\n\n//! VRAM-safe memset, byte version. Size in bytes.\nstatic inline void toncset(void *dst, u8 src, uint size)\n{   __toncset(dst, quad8(src), size);               }\n\n//! VRAM-safe memset, halfword version. Size in hwords.\nstatic inline void toncset16(void *dst, u16 src, uint size)\n{   __toncset(dst, src|src<<16, size*2);            }\n\n//! VRAM-safe memset, word version. Size in words.\nstatic inline void toncset32(void *dst, u32 src, uint size)\n{   __toncset(dst, src, size*4);                    }\n\n#ifdef __cplusplus\n}\n#endif\n#endif\n"
  },
  {
    "path": "bootloader/Makefile",
    "content": "#---------------------------------------------------------------------------------\n.SUFFIXES:\n#---------------------------------------------------------------------------------\nifeq ($(strip $(DEVKITARM)),)\n$(error \"Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM)\nendif\n\n-include $(DEVKITARM)/ds_rules\n\n#---------------------------------------------------------------------------------\n# BUILD is the directory where object files & intermediate files will be placed\n# SOURCES is a list of directories containing source code\n# INCLUDES is a list of directories containing extra header files\n#---------------------------------------------------------------------------------\nTARGET\t\t:=\tload\nBUILD\t\t:=\tbuild\nSOURCES\t\t:=\tsource\nINCLUDES\t:=\tbuild\nSPECS\t\t:=\tspecs\n\n#---------------------------------------------------------------------------------\n# options for code generation\n#---------------------------------------------------------------------------------\nARCH\t:=\t-mthumb -mthumb-interwork\n\nCFLAGS\t:=\t-g -Wall -Os\\\n\t\t\t-mcpu=arm7tdmi -mtune=arm7tdmi -fomit-frame-pointer\\\n\t\t\t-ffast-math \\\n\t\t\t$(ARCH)\n\nCFLAGS\t+=\t$(INCLUDE) $(EXTRA_CFLAGS) -DARM7\n\nASFLAGS\t:=\t-g $(ARCH) $(EXTRA_CFLAGS) $(INCLUDE)\nLDFLAGS\t=\t-nostartfiles -T $(TOPDIR)/load.ld -g $(ARCH) -Wl,-Map,$(TARGET).map\n\nLIBS\t:=\n\n#---------------------------------------------------------------------------------\n# list of directories containing libraries, this must be the top level containing\n# include and lib\n#---------------------------------------------------------------------------------\nLIBDIRS\t:=\t$(LIBNDS)\n\n\n#---------------------------------------------------------------------------------\n# no real need to edit anything past this point unless you need to add additional\n# rules for different file extensions\n#---------------------------------------------------------------------------------\nifneq ($(BUILD),$(notdir $(CURDIR)))\n#---------------------------------------------------------------------------------\n\nexport TOPDIR\t:=\t$(CURDIR)\nexport LOADBIN\t?=\t$(CURDIR)/../data/$(TARGET).bin\nexport LOADELF\t:=\t$(CURDIR)/$(TARGET).elf\nexport DEPSDIR\t:=\t$(CURDIR)/$(BUILD)\n\nexport VPATH\t:=\t$(foreach dir,$(SOURCES),$(CURDIR)/$(dir))\n\nexport CC\t\t:=\t$(PREFIX)gcc\nexport CXX\t\t:=\t$(PREFIX)g++\nexport AR\t\t:=\t$(PREFIX)ar\nexport OBJCOPY\t:=\t$(PREFIX)objcopy\n\nCFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))\nCPPFILES\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))\nSFILES\t\t:=\t$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))\n\nexport OFILES\t:=\t$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)\n\nexport INCLUDE\t:=\t$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \\\n\t\t\t\t\t$(foreach dir,$(LIBDIRS),-I$(dir)/include) \\\n\t\t\t\t\t-I$(CURDIR)/$(BUILD)\n\nexport LIBPATHS\t:=\t$(foreach dir,$(LIBDIRS),-L$(dir)/lib)\n\n#---------------------------------------------------------------------------------\n# use CC for linking standard C\n#---------------------------------------------------------------------------------\nexport LD\t:=\t$(CC)\n#---------------------------------------------------------------------------------\n\n.PHONY: $(BUILD) clean\n\n#---------------------------------------------------------------------------------\n$(BUILD):\n\t@[ -d $@ ] || mkdir -p $@\n\t@$(MAKE) -C $(BUILD) -f $(CURDIR)/Makefile\n\n#---------------------------------------------------------------------------------\nclean:\n\t@echo clean ...\n\t@rm -fr $(BUILD) *.elf *.bin\n\n#---------------------------------------------------------------------------------\nelse\n\nDEPENDS\t:=\t$(OFILES:.o=.d)\n\n#---------------------------------------------------------------------------------\n# main targets\n#---------------------------------------------------------------------------------\n$(LOADBIN)\t:\t$(LOADELF)\n\t@mkdir -p ../../data\n\t@$(OBJCOPY) -O binary $< $@\n\t@echo built ... $(notdir $@)\n\n$(LOADELF)\t: $(OFILES)\n\t@echo linking $(notdir $@)\n\t@$(LD)  $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@\n\narm9mpu_reset.o: mpu_reset.bin\n\nmpu_reset.bin: mpu_reset.elf\n\t$(OBJCOPY) -O binary $< $@\n\nmpu_reset.elf: $(TOPDIR)/arm9code/mpu_reset.s\n\t$(CC) $(ASFLAGS) -Ttext=0 -x assembler-with-cpp -nostartfiles -nostdlib $< -o $@\n\n-include $(DEPENDS)\n#---------------------------------------------------------------------------------------\nendif\n#---------------------------------------------------------------------------------------\n"
  },
  {
    "path": "bootloader/arm9code/mpu_reset.s",
    "content": "/*\n\tCopyright 2006 - 2015 Dave Murphy (WinterMute)\n\n\tThis program is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 2 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n*/\n\n#include <nds/arm9/cache_asm.h>\n\n\t.text\n\t.align 4\n\n\t.arm\n\n\t.arch\tarmv5te\n\t.cpu\tarm946e-s\n\n@---------------------------------------------------------------------------------\n\t.global _start\n\t.type\t_start STT_FUNC\n@---------------------------------------------------------------------------------\n_start:\n@---------------------------------------------------------------------------------\n\t@ Switch off MPU\n\tmrc\tp15, 0, r0, c1, c0, 0\n\tbic\tr0, r0, #PROTECT_ENABLE\n\tmcr\tp15, 0, r0, c1, c0, 0\n\n\n\tadr\tr12, mpu_initial_data\n\tldmia\tr12, {r0-r10}\n\n\tmcr\tp15, 0, r0, c2, c0, 0\n\tmcr\tp15, 0, r0, c2, c0, 1\n\tmcr\tp15, 0, r1, c3, c0, 0\n\tmcr\tp15, 0, r2, c5, c0, 2\n\tmcr\tp15, 0, r3, c5, c0, 3\n\tmcr\tp15, 0, r4, c6, c0, 0\n\tmcr\tp15, 0, r5, c6, c1, 0\n\tmcr\tp15, 0, r6, c6, c3, 0\n\tmcr\tp15, 0, r7, c6, c4, 0\n\tmcr\tp15, 0, r8, c6, c6, 0\n\tmcr\tp15, 0, r9, c6, c7, 0\n\tmcr\tp15, 0, r10, c9, c1, 0\n\n\tmov\tr0, #0\n\tmcr\tp15, 0, r0, c6, c2, 0   @ PU Protection Unit Data/Unified Region 2\n\tmcr\tp15, 0, r0, c6, c5, 0   @ PU Protection Unit Data/Unified Region 5\n\n\tmrc\tp15, 0, r0, c9, c1, 0   @ DTCM\n\tmov\tr0, r0, lsr #12         @ base\n\tmov\tr0, r0, lsl #12         @ size\n\tadd\tr0, r0, #0x4000         @ dtcm top\n\n\tsub\tr0, r0, #4              @ irq vector\n\tmov\tr1, #0\n\tstr \tr1, [r0]\n\tsub\tr0, r0, #4              @ IRQ1 Check Bits\n\tstr \tr1, [r0]\n\n\tsub\tr0, r0, #128\n\tbic\tr0, r0, #7\n\n\tmsr\tcpsr_c, #0xd3      @ svc mode\n\tmov\tsp, r0\n\tsub\tr0, r0, #128\n\tmsr\tcpsr_c, #0xd2      @ irq mode\n\tmov\tsp, r0\n\tsub\tr0, r0, #128\n\tmsr\tcpsr_c, #0xdf      @ system mode\n\tmov\tsp, r0\n\n\t@ enable cache & tcm\n\tmrc\tp15, 0, r0, c1, c0, 0\n\tldr\tr1,= ITCM_ENABLE | DTCM_ENABLE | ICACHE_ENABLE | DCACHE_ENABLE\n\torr\tr0,r0,r1\n\tmcr\tp15, 0, r0, c1, c0, 0\n\n\tldr\tr10, =0x2FFFE04\n\tldr\tr0, =0xE59FF018\n\tstr\tr0, [r10]\n\tadd\tr1, r10, #0x20\n\tstr\tr10, [r1]\n\tbx\tr10\n\n\t.pool\n\nmpu_initial_data:\n\t.word 0x00000042  @ p15,0,c2,c0,0..1,r0 ;PU Cachability Bits for Data/Unified+Instruction Protection Region\n\t.word 0x00000002  @ p15,0,c3,c0,0,r1    ;PU Write-Bufferability Bits for Data Protection Regions\n\t.word 0x15111011  @ p15,0,c5,c0,2,r2    ;PU Extended Access Permission Data/Unified Protection Region\n\t.word 0x05100011  @ p15,0,c5,c0,3,r3    ;PU Extended Access Permission Instruction Protection Region\n\t.word 0x04000033  @ p15,0,c6,c0,0,r4    ;PU Protection Unit Data/Unified Region 0\n\t.word 0x0200002b  @ p15,0,c6,c1,0,r5    ;PU Protection Unit Data/Unified Region 1 4MB\n\t.word 0x08000035  @ p15,0,c6,c3,0,r6    ;PU Protection Unit Data/Unified Region 3\n\t.word 0x0300001b  @ p15,0,c6,c4,0,r7    ;PU Protection Unit Data/Unified Region 4\n\t.word 0xffff001d  @ p15,0,c6,c6,0,r8    ;PU Protection Unit Data/Unified Region 6\n\t.word 0x02fff017  @ p15,0,c6,c7,0,r9    ;PU Protection Unit Data/Unified Region 7 4KB\n\t.word 0x0300000a  @ p15,0,c9,c1,0,r10   ;TCM Data TCM Base and Virtual Size\n"
  },
  {
    "path": "bootloader/load.ld",
    "content": "OUTPUT_FORMAT(\"elf32-littlearm\", \"elf32-bigarm\", \"elf32-littlearm\")\nOUTPUT_ARCH(arm)\nENTRY(_start)\n\nMEMORY {\n\n\tvram\t: ORIGIN = 0x06000000, LENGTH = 128K\n}\n\n__vram_start\t=\tORIGIN(vram);\n__vram_top\t=\tORIGIN(vram)+ LENGTH(vram);\n__sp_irq\t=\t__vram_top - 0x60;\n__sp_svc\t=\t__sp_irq - 0x100;\n__sp_usr\t=\t__sp_svc - 0x100;\n\n__irq_flags\t=\t__vram_top - 8;\n__irq_vector\t=\t__vram_top - 4;\n\nSECTIONS\n{\n\t.init\t:\n\t{\n\t\t__text_start = . ;\n\t\tKEEP (*(.init))\n\t\t. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\t\t\n\t.plt : \n\t{ \n\t\t*(.plt) \n\t} >vram = 0xff\n\n\t.text :   /* ALIGN (4): */\n\t{\n\n\t\t*(.text*)\n\t\t*(.stub)\n\t\t/* .gnu.warning sections are handled specially by elf32.em.  */\n\t\t*(.gnu.warning)\n\t\t*(.gnu.linkonce.t*)\n\t\t*(.glue_7)\n\t\t*(.glue_7t)\n\t\t. = ALIGN(4);  /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\n\t.fini           :\n\t{\n\t\tKEEP (*(.fini))\n\t} >vram =0xff\n\n\t__text_end = . ;\n\n\t.rodata :\n\t{\n\t\t*(.rodata)\n\t\t*all.rodata*(*)\n\t\t*(.roda)\n\t\t*(.rodata.*)\n\t\t*(.gnu.linkonce.r*)\n\t\tSORT(CONSTRUCTORS)\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\n\t.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >vram\n\t__exidx_start = .;\n\t.ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >vram\n\t__exidx_end = .;\n\n/* Ensure the __preinit_array_start label is properly aligned.  We\n   could instead move the label definition inside the section, but\n   the linker would then create the section even if it turns out to\n   be empty, which isn't pretty.  */\n\t. = ALIGN(32 / 8);\n\tPROVIDE (__preinit_array_start = .);\n\t.preinit_array     : { KEEP (*(.preinit_array)) } >vram = 0xff\n\tPROVIDE (__preinit_array_end = .);\n\tPROVIDE (__init_array_start = .);\n\t.init_array     : { KEEP (*(.init_array)) } >vram = 0xff\n\tPROVIDE (__init_array_end = .);\n\tPROVIDE (__fini_array_start = .);\n\t.fini_array     : { KEEP (*(.fini_array)) } >vram = 0xff\n\tPROVIDE (__fini_array_end = .);\n\n\t.ctors :\n\t{\n\t/* gcc uses crtbegin.o to find the start of the constructors, so\n\t\twe make sure it is first.  Because this is a wildcard, it\n\t\tdoesn't matter if the user does not actually link against\n\t\tcrtbegin.o; the linker won't look for a file to match a\n\t\twildcard.  The wildcard also means that it doesn't matter which\n\t\tdirectory crtbegin.o is in.  */\n\t\tKEEP (*crtbegin.o(.ctors))\n\t\tKEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))\n\t\tKEEP (*(SORT(.ctors.*)))\n\t\tKEEP (*(.ctors))\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\n\t.dtors :\n\t{\n\t\tKEEP (*crtbegin.o(.dtors))\n\t\tKEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))\n\t\tKEEP (*(SORT(.dtors.*)))\n\t\tKEEP (*(.dtors))\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\n\t.eh_frame :\n\t{\n\t\tKEEP (*(.eh_frame))\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\n\t.gcc_except_table :\n\t{\n\t\t*(.gcc_except_table)\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t} >vram = 0xff\n\t.jcr            : { KEEP (*(.jcr)) } >vram = 0\n\t.got            : { *(.got.plt) *(.got) } >vram = 0\n\n\t\n\t.vram ALIGN(4) :\n\t{\n\t\t__vram_start = ABSOLUTE(.) ;\n\t\t*(.vram)\n\t\t*vram.*(.text)\n\t\t. = ALIGN(4);   /* REQUIRED. LD is flaky without it. */\n\t\t__vram_end = ABSOLUTE(.) ;\n\t} >vram = 0xff\n\n\n\t.data ALIGN(4) : \t{\n\t\t__data_start = ABSOLUTE(.);\n\t\t*(.data)\n\t\t*(.data.*)\n\t\t*(.gnu.linkonce.d*)\n\t\tCONSTRUCTORS\n\t\t. = ALIGN(4);\n\t\t__data_end = ABSOLUTE(.) ;\n\t} >vram = 0xff\n\n\n\n\t.bss ALIGN(4) :\n\t{\n\t\t__bss_start = ABSOLUTE(.);\n\t\t__bss_start__ = ABSOLUTE(.);\n\t\t*(.dynbss)\n\t\t*(.gnu.linkonce.b*)\n\t\t*(.bss*)\n\t\t*(COMMON)\n\t\t. = ALIGN(4);    /* REQUIRED. LD is flaky without it. */\n\t} >vram\n\n\t__bss_end = . ;\n\t__bss_end__ = . ;\n\n\t_end = . ;\n\t__end__ = . ;\n\tPROVIDE (end = _end);\n\n\t/* Stabs debugging sections.  */\n\t.stab 0 : { *(.stab) }\n\t.stabstr 0 : { *(.stabstr) }\n\t.stab.excl 0 : { *(.stab.excl) }\n\t.stab.exclstr 0 : { *(.stab.exclstr) }\n\t.stab.index 0 : { *(.stab.index) }\n\t.stab.indexstr 0 : { *(.stab.indexstr) }\n\t.comment 0 : { *(.comment) }\n\t/*\tDWARF debug sections.\n\t\tSymbols in the DWARF debugging sections are relative to the beginning\n\t\tof the section so we begin them at 0.  */\n\t/* DWARF 1 */\n\t.debug          0 : { *(.debug) }\n\t.line           0 : { *(.line) }\n\t/* GNU DWARF 1 extensions */\n\t.debug_srcinfo  0 : { *(.debug_srcinfo) }\n\t.debug_sfnames  0 : { *(.debug_sfnames) }\n\t/* DWARF 1.1 and DWARF 2 */\n\t.debug_aranges  0 : { *(.debug_aranges) }\n\t.debug_pubnames 0 : { *(.debug_pubnames) }\n\t/* DWARF 2 */\n\t.debug_info     0 : { *(.debug_info) }\n\t.debug_abbrev   0 : { *(.debug_abbrev) }\n\t.debug_line     0 : { *(.debug_line) }\n\t.debug_frame    0 : { *(.debug_frame) }\n\t.debug_str      0 : { *(.debug_str) }\n\t.debug_loc      0 : { *(.debug_loc) }\n\t.debug_macinfo  0 : { *(.debug_macinfo) }\n\t/* SGI/MIPS DWARF 2 extensions */\n\t.debug_weaknames 0 : { *(.debug_weaknames) }\n\t.debug_funcnames 0 : { *(.debug_funcnames) }\n\t.debug_typenames 0 : { *(.debug_typenames) }\n\t.debug_varnames  0 : { *(.debug_varnames) }\n\t.stack 0x80000 : { _stack = .; *(.stack) }\n\t/* These must appear regardless of  .  */\n}\n"
  },
  {
    "path": "bootloader/source/arm7clear.s",
    "content": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n\n\t.arm\n\t.global arm7clearRAM\n\t.type\tarm7clearRAM STT_FUNC\narm7clearRAM:\n\n\tpush\t{r0-r9}\n\t// clear exclusive IWRAM\n\t// 0380:0000 to 0380:FFFF, total 64KiB\n\tmov\tr0, #0\n\tmov\tr1, #0\n\tmov\tr2, #0\n\tmov\tr3, #0\n\tmov\tr4, #0\n\tmov\tr5, #0\n\tmov\tr6, #0\n\tmov\tr7, #0\n\tmov\tr8, #0x03800000\n\tsub\tr8, #0x00008000\n\tmov\tr9, #0x03800000\n\torr\tr9, r9, #0x10000\nclear_IWRAM_loop:\n\tstmia\tr8!, {r0, r1, r2, r3, r4, r5, r6, r7}\n\tcmp\tr8, r9\n\tblt\tclear_IWRAM_loop\n\n\t// clear most of EWRAM - except after RAM end - 0xc000, which has the bootstub\n\tmov\tr8, #0x02000000\n\tadd\tr8, #0x00000800\n\t\n\tldr\tr9,=0x4004008\n\tldr\tr9,[r9]\n\tands\tr9,r9,#0x8000\n\tbne\tdsi_mode\n\n\tmov\tr9, #0x02400000\n\tb\tds_mode\ndsi_mode:\n\tmov\tr9, #0x03000000\t\nds_mode:\n\tsub\tr9, #0x0000c000\nclear_EWRAM_loop:\n\tstmia\tr8!, {r0, r1, r2, r3, r4, r5, r6, r7}\n\tcmp\tr8, r9\n\tblt\tclear_EWRAM_loop\n\n\tpop\t{r0-r9}\n\t\n\tbx\tlr\n  \n"
  },
  {
    "path": "bootloader/source/arm9clear.arm.c",
    "content": "#define ARM9\n#undef ARM7\n\n#include <nds/ndstypes.h>\n#include <nds/dma.h>\n#include <nds/system.h>\n#include <nds/interrupts.h>\n#include <nds/timers.h>\n\n#include <nds/memory.h>\n#include <nds/arm9/video.h>\n#include <nds/arm9/input.h>\n\n#include \"boot.h\"\n\n/*-------------------------------------------------------------------------\nresetMemory2_ARM9\nClears the ARM9's DMA channels and resets video memory\nWritten by Darkain.\nModified by Chishm:\n * Changed MultiNDS specific stuff\n--------------------------------------------------------------------------*/\nvoid __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) resetMemory2_ARM9 (void) \n{\n \tregister int i;\n\t// int reg;\n  \n\t//clear out ARM9 DMA channels\n\tfor (i=0; i<4; i++) {\n\t\tDMA_CR(i) = 0;\n\t\tDMA_SRC(i) = 0;\n\t\tDMA_DEST(i) = 0;\n\t\tTIMER_CR(i) = 0;\n\t\tTIMER_DATA(i) = 0;\n\t\t// for(reg=0; reg<0x1c; reg+=4)*((u32*)(0x04004104 + ((i*0x1c)+reg))) = 0;//Reset NDMA.\n\t}\n\n\tVRAM_CR = (VRAM_CR & 0xffff0000) | 0x00008080 ;\n\t\n\tvu16 *mainregs = (vu16*)0x04000000;\n\tvu16 *subregs = (vu16*)0x04001000;\n\t\n\tfor (i=0; i<43; i++) {\n\t\tmainregs[i] = 0;\n\t\tsubregs[i] = 0;\n\t}\n\t\n\tREG_DISPSTAT = 0;\n\n\tVRAM_A_CR = 0;\n\tVRAM_B_CR = 0;\n\tVRAM_D_CR = 0;\n\tVRAM_E_CR = 0;\n\tVRAM_F_CR = 0;\n\tVRAM_G_CR = 0;\n\tVRAM_H_CR = 0;\n\tVRAM_I_CR = 0;\n\tREG_POWERCNT  = 0x820F;\n\t//set shared ram to ARM7\n\tWRAM_CR = 0x03;\n\t// REG_EXMEMCNT = 0xE880;\n\n\t// Return to passme loop\n\t*((vu32*)0x02FFFE04) = (u32)0xE59FF018;\t\t// ldr pc, 0x02FFFE24\n\t*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;\t\t// Set ARM9 Loop address\n\n\tasm volatile(\n\t\t\"\\tbx %0\\n\"\n\t\t: : \"r\" (0x02FFFE04)\n\t);\n\twhile(1);\n}\n\n/*\nvoid __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) initMBK_ARM9 (void) \n{\n\n\t*((vu32*)REG_MBK1)=0x8C888480;\n\t*((vu32*)REG_MBK2)=0x8D898581;\n\t*((vu32*)REG_MBK3)=0x9C999591;\n\t*((vu32*)REG_MBK4)=0x8D898581;\n\t*((vu32*)REG_MBK5)=0x9D999591;\n\n\tREG_MBK6=0x080037C0;\n\tREG_MBK7=0x07C03000;\n\tREG_MBK8=0x00003000;\n\tREG_MBK9=0xFF000000;\n\n\t// Return to passme loop\n\t*((vu32*)0x02FFFE04) = (u32)0xE59FF018;\t\t// ldr pc, 0x02FFFE24\n\t*((vu32*)0x02FFFE24) = (u32)0x02FFFE04;\t\t// Set ARM9 Loop address\n\n\tasm volatile(\n\t\t\"\\tbx %0\\n\"\n\t\t: : \"r\" (0x02FFFE04)\n\t);\n\twhile(1);\n}\n*/\n\n/*-------------------------------------------------------------------------\nstartBinary_ARM9\nJumps to the ARM9 NDS binary in sync with the display and ARM7\nWritten by Darkain.\nModified by Chishm:\n * Removed MultiNDS specific stuff\n--------------------------------------------------------------------------*/\nvoid __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) startBinary_ARM9 (void)\n{\n\t// REG_SCFG_CLK = 0x87;\n\t// REG_SCFG_RST = 0x0001;\n\t// REG_SCFG_MC = 0x0018;\n\n\tREG_IME=0;\n\tREG_EXMEMCNT = 0xE880;\n\t// set ARM9 load address to 0 and wait for it to change again\n\tARM9_START_FLAG = 0;\n\twhile(REG_VCOUNT!=191);\n\twhile(REG_VCOUNT==191);\n\twhile ( ARM9_START_FLAG != 1 );\n\tVoidFn arm9code = *(VoidFn*)(0x2FFFE24);\n\tarm9code();\n\twhile(1);\n}\n\n"
  },
  {
    "path": "bootloader/source/arm9mpu_reset.s",
    "content": "\t.arm\n\t.global mpu_reset, mpu_reset_end\n\nmpu_reset:\n\t.incbin \"mpu_reset.bin\"\nmpu_reset_end:\n"
  },
  {
    "path": "bootloader/source/bios.s",
    "content": "\t.text\n\t.align 4\n\n\t.thumb\n\n@---------------------------------------------------------------------------------\n\t.global swiDelay\n\t.thumb_func\n@---------------------------------------------------------------------------------\nswiDelay:\n@---------------------------------------------------------------------------------\n\tswi\t0x03\n\tbx\tlr\n"
  },
  {
    "path": "bootloader/source/boot.c",
    "content": "/*-----------------------------------------------------------------\n boot.c\n \n BootLoader\n Loads a file into memory and runs it\n\n All resetMemory and startBinary functions are based \n on the MultiNDS loader by Darkain.\n Original source available at:\n http://cvs.sourceforge.net/viewcvs.py/ndslib/ndslib/examples/loader/boot/main.cpp\n\nLicense:\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n \nHelpful information:\n This code runs from VRAM bank C on ARM7\n------------------------------------------------------------------*/\n\n#include <nds/ndstypes.h>\n#include <nds/dma.h>\n#include <nds/system.h>\n#include <nds/interrupts.h>\n#include <nds/timers.h>\n#define ARM9\n#undef ARM7\n#include <nds/memory.h>\n#include <nds/arm9/video.h>\n#include <nds/arm9/input.h>\n#undef ARM9\n#define ARM7\n#include <nds/arm7/audio.h>\n#include <string.h>\n\n#include \"sdmmc.h\"\n#include \"fat.h\"\n#include \"card.h\"\n#include \"boot.h\"\n\nvoid mpu_reset();\nvoid mpu_reset_end();\nvoid arm7clearRAM();\n\n//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n// Important things\n#define TEMP_MEM 0x02FFD000\n#define NDS_HEAD 0x02FFFE00\n#define TEMP_ARM9_START_ADDRESS (*(vu32*)0x02FFFFF4)\n\nconst char* bootName = \"BOOTLOADER.NDS\";\n\nextern unsigned long _start;\nextern unsigned long storedFileCluster;\nextern unsigned long initDisc;\nextern unsigned long wantToPatchDLDI;\nextern unsigned long argStart;\nextern unsigned long argSize;\nextern unsigned long dsiSD;\nextern unsigned long dsiMode;\n\n/*-------------------------------------------------------------------------\nresetMemory_ARM7\nClears all of the NDS's RAM that is visible to the ARM7\nWritten by Darkain.\nModified by Chishm:\n * Added STMIA clear mem loop\n--------------------------------------------------------------------------*/\nvoid resetMemory_ARM7 (void)\n{\n\tint i;\n\t\n\tREG_IME = 0;\n\n\tfor (i=0; i<16; i++) {\n\t\tSCHANNEL_CR(i) = 0;\n\t\tSCHANNEL_TIMER(i) = 0;\n\t\tSCHANNEL_SOURCE(i) = 0;\n\t\tSCHANNEL_LENGTH(i) = 0;\n\t}\n\n\tREG_SOUNDCNT = 0;\n\n\t//clear out ARM7 DMA channels and timers\n\tfor (i=0; i<4; i++) {\n\t\tDMA_CR(i) = 0;\n\t\tDMA_SRC(i) = 0;\n\t\tDMA_DEST(i) = 0;\n\t\tTIMER_CR(i) = 0;\n\t\tTIMER_DATA(i) = 0;\n\t}\n\t\n\tarm7clearRAM();\n\n\tREG_IE = 0;\n\tREG_IF = ~0;\n\t(*(vu32*)(0x04000000-4)) = 0;  //IRQ_HANDLER ARM7 version\n\t(*(vu32*)(0x04000000-8)) = ~0; //VBLANK_INTR_WAIT_FLAGS, ARM7 version\n\tREG_POWERCNT = 1;  //turn off power to stuff\n\n}\n\n\nvoid loadBinary_ARM7 (u32 fileCluster)\n{\n\tu32 ndsHeader[0x170>>2];\n\n\t// read NDS header\n\tfileRead ((char*)ndsHeader, fileCluster, 0, 0x170);\n\t// read ARM9 info from NDS header\n\tu32 ARM9_SRC = ndsHeader[0x020>>2];\n\tchar* ARM9_DST = (char*)ndsHeader[0x028>>2];\n\tu32 ARM9_LEN = ndsHeader[0x02C>>2];\n\t// read ARM7 info from NDS header\n\tu32 ARM7_SRC = ndsHeader[0x030>>2];\n\tchar* ARM7_DST = (char*)ndsHeader[0x038>>2];\n\tu32 ARM7_LEN = ndsHeader[0x03C>>2];\n\t\n\t// Load binaries into memory\n\tfileRead(ARM9_DST, fileCluster, ARM9_SRC, ARM9_LEN);\n\tfileRead(ARM7_DST, fileCluster, ARM7_SRC, ARM7_LEN);\n\n\t// first copy the header to its proper location, excluding\n\t// the ARM9 start address, so as not to start it\n\tTEMP_ARM9_START_ADDRESS = ndsHeader[0x024>>2];\t\t// Store for later\n\tndsHeader[0x024>>2] = 0;\n\tdmaCopyWords(3, (void*)ndsHeader, (void*)NDS_HEAD, 0x170);\n\n}\n\n/*-------------------------------------------------------------------------\nstartBinary_ARM7\nJumps to the ARM7 NDS binary in sync with the display and ARM9\nWritten by Darkain.\nModified by Chishm:\n * Removed MultiNDS specific stuff\n--------------------------------------------------------------------------*/\nvoid startBinary_ARM7 (void) {\t\n\n\tREG_IME=0;\n\twhile(REG_VCOUNT!=191);\n\twhile(REG_VCOUNT==191);\n\t// copy NDS ARM9 start address into the header, starting ARM9\n\t*((vu32*)0x02FFFE24) = TEMP_ARM9_START_ADDRESS;\n\tARM9_START_FLAG = 1;\n\n\t// Start ARM7\n\tVoidFn arm7code = *(VoidFn*)(0x2FFFE34);\n\tarm7code();\n}\n#ifndef NO_SDMMC\nint sdmmc_sd_readsectors(u32 sector_no, u32 numsectors, void *out);\n//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n// Main function\nbool sdmmc_inserted() {\n\treturn true;\n}\n\nbool sdmmc_startup() {\n\tsdmmc_controller_init();\n\treturn sdmmc_sdcard_init() == 0;\n}\n\nbool sdmmc_readsectors(u32 sector_no, u32 numsectors, void *out) {\n\treturn sdmmc_sdcard_readsectors(sector_no, numsectors, out) == 0;\n}\n#endif\n\nint main (void) {\n#ifndef NO_SDMMC\n\tif (dsiSD) {\n\t\t_io_dldi.fn_readSectors = sdmmc_readsectors;\n\t\t_io_dldi.fn_isInserted = sdmmc_inserted;\n\t\t_io_dldi.fn_startup = sdmmc_startup;\n\t}\n#endif\n\tu32 fileCluster = storedFileCluster;\n\t// Init card\n\tif(!FAT_InitFiles(initDisc))\n\t{\n\t\treturn -1;\n\t}\n\tif (fileCluster == CLUSTER_FREE)\n\t{\n\t\treturn -1;\n\t}\n\t\n\t// ARM9 clears its memory part 2\n\t// copy ARM9 function to RAM, and make the ARM9 jump to it\n\tmemcpy((u32*)TEMP_MEM, (u32*)resetMemory2_ARM9, resetMemory2_ARM9_size);\n\t(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;\t// Make ARM9 jump to the function\n\t// Wait until the ARM9 has completed its task\n\twhile ((*(vu32*)0x02FFFE24) == (u32)TEMP_MEM);\n\n\t// ARM9 sets up mpu\n\t// copy ARM9 function to RAM, and make the ARM9 jump to it\n\tmemcpy((u32*)TEMP_MEM, (u32*)mpu_reset, mpu_reset_end - mpu_reset);\n\t(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;\t// Make ARM9 jump to the function\n\t// Wait until the ARM9 has completed its task\n\twhile ((*(vu32*)0x02FFFE24) == (u32)TEMP_MEM);\n\n\t// ARM9 enters a wait loop\n\t// copy ARM9 function to RAM, and make the ARM9 jump to it\n\tmemcpy((u32*)TEMP_MEM, (u32*)startBinary_ARM9, startBinary_ARM9_size);\n\t(*(vu32*)0x02FFFE24) = (u32)TEMP_MEM;\t// Make ARM9 jump to the function\n\n\t// Load the NDS file\n\tloadBinary_ARM7(fileCluster);\n\n\t// Reset SDMC. Required to get bootloader to init things correctly.\n\tsdmmc_controller_init();\n\t*(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFDu;\n\t*(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDDu;\n\t*(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 0;\n\n\tstartBinary_ARM7();\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "bootloader/source/boot.h",
    "content": "#ifndef _BOOT_H_\n#define _BOOT_H_\n\n#define initMBK_ARM9_size 0x400\nvoid __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) initMBK_ARM9 ();\n#define resetMemory2_ARM9_size 0x400\nvoid __attribute__ ((long_call)) __attribute__((naked)) __attribute__((noreturn)) resetMemory2_ARM9();\n#define startBinary_ARM9_size 0x100\nvoid __attribute__ ((long_call)) __attribute__((noreturn)) __attribute__((naked)) startBinary_ARM9 ();\n#define ARM9_START_FLAG (*(vu8*)0x02FFFDFB)\n\n#endif // _BOOT_H_\n"
  },
  {
    "path": "bootloader/source/card.h",
    "content": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n\n#ifndef CARD_H\n#define CARD_H\n\n#include \"disc_io.h\"\n#include \"io_dldi.h\"\n\nstatic inline bool CARD_StartUp (void) {\n\treturn _io_dldi.fn_startup();\n}\n\nstatic inline bool CARD_IsInserted (void) {\n\treturn _io_dldi.fn_isInserted();\n}\n\nstatic inline bool CARD_ReadSector (u32 sector, void *buffer) {\n\treturn _io_dldi.fn_readSectors(sector, 1, buffer);\n}\n\nstatic inline bool CARD_ReadSectors (u32 sector, int count, void *buffer) {\n\treturn _io_dldi.fn_readSectors(sector, count, buffer);\n}\n\n#endif // CARD_H\n"
  },
  {
    "path": "bootloader/source/disc_io.h",
    "content": "/*\n disc_io.h\n Interface template for low level disc functions.\n\n Copyright (c) 2006 Michael \"Chishm\" Chisholm\n\t\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n  1. Redistributions of source code must retain the above copyright notice,\n     this list of conditions and the following disclaimer.\n  2. Redistributions in binary form must reproduce the above copyright notice,\n     this list of conditions and the following disclaimer in the documentation and/or\n     other materials provided with the distribution.\n  3. The name of the author may not be used to endorse or promote products derived\n     from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\t2006-07-11 - Chishm\n\t\t* Original release\n\t\t\n\t2006-07-16 - Chishm\n\t\t* Renamed _CF_USE_DMA to _IO_USE_DMA\n\t\t* Renamed _CF_ALLOW_UNALIGNED to _IO_ALLOW_UNALIGNED\n*/\n\n#ifndef _DISC_IO_H\n#define _DISC_IO_H\n\n#include <nds/ndstypes.h>\n#define BYTES_PER_SECTOR 512\n\n//----------------------------------------------------------------------\n// Customisable features\n\n// Use DMA to read the card, remove this line to use normal reads/writes\n// #define _IO_USE_DMA\n\n// Allow buffers not alligned to 16 bits when reading files. \n// Note that this will slow down access speed, so only use if you have to.\n// It is also incompatible with DMA\n#define _IO_ALLOW_UNALIGNED\n\n#if defined _IO_USE_DMA && defined _IO_ALLOW_UNALIGNED\n #error \"You can't use both DMA and unaligned memory\"\n#endif\n\n#define FEATURE_MEDIUM_CANREAD\t\t0x00000001\n#define FEATURE_MEDIUM_CANWRITE\t\t0x00000002\n#define FEATURE_SLOT_GBA\t\t\t0x00000010\n#define FEATURE_SLOT_NDS\t\t\t0x00000020\n\ntypedef bool (* FN_MEDIUM_STARTUP)(void) ;\ntypedef bool (* FN_MEDIUM_ISINSERTED)(void) ;\ntypedef bool (* FN_MEDIUM_READSECTORS)(u32 sector, u32 numSectors, void* buffer) ;\ntypedef bool (* FN_MEDIUM_WRITESECTORS)(u32 sector, u32 numSectors, const void* buffer) ;\ntypedef bool (* FN_MEDIUM_CLEARSTATUS)(void) ;\ntypedef bool (* FN_MEDIUM_SHUTDOWN)(void) ;\n\nstruct IO_INTERFACE_STRUCT {\n\tunsigned long\t\t\tioType ;\n\tunsigned long\t\t\tfeatures ;\n\tFN_MEDIUM_STARTUP\t\tfn_startup ;\n\tFN_MEDIUM_ISINSERTED\tfn_isInserted ;\n\tFN_MEDIUM_READSECTORS\tfn_readSectors ;\n\tFN_MEDIUM_WRITESECTORS\tfn_writeSectors ;\n\tFN_MEDIUM_CLEARSTATUS\tfn_clearStatus ;\n\tFN_MEDIUM_SHUTDOWN\t\tfn_shutdown ;\n} ;\n\ntypedef struct IO_INTERFACE_STRUCT IO_INTERFACE ;\n\n#endif\t// define _DISC_IO_H\n"
  },
  {
    "path": "bootloader/source/fat.c",
    "content": "/*-----------------------------------------------------------------\n fat.c\n \n NDS MP\n GBAMP NDS Firmware Hack Version 2.12\n An NDS aware firmware patch for the GBA Movie Player.\n By Michael Chisholm (Chishm)\n \n Filesystem code based on GBAMP_CF.c by Chishm (me).\n \nLicense:\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n\n#include \"fat.h\"\n#include \"card.h\"\n\n\n//---------------------------------------------------------------\n// FAT constants\n\n#define FILE_LAST 0x00\n#define FILE_FREE 0xE5\n\n#define ATTRIB_ARCH\t0x20\n#define ATTRIB_DIR\t0x10\n#define ATTRIB_LFN\t0x0F\n#define ATTRIB_VOL\t0x08\n#define ATTRIB_HID\t0x02\n#define ATTRIB_SYS\t0x04\n#define ATTRIB_RO\t0x01\n\n#define FAT16_ROOT_DIR_CLUSTER 0x00\n\n// File Constants\n#ifndef EOF\n#define EOF -1\n#define SEEK_SET\t0\n#define SEEK_CUR\t1\n#define SEEK_END\t2\n#endif\n\n\n//-----------------------------------------------------------------\n// FAT constants\n#define CLUSTER_EOF_16\t0xFFFF\n\n#define ATTRIB_ARCH\t0x20\n#define ATTRIB_DIR\t0x10\n#define ATTRIB_LFN\t0x0F\n#define ATTRIB_VOL\t0x08\n#define ATTRIB_HID\t0x02\n#define ATTRIB_SYS\t0x04\n#define ATTRIB_RO\t0x01\n\n//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n// Data Structures\n\n#define __PACKED __attribute__ ((__packed__))\n\n// Boot Sector - must be packed\ntypedef struct\n{\n\tu8\tjmpBoot[3];\n\tu8\tOEMName[8];\n\t// BIOS Parameter Block\n\tu16\tbytesPerSector;\n\tu8\tsectorsPerCluster;\n\tu16\treservedSectors;\n\tu8\tnumFATs;\n\tu16\trootEntries;\n\tu16\tnumSectorsSmall;\n\tu8\tmediaDesc;\n\tu16\tsectorsPerFAT;\n\tu16\tsectorsPerTrk;\n\tu16\tnumHeads;\n\tu32\tnumHiddenSectors;\n\tu32\tnumSectors;\n\tunion\t// Different types of extended BIOS Parameter Block for FAT16 and FAT32\n\t{\n\t\tstruct  \n\t\t{\n\t\t\t// Ext BIOS Parameter Block for FAT16\n\t\t\tu8\tdriveNumber;\n\t\t\tu8\treserved1;\n\t\t\tu8\textBootSig;\n\t\t\tu32\tvolumeID;\n\t\t\tu8\tvolumeLabel[11];\n\t\t\tu8\tfileSysType[8];\n\t\t\t// Bootcode\n\t\t\tu8\tbootCode[448];\n\t\t} __PACKED fat16;\n\t\tstruct  \n\t\t{\n\t\t\t// FAT32 extended block\n\t\t\tu32\tsectorsPerFAT32;\n\t\t\tu16\textFlags;\n\t\t\tu16\tfsVer;\n\t\t\tu32\trootClus;\n\t\t\tu16\tfsInfo;\n\t\t\tu16\tbkBootSec;\n\t\t\tu8\treserved[12];\n\t\t\t// Ext BIOS Parameter Block for FAT16\n\t\t\tu8\tdriveNumber;\n\t\t\tu8\treserved1;\n\t\t\tu8\textBootSig;\n\t\t\tu32\tvolumeID;\n\t\t\tu8\tvolumeLabel[11];\n\t\t\tu8\tfileSysType[8];\n\t\t\t// Bootcode\n\t\t\tu8\tbootCode[420];\n\t\t} __PACKED fat32;\n\t}\textBlock;\n\n\t__PACKED\tu16\tbootSig;\n\n}\t__PACKED BOOT_SEC;\n\n// Directory entry - must be packed\ntypedef struct\n{\n\tu8\tname[8];\n\tu8\text[3];\n\tu8\tattrib;\n\tu8\treserved;\n\tu8\tcTime_ms;\n\tu16\tcTime;\n\tu16\tcDate;\n\tu16\taDate;\n\tu16\tstartClusterHigh;\n\tu16\tmTime;\n\tu16\tmDate;\n\tu16\tstartCluster;\n\tu32\tfileSize;\n}\t__PACKED DIR_ENT;\n\n// File information - no need to pack\ntypedef struct\n{\n\tu32 firstCluster;\n\tu32 length;\n\tu32 curPos;\n\tu32 curClus;\t\t\t// Current cluster to read from\n\tint curSect;\t\t\t// Current sector within cluster\n\tint curByte;\t\t\t// Current byte within sector\n\tchar readBuffer[512];\t// Buffer used for unaligned reads\n\tu32 appClus;\t\t\t// Cluster to append to\n\tint appSect;\t\t\t// Sector within cluster for appending\n\tint appByte;\t\t\t// Byte within sector for appending\n\tbool read;\t// Can read from file\n\tbool write;\t// Can write to file\n\tbool append;// Can append to file\n\tbool inUse;\t// This file is open\n\tu32 dirEntSector;\t// The sector where the directory entry is stored\n\tint dirEntOffset;\t// The offset within the directory sector\n}\tFAT_FILE;\n\n\n//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n// Global Variables\n\n// _VARS_IN_RAM variables are stored in the largest section of WRAM \n// available: IWRAM on NDS ARM7, EWRAM on NDS ARM9 and GBA\n\n// Locations on card\nint discRootDir;\nint discRootDirClus;\nint discFAT;\nint discSecPerFAT;\nint discNumSec;\nint discData;\nint discBytePerSec;\nint discSecPerClus;\nint discBytePerClus;\n\nenum {FS_UNKNOWN, FS_FAT12, FS_FAT16, FS_FAT32} discFileSystem;\n\n// Global sector buffer to save on stack space\nunsigned char globalBuffer[BYTES_PER_SECTOR];\n\n\n//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n//FAT routines\n\nu32 FAT_ClustToSect (u32 cluster) {\n\treturn (((cluster-2) * discSecPerClus) + discData);\n}\n\n/*-----------------------------------------------------------------\nFAT_NextCluster\nInternal function - gets the cluster linked from input cluster\n-----------------------------------------------------------------*/\nu32 FAT_NextCluster(u32 cluster)\n{\n\tu32 nextCluster = CLUSTER_FREE;\n\tu32 sector;\n\tint offset;\n\t\n\t\n\tswitch (discFileSystem) \n\t{\n\t\tcase FS_UNKNOWN:\n\t\t\tnextCluster = CLUSTER_FREE;\n\t\t\tbreak;\n\t\t\t\n\t\tcase FS_FAT12:\n\t\t\tsector = discFAT + (((cluster * 3) / 2) / BYTES_PER_SECTOR);\n\t\t\toffset = ((cluster * 3) / 2) % BYTES_PER_SECTOR;\n\t\t\tCARD_ReadSector(sector, globalBuffer);\n\t\t\tnextCluster = ((u8*) globalBuffer)[offset];\n\t\t\toffset++;\n\t\t\t\n\t\t\tif (offset >= BYTES_PER_SECTOR) {\n\t\t\t\toffset = 0;\n\t\t\t\tsector++;\n\t\t\t}\n\t\t\t\n\t\t\tCARD_ReadSector(sector, globalBuffer);\n\t\t\tnextCluster |= (((u8*) globalBuffer)[offset]) << 8;\n\t\t\t\n\t\t\tif (cluster & 0x01) {\n\t\t\t\tnextCluster = nextCluster >> 4;\n\t\t\t} else \t{\n\t\t\t\tnextCluster &= 0x0FFF;\n\t\t\t}\n\t\t\t\n\t\t\tbreak;\n\t\t\t\n\t\tcase FS_FAT16:\n\t\t\tsector = discFAT + ((cluster << 1) / BYTES_PER_SECTOR);\n\t\t\toffset = cluster % (BYTES_PER_SECTOR >> 1);\n\t\t\t\n\t\t\tCARD_ReadSector(sector, globalBuffer);\n\t\t\t// read the nextCluster value\n\t\t\tnextCluster = ((u16*)globalBuffer)[offset];\n\t\t\t\n\t\t\tif (nextCluster >= 0xFFF7)\n\t\t\t{\n\t\t\t\tnextCluster = CLUSTER_EOF;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\tcase FS_FAT32:\n\t\t\tsector = discFAT + ((cluster << 2) / BYTES_PER_SECTOR);\n\t\t\toffset = cluster % (BYTES_PER_SECTOR >> 2);\n\t\t\t\n\t\t\tCARD_ReadSector(sector, globalBuffer);\n\t\t\t// read the nextCluster value\n\t\t\tnextCluster = (((u32*)globalBuffer)[offset]) & 0x0FFFFFFF;\n\t\t\t\n\t\t\tif (nextCluster >= 0x0FFFFFF7)\n\t\t\t{\n\t\t\t\tnextCluster = CLUSTER_EOF;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\tdefault:\n\t\t\tnextCluster = CLUSTER_FREE;\n\t\t\tbreak;\n\t}\n\t\n\treturn nextCluster;\n}\n\n/*-----------------------------------------------------------------\nucase\nReturns the uppercase version of the given char\nchar IN: a character\nchar return OUT: uppercase version of character\n-----------------------------------------------------------------*/\nchar ucase (char character)\n{\n\tif ((character > 0x60) && (character < 0x7B))\n\t\tcharacter = character - 0x20;\n\treturn (character);\n}\n\n/*-----------------------------------------------------------------\nFAT_InitFiles\nReads the FAT information from the CF card.\nYou need to call this before reading any files.\nbool return OUT: true if successful.\n-----------------------------------------------------------------*/\nbool FAT_InitFiles (bool initCard)\n{\n\tint i;\n\tint bootSector;\n\tBOOT_SEC* bootSec;\n\t\n\tif (initCard && !CARD_StartUp())\n\t{\n\t\treturn (false);\n\t}\n\t\n\t// Read first sector of card\n\tif (!CARD_ReadSector (0, globalBuffer)) \n\t{\n\t\treturn false;\n\t}\n\t// Check if there is a FAT string, which indicates this is a boot sector\n\tif ((globalBuffer[0x36] == 'F') && (globalBuffer[0x37] == 'A') && (globalBuffer[0x38] == 'T'))\n\t{\n\t\tbootSector = 0;\n\t}\n\t// Check for FAT32\n\telse if ((globalBuffer[0x52] == 'F') && (globalBuffer[0x53] == 'A') && (globalBuffer[0x54] == 'T'))\n\t{\n\t\tbootSector = 0;\n\t}\n\telse\t// This is an MBR\n\t{\n\t\t// Find first valid partition from MBR\n\t\t// First check for an active partition\n\t\tfor (i=0x1BE; (i < 0x1FE) && (globalBuffer[i] != 0x80); i+= 0x10);\n\t\t// If it didn't find an active partition, search for any valid partition\n\t\tif (i == 0x1FE) \n\t\t\tfor (i=0x1BE; (i < 0x1FE) && (globalBuffer[i+0x04] == 0x00); i+= 0x10);\n\t\t\n\t\t// Go to first valid partition\n\t\tif ( i != 0x1FE)\t// Make sure it found a partition\n\t\t{\n\t\t\tbootSector = globalBuffer[0x8 + i] + (globalBuffer[0x9 + i] << 8) + (globalBuffer[0xA + i] << 16) + ((globalBuffer[0xB + i] << 24) & 0x0F);\n\t\t} else {\n\t\t\tbootSector = 0;\t// No partition found, assume this is a MBR free disk\n\t\t}\n\t}\n\n\t// Read in boot sector\n\tbootSec = (BOOT_SEC*) globalBuffer;\n\tCARD_ReadSector (bootSector,  bootSec);\n\n\t// Store required information about the file system\n\tif (bootSec->sectorsPerFAT != 0)\n\t{\n\t\tdiscSecPerFAT = bootSec->sectorsPerFAT;\n\t}\n\telse\n\t{\n\t\tdiscSecPerFAT = bootSec->extBlock.fat32.sectorsPerFAT32;\n\t}\n\t\n\tif (bootSec->numSectorsSmall != 0)\n\t{\n\t\tdiscNumSec = bootSec->numSectorsSmall;\n\t}\n\telse\n\t{\n\t\tdiscNumSec = bootSec->numSectors;\n\t}\n\n\tdiscBytePerSec = BYTES_PER_SECTOR;\t// Sector size is redefined to be 512 bytes\n\tdiscSecPerClus = bootSec->sectorsPerCluster * bootSec->bytesPerSector / BYTES_PER_SECTOR;\n\tdiscBytePerClus = discBytePerSec * discSecPerClus;\n\tdiscFAT = bootSector + bootSec->reservedSectors;\n\n\tdiscRootDir = discFAT + (bootSec->numFATs * discSecPerFAT);\n\tdiscData = discRootDir + ((bootSec->rootEntries * sizeof(DIR_ENT)) / BYTES_PER_SECTOR);\n\n\tif ((discNumSec - discData) / bootSec->sectorsPerCluster < 4085)\n\t{\n\t\tdiscFileSystem = FS_FAT12;\n\t}\n\telse if ((discNumSec - discData) / bootSec->sectorsPerCluster < 65525)\n\t{\n\t\tdiscFileSystem = FS_FAT16;\n\t}\n\telse\n\t{\n\t\tdiscFileSystem = FS_FAT32;\n\t}\n\n\tif (discFileSystem != FS_FAT32)\n\t{\n\t\tdiscRootDirClus = FAT16_ROOT_DIR_CLUSTER;\n\t}\n\telse\t// Set up for the FAT32 way\n\t{\n\t\tdiscRootDirClus = bootSec->extBlock.fat32.rootClus;\n\t\t// Check if FAT mirroring is enabled\n\t\tif (!(bootSec->extBlock.fat32.extFlags & 0x80))\n\t\t{\n\t\t\t// Use the active FAT\n\t\t\tdiscFAT = discFAT + ( discSecPerFAT * (bootSec->extBlock.fat32.extFlags & 0x0F));\n\t\t}\n\t}\n\n\treturn (true);\n}\n\n\n/*-----------------------------------------------------------------\nfileRead(buffer, cluster, startOffset, length)\n-----------------------------------------------------------------*/\nu32 fileRead (char* buffer, u32 cluster, u32 startOffset, u32 length)\n{\n\tint curByte;\n\tint curSect;\n\t\n\tint dataPos = 0;\n\tint chunks;\n\tint beginBytes;\n\n\tif (cluster == CLUSTER_FREE || cluster == CLUSTER_EOF) \n\t{\n\t\treturn 0;\n\t}\n\t\n\t// Follow cluster list until desired one is found\n\tfor (chunks = startOffset / discBytePerClus; chunks > 0; chunks--)\n\t{\n\t\tcluster = FAT_NextCluster (cluster);\n\t}\n\t\n\t// Calculate the sector and byte of the current position,\n\t// and store them\n\tcurSect = (startOffset % discBytePerClus) / BYTES_PER_SECTOR;\n\tcurByte = startOffset % BYTES_PER_SECTOR;\n\n\t// Load sector buffer for new position in file\n\tCARD_ReadSector( curSect + FAT_ClustToSect(cluster), globalBuffer);\n\tcurSect++;\n\n\t// Number of bytes needed to read to align with a sector\n\tbeginBytes = (BYTES_PER_SECTOR < length + curByte ? (BYTES_PER_SECTOR - curByte) : length);\n\n\t// Read first part from buffer, to align with sector boundary\n\tfor (dataPos = 0 ; dataPos < beginBytes; dataPos++)\n\t{\n\t\tbuffer[dataPos] = globalBuffer[curByte++];\n\t}\n\n\t// Read in all the 512 byte chunks of the file directly, saving time\n\tfor ( chunks = ((int)length - beginBytes) / BYTES_PER_SECTOR; chunks > 0;)\n\t{\n\t\tint sectorsToRead;\n\n\t\t// Move to the next cluster if necessary\n\t\tif (curSect >= discSecPerClus)\n\t\t{\n\t\t\tcurSect = 0;\n\t\t\tcluster = FAT_NextCluster (cluster);\n\t\t}\n\n\t\t// Calculate how many sectors to read (read a maximum of discSecPerClus at a time)\n\t\tsectorsToRead = discSecPerClus - curSect;\n\t\tif(chunks < sectorsToRead)\n\t\t\tsectorsToRead = chunks;\n\n\t\t// Read the sectors\n\t\tCARD_ReadSectors(curSect + FAT_ClustToSect(cluster), sectorsToRead, buffer + dataPos);\n\t\tchunks  -= sectorsToRead;\n\t\tcurSect += sectorsToRead;\n\t\tdataPos += BYTES_PER_SECTOR * sectorsToRead;\n\t}\n\n\t// Take care of any bytes left over before end of read\n\tif (dataPos < length)\n\t{\n\n\t\t// Update the read buffer\n\t\tcurByte = 0;\n\t\tif (curSect >= discSecPerClus)\n\t\t{\n\t\t\tcurSect = 0;\n\t\t\tcluster = FAT_NextCluster (cluster);\n\t\t}\n\t\tCARD_ReadSector( curSect + FAT_ClustToSect( cluster), globalBuffer);\n\t\t\n\t\t// Read in last partial chunk\n\t\tfor (; dataPos < length; dataPos++)\n\t\t{\n\t\t\tbuffer[dataPos] = globalBuffer[curByte];\n\t\t\tcurByte++;\n\t\t}\n\t}\n\t\n\treturn dataPos;\n}\n"
  },
  {
    "path": "bootloader/source/fat.h",
    "content": "/*-----------------------------------------------------------------\n fat.h\n \n NDS MP\n GBAMP NDS Firmware Hack Version 2.12\n An NDS aware firmware patch for the GBA Movie Player.\n By Michael Chisholm (Chishm)\n \n Filesystem code based on GBAMP_CF.c by Chishm (me).\n \nLicense:\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n\n#ifndef FAT_H\n#define FAT_H\n\n#include <nds/ndstypes.h>\n\n#define CLUSTER_FREE\t0x00000000\n#define\tCLUSTER_EOF\t\t0x0FFFFFFF\n#define CLUSTER_FIRST\t0x00000002\n\nbool FAT_InitFiles (bool initCard);\nu32 getBootFileCluster (const char* bootName);\nu32 fileRead (char* buffer, u32 cluster, u32 startOffset, u32 length);\nu32 FAT_ClustToSect (u32 cluster);\n\n#endif // FAT_H\n"
  },
  {
    "path": "bootloader/source/io_dldi.h",
    "content": "/*\n io_dldi.h \n\n Reserved space for post-compilation adding of an extra driver\n\n Copyright (c) 2006 Michael \"Chishm\" Chisholm\n\t\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n  1. Redistributions of source code must retain the above copyright notice,\n     this list of conditions and the following disclaimer.\n  2. Redistributions in binary form must reproduce the above copyright notice,\n     this list of conditions and the following disclaimer in the documentation and/or\n     other materials provided with the distribution.\n  3. The name of the author may not be used to endorse or promote products derived\n     from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\t2006-12-22 - Chishm\n\t\t* Original release\n*/\n\n#ifndef IO_DLDI_H\n#define IO_DLDI_H\n\n// 'DLDD'\n#define DEVICE_TYPE_DLDD 0x49444C44\n\n#include \"disc_io.h\"\n\n// export interface\nextern IO_INTERFACE _io_dldi ;\n\n#endif\t// define IO_DLDI_H\n"
  },
  {
    "path": "bootloader/source/io_dldi.s",
    "content": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n@---------------------------------------------------------------------------------\n\t.align\t4\n\t.arm\n\t.global _dldi_start\n\t.global _io_dldi\n@---------------------------------------------------------------------------------\n.equ FEATURE_MEDIUM_CANREAD,\t\t0x00000001\n.equ FEATURE_MEDIUM_CANWRITE,\t\t0x00000002\n.equ FEATURE_SLOT_GBA,\t\t\t0x00000010\n.equ FEATURE_SLOT_NDS,\t\t\t0x00000020\n\n\n_dldi_start:\n#ifndef NO_DLDI\n\n@---------------------------------------------------------------------------------\n@ Driver patch file standard header -- 16 bytes\n#ifdef STANDARD_DLDI\n\t.word\t0xBF8DA5ED\t\t@ Magic number to identify this region\n#else\n\t.word\t0xBF8DA5EE\t\t@ Magic number to identify this region\n#endif\n\t.asciz\t\" Chishm\"\t\t@ Identifying Magic string (8 bytes with null terminator)\n\t.byte\t0x01\t\t\t@ Version number\n\t.byte\t0x0e\t\t@ 16KiB\t@ Log [base-2] of the size of this driver in bytes.\n\t.byte\t0x00\t\t\t@ Sections to fix\n\t.byte \t0x0e\t\t@ 16KiB\t@ Log [base-2] of the allocated space in bytes.\n\t\n@---------------------------------------------------------------------------------\n@ Text identifier - can be anything up to 47 chars + terminating null -- 16 bytes\n\t.align\t4\n\t.asciz \"Loader (No interface)\"\n\n@---------------------------------------------------------------------------------\n@ Offsets to important sections within the data\t-- 32 bytes\n\t.align\t6\n\t.word   _dldi_start\t\t@ data start\n\t.word   _dldi_end\t\t@ data end\n\t.word\t0x00000000\t\t@ Interworking glue start\t-- Needs address fixing\n\t.word\t0x00000000\t\t@ Interworking glue end\n\t.word   0x00000000\t\t@ GOT start\t\t\t-- Needs address fixing\n\t.word   0x00000000\t\t@ GOT end\n\t.word   0x00000000\t\t@ bss start\t\t\t-- Needs setting to zero\n\t.word   0x00000000\t\t@ bss end\n@---------------------------------------------------------------------------------\n@ IO_INTERFACE data -- 32 bytes\n_io_dldi:\n\t.ascii\t\"DLDI\"\t\t\t\t@ ioType\n\t.word\t0x00000000\t\t\t@ Features\n\t.word\t_DLDI_startup\t\t\t@ \n\t.word\t_DLDI_isInserted\t\t@ \n\t.word\t_DLDI_readSectors\t\t@   Function pointers to standard device driver functions\n\t.word\t_DLDI_writeSectors\t\t@ \n\t.word\t_DLDI_clearStatus\t\t@ \n\t.word\t_DLDI_shutdown\t\t\t@ \n\n\t\n@---------------------------------------------------------------------------------\n\n_DLDI_startup:\n_DLDI_isInserted:\n_DLDI_readSectors:\n_DLDI_writeSectors:\n_DLDI_clearStatus:\n_DLDI_shutdown:\n\tmov\t\tr0, #0x00\t\t@ Return false for every function\n\tbx\t\tlr\n\n\n\n@---------------------------------------------------------------------------------\n\t.align\n\t.pool\n\n\t.space (_dldi_start + 16384) - .\t@ Fill to 16KiB\n\n_dldi_end:\n\t.end\n@---------------------------------------------------------------------------------\n#else\n@---------------------------------------------------------------------------------\n@ IO_INTERFACE data -- 32 bytes\n_io_dldi:\n\t.ascii\t\"DLDI\"\t\t\t\t@ ioType\n\t.word\t0x00000000\t\t\t@ Features\n\t.word\t_DLDI_startup\t\t\t@\n\t.word\t_DLDI_isInserted\t\t@\n\t.word\t_DLDI_readSectors\t\t@   Function pointers to standard device driver functions\n\t.word\t_DLDI_writeSectors\t\t@\n\t.word\t_DLDI_clearStatus\t\t@\n\t.word\t_DLDI_shutdown\t\t\t@\n\n\t_DLDI_startup:\n_DLDI_isInserted:\n_DLDI_readSectors:\n_DLDI_writeSectors:\n_DLDI_clearStatus:\n_DLDI_shutdown:\n\tmov\t\tr0, #0x00\t\t@ Return false for every function\n\tbx\t\tlr\n\n\n#endif\n"
  },
  {
    "path": "bootloader/source/load_crt0.s",
    "content": "/*-----------------------------------------------------------------\n\n Copyright (C) 2005  Michael \"Chishm\" Chisholm\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n\n If you use this code, please give due credit and email me about your\n project at chishm@hotmail.com\n------------------------------------------------------------------*/\n\n@---------------------------------------------------------------------------------\n\t.section \".init\"\n\t.global _start\n\t.global storedFileCluster\n\t.global initDisc\n\t.global wantToPatchDLDI\n\t.global argStart\n\t.global argSize\n\t.global dsiSD\n\t.global dsiMode\n@---------------------------------------------------------------------------------\n\t.align\t4\n\t.arm\n@---------------------------------------------------------------------------------\n_start:\n@---------------------------------------------------------------------------------\n\tb\tstartUp\n\nstoredFileCluster:\n\t.word\t0x0FFFFFFF\t\t@ default BOOT.NDS\ninitDisc:\n\t.word\t0x00000001\t\t@ init the disc by default\nwantToPatchDLDI:\n\t.word\t0x00000001\t\t@ by default patch the DLDI section of the loaded NDS\n@ Used for passing arguments to the loaded app\nargStart:\n\t.word\t_end - _start\nargSize:\n\t.word\t0x00000000\ndldiOffset:\n\t.word\t_dldi_start - _start\ndsiSD:\n\t.word\t0\ndsiMode:\n\t.word\t0\n\nstartUp:\n\tmov\tr0, #0x04000000\n\tmov\tr1, #0\n\tstr\tr1, [r0,#0x208]\t\t@ REG_IME\n\tstr\tr1, [r0,#0x210]\t\t@ REG_IE\n\tstr\tr1, [r0,#0x218]\t\t@ REG_AUXIE\n\n\tmov\tr0, #0x12\t\t@ Switch to IRQ Mode\n\tmsr\tcpsr, r0\n\tldr\tsp, =__sp_irq\t\t@ Set IRQ stack\n\n\tmov\tr0, #0x13\t\t@ Switch to SVC Mode\n\tmsr\tcpsr, r0\n\tldr\tsp, =__sp_svc\t\t@ Set SVC stack\n\n\tmov\tr0, #0x1F\t\t@ Switch to System Mode\n\tmsr\tcpsr, r0\n\tldr\tsp, =__sp_usr\t\t@ Set user stack\n\n\tldr\tr0, =__bss_start\t@ Clear BSS section to 0x00\n\tldr\tr1, =__bss_end\n\tsub\tr1, r1, r0\n\tbl\tClearMem\n\n\tmov\tr0, #0\t\t\t@ int argc\n\tmov\tr1, #0\t\t\t@ char *argv[]\n\tldr\tr3, =main\n\tbl\t_blx_r3_stub\t\t@ jump to user code\n\n\t@ If the user ever returns, restart\n\tb\t_start\n\n@---------------------------------------------------------------------------------\n_blx_r3_stub:\n@---------------------------------------------------------------------------------\n\tbx\tr3\n\n@---------------------------------------------------------------------------------\n@ Clear memory to 0x00 if length != 0\n@  r0 = Start Address\n@  r1 = Length\n@---------------------------------------------------------------------------------\nClearMem:\n@---------------------------------------------------------------------------------\n\tmov\tr2, #3\t\t\t@ Round down to nearest word boundary\n\tadd\tr1, r1, r2\t\t@ Shouldn't be needed\n\tbics\tr1, r1, r2\t\t@ Clear 2 LSB (and set Z)\n\tbxeq\tlr\t\t\t@ Quit if copy size is 0\n\n\tmov\tr2, #0\nClrLoop:\n\tstmia\tr0!, {r2}\n\tsubs\tr1, r1, #4\n\tbne\tClrLoop\n\tbx\tlr\n\n@---------------------------------------------------------------------------------\n@ Copy memory if length\t!= 0\n@  r1 = Source Address\n@  r2 = Dest Address\n@  r4 = Dest Address + Length\n@---------------------------------------------------------------------------------\nCopyMemCheck:\n@---------------------------------------------------------------------------------\n\tsub\tr3, r4, r2\t\t@ Is there any data to copy?\n@---------------------------------------------------------------------------------\n@ Copy memory\n@  r1 = Source Address\n@  r2 = Dest Address\n@  r3 = Length\n@---------------------------------------------------------------------------------\nCopyMem:\n@---------------------------------------------------------------------------------\n\tmov\tr0, #3\t\t\t@ These commands are used in cases where\n\tadd\tr3, r3, r0\t\t@ the length is not a multiple of 4,\n\tbics\tr3, r3, r0\t\t@ even though it should be.\n\tbxeq\tlr\t\t\t@ Length is zero, so exit\nCIDLoop:\n\tldmia\tr1!, {r0}\n\tstmia\tr2!, {r0}\n\tsubs\tr3, r3, #4\n\tbne\tCIDLoop\n\tbx\tlr\n\n@---------------------------------------------------------------------------------\n\t.align\n\t.pool\n\t.end\n@---------------------------------------------------------------------------------\n"
  },
  {
    "path": "bootloader/source/sdmmc.c",
    "content": "#ifndef NO_SDMMC\n#include <nds/bios.h>\n#include \"sdmmc.h\"\n#include <stddef.h>\n\nstatic struct mmcdevice deviceSD;\n\n//---------------------------------------------------------------------------------\nint geterror(struct mmcdevice *ctx) {\n//---------------------------------------------------------------------------------\n    //if(ctx->error == 0x4) return -1;\n    //else return 0;\n    return (ctx->error << 29) >> 31;\n}\n\n\n//---------------------------------------------------------------------------------\nvoid setTarget(struct mmcdevice *ctx) {\n//---------------------------------------------------------------------------------\n    sdmmc_mask16(REG_SDPORTSEL,0x3,(u16)ctx->devicenumber);\n    setckl(ctx->clk);\n    if (ctx->SDOPT == 0) {\n        sdmmc_mask16(REG_SDOPT, 0, 0x8000);\n    } else {\n        sdmmc_mask16(REG_SDOPT, 0x8000, 0);\n    }\n\n}\n\n\n//---------------------------------------------------------------------------------\nvoid sdmmc_send_command(struct mmcdevice *ctx, uint32_t cmd, uint32_t args) {\n//---------------------------------------------------------------------------------\n\tconst bool getSDRESP = (cmd << 15) >> 31;\n\tu16 flags = (cmd << 15) >> 31;\n\tconst bool readdata = cmd & 0x20000;\n\tconst bool writedata = cmd & 0x40000;\n\n\tif(readdata || writedata)\n\t{\n\t\tflags |= TMIO_STAT0_DATAEND;\n\t}\n\n\tctx->error = 0;\n\twhile((sdmmc_read16(REG_SDSTATUS1) & TMIO_STAT1_CMD_BUSY)); //mmc working?\n\tsdmmc_write16(REG_SDIRMASK0,0);\n\tsdmmc_write16(REG_SDIRMASK1,0);\n\tsdmmc_write16(REG_SDSTATUS0,0);\n\tsdmmc_write16(REG_SDSTATUS1,0);\n\tsdmmc_mask16(REG_SDDATACTL32,0x1800,0x400); // Disable TX32RQ and RX32RDY IRQ. Clear fifo.\n\tsdmmc_write16(REG_SDCMDARG0,args &0xFFFF);\n\tsdmmc_write16(REG_SDCMDARG1,args >> 16);\n\tsdmmc_write16(REG_SDCMD,cmd &0xFFFF);\n\n\tu32 size = ctx->size;\n\tconst u16 blkSize = sdmmc_read16(REG_SDBLKLEN32);\n\tu32 *rDataPtr32 = (u32*)ctx->rData;\n\tu8  *rDataPtr8  = ctx->rData;\n\tconst u32 *tDataPtr32 = (u32*)ctx->tData;\n\tconst u8  *tDataPtr8  = ctx->tData;\n\n\tbool rUseBuf = ( NULL != rDataPtr32 );\n\tbool tUseBuf = ( NULL != tDataPtr32 );\n\n\tu16 status0 = 0;\n\twhile(1)\n\t{\n\t\tvolatile u16 status1 = sdmmc_read16(REG_SDSTATUS1);\n#ifdef DATA32_SUPPORT\n\t\tvolatile u16 ctl32 = sdmmc_read16(REG_SDDATACTL32);\n\t\tif((ctl32 & 0x100))\n#else\n\t\tif((status1 & TMIO_STAT1_RXRDY))\n#endif\n\t\t{\n\t\t\tif(readdata)\n\t\t\t{\n\t\t\t\tif(rUseBuf)\n\t\t\t\t{\n\t\t\t\t\tsdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_RXRDY, 0);\n\t\t\t\t\tif(size >= blkSize)\n\t\t\t\t\t{\n\t\t\t\t\t\t#ifdef DATA32_SUPPORT\n\t\t\t\t\t\tif(!((u32)rDataPtr32 & 3))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t*rDataPtr32++ = sdmmc_read32(REG_SDFIFO32);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tu32 data = sdmmc_read32(REG_SDFIFO32);\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data;\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data >> 8;\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data >> 16;\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data >> 24;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#else\n\t\t\t\t\t\tif(!((u32)rDataPtr16 & 1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t*rDataPtr16++ = sdmmc_read16(REG_SDFIFO);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tu16 data = sdmmc_read16(REG_SDFIFO);\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data;\n\t\t\t\t\t\t\t\t*rDataPtr8++ = data >> 8;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tsize -= blkSize;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsdmmc_mask16(REG_SDDATACTL32, 0x800, 0);\n\t\t\t}\n\t\t}\n#ifdef DATA32_SUPPORT\n\t\tif(!(ctl32 & 0x200))\n#else\n\t\tif((status1 & TMIO_STAT1_TXRQ))\n#endif\n\t\t{\n\t\t\tif(writedata)\n\t\t\t{\n\t\t\t\tif(tUseBuf)\n\t\t\t\t{\n\t\t\t\t\tsdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_TXRQ, 0);\n\t\t\t\t\tif(size >= blkSize)\n\t\t\t\t\t{\n\t\t\t\t\t\t#ifdef DATA32_SUPPORT\n\t\t\t\t\t\tif(!((u32)tDataPtr32 & 3))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsdmmc_write32(REG_SDFIFO32, *tDataPtr32++);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tu32 data = *tDataPtr8++;\n\t\t\t\t\t\t\t\tdata |= (u32)*tDataPtr8++ << 8;\n\t\t\t\t\t\t\t\tdata |= (u32)*tDataPtr8++ << 16;\n\t\t\t\t\t\t\t\tdata |= (u32)*tDataPtr8++ << 24;\n\t\t\t\t\t\t\t\tsdmmc_write32(REG_SDFIFO32, data);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#else\n\t\t\t\t\t\tif(!((u32)tDataPtr16 & 1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsdmmc_write16(REG_SDFIFO, *tDataPtr16++);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(u32 i = 0; i < blkSize; i += 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tu16 data = *tDataPtr8++;\n\t\t\t\t\t\t\t\tdata |= (u16)(*tDataPtr8++ << 8);\n\t\t\t\t\t\t\t\tsdmmc_write16(REG_SDFIFO, data);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tsize -= blkSize;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsdmmc_mask16(REG_SDDATACTL32, 0x1000, 0);\n\t\t\t}\n\t\t}\n\t\tif(status1 & TMIO_MASK_GW)\n\t\t{\n\t\t\tctx->error |= 4;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(!(status1 & TMIO_STAT1_CMD_BUSY))\n\t\t{\n\t\t\tstatus0 = sdmmc_read16(REG_SDSTATUS0);\n\t\t\tif(sdmmc_read16(REG_SDSTATUS0) & TMIO_STAT0_CMDRESPEND)\n\t\t\t{\n\t\t\t\tctx->error |= 0x1;\n\t\t\t}\n\t\t\tif(status0 & TMIO_STAT0_DATAEND)\n\t\t\t{\n\t\t\t\tctx->error |= 0x2;\n\t\t\t}\n\n\t\t\tif((status0 & flags) == flags)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tctx->stat0 = sdmmc_read16(REG_SDSTATUS0);\n\tctx->stat1 = sdmmc_read16(REG_SDSTATUS1);\n\tsdmmc_write16(REG_SDSTATUS0,0);\n\tsdmmc_write16(REG_SDSTATUS1,0);\n\n\tif(getSDRESP != 0)\n\t{\n\t\tctx->ret[0] = (u32)(sdmmc_read16(REG_SDRESP0) | (sdmmc_read16(REG_SDRESP1) << 16));\n\t\tctx->ret[1] = (u32)(sdmmc_read16(REG_SDRESP2) | (sdmmc_read16(REG_SDRESP3) << 16));\n\t\tctx->ret[2] = (u32)(sdmmc_read16(REG_SDRESP4) | (sdmmc_read16(REG_SDRESP5) << 16));\n\t\tctx->ret[3] = (u32)(sdmmc_read16(REG_SDRESP6) | (sdmmc_read16(REG_SDRESP7) << 16));\n\t}\n}\n\n//---------------------------------------------------------------------------------\nstatic u32 calcSDSize(u8* csd, int type) {\n//---------------------------------------------------------------------------------\n    u32 result = 0;\n    if (type == -1) type = csd[14] >> 6;\n    switch (type) {\n        case 0:\n            {\n                u32 block_len = csd[9] & 0xf;\n                block_len = 1 << block_len;\n                u32 mult = (csd[4] >> 7) | ((csd[5] & 3) << 1);\n                mult = 1 << (mult + 2);\n                result = csd[8] & 3;\n                result = (result << 8) | csd[7];\n                result = (result << 2) | (csd[6] >> 6);\n                result = (result + 1) * mult * block_len / 512;\n            }\n            break;\n        case 1:\n            result = csd[7] & 0x3f;\n            result = (result << 8) | csd[6];\n            result = (result << 8) | csd[5];\n            result = (result + 1) * 1024;\n            break;\n    }\n    return result;\n}\n\n//---------------------------------------------------------------------------------\nvoid sdmmc_controller_init() {\n//---------------------------------------------------------------------------------\n    deviceSD.isSDHC = 0;\n    deviceSD.SDOPT = 0;\n    deviceSD.res = 0;\n    deviceSD.initarg = 0;\n    deviceSD.clk = 0x80;\n    deviceSD.devicenumber = 0;\n\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xF7FFu;\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xEFFFu;\n#ifdef DATA32_SUPPORT\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) |= 0x402u;\n#else\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) |= 0x402u;\n#endif\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) = (*(vu16*)(SDMMC_BASE + REG_SDDATACTL) & 0xFFDD) | 2;\n#ifdef DATA32_SUPPORT\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFFu;\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDFu;\n    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 512;\n#else\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL32) &= 0xFFFDu;\n    *(vu16*)(SDMMC_BASE + REG_SDDATACTL) &= 0xFFDDu;\n    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN32) = 0;\n#endif\n    *(vu16*)(SDMMC_BASE + REG_SDBLKCOUNT32) = 1;\n    *(vu16*)(SDMMC_BASE + REG_SDRESET) &= 0xFFFEu;\n    *(vu16*)(SDMMC_BASE + REG_SDRESET) |= 1u;\n    *(vu16*)(SDMMC_BASE + REG_SDIRMASK0) |= TMIO_MASK_ALL;\n    *(vu16*)(SDMMC_BASE + REG_SDIRMASK1) |= TMIO_MASK_ALL>>16;\n    *(vu16*)(SDMMC_BASE + 0x0fc) |= 0xDBu; //SDCTL_RESERVED7\n    *(vu16*)(SDMMC_BASE + 0x0fe) |= 0xDBu; //SDCTL_RESERVED8\n    *(vu16*)(SDMMC_BASE + REG_SDPORTSEL) &= 0xFFFCu;\n#ifdef DATA32_SUPPORT\n    *(vu16*)(SDMMC_BASE + REG_SDCLKCTL) = 0x20;\n    *(vu16*)(SDMMC_BASE + REG_SDOPT) = 0x40EE;\n#else\n    *(vu16*)(SDMMC_BASE + REG_SDCLKCTL) = 0x40; //Nintendo sets this to 0x20\n    *(vu16*)(SDMMC_BASE + REG_SDOPT) = 0x40EB; //Nintendo sets this to 0x40EE\n#endif\n    *(vu16*)(SDMMC_BASE + REG_SDPORTSEL) &= 0xFFFCu;\n    *(vu16*)(SDMMC_BASE + REG_SDBLKLEN) = 512;\n    *(vu16*)(SDMMC_BASE + REG_SDSTOP) = 0;\n\n    setTarget(&deviceSD);\n}\n\n//---------------------------------------------------------------------------------\nint sdmmc_sdcard_init() {\n//---------------------------------------------------------------------------------\n\t// We need to send at least 74 clock pulses.\n    setTarget(&deviceSD);\n\tswiDelay(0x1980); // ~75-76 clocks\n\n    // card reset\n    sdmmc_send_command(&deviceSD,0,0);\n\n    // CMD8 0x1AA\n    sdmmc_send_command(&deviceSD,0x10408,0x1AA);\n    u32 temp = (deviceSD.error & 0x1) << 0x1E;\n\n    u32 temp2 = 0;\n    do {\n        do {\n            // CMD55\n            sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);\n            // ACMD41\n            sdmmc_send_command(&deviceSD,0x10769,0x00FF8000 | temp);\n            temp2 = 1;\n        } while ( !(deviceSD.error & 1) );\n\n    } while((deviceSD.ret[0] & 0x80000000) == 0);\n\n    if(!((deviceSD.ret[0] >> 30) & 1) || !temp)\n        temp2 = 0;\n\n    deviceSD.isSDHC = temp2;\n\n    sdmmc_send_command(&deviceSD,0x10602,0);\n    if (deviceSD.error & 0x4) return -1;\n\n    sdmmc_send_command(&deviceSD,0x10403,0);\n    if (deviceSD.error & 0x4) return -2;\n    deviceSD.initarg = deviceSD.ret[0] >> 0x10;\n\n    sdmmc_send_command(&deviceSD,0x10609,deviceSD.initarg << 0x10);\n    if (deviceSD.error & 0x4) return -3;\n\n\t// Command Class 10 support\n\tconst bool cmd6Supported = ((u8*)deviceSD.ret)[10] & 0x40;\n    deviceSD.total_size = calcSDSize((u8*)&deviceSD.ret[0],-1);\n    setckl(0x201); // 16.756991 MHz\n\n    sdmmc_send_command(&deviceSD,0x10507,deviceSD.initarg << 0x10);\n    if (deviceSD.error & 0x4) return -4;\n\n    // CMD55\n    sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);\n    if (deviceSD.error & 0x4) return -5;\n\n    // ACMD42\n    sdmmc_send_command(&deviceSD,0x1076A,0x0);\n    if (deviceSD.error & 0x4) return -6;\n\n    // CMD55\n    sdmmc_send_command(&deviceSD,0x10437,deviceSD.initarg << 0x10);\n    if (deviceSD.error & 0x4) return -7;\n\n    deviceSD.SDOPT = 1;\n    sdmmc_send_command(&deviceSD,0x10446,0x2);\n    if (deviceSD.error & 0x4) return -8;\n\tsdmmc_mask16(REG_SDOPT, 0x8000, 0); // Switch to 4 bit mode.\n\n\t// TODO: CMD6 to switch to high speed mode.\n\tif(cmd6Supported)\n\t{\n\t\tsdmmc_write16(REG_SDSTOP,0);\n\t\tsdmmc_write16(REG_SDBLKLEN32,64);\n\t\tsdmmc_write16(REG_SDBLKLEN,64);\n\t\tdeviceSD.rData = NULL;\n\t\tdeviceSD.size = 64;\n\t\tsdmmc_send_command(&deviceSD,0x31C06,0x80FFFFF1);\n\t\tsdmmc_write16(REG_SDBLKLEN,512);\n\t\tif(deviceSD.error & 0x4) return -9;\n\n\t\tdeviceSD.clk = 0x200; // 33.513982 MHz\n\t\tsetckl(0x200);\n\t}\n\telse deviceSD.clk = 0x201; // 16.756991 MHz\n\n    sdmmc_send_command(&deviceSD,0x1040D,deviceSD.initarg << 0x10);\n    if (deviceSD.error & 0x4) return -9;\n\n    sdmmc_send_command(&deviceSD,0x10410,0x200);\n    if (deviceSD.error & 0x4) return -10;\n\n    return 0;\n\n}\n\n//---------------------------------------------------------------------------------\nint sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, void *out) {\n//---------------------------------------------------------------------------------\n    if (deviceSD.isSDHC == 0)\n        sector_no <<= 9;\n    setTarget(&deviceSD);\n    sdmmc_write16(REG_SDSTOP,0x100);\n\n#ifdef DATA32_SUPPORT\n    sdmmc_write16(REG_SDBLKCOUNT32,numsectors);\n    sdmmc_write16(REG_SDBLKLEN32,0x200);\n#endif\n\n    sdmmc_write16(REG_SDBLKCOUNT,numsectors);\n    deviceSD.rData = out;\n    deviceSD.size = numsectors << 9;\n    sdmmc_send_command(&deviceSD,0x33C12,sector_no);\n    return geterror(&deviceSD);\n}\n#endif"
  },
  {
    "path": "bootloader/source/sdmmc.h",
    "content": "#ifndef __SDMMC_H__\n#define __SDMMC_H__\n\n#include <nds/ndstypes.h>\n\n#define DATA32_SUPPORT\n\n#define SDMMC_BASE\t0x04004800\n\n\n#define REG_SDCMD       0x00\n#define REG_SDPORTSEL   0x02\n#define REG_SDCMDARG    0x04\n#define REG_SDCMDARG0   0x04\n#define REG_SDCMDARG1  \t0x06\n#define REG_SDSTOP      0x08\n#define REG_SDRESP      0x0c\n#define REG_SDBLKCOUNT  0x0a\n\n#define REG_SDRESP0     0x0c\n#define REG_SDRESP1     0x0e\n#define REG_SDRESP2     0x10\n#define REG_SDRESP3     0x12\n#define REG_SDRESP4     0x14\n#define REG_SDRESP5     0x16\n#define REG_SDRESP6     0x18\n#define REG_SDRESP7     0x1a\n\n#define REG_SDSTATUS0   0x1c\n#define REG_SDSTATUS1   0x1e\n\n#define REG_SDIRMASK0   0x20\n#define REG_SDIRMASK1   0x22\n#define REG_SDCLKCTL    0x24\n\n#define REG_SDBLKLEN    0x26\n#define REG_SDOPT       0x28\n#define REG_SDFIFO      0x30\n\n#define REG_SDDATACTL   0xd8\n#define REG_SDRESET     0xe0\n#define REG_SDPROTECTED 0xf6 //bit 0 determines if sd is protected or not?\n\n#define REG_SDDATACTL32         0x100\n#define REG_SDBLKLEN32          0x104\n#define REG_SDBLKCOUNT32        0x108\n#define REG_SDFIFO32            0x10C\n\n#define REG_CLK_AND_WAIT_CTL    0x138\n#define REG_RESET_SDIO          0x1e0\n//The below defines are from linux kernel drivers/mmc tmio_mmc.h.\n/* Definitions for values the CTRL_STATUS register can take. */\n#define TMIO_STAT0_CMDRESPEND    0x0001\n#define TMIO_STAT0_DATAEND       0x0004\n#define TMIO_STAT0_CARD_REMOVE   0x0008\n#define TMIO_STAT0_CARD_INSERT   0x0010\n#define TMIO_STAT0_SIGSTATE      0x0020\n#define TMIO_STAT0_WRPROTECT     0x0080\n#define TMIO_STAT0_CARD_REMOVE_A 0x0100\n#define TMIO_STAT0_CARD_INSERT_A 0x0200\n#define TMIO_STAT0_SIGSTATE_A    0x0400\n\n#define TMIO_STAT1_CMD_IDX_ERR   0x0001\n#define TMIO_STAT1_CRCFAIL       0x0002\n#define TMIO_STAT1_STOPBIT_ERR   0x0004\n#define TMIO_STAT1_DATATIMEOUT   0x0008\n#define TMIO_STAT1_RXOVERFLOW    0x0010\n#define TMIO_STAT1_TXUNDERRUN    0x0020\n#define TMIO_STAT1_CMDTIMEOUT    0x0040\n#define TMIO_STAT1_RXRDY         0x0100\n#define TMIO_STAT1_TXRQ          0x0200\n#define TMIO_STAT1_ILL_FUNC      0x2000\n#define TMIO_STAT1_CMD_BUSY      0x4000\n#define TMIO_STAT1_ILL_ACCESS    0x8000\n\n#define SDMC_NORMAL              0x00000000\n#define SDMC_ERR_COMMAND         0x00000001\n#define SDMC_ERR_CRC             0x00000002\n#define SDMC_ERR_END             0x00000004\n#define SDMC_ERR_TIMEOUT         0x00000008\n#define SDMC_ERR_FIFO_OVF        0x00000010\n#define SDMC_ERR_FIFO_UDF        0x00000020\n#define SDMC_ERR_WP              0x00000040\n#define SDMC_ERR_ABORT           0x00000080\n#define SDMC_ERR_FPGA_TIMEOUT    0x00000100\n#define SDMC_ERR_PARAM           0x00000200\n#define SDMC_ERR_R1_STATUS       0x00000800\n#define SDMC_ERR_NUM_WR_SECTORS  0x00001000\n#define SDMC_ERR_RESET           0x00002000\n#define SDMC_ERR_ILA             0x00004000\n#define SDMC_ERR_INFO_DETECT     0x00008000\n\n#define SDMC_STAT_ERR_UNKNOWN    0x00080000\n#define SDMC_STAT_ERR_CC         0x00100000\n#define SDMC_STAT_ERR_ECC_FAILED 0x00200000\n#define SDMC_STAT_ERR_CRC        0x00800000\n#define SDMC_STAT_ERR_OTHER      0xf9c70008\n\n#define TMIO_MASK_ALL           0x837f031d\n\n#define TMIO_MASK_GW      (TMIO_STAT1_ILL_ACCESS | TMIO_STAT1_CMDTIMEOUT | TMIO_STAT1_TXUNDERRUN | TMIO_STAT1_RXOVERFLOW | \\\n                           TMIO_STAT1_DATATIMEOUT | TMIO_STAT1_STOPBIT_ERR | TMIO_STAT1_CRCFAIL | TMIO_STAT1_CMD_IDX_ERR)\n\n#define TMIO_MASK_READOP  (TMIO_STAT1_RXRDY | TMIO_STAT1_DATAEND)\n#define TMIO_MASK_WRITEOP (TMIO_STAT1_TXRQ | TMIO_STAT1_DATAEND)\n\ntypedef struct mmcdevice {\n\tu8* rData;\n\tconst u8* tData;\n    u32 size;\n    u32 startOffset;\n    u32 endOffset;\n    u32 error;\n    u16 stat0;\n    u16 stat1;\n    u32 ret[4];\n    u32 initarg;\n    u32 isSDHC;\n    u32 clk;\n    u32 SDOPT;\n    u32 devicenumber;\n    u32 total_size; //size in sectors of the device\n    u32 res;\n} mmcdevice;\n\nenum {\n    MMC_DEVICE_SDCARD,\n    MMC_DEVICE_NAND,\n};\n\nvoid sdmmc_controller_init();\nvoid sdmmc_initirq();\nint sdmmc_cardinserted();\n\nint sdmmc_sdcard_init();\nint sdmmc_nand_init();\nvoid sdmmc_get_cid(int devicenumber, u32 *cid);\n\nstatic inline void sdmmc_nand_cid( u32 *cid) {\n    sdmmc_get_cid(MMC_DEVICE_NAND,cid);\n}\n\nstatic inline void sdmmc_sdcard_cid( u32 *cid) {\n    sdmmc_get_cid(MMC_DEVICE_SDCARD,cid);\n}\n\nint sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, void *out);\nint sdmmc_sdcard_writesectors(u32 sector_no, u32 numsectors, void *in);\nint sdmmc_nand_readsectors(u32 sector_no, u32 numsectors, void *out);\nint sdmmc_nand_writesectors(u32 sector_no, u32 numsectors, void *in);\n\nextern u32 sdmmc_cid[];\nextern int sdmmc_curdevice;\n\n//---------------------------------------------------------------------------------\nstatic inline u16 sdmmc_read16(u16 reg) {\n//---------------------------------------------------------------------------------\n\treturn *(vu16*)(SDMMC_BASE + reg);\n}\n\n//---------------------------------------------------------------------------------\nstatic inline void sdmmc_write16(u16 reg, u16 val) {\n//---------------------------------------------------------------------------------\n\t*(vu16*)(SDMMC_BASE + reg) = val;\n}\n\n//---------------------------------------------------------------------------------\nstatic inline u32 sdmmc_read32(u16 reg) {\n//---------------------------------------------------------------------------------\n    return *(vu32*)(SDMMC_BASE + reg);\n}\n\n//---------------------------------------------------------------------------------\nstatic inline void sdmmc_write32(u16 reg, u32 val) {\n//---------------------------------------------------------------------------------\n    *(vu32*)(SDMMC_BASE + reg) = val;\n}\n\n//---------------------------------------------------------------------------------\nstatic inline void sdmmc_mask16(u16 reg, u16 clear, u16 set) {\n//---------------------------------------------------------------------------------\n\tu16 val = sdmmc_read16(reg);\n\tval &= ~clear;\n\tval |= set;\n\tsdmmc_write16(reg, val);\n}\n\n\n//---------------------------------------------------------------------------------\nstatic inline void setckl(u32 data) {\n//---------------------------------------------------------------------------------\n    sdmmc_mask16(REG_SDCLKCTL, 0x100, 0);\n    sdmmc_mask16(REG_SDCLKCTL, 0x2FF, data & 0x2FF);\n    sdmmc_mask16(REG_SDCLKCTL, 0x0, 0x100);\n}\n\n#endif\n"
  },
  {
    "path": "fix_ndsheader.py",
    "content": "# -*- coding: utf8 -*-\n# Patch an .nds (works with homebrew and ds demo only) to make it ready for make_cia\n#\n# 2016-02-28, Ahezard \n#\n# inspired by \n# Apache Thunder .nds edited files and comments\n# https://github.com/Relys/Project_CTR/blob/master/makerom/srl.h\n# https://dsibrew.org/wiki/DSi_Cartridge_Header\n# if the header size of the input nds file is 0x200 (homebrew)\n# the header size of the output nds file will be patched to 0x4000 (normal ds/dsi header), 0x3E00 offset\n\nfrom struct import *\nfrom collections import namedtuple\n# from collections import OrderedDict\nfrom pprint import pprint\nimport os  # , sys\n# import binascii\nimport argparse\nfrom ctypes import c_ushort\n\n\nparser = argparse.ArgumentParser(description='Patch an nds in order to be ready cia conversion via make_cia --srl=.')\nparser.add_argument('file', metavar='file.nds', type=argparse.FileType('rb'), help='nds file to patch')\nparser.add_argument('--verbose', help='verbose mode', action=\"store_true\")\nparser.add_argument('--out', help='output file [optionnal]')\nparser.add_argument('--read', help='print only the header content, do not patch', action=\"store_true\")\nparser.add_argument('--extract', help='extract the content of the rom : header.bin,arm9.bin,arm7.bin,icon.bin,arm9i.bin,arm7i.bin, do not patch', action=\"store_true\")  # Not yet implemented\nparser.add_argument('--title', help='Game title')\nparser.add_argument('--code', help='Game code')\nparser.add_argument('--maker', help='Maker code')\nparser.add_argument('--mode', help='target mode, default mode is ds [ds|dsi|dsinogba|nitrohax]')\nparser.add_argument('--arm9', type=argparse.FileType('rb'), help='swap the ds arm9 binary by the one provided')\nparser.add_argument('--arm7', type=argparse.FileType('rb'), help='swap the ds arm7 binary by the one provided')\nparser.add_argument('--arm9EntryAddress', help='arm9 ram address of the binary provided')\nparser.add_argument('--arm7EntryAddress', help='arm7 ram address of the binary provided')\nparser.add_argument('--arm9i', type=argparse.FileType('rb'), help='add a dsi arm9i binary to the file')\nparser.add_argument('--arm7i', type=argparse.FileType('rb'), help='add a dsi arm7i binary to the file')\nparser.add_argument('--accessControl', help='access control field')\t\nargs = parser.parse_args()\n\nif args.mode is None:\n\targs.mode = \"dsi\"\n\nclass CRC16(object):\n\n\t\"\"\"Source:  https://github.com/cristianav/PyCRC/blob/master/demo.py\"\"\"\n\tcrc16_tab = []\n\n\t# The CRC's are computed using polynomials. Here is the most used\n\t# coefficient for CRC16\n\tcrc16_constant = 0xA001  # 40961\n\n\tdef __init__(self, modbus_flag=False):\n\t\t# initialize the precalculated tables\n\t\tif not len(self.crc16_tab):\n\t\t\tself.init_crc16()\n\t\tself.mdflag = bool(modbus_flag)\n\n\tdef calculate(self, input_data=None):\n\t\ttry:\n\t\t\tis_string = isinstance(input_data, str)\n\t\t\tis_bytes = isinstance(input_data, (bytes, bytearray))\n\n\t\t\tif not is_string and not is_bytes:\n\t\t\t\traise Exception(\"Please provide a string or a byte sequence \"\n\t\t\t\t\t\t\t\t\"as argument for calculation.\")\n\n\t\t\tcrc_value = 0x0000 if not self.mdflag else 0xffff\n\n\t\t\tfor c in input_data:\n\t\t\t\td = ord(c) if is_string else c\n\t\t\t\ttmp = crc_value ^ d\n\t\t\t\trotated = crc_value >> 8\n\t\t\t\tcrc_value = rotated ^ self.crc16_tab[(tmp & 0x00ff)]\n\n\t\t\treturn crc_value\n\t\texcept Exception as e:\n\t\t\tprint(\"EXCEPTION(calculate): {}\".format(e))\n\n\tdef init_crc16(self):\n\t\t\"\"\"The algorithm uses tables with precalculated values\"\"\"\n\t\tfor i in range(0, 256):\n\t\t\tcrc = c_ushort(i).value\n\t\t\tfor j in range(0, 8):\n\t\t\t\tif crc & 0x0001:\n\t\t\t\t\tcrc = c_ushort(crc >> 1).value ^ self.crc16_constant\n\t\t\t\telse:\n\t\t\t\t\tcrc = c_ushort(crc >> 1).value\n\t\t\tself.crc16_tab.append(crc)\n\n\ndef getSize(fileobject):\n\tcurrent = fileobject.tell()\n\tfileobject.seek(0, 2)  # move the cursor to the end of the file\n\tsize = fileobject.tell()\n\tfileobject.seek(current, 0)\n\treturn size\n\ndef skipUntilAddress(f_in, f_out, caddr, taddr):\n\tchunk = f_in.read(taddr - caddr)\n\tf_out.write(chunk)\n\ndef writeBlankuntilAddress(f_out, caddr, taddr):\n\tf_out.write(b\"\\x00\"*(taddr-caddr))\n\nfname=args.file.name\nargs.file.close()\n\nif not args.read:\n\tprint(\"Patching file : \"+fname)\nelse:\n\tprint(\"Reading header of file : \"+fname)\n\n# offset of 0x4600 created\n\n# File size compute\nfile = open(fname, 'rb')\nfsize=getSize(file)\nfile.close()\n\n# CRC header compute \"CRC-16 (Modbus)\"\nfile = open(fname, 'rb')\n# 0x15E from https://github.com/devkitPro/ndstool/ ... source/header.cpp\nhdr = file.read(0x15E)\nhdrCrc=CRC16(modbus_flag=True).calculate(hdr)\nif args.verbose:\n\tprint(\"{:10s} {:20X}\".format('HDR CRC-16 ModBus', hdrCrc))\n# print(\"origin header cr c\"+hdr[0x15E:0x15F])\n# filew = open(fname+\".hdr\", \"wb\")\n# filew.write(hdr);\n# filew.close()\nfile.close()\n\nif args.arm9 is not None:\n\tarm9Fname = args.arm9.name\n\targs.arm9.close()\n\tarm9File = open(arm9Fname, 'rb')\n\tarm9FileSize = getSize(arm9File)\n\tdataArm9 = arm9File.read(arm9FileSize)\n\tarm9File.close()\n\nif args.arm7 is not None:\n\tarm7Fname = args.arm7.name\n\targs.arm7.close()\n\tarm7File = open(arm7Fname, 'rb')\n\tarm7FileSize = getSize(arm7File)\n\tdataArm7 = arm7File.read(arm7FileSize)\n\tarm7File.close()\n\nfiler = open(fname, 'rb')\ndata = filer.read(0xB0)\ndata += b'DoNotZeroFillMem'\nfiler.read(0x10)\ndata = data + filer.read(0xC0)\ncaddr = 0x180\n\n# DS Data 180 bytes\nSrlHeader = namedtuple('SrlHeader', \n\t\"gameTitle \"\n\t\"gameCode \"\n\t\"makerCode \"\n\t\"unitCode \"\n\t\"encryptionSeedSelect \"\n\t\"deviceCapacity \"\n\t\"reserved0 \" \n\t\"dsiflags \" \n\t\"romVersion \"\n\t\"internalFlag \"\n\t\"arm9RomOffset \"\n\t\"arm9EntryAddress \"\n\t\"arm9RamAddress \"\n\t\"arm9Size \"\n\t\"arm7RomOffset \"\n\t\"arm7EntryAddress \"\n\t\"arm7RamAddress \"\n\t\"arm7Size \"\n\t\"fntOffset \"\n\t\"fntSize \"\n\t\"fatOffset \"\n\t\"fatSize \"\n\t\"arm9OverlayOffset \"\n\t\"arm9OverlaySize \"\n\t\"arm7OverlayOffset \"\n\t\"arm7OverlaySize \"\n\t\"normalCardControlRegSettings \"\n\t\"secureCardControlRegSettings \"\n\t\"icon_bannerOffset \"\n\t\"secureAreaCrc \"\n\t\"secure_transfer_timeout \"\n\t\"arm9Autoload \"\n\t\"arm7Autoload \"\n\t\"secureDisable \"\n\t\"ntrRomSize \"\n\t\"headerSize \"\n\t\"reserved1 \"\n\t\"nintendoLogo \"\n\t\"nintendoLogoCrc \"\n\t\"headerCrc \"\n\t\"debugReserved \")\nsrlHeaderFormat = '<12s4s2scbb7s2sbcIIIIIIIIIIIIIIIIIIIHHII8sII56s156s2sH32s'\nsrlHeader = SrlHeader._make(unpack_from(srlHeaderFormat, data))\nif args.verbose:\n\tprint(\"origin header crc \"+hex(srlHeader.headerCrc))\n\tprint(\"origin secure crc \"+hex(srlHeader.secureAreaCrc))\n\n# SecureArea CRC compute \"CRC-16 (Modbus)\"\nfile = open(fname, 'rb')\n# 0x15E from https://github.com/devkitPro/ndstool/ ... source/header.cpp\nfile.read(0x200)\nsec = file.read(0x4000)\nsecCrc = CRC16(modbus_flag=True).calculate(sec)\nif args.verbose:\n\tprint(\"{:10s} {:20X}\".format('SEC CRC-16 ModBus', secCrc))\nfile.close()\n\nif srlHeader.arm7EntryAddress > 0x2400000 and not args.read and args.arm7 is None:\n\tprint(\"WARNING: .nds arm7EntryAddress greater than 0x2400000 will not boot as cia\")\n\tprint(\"you need to recompile or swap the arm7 binary with a precompiled one with --arm7 and --arm7EntryAddress\")\n\nif \"dsi\" in args.mode:\n\tsrlHeaderPatched = srlHeader._replace(\n\t\tdsiflags=\t\t\t\t\tb'\\x01\\x00',  # disable modcrypt but enable twl\n\t\tunitCode=\t\t\t\t\tb'\\x03',\n\t\t)\n\ndata1 = pack(srlHeaderFormat, *srlHeaderPatched._asdict().values())\nnewHdrCrc = CRC16(modbus_flag = True).calculate(data1[0:0x15E])\nsrlHeaderPatched = srlHeaderPatched._replace(headerCrc = newHdrCrc)\n\nif args.verbose:\n\tprint(\"new header crc \"+hex(newHdrCrc))\nif not args.read:\n\tif args.verbose:\n\t\tpprint(dict(srlHeaderPatched._asdict()))\nelse:\n\tpprint(dict(srlHeader._asdict()))\n\ndata1 = pack(srlHeaderFormat, *srlHeaderPatched._asdict().values())\n\narm9isize = 0\narm7isize = 0\n\n# TWL Only Data 384 bytes\nSrlTwlExtHeader = namedtuple('SrlTwlExtHeader', \n\t\"MBK_1_5_Settings \"\n\t\"MBK_6_8_Settings_ARM9 \"\n\t\"MBK_6_8_Settings_ARM7 \"\n\t\"global_MBK_9_Setting \"\n\t\"regionFlags \"\n\t\"accessControl \"\n\t\"arm7ScfgExtMask \"\n\t\"reserved_flags \"\n\t\"arm9iRomOffset \"\n\t\"reserved2 \"\n\t\"arm9iLoadAddress \"\n\t\"arm9iSize \"\n\t\"arm7iRomOffset \"\n\t\"struct_param_baseAddress \"\n\t\"arm7iLoadAddress \"\n\t\"arm7iSize \"\n\t\"digest_ntrRegionOffset \"\n\t\"digest_ntrRegionSize \"\n\t\"digest_twlRegionOffset \"\n\t\"digest_twlRegionSize \"\n\t\"digestSectorHashtableOffset \"\n\t\"digestSectorHashtableSize \"\n\t\"digest_blockHashtableOffset \"\n\t\"digest_blockHashtableSize \"\n\t\"digestSectorSize \"\n\t\"digest_blockSectorcount \"\n\t\"iconSize \"\t#usually 0x23C0 or 2112 in homebrew\n\t\"unknown1 \"\n\t\"twlRomSize \"\n\t\"unknown2 \"\n\t\"modcryptArea1Offset \"\n\t\"modcryptArea1Size \"\n\t\"modcryptArea2Offset \"\n\t\"modcryptArea2Size \"\n\t\"title_id \"\n\t\"pubSaveDataSize \"\n\t\"privSaveDataSize \"\n\t\"reserved4 \"\n\t\"parentalControl \")\nsrlTwlExtHeaderFormat = \"<20s12s12s4s4sIIII4sIIIIIIIIIIIIIIIII4sI12sIIII8sII176s16s\"\nif srlHeader.headerSize < 0x300:\n\t# homebrew\n\tsrlTwlExtHeader = SrlTwlExtHeader._make(unpack_from(srlTwlExtHeaderFormat, \"\\x00\" * (0x300-0x180)))\nelse:\n\tdata = filer.read(0x300-0x180)\n\tsrlTwlExtHeader = SrlTwlExtHeader._make(unpack_from(srlTwlExtHeaderFormat, data))\n\tcaddr = 0x300\n\n# pprint(dict(srlTwlExtHeader._asdict()))\n\nif not args.read:\n\t# Fix srlTwlExtHeader\n\tif \"dsi\" in args.mode:\n\t\tarm7iRomOffset = srlHeaderPatched.arm7RomOffset\n\t\tarm9iRomOffset = srlHeaderPatched.arm9RomOffset\t\n\t\tarm7isize = srlHeaderPatched.arm7Size\n\t\tarm9isize = srlHeaderPatched.arm9Size\n\t\ttotaldsisize = 0\n\t\tarm7iname = None\n\t\tarm9iname = None\n\n\t\tif args.arm9i is not None:\n\t\t\tarm9iname = args.arm9i.name\n\t\t\tarm9isize = getSize(args.arm9i)\n\t\t\tarm9iRomOffset = srlHeaderPatched.ntrRomSize\n\t\t\tif args.verbose:\n\t\t\t\tprint(\"arm9isize : \"+hex(arm9isize))\n\t\t\t\tprint(\"arm9ioffset : \"+hex(srlHeaderPatched.ntrRomSize))\n\t\t\targs.arm9i.close()\n\t\t\ttotaldsisize = arm9isize\n\n\t\tif args.arm7i is not None:\n\t\t\tarm7iname = args.arm7i.name\n\t\t\tarm7isize = getSize(args.arm7i)\n\t\t\tarm7iRomOffset = srlHeaderPatched.ntrRomSize+arm9isize\n\t\t\tif args.verbose:\n\t\t\t\tprint(\"arm7isize : \"+hex(arm7isize))\n\t\t\t\tprint(\"arm9ioffset : \"+hex(srlHeaderPatched.ntrRomSize+arm9isize))\n\t\t\targs.arm7i.close()\n\t\t\ttotaldsisize = arm9isize + arm7isize\n\t\t\t\n\n\n\t\tsrlTwlExtHeader = srlTwlExtHeader._replace(\n\t\t\tMBK_1_5_Settings=\t\tb\"\\x80\\x84\\x88\\x8C\\x81\\x85\\x89\\x8D\\x91\\x95\\x99\\x9C\\x81\\x85\\x89\\x8D\\x91\\x95\\x99\\x9D\",\n\t\t\tMBK_6_8_Settings_ARM9=\tb\"\\xC0\\x37\\x00\\x08\\x00\\x30\\xC0\\x07\\x00\\x30\\x00\\x00\",\n\t\t\tMBK_6_8_Settings_ARM7=\tb\"\\x00\\x30\\x00\\x00\\x00\\x30\\x40\\x00\\xB8\\x37\\xF8\\x07\",\n\t\t\tglobal_MBK_9_Setting=\tb\"\\x00\\x00\\x00\\xFF\",\n\t\t\taccessControl=\t\t\t0x001FFEFF,\n\t\t\tarm7ScfgExtMask=\t\t0x80040407,\n\t\t\treserved_flags=\t\t    0x01000000\n\t\t\t)\n\n\t\tif args.accessControl is not None:\n\t\t\tsrlTwlExtHeader = srlTwlExtHeader._replace(accessControl=int(args.accessControl, 0))\n\nif args.verbose or args.read:\t\n\tpprint(dict(srlTwlExtHeader._asdict()))\n\ndata2=pack(srlTwlExtHeaderFormat, *srlTwlExtHeader._asdict().values())\n\nif not args.read:\n\t# write the file\n\tif args.out is not None:\n\t\tfilew = open(args.out, \"wb\")\n\telse:\n\t\tfilew = open(fname + \".tmp\", \"wb\")\n\n\tfilew.write(data1)\n\tfilew.write(data2)\n\t\n\tskipUntilAddress(filer, filew, caddr, srlTwlExtHeader.twlRomSize)\n\n\tfilew.close()\n\tfiler.close()\n\t\n\tif args.out is None:\n\t\tif os.path.exists(fname + \".orig.nds\"):\n\t\t\tos.remove(fname + \".orig.nds\")\n\t\tos.rename(fname, fname + \".orig.nds\")\n\t\tos.rename(fname + \".tmp\", fname)\t\n\tprint(\"file patched\")"
  },
  {
    "path": "hiyaCFW.pnproj",
    "content": "<Project name=\"hiyaCFW\"><MagicFolder excludeFolders=\"CVS;.svn\" filter=\"*\" name=\"arm9\" path=\"arm9\\\"><MagicFolder excludeFolders=\"CVS;.svn\" filter=\"*\" name=\"graphics\" path=\"graphics\\\"><File path=\"subError.bmp\"></File><File path=\"subLoad.bmp\"></File><File path=\"topError.bmp\"></File><File path=\"topLoad.bmp\"></File></MagicFolder><MagicFolder excludeFolders=\"CVS;.svn\" filter=\"*\" name=\"graphics_xcf\" path=\"graphics_xcf\\\"><File path=\"credits.xcf\"></File><File path=\"topSplash.xcf\"></File></MagicFolder><MagicFolder excludeFolders=\"CVS;.svn\" filter=\"*\" name=\"source\" path=\"source\\\"><File path=\"bios_decompress_callback.c\"></File><File path=\"bios_decompress_callback.h\"></File><File path=\"inifile.cpp\"></File><File path=\"inifile.h\"></File><File path=\"main.cpp\"></File><File path=\"nds_loader_arm9.c\"></File><File path=\"nds_loader_arm9.h\"></File><File path=\"stringtool.cpp\"></File><File path=\"stringtool.h\"></File></MagicFolder><File path=\"Makefile\"></File></MagicFolder></Project>"
  },
  {
    "path": "hiyaCFW.pnps",
    "content": "<pd><ViewState><e p=\"hiyaCFW\\arm9\" x=\"true\"></e><e p=\"hiyaCFW\\arm9\\graphics_xcf\" x=\"false\"></e><e p=\"hiyaCFW\\arm9\\source\" x=\"true\"></e><e p=\"hiyaCFW\" x=\"true\"></e><e p=\"hiyaCFW\\arm9\\graphics\" x=\"false\"></e></ViewState></pd>"
  },
  {
    "path": "hiyacfw_helper.py",
    "content": "import hashlib\nimport os\nimport sys\nimport subprocess\n\n# use apply ips function for https://github.com/meunierd/python-ips\n\nimport shutil\nimport struct\n\nfrom os.path import getsize\n\n\ndef unpack_int(string):\n    \"\"\"Read an n-byte big-endian integer from a byte string.\"\"\"\n    (ret,) = struct.unpack_from('>I', b'\\x00' * (4 - len(string)) + string)\n    return ret\n\ndef apply(patchpath, filepath):\n    patch_size = getsize(patchpath)\n    patchfile = open(patchpath, 'rb')\n    target = open(filepath, 'r+b')\n\n    if patchfile.read(5) != b'PATCH':\n        raise Exception('Invalid patch header.')\n\n    # Read First Record\n    r = patchfile.read(3)\n    while patchfile.tell() not in [patch_size, patch_size - 3]:\n        # Unpack 3-byte pointers.\n        offset = unpack_int(r)\n        # Read size of data chunk\n        r = patchfile.read(2)\n        size = unpack_int(r)\n\n        if size == 0:  # RLE Record\n            r = patchfile.read(2)\n            rle_size = unpack_int(r)\n            data = patchfile.read(1) * rle_size\n        else:\n            data = patchfile.read(size)\n\n        # Write to file\n        target.seek(offset)\n        target.write(data)\n        # Read Next Record\n        r = patchfile.read(3)\n\n    if patch_size - 3 == patchfile.tell():\n        trim_size = unpack_int(patchfile.read(3))\n        target.truncate(trim_size)\n\n    # Cleanup\n    target.close()\n    patchfile.close()\n\nlauncher_region = \"\"\n\nprint('---HIYACFW HELPER---')\nprint('This is an updated version for Au, USA, EUR, Jap DSI. Edited by LmN')\nprint('Running self-check')\ndependencies = ['nand.bin', \"00000002.app\"]\ntry:\n    if os.name == 'nt':\n        char = \"\\\\\"\n    else:\n        char = \"/\"\n\n    if os.getcwd().split(char)[-1].replace(\"\\\\\", \"\") != 'for PC':\n        raise Exception('Script not placed in the HiyaCFW \"for PC\" directory. Please place the script in the correct location before proceeding.')\n    for dependency in dependencies:\n        if not os.path.isfile(dependency):\n            raise Exception('File {} not found. Ensure you placed these in the directory.'.format(dependency))\n    with open('00000002.app', 'rb') as launcher:\n        expected_sha1s = { 'usa': '1339bd7457484839f1d71f27de2f8da8098834b4', 'jap': '69c422a1ab1f26344a3d2b294ec714db362f57f0', 'eur': 'c5a3507181489f5190976a905b2953799e421363', 'aus': '8f79c6c1442d3e33d211454ec92bbe42c94a599d'}\n        sha1 = hashlib.sha1()\n        sha1.update(launcher.read())\n        for region, expected_sha1 in expected_sha1s.items():\n            if sha1.hexdigest() == expected_sha1:\n                launcher_region = region\n        if launcher_region == \"\":\n            raise Exception('Launcher is not v512 of AUS, USA, EUR or JAP. Is your launcher the right version and decrypted?')\nexcept Exception as e:\n    print('Self-check failed! {}'.format(e))\n    input('Press Enter to continue...')  \n    sys.exit()\n\nprint('Decrypting NAND')\ntry:\n    if os.name == 'nt':\n        subprocess.call([\"twltool\", \"nandcrypt\", \"--in\", \"nand.bin\"])\n    else:\n        print(\"WARNING: Non-Windows operating system detected!\")\n        print(\"The script will continue, but please ensure that Wine is installed.\")\n        input(\"Press the Enter key to continue...\")\n        subprocess.call([\"wine\", \"twltool\", \"nandcrypt\", \"--in\", \"nand.bin\"])\n\nexcept Exception as e:\n    print('Error occured! Does this backup have the required NO$GBA footer? ({0})'.format(e))\n    input('Press Enter to continue...')       \n    sys.exit()\n\nprint('\\nExtracting ARM7/ARM9 BIOS from NAND')\nif os.name == 'nt':\n    subprocess.call([\"twltool\", \"boot2\", \"--in\", \"nand.bin\"])\nelse: \n    subprocess.call([\"wine\", \"twltool\", \"boot2\", \"--in\", \"nand.bin\"])\n\nprint('\\nIPS patching ARM7/ARM9 BIOS')\napply(\"bootloader files/bootloader arm7 patch.ips\", \"arm7.bin\")\napply(\"bootloader files/bootloader arm9 patch.ips\", \"arm9.bin\")\nprint('\\nPrepending data to ARM9 BIOS')\n\ntry:\n    with open('bootloader files/bootloader arm9 append to start.bin', 'rb') as arm9_prepend, open('arm9.bin', 'rb') as arm9_bin, open('arm9_new.bin', 'ab') as arm9_new:\n        arm9_new.write(arm9_prepend.read() + arm9_bin.read())\n    os.remove('arm9.bin')\n    os.rename('arm9_new.bin', 'arm9.bin')\nexcept Exception as e:\n    print('Error occured! Does the bootloader files folder exist?')\n    input('Press Enter to continue...')       \n    sys.exit()\n\nprint('\\nGenerating new bootloader')\nif os.name == 'nt': \n    subprocess.call(['bootloader files/ndstool', '-c', 'bootloader.nds', '-9', 'arm9.bin', '-7', 'arm7.bin', '-t', 'bootloader files/banner.bin', '-h', 'bootloader files/header.bin'])\nelse:\n    subprocess.call(['wine', 'bootloader files/ndstool', '-c', 'bootloader.nds', '-9', 'arm9.bin', '-7', 'arm7.bin', '-t', 'bootloader files/banner.bin', '-h', 'bootloader files/header.bin'])\n\n# wine twltool modcrypt --in \"00000002.app\" --out \"00000002_dec.app\"  \nprint('\\nDecrypting launcher')\nif os.name == 'nt':\n    subprocess.call([\"twltool\", \"modcrypt\", \"--in\", \"00000002.app\"])\nelse:\n    subprocess.call([\"wine\", \"twltool\", \"modcrypt\", \"--in\", \"00000002.app\"])\n\nprint('\\nIPS patching launcher')\npatch = \"v1.4 Launcher (00000002.app) (JAP-KOR) patch.ips\" if launcher_region == \"jap\" else \"v1.4 Launcher (00000002.app) patch.ips\"\n\n\napply(patch, \"00000002.app\")\n\nprint('\\nMoving new files')\nif not os.path.isdir('Modified Files'):\n    os.mkdir('Modified Files')\nos.rename('bootloader.nds', 'Modified Files/bootloader.nds')\nos.rename('00000002.app', 'Modified Files/00000002.app')\n\nprint('Done!')\nprint('Navigate to the Modified Files folder.')\nprint('Copy bootloader.nds to the hiya folder on your <2GB SD card.')\nprint('Copy 00000002.app to title/00030017/484e41XX/content folder on your <2GB SD card.')\ninput('Press Enter to continue...')       \nsys.exit()\n"
  }
]