From 70c7e84d963d5cad3408ab4c446cb3281405ffa3 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:11:56 -0500 Subject: [PATCH 01/19] docs: credit original authors and add GPL text --- COPYING | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 10 +- 2 files changed, 683 insertions(+), 1 deletion(-) create mode 100644 COPYING diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 0866b5d..c85624f 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,14 @@ This project has one goal - a compatible re-implementation of the Famicom Disk S FreeDiskSysROM aims to provide a replacement for the original FDS BIOS that can be freely redistributed and that is capable of running all published FDS software. +# Credits + +This repository is a fork maintained by [rom-weaver](https://github.com/rom-weaver), for use as a freely redistributable FDS BIOS in [EmulatorJS](https://github.com/EmulatorJS/EmulatorJS). + +- [James Athey](https://github.com/jamesathey) created FreeDiskSysROM and wrote the original BIOS, VRAM, and input routines: [jamesathey/FreeDiskSysROM](https://github.com/jamesathey/FreeDiskSysROM) +- [yeah4578](https://github.com/yeah4578) (Nicholas Qualls) wrote the disk I/O routines and the boot screen: [yeah4578/FreeDiskSysROM](https://github.com/yeah4578/FreeDiskSysROM) +- Changes made in this fork are listed in its git history. + # Audience ## Emulators @@ -108,6 +116,6 @@ Rules: # License -FreeDiskSysROM is licensed under the GNU LGPL v3. The intent in using this license is to allow anyone to replace the 8 KiB official FDS BIOS with FreeDiskSysROM, whether for commerical or non-commercial purposes, so long as the source of FreeDiskSysROM (including any modifications) is made available to the end-user under the same license. +FreeDiskSysROM is licensed under the GNU LGPL v3 (see `LICENSE`), which builds on the GNU GPL v3 (see `COPYING`). The intent in using this license is to allow anyone to replace the 8 KiB official FDS BIOS with FreeDiskSysROM, whether for commerical or non-commercial purposes, so long as the source of FreeDiskSysROM (including any modifications) is made available to the end-user under the same license. Although the Famicom does not have an OS or any concept of dynamic linking, the FDS BIOS is analogous to a system library in practice. FDS titles, FDS emulators, and FDS clone systems are all permitted to utilize FreeDiskSysROM without regard to or changes to the licenses of their own code. From 4ea454766094eefd825153ee1b4551c091912a4e Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:33:54 -0500 Subject: [PATCH 02/19] feat: implement remaining BIOS entry points Fill the disk, file count, disk info, keyboard, and object stubs. Fix save and verify, VRAM loads, error unwinding, write mode, soft reset, and the A value GetHardCodedPointers passes in $02. --- freedisksys.asm | 384 +++++++++++++++++++++++++++++---------- gethardcodedpointers.asm | 7 +- keyboard.asm | 73 ++++++++ reset.asm | 25 +++ uploadobject.asm | 195 ++++++++++++++++++++ 5 files changed, 582 insertions(+), 102 deletions(-) create mode 100644 keyboard.asm create mode 100644 uploadobject.asm diff --git a/freedisksys.asm b/freedisksys.asm index 257b85c..51df7af 100644 --- a/freedisksys.asm +++ b/freedisksys.asm @@ -117,6 +117,8 @@ LoadFiles: PHA JSR CheckDiskHeader JSR GetNumFiles + LDA $06 + BEQ @done ; a disk with no files would otherwise loop 256 times @FileLoop: LDA #$03 JSR CheckBlockType @@ -124,8 +126,10 @@ LoadFiles: JSR LoadData DEC $06 BNE @FileLoop +@done: PLA STA $101 + LDY $0e ; number of files loaded JSR XferDone RTS @@ -151,7 +155,7 @@ API_ENTRYPOINT $e239 WriteFile: STA $05 LDA #$ff - JSR GetHardCodedPointers + JSR GetHardCodedPointersWriteProtected LDA $101 PHA @@ -159,43 +163,36 @@ WriteFile: JSR GetNumFiles LDA $05 CMP #$ff - BEQ @WdoneNumFiles + BNE @haveFileNum + LDA $06 ; appending, so the new file goes after the last one + STA $05 +@haveFileNum: STA $06 -@WdoneNumFiles: JSR SkipFiles LDA #$03 JSR WriteBlockType LDA #$00 JSR SaveData;write the file to disk - JSR XferDone JSR CheckDiskHeader;verify write pass JSR GetNumFiles LDA $05 - CMP #$ff - BNE @VstoreNum - LDA $06 - STA $05 - INC $05 -@VstoreNum: STA $06 -@VdoneNumFiles: JSR SkipFiles LDA #$03 JSR CheckBlockType LDA #$FF - JSR SaveData;verify written data - BNE @end;if verification fails, return without updating file count - JSR XferDone + JSR SaveData;verify written data. A mismatch exits with error $26. + ; The written file stays visible and any files after it are hidden. JSR CheckDiskHeader;adjust file count pass - LDA $05 + LDX $05 + INX + TXA JSR SetNumFiles - JSR XferDone -@end: PLA STA $101 - JSR XferDone + LDA #OK RTS ; Reads in disk's file count, compares it to A, then sets the disk's file count @@ -204,7 +201,9 @@ WriteFile: ; Returns: A = error # API_ENTRYPOINT $e2b7 CheckFileCount: - RTS + LDX #$ff + NOP + DB $2C ; BIT abs: skip the LDX #$00 of AdjustFileCount ; Reads in disk's file count, decrements it by A, then writes the new value ; back. @@ -212,6 +211,30 @@ CheckFileCount: ; Returns: A = error # API_ENTRYPOINT $e2bb AdjustFileCount: + LDX #$00 + STX $09 ; $ff = CheckFileCount, $00 = AdjustFileCount + JSR GetHardCodedPointersWriteProtected ; A goes to $02 + LDA $101 + PHA + JSR CheckDiskHeader + JSR GetNumFiles + LDA $06 + CMP $02 + BCS @inRange + LDA #$31 ; A is greater than the file count + JMP ErrorOccurred +@inRange: + BIT $09 + BMI @setCount + SBC $02 ; carry is still set from the CMP + STA $02 +@setCount: + JSR CheckDiskHeader + LDA $02 + JSR SetNumFiles + PLA + STA $101 + LDA #OK RTS ; Set the file count to A + 1 @@ -229,22 +252,124 @@ SetFileCount1: ; Returns: A = error # API_ENTRYPOINT $e305 SetFileCount: - tax - lda #$00 - jsr GetHardCodedPointers;get a single pointer (disk ID) - jsr CheckDiskHeader;read disk header, the data we want is in block 2 - + JSR GetHardCodedPointersWriteProtected ; single pointer (disk ID), A goes to $02 + LDA $101 + PHA + JSR CheckDiskHeader ; leaves the disk at block 2, the file count + LDA $02 + JSR SetNumFiles + PLA + STA $101 + LDA #OK RTS ; Fills provided DiskInfo structure with data read off the current disk. +; DiskInfo layout: 10 Disk ID bytes, file count, then file ID and 8-byte name +; for each file, then disk size (big endian). Disk size is the sum of every +; file's size plus 261 per file. ; Parameters: Pointer to Disk Info ; Returns: A = error # +; Affects: $00-$0F API_ENTRYPOINT $e32a GetDiskInfo: - RTS + LDA #$00 + JSR GetHardCodedPointers ; ($00) = DiskInfo + LDA $101 + PHA + LDA #$00 + STA $0e ; disk size, low byte + STA $0f ; disk size, high byte + JSR StartXfer + LDY #$00 +@diskIdLoop: + JSR XferByte + STA ($00),y + INY + CPY #10 + BNE @diskIdLoop + LDY #31 ; skip the boot file ID and the rest of block 1 +@skipBlock1: + JSR XferByte + DEY + BNE @skipBlock1 + JSR EndOfBlockRead + JSR GetNumFiles + LDA $06 + LDY #10 + STA ($00),y + INY + STY $05 ; next DiskInfo index + LDA $06 + BEQ @done +@fileLoop: + LDA #$03 + JSR CheckBlockType + JSR XferByte ; file number, not reported + LDX #9 ; file ID and 8-byte name +@nameLoop: + JSR XferByte + LDY $05 + STA ($00),y + INC $05 + DEX + BNE @nameLoop + JSR XferByte ; load address, not reported + JSR XferByte + JSR XferByte + STA $0c ; file size + JSR XferByte + STA $0d + JSR XferByte ; file type, not reported + ; disk size += file size + 261 ($105) + LDA $0c + CLC + ADC $0e + STA $0e + LDA $0d + ADC $0f + STA $0f + LDA $0e + CLC + ADC #$05 + STA $0e + LDA $0f + ADC #$01 + STA $0f + JSR EndOfBlockRead + LDA #$04 + JSR CheckBlockType +@skipData: + JSR DecPtr0C + BCC @endData + JSR XferByte + JMP @skipData +@endData: + JSR EndOfBlockRead + DEC $06 + BNE @fileLoop +@done: + LDY $05 + LDA $0f + STA ($00),y + INY + LDA $0e + STA ($00),y + PLA + STA $101 + JMP XferDone +; Adds Y to the 16-bit pointer at $0A. +; Parameters: Y = value to add +; Affects: A, $0A, $0B API_ENTRYPOINT $e3da AddYtoPtr0A: + TYA + CLC + ADC $0a + STA $0a + BCC + + INC $0b ++: RTS INCLUDE gethardcodedpointers.asm @@ -366,8 +491,25 @@ FileMatchTest: ; Skips over specified number of files. ; Parameters: Number of files to skip in $06 +; Affects: $06, $09, $0A-$0D, $0F API_ENTRYPOINT $e4da SkipFiles: + LDA $06 + BEQ @done +@loop: + LDA #$03 + JSR CheckBlockType + LDY #10 ; file number, file ID, and 8-byte name +@skipHeader: + JSR XferByte + DEY + BNE @skipHeader + LDA #$ff ; read the file without storing it + STA $09 + JSR LoadData + DEC $06 + BNE @loop +@done: RTS ;load if $09 is 0, otherwise skip @@ -384,7 +526,7 @@ LoadData: API_ENTRYPOINT $e506 ReadData: JSR XferByte - STA #$05 + STA $0f ; file type. $05 stays free for WriteFile's file number. BEQ @notVram BIT $09 BMI @notVram;if dummy read, don't set up PPU for write @@ -407,14 +549,15 @@ ReadData: JSR DecPtr0C;decrement before loop to prevent off-by-one BCC @endloop;because eof is determined by underflow @loop: - JSR Xfer1stByte + JSR XferByte ; CheckBlockType already enabled transfer IRQs BIT $09 BMI @loopDec0C;if $09 is $ff, don't store data - LDY $05 + LDY $0f BEQ @storePRG - STA $2007 - BNE @loopDec0C + STA PPUDATA + JMP @loopDec0C ; a BNE here would fall through when the byte is 0 @storePRG: + LDY #$00 STA ($0a),y JSR Inc0ADec0C BCS @loop @@ -422,9 +565,15 @@ ReadData: JSR EndOfBlockRead RTS +; Writes or verifies one file: the rest of the header block (whose block type +; was already transferred), then the data block. +; Parameters: A = $00 to write, $ff to verify; ($02) = File Header; $05 = file +; number on disk +; Returns: on a verify mismatch, exits through ErrorOccurred with error $26 +; Affects: $07-$0E API_ENTRYPOINT $e5b5 SaveData: - TAX + STA $09 LDY #$0b LDA ($02),y;get file size STA $0c @@ -440,66 +589,46 @@ SaveData: INY LDA ($02),y;get file location (RAM/VRAM) STA $0e; 0 means CPU RAM + + LDA $05 ; file number + JSR XferOrVerify + LDY #$00 +@headerLoop: + LDA ($02),y ; file ID, name, load address, size, and type + JSR XferOrVerify + INY + CPY #$0e + BNE @headerLoop + JSR EndOfBlockXfer + LDA #$04 + JSR StartDataBlock + + LDA $0e BEQ @begin JSR DisPFObj - BIT PPUADDR - LDY $0b - STY PPUADDR - LDY $0a - STY PPUADDR + BIT PPUSTATUS + LDA $0b + STA PPUADDR + LDA $0a + STA PPUADDR + LDA PPUDATA ; VRAM reads are buffered, so discard the first one @begin: - INX - BEQ @verifyData + JSR DecPtr0C ; the loop ends when the size underflows + BCC @end +@dataLoop: LDY #$00 -@saveLoop: LDA $0e BEQ @RAMSource LDA PPUDATA - JMP @save + JMP @xfer @RAMSource: LDA ($0a),y -@save: - JSR Xfer1stByte - JSR Inc0ADec0C - BCS @saveLoop - RTS - - - - -@verifyData: - LDY #$00 -@verifyHeaderLoop: - JSR Xfer1stByte - CMP ($02),y - BNE @errorH - INY - CPY #$0e - BCC @verifyHeaderLoop - ; - - LDA #$04 - JSR CheckBlockType - LDY #$00 -@verifyFileLoop: - JSR Xfer1stByte - LDX $0e - BEQ @WRAMCompare - CMP PPUDATA - BNE @errorF - BEQ @continue -@WRAMCompare: - CMP ($0a),y - BNE @errorF -@continue: +@xfer: + JSR XferOrVerify JSR Inc0ADec0C - BCS @verifyFileLoop - RTS - -@errorH: -@errorF: - LDA #$ff - RTS + BCS @dataLoop +@end: + JMP EndOfBlockXfer API_ENTRYPOINT $e64d WaitForDriveReady: @@ -589,7 +718,7 @@ StartXfer: BPL @loop RTS @error: - LDA #$20 + LDA #WRONG_SIGNATURE JSR ErrorOccurred API_ENTRYPOINT $e706 @@ -609,9 +738,27 @@ EndOfBlockRead: @error: JSR ErrorOccurred +; Finishes writing a block: has the drive write the block's CRC, checks that +; the disk did not run out, then switches the drive back to read mode. +; Returns: on a full disk, exits through ErrorOccurred with error $30 API_ENTRYPOINT $e729 EndOfBlkWrite: - RTS + LDA ZP_FDSCTRL + ORA #$10 ; transfer the CRC + STA ZP_FDSCTRL + STA FDSCTRL + JSR XferByte ; two CRC bytes + JSR XferByte + LDA DRIVESTATUS + AND #$02 + BEQ @ok + LDA #DISK_FULL + JMP ErrorOccurred +@ok: + LDA ZP_FDSCTRL + ORA #$04 ; read mode + STA ZP_FDSCTRL + JMP XferDone API_ENTRYPOINT $e778 XferDone: @@ -623,10 +770,7 @@ ErrorNotZero: BNE ErrorOccurred RTS ErrorOccurred: - LDX $04 - TXS - NOP -API_ENTRYPOINT $e786 + JMP ErrorUnwind EndRead: PHA LDA ZP_FDSCTRL @@ -814,19 +958,9 @@ JumpEngine: ; (indirect) jump! JMP ($00) -; Read Family Basic Keyboard expansion -API_ENTRYPOINT $eb13 -ReadKeyboard: - RTS - +INCLUDE keyboard.asm INCLUDE loadtileset.asm - -; Some kind of logic that some games use. (detail is under analysis) -; Parameters: $00-$01 Pointer to structure... ? -; Affects: A, X, Y, $02, $03, $04, $05, $06, $07, $08, $09 -API_ENTRYPOINT $ec22 -unk_EC22: - RTS +INCLUDE uploadobject.asm API_ENTRYPOINT $ee17 StartMotor: @@ -838,6 +972,58 @@ StartMotor: ; private functions +; Returns from a disk API with an error. GetHardCodedPointers saved the stack +; position in $04, and every disk API pushes $0101 right after calling it, so +; that byte sits just below the saved position. +; Parameters: A = error # +ErrorUnwind: + LDX $04 + TXS + LDY $0100,x + STY IRQ_ACTION + PHA + LDA ZP_FDSCTRL + ORA #$04 ; leave the drive in read mode, even after a failed write + STA ZP_FDSCTRL + PLA + JMP EndRead + +; Writes A to the disk, or reads a byte and compares it to A, depending on $09. +; The block must already be started, so XferByte is fast enough here. +; Parameters: A = byte, $09 = $00 to write, $ff to verify +; Returns: on a mismatch, exits through ErrorOccurred with error $26 +; Affects: A, $08 +XferOrVerify: + BIT $09 + BMI @verify + JMP XferByte +@verify: + STA $08 + JSR XferByte + CMP $08 + BNE @mismatch + RTS +@mismatch: + LDA #$26 ; readback verification failed + JMP ErrorOccurred + +; Ends the current block with EndOfBlkWrite or EndOfBlockRead, depending on $09. +EndOfBlockXfer: + BIT $09 + BMI @read + JMP EndOfBlkWrite +@read: + JMP EndOfBlockRead + +; Starts the next block with WriteBlockType or CheckBlockType, depending on $09. +; Parameters: A = block type +StartDataBlock: + BIT $09 + BMI @read + JMP WriteBlockType +@read: + JMP CheckBlockType + ; Checks whether the little-endian address provided in ($02) plus the offset in ; $04 is in the range $3Fxx (or one of its mirrors). Checks the current PPU ; increment mode to do the correct arithmetic. If the current PPU address is in diff --git a/gethardcodedpointers.asm b/gethardcodedpointers.asm index 874c7e7..c4edd53 100644 --- a/gethardcodedpointers.asm +++ b/gethardcodedpointers.asm @@ -73,8 +73,9 @@ GetHardCodedPointersImpl: iny lda ($03),y sta $01 - inc $02 - bne @endLoadPointers;if A was $ff + lda $02 + eor #$ff ; unlike INC, this leaves A intact in $02 and keeps C + bne @endLoadPointers;if A was not $ff iny ;load 2 more bytes lda ($03),y sta $02 @@ -102,7 +103,7 @@ GetHardCodedPointersImpl: LDA DRIVESTATUS AND #%00000100 ; bit 2 contains the write-protect status BEQ @end - lda WRITE_PROTECTED + lda #WRITE_PROTECTED @error: PLP;return to user program rather than function in case of error PLP diff --git a/keyboard.asm b/keyboard.asm new file mode 100644 index 0000000..50d503b --- /dev/null +++ b/keyboard.asm @@ -0,0 +1,73 @@ +; FreeDiskSysROM +; Copyright (c) 2026 rom-weaver contributors +; +; This program is free software: you can redistribute it and/or modify it under +; the terms of the GNU Lesser General Public License version 3 as published by +; the Free Software Foundation. +; +; This program is distributed in the hope that it will be useful, but WITHOUT +; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +; FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +; details. +; +; You should have received a copy of the GNU Lesser General Public License +; along with this program. If not, see . + +; Read the Family BASIC Keyboard on the expansion port. +; The keyboard is scanned through $4016: bit 0 resets the scan to row 0, bit 1 +; selects the column, and bit 2 enables the keyboard. Writing column 0 after +; column 1 advances to the next row. Keys are read from $4017 bits 1-4, where a +; 0 means pressed. With no keyboard connected, those bits read as 0. +; Parameters: $FB = controller latch bits to keep in bits 3-7 +; Returns: A = $FF if a keyboard was read, $00 if none is connected. +; $00 = row 8 down to $08 = row 0. Lower nybble = column 0, upper +; nybble = column 1. A set bit means the key is pressed. +; Affects: A, X, Y, $00-$08, $FB +API_ENTRYPOINT $eb13 +ReadKeyboard: + LDA ZP_JOYPAD1 + AND #%11111000 + TAY ; Y = latch bits to keep + ORA #%00000101 ; reset to row 0 + STA JOYPAD1 + JSR Delay131 + LDX #$08 +@rowLoop: + TYA + ORA #%00000100 ; column 0 + STA JOYPAD1 + JSR Delay131 + LDA JOYPAD2 + LSR A + AND #$0F + STA $00,x + TYA + ORA #%00000110 ; column 1 + STA JOYPAD1 + JSR Delay131 + LDA JOYPAD2 + ASL A + ASL A + ASL A + AND #$F0 + ORA $00,x + EOR #$FF ; the keyboard reports pressed keys as 0 + STA $00,x + DEX + BPL @rowLoop + TYA + STA JOYPAD1 ; stop scanning + STY ZP_JOYPAD1 + + ; Without a keyboard every key reads as pressed. + LDA #$FF + LDX #$08 +@detectLoop: + AND $00,x + DEX + BPL @detectLoop + EOR #$FF ; $00 if every key read as pressed + BEQ @done + LDA #$FF +@done: + RTS diff --git a/reset.asm b/reset.asm index b8f727f..db6b89b 100644 --- a/reset.asm +++ b/reset.asm @@ -23,6 +23,8 @@ DISK_RESET_VEC EQU $DFFC RESET: SEI ; disable interrupts CLD ; clear decimal mode flag, which doesn't work on the 2A03 anyway + LDX #$FF + TXS ; don't allow NMIs until we're ready LDY #$00 @@ -74,6 +76,29 @@ RESET: STA ZP_EXTCONN STA EXTCONNWR + LDA #$C0 ; game NMI #3 + STA NMI_ACTION + LDA #$80 ; BIOS acknowledge and delay + STA IRQ_ACTION + + ; A game that is already loaded restarts at its own reset vector. + LDA RESET_ACTION_1 + CMP #$35 + BNE @coldBoot + LDA RESET_ACTION_2 + CMP #$AC + BEQ @softReset + CMP #$53 + BNE @coldBoot +@softReset: + LDA #$53 ; the game has already booted once + STA RESET_ACTION_2 + LDA #$80 + STA ZP_PPUCTRL + STA PPUCTRL + JMP (DISK_RESET_VEC) +@coldBoot: + ; prepare the VRAM buffer LDA #$7D ; initial write buffer found at $302-$37F STA $300 diff --git a/uploadobject.asm b/uploadobject.asm new file mode 100644 index 0000000..83e210a --- /dev/null +++ b/uploadobject.asm @@ -0,0 +1,195 @@ +; FreeDiskSysROM +; Copyright (c) 2026 rom-weaver contributors +; +; This program is free software: you can redistribute it and/or modify it under +; the terms of the GNU Lesser General Public License version 3 as published by +; the Free Software Foundation. +; +; This program is distributed in the hope that it will be useful, but WITHOUT +; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +; FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +; details. +; +; You should have received a copy of the GNU Lesser General Public License +; along with this program. If not, see . + +; Object structure offsets +OBJ_RENDER EQU $00 ; $00 = render, $01-$7F = skip, $80-$FF = hide +OBJ_Y EQU $01 ; Y position of the upper left corner +OBJ_X EQU $03 ; X position of the upper left corner +OBJ_FRAME EQU $05 ; animation frame +OBJ_TILES EQU $06 ; tile arrangement pointer, big endian +OBJ_FLAGS EQU $08 ; bit 4 = flip horizontally, bit 0 = flip vertically +OBJ_PALETTE EQU $09 +OBJ_SIZE EQU $0A ; upper nybble = height, lower nybble = width, in tiles +OBJ_OAM EQU $0B ; byte offset of the object's first sprite in $0200-$02FF +; Offsets $02 and $04 hold fractional positions, which this routine ignores. + +; Upload an object (a group of sprites) to the OAM buffer at $0200-$02FF. +; Tiles are arranged column by column. If the tile arrangement pointer is less +; than $100, it is the upper left tile ID, and the tiles that follow are +; consecutive. Otherwise it points to a list of tile IDs. Either way, each +; animation frame advances by width * height tiles. +; Parameters: ($00) = object structure +; Affects: A, X, Y, $02-$0C +API_ENTRYPOINT $ec22 +UploadObject: + LDY #OBJ_SIZE + LDA ($00),y + AND #$0F + STA $02 ; width + LDA ($00),y + LSR A + LSR A + LSR A + LSR A + STA $03 ; height + ; $0C = width * height + LDA #$00 + LDX $03 + BEQ @haveCount +@multiply: + CLC + ADC $02 + DEX + BNE @multiply +@haveCount: + STA $0C + TAY ; STA does not set the flags + BEQ @rts ; empty object + LDY #OBJ_OAM + LDA ($00),y + TAX ; X = OAM buffer offset + + LDY #OBJ_RENDER + LDA ($00),y + BEQ @render + BPL @rts + ; hide every sprite in the object + LDY $0C + LDA #$FF +@hideLoop: + STA $0200,x + INX + INX + INX + INX + DEY + BNE @hideLoop +@rts: + RTS + +@render: + ; $04 = OAM attributes + LDY #OBJ_PALETTE + LDA ($00),y + AND #%00000011 + STA $04 + LDY #OBJ_FLAGS + LDA ($00),y + AND #%00010000 + BEQ @noHFlip + LDA #%01000000 + ORA $04 + STA $04 +@noHFlip: + LDA ($00),y + LSR A + BCC @noVFlip + LDA #%10000000 + ORA $04 + STA $04 +@noVFlip: + ; $05-$06 = tile pointer advanced by frame * width * height + LDY #OBJ_TILES + LDA ($00),y + STA $06 + INY + LDA ($00),y + STA $05 + LDY #OBJ_FRAME + LDA ($00),y + TAY + BEQ @haveTiles +@frameLoop: + LDA $05 + CLC + ADC $0C + STA $05 + BCC + + INC $06 ++: + DEY + BNE @frameLoop +@haveTiles: + LDA #$00 + STA $07 ; column + STA $09 ; tile index within the frame +@columnLoop: + ; $0A = X position of this column + LDA $07 + BIT $04 + BVC + + EOR #$FF ; flipped: column (width - 1 - column) + SEC + ADC $02 + SEC + SBC #$01 ++: + ASL A + ASL A + ASL A + LDY #OBJ_X + CLC + ADC ($00),y + STA $0A + LDA #$00 + STA $08 ; row +@rowLoop: + ; Y position of this row + LDA $08 + BIT $04 + BPL + + EOR #$FF ; flipped: row (height - 1 - row) + SEC + ADC $03 + SEC + SBC #$01 ++: + ASL A + ASL A + ASL A + LDY #OBJ_Y + CLC + ADC ($00),y + STA $0200,x + ; tile ID + LDA $06 + BNE @tileFromList + LDA $05 + CLC + ADC $09 + JMP @haveTile +@tileFromList: + LDY $09 + LDA ($05),y +@haveTile: + STA $0201,x + LDA $04 + STA $0202,x + LDA $0A + STA $0203,x + INX + INX + INX + INX + INC $09 + INC $08 + LDA $08 + CMP $03 + BNE @rowLoop + INC $07 + LDA $07 + CMP $02 + BNE @columnLoop + RTS From 1536820c7dc807a560580755423851614d0fdebe Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:33:57 -0500 Subject: [PATCH 03/19] test: run the BIOS in a simulated FDS --- .gitignore | 2 + tests/fds_sim.py | 320 +++++++++++++++++++++++++++++++++++++++++++++ tests/test_bios.py | 306 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 628 insertions(+) create mode 100644 tests/fds_sim.py create mode 100644 tests/test_bios.py diff --git a/.gitignore b/.gitignore index 3774670..8a83bea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ .vscode *.bin *.lst +disksys.rom +__pycache__/ diff --git a/tests/fds_sim.py b/tests/fds_sim.py new file mode 100644 index 0000000..e226b28 --- /dev/null +++ b/tests/fds_sim.py @@ -0,0 +1,320 @@ +"""A small Famicom Disk System simulator for testing the BIOS. + +It models the 6502 (through py65), a minimal PPU, and an FDS drive whose +disk is a list of blocks. Drive positioning is event based: starting a +transfer moves to the next block, and transfer reset rewinds to block 0. +Bytes arrive every BYTE_CYCLES CPU cycles while a transfer runs. +""" + +from py65.devices.mpu6502 import MPU +from py65.memory import ObservableMemory + +BYTE_CYCLES = 148 # 96.4 kbit/s at 1.79 MHz is about 148.5 cycles per byte +FRAME_CYCLES = 29781 +DELAYMS = 0xE153 + + +class Kil(Exception): + pass + + +class FdsMPU(MPU): + """py65 MPU with the unofficial opcodes the BIOS uses.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.instruct = list(self.instruct) + self.cycletime = list(self.cycletime) + self.instruct[0x0C] = FdsMPU._top + self.cycletime[0x0C] = 4 + self.instruct[0x72] = FdsMPU._kil + + def _top(self): + self.memory[self.WordAt(self.pc)] + self.pc += 2 + + def _kil(self): + raise Kil("KIL at $%04X" % ((self.pc - 1) & 0xFFFF)) + + +def crc_bytes(): + return [0x00, 0x00] + + +def build_disk(disk_id, boot_id, files): + """Builds disk blocks. disk_id is 10 bytes; files are dicts with id, + name (8 bytes), addr, type, data.""" + block1 = [0x01] + list(b"*NINTENDO-HVC*") + list(disk_id) + [boot_id] + block1 += [0x00] * (56 - len(block1)) + blocks = [block1, [0x02, len(files)]] + for number, f in enumerate(files): + data = list(f["data"]) + header = [0x03, number, f["id"]] + list(f["name"]) + header += [f["addr"] & 0xFF, f["addr"] >> 8] + header += [len(data) & 0xFF, len(data) >> 8, f.get("type", 0)] + blocks.append(header) + blocks.append([0x04] + data) + return blocks + + +class Machine: + def __init__(self, rom, blocks=None, inserted=True, write_protected=False): + self.mem = ObservableMemory() + self.mem.write(0xE000, list(rom)) + # register mirrors and vector flags as left by the BIOS boot + self.mem.write(0x00F9, [0xFF, 0x2E, 0x00, 0x00, 0x00, 0x06, 0x80]) + self.mem.write(0x0100, [0xC0, 0x80]) + self.mpu = FdsMPU(memory=self.mem) + self.blocks = [list(b) for b in (blocks or [])] + self.inserted = inserted + self.write_protected = write_protected + self.keyboard = None # None = no keyboard connected + + # PPU + self.vram = [0] * 0x4000 + self.ppuctrl = 0 + self.ppuaddr = 0 + self.latch = False + self.read_buffer = 0 + self.vblank = False + self.next_frame = FRAME_CYCLES + self.nmi_pending = False + + # drive + self.fdsctrl = 0x2E + self.next_block = 0 + self.current = None + self.stream = [] + self.stream_pos = 0 + self.capture = None + self.byte_flag = False + self.data = 0 + self.next_byte = None + self.overruns = 0 + self.pending = False # a byte arrived and was not yet read or written + self.irq_line = False + + m = self.mem + m.subscribe_to_write(range(0xE000, 0x10000), lambda a, v: m._subject[a]) + m.subscribe_to_write(range(0x2000, 0x2008), self._ppu_write) + m.subscribe_to_read(range(0x2000, 0x2008), self._ppu_read) + m.subscribe_to_write(range(0x4020, 0x4027), self._fds_write) + m.subscribe_to_read(range(0x4030, 0x4034), self._fds_read) + m.subscribe_to_read([0x4016, 0x4017], self._pad_read) + m.subscribe_to_write([0x4016], self._pad_write) + self.kb_row = 0 + self.kb_col = 0 + self.kb_enabled = False + + # PPU + def _ppu_write(self, addr, value): + reg = addr & 7 + if reg == 0: + if value & 0x80 and not self.ppuctrl & 0x80 and self.vblank: + self.nmi_pending = True + self.ppuctrl = value + elif reg == 6: + if not self.latch: + self.ppuaddr = (value << 8) | (self.ppuaddr & 0xFF) + else: + self.ppuaddr = (self.ppuaddr & 0xFF00) | value + self.ppuaddr &= 0x3FFF + self.latch = not self.latch + elif reg == 5: + self.latch = not self.latch + elif reg == 7: + self.vram[self.ppuaddr & 0x3FFF] = value + self._ppu_inc() + return value + + def _ppu_inc(self): + self.ppuaddr = (self.ppuaddr + (32 if self.ppuctrl & 4 else 1)) & 0x3FFF + + def _ppu_read(self, addr): + reg = addr & 7 + if reg == 2: + value = 0x80 if self.vblank else 0 + self.vblank = False + self.latch = False + return value + if reg == 7: + value = self.read_buffer + self.read_buffer = self.vram[self.ppuaddr & 0x3FFF] + self._ppu_inc() + return value + return 0 + + # controllers and keyboard + def _pad_write(self, addr, value): + if value & 1: + self.kb_row = 0 + self.kb_col = 0 + else: + col = (value >> 1) & 1 + if self.kb_col == 1 and col == 0: + self.kb_row = (self.kb_row + 1) % 10 + self.kb_col = col + self.kb_enabled = bool(value & 4) + return value + + def _pad_read(self, addr): + if addr == 0x4017 and self.keyboard is not None and self.kb_enabled: + if self.kb_row < 9: + pressed = self.keyboard[self.kb_row][self.kb_col] # 4 bits + return ((~pressed) & 0x0F) << 1 + return 0x1E + return 0 + + # FDS drive + def _transferring(self): + return self.fdsctrl & 0x40 and self.fdsctrl & 0x01 and not self.fdsctrl & 0x02 + + def _fds_write(self, addr, value): + if addr == 0x4024: + self._ack() + self.pending = False + if self.capture is not None and not self.fdsctrl & 0x10: + self.capture.append(value) + elif addr == 0x4025: + old = self.fdsctrl + self.fdsctrl = value + if value & 0x02: + self.next_block = 0 + if not old & 0x40 and value & 0x40 and self.current is None: + self._start_block() + if old & 0x40 and not value & 0x40: + self._end_block() + if not value & 0x80: + self.irq_line = False + return value + + def _start_block(self): + self.current = self.next_block + if self.fdsctrl & 0x04: # read + block = self.blocks[self.current] if self.current < len(self.blocks) else [] + self.stream = block + crc_bytes() + self.stream_pos = 0 + self.capture = None + else: + self.capture = [] + self.next_byte = self.mpu.processorCycles + BYTE_CYCLES + self.pending = False + + def _end_block(self): + if self.current is None: + return + if self.capture is not None: + block = self.capture + if self.current < len(self.blocks): + self.blocks[self.current] = block + else: + self.blocks.append(block) + self.capture = None + self.next_block = self.current + 1 + self.current = None + self.next_byte = None + + def _ack(self): + self.byte_flag = False + self.irq_line = False + + def _fds_read(self, addr): + if addr == 0x4030: + value = 0x02 if self.byte_flag else 0 + self._ack() + return value + if addr == 0x4031: + self._ack() + self.pending = False + return self.data + if addr == 0x4032: + value = 0 + if not self.inserted: + value |= 0x07 + else: + if self.next_block > len(self.blocks): + value |= 0x02 + if self.write_protected: + value |= 0x04 + return value | 0x40 + if addr == 0x4033: + return 0x80 + return 0 + + def _tick_drive(self): + if self.next_byte is None or not self._transferring(): + return + if self.mpu.processorCycles < self.next_byte: + return + self.next_byte += BYTE_CYCLES + if self.pending and not self.fdsctrl & 0x10: + self.overruns += 1 + self.pending = True + if self.fdsctrl & 0x04: + if self.stream_pos < len(self.stream): + self.data = self.stream[self.stream_pos] + else: + self.data = 0 + self.stream_pos += 1 + self.byte_flag = True + if self.fdsctrl & 0x80: + self.irq_line = True + + # execution + def step(self): + mpu = self.mpu + if mpu.pc == DELAYMS: + # Fast-forward the millisecond delay loop, keeping cycle time. + y = mpu.y or 256 + mpu.processorCycles += y * 1790 + mpu.x = 0 + mpu.y = 0 + mpu.p |= mpu.ZERO + lo = mpu.stPop() + hi = mpu.stPop() + mpu.pc = ((hi << 8) | lo) + 1 + else: + mpu.step() + if mpu.processorCycles >= self.next_frame: + self.next_frame += FRAME_CYCLES + self.vblank = True + if self.ppuctrl & 0x80: + self.nmi_pending = True + self._tick_drive() + if self.nmi_pending: + self.nmi_pending = False + mpu.nmi() + elif self.irq_line and not mpu.p & mpu.INTERRUPT: + mpu.irq() + + def run_until(self, pc, max_cycles=40_000_000): + limit = self.mpu.processorCycles + max_cycles + while self.mpu.pc != pc: + if self.mpu.processorCycles > limit: + raise TimeoutError("PC $%04X after %d cycles" % (self.mpu.pc, max_cycles)) + self.step() + + def reset(self): + self.mpu.pc = self.mpu.WordAt(0xFFFC) + self.mpu.p |= self.mpu.INTERRUPT + + def call(self, address, a=0, x=0, params=(), max_cycles=40_000_000): + """Calls a BIOS routine from a stub at $0400, followed by 16-bit + parameter words. Returns (A, X, Y).""" + stub = [0x20, address & 0xFF, address >> 8] + for p in params: + stub += [p & 0xFF, p >> 8] + end = 0x0400 + len(stub) + stub += [0x4C, end & 0xFF, end >> 8] + self.mem.write(0x0400, stub) + mpu = self.mpu + mpu.pc = 0x0400 + mpu.sp = 0xFF + mpu.a = a + mpu.x = x + mpu.p = mpu.UNUSED | mpu.INTERRUPT + self.run_until(end, max_cycles) + return mpu.a, mpu.x, mpu.y + + def file_count(self): + return self.blocks[1][1] diff --git a/tests/test_bios.py b/tests/test_bios.py new file mode 100644 index 0000000..0484c8c --- /dev/null +++ b/tests/test_bios.py @@ -0,0 +1,306 @@ +"""Tests for FreeDiskSysROM, run against an assembled ROM in a simulator. + +Usage: python tests/test_bios.py [path/to/rom.bin] +""" + +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from fds_sim import Machine, build_disk # noqa: E402 + +ROM_PATH = os.environ.get("FDS_ROM", "disksys.rom") + +LOAD_FILES = 0xE1F8 +APPEND_FILE = 0xE237 +WRITE_FILE = 0xE239 +CHECK_FILE_COUNT = 0xE2B7 +ADJUST_FILE_COUNT = 0xE2BB +SET_FILE_COUNT1 = 0xE301 +SET_FILE_COUNT = 0xE305 +GET_DISK_INFO = 0xE32A +READ_KEYBOARD = 0xEB13 +UPLOAD_OBJECT = 0xEC22 + +DISK_ID = [0x01, 0x54, 0x53, 0x54, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00] +GAME_LOOP = 0x6005 + +# Boot program: store $AA at $10, then loop forever at GAME_LOOP. +BOOT_CODE = [0xA9, 0xAA, 0x85, 0x10, 0xEA, 0x4C, GAME_LOOP & 0xFF, GAME_LOOP >> 8] +VECTORS = [0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60] # $DFF6-$DFFF +CHR = [0x00, 0x11, 0x00, 0x22, 0x00, 0x00, 0x33, 0x44] # zeros catch doubled VRAM writes + + +def files(): + return [ + dict(id=0, name=b"KYODAKU-", addr=0x6000, data=BOOT_CODE), + dict(id=1, name=b"VECTORS-", addr=0xDFF6, data=VECTORS), + dict(id=2, name=b"CHARS---", addr=0x0000, type=1, data=CHR), + dict(id=5, name=b"LATER---", addr=0x7000, data=[0x55] * 20), + ] + + +def disk(): + return build_disk(DISK_ID, 2, files()) + + +class BiosTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + with open(ROM_PATH, "rb") as f: + cls.rom = f.read() + assert len(cls.rom) == 8192, "ROM must be 8 KiB" + + def machine(self, **kwargs): + kwargs.setdefault("blocks", disk()) + return Machine(self.rom, **kwargs) + + def write_disk_id(self, m, address=0x0300): + m.mem.write(address, DISK_ID) + return address + + def assertNoOverruns(self, m): + self.assertEqual(m.overruns, 0, "BIOS missed disk bytes") + + +class BootTest(BiosTest): + def test_boots_disk_and_jumps_to_reset_vector(self): + m = self.machine() + m.reset() + m.run_until(GAME_LOOP) + self.assertEqual(m.mem[0x10], 0xAA) + self.assertEqual(m.mem[0x7000], 0x00, "file above the boot ID was loaded") + self.assertEqual(m.vram[0:len(CHR)], CHR) + self.assertEqual(m.mem[0x0102], 0x35) + self.assertEqual(m.mem[0x0103], 0xAC) + self.assertNoOverruns(m) + + def test_soft_reset_skips_loading(self): + m = self.machine() + m.reset() + m.run_until(GAME_LOOP) + m.mem[0x10] = 0 + m.mem[0x6002] = 0x85 # unchanged code; jump straight back in + m.reset() + m.run_until(GAME_LOOP, max_cycles=200_000) + self.assertEqual(m.mem[0x0103], 0x53) + + +class LoadFilesTest(BiosTest): + def test_loads_listed_file(self): + m = self.machine() + disk_id = self.write_disk_id(m) + m.mem.write(0x0310, [0x05, 0xFF]) + a, _, y = m.call(LOAD_FILES, params=[disk_id, 0x0310]) + self.assertEqual(a, 0) + self.assertEqual(y, 1) + self.assertEqual(m.mem[0x7000:0x7014], [0x55] * 20) + self.assertEqual(m.mem[0x6000], 0x00) + self.assertNoOverruns(m) + + def test_disk_not_set(self): + m = self.machine(inserted=False) + disk_id = self.write_disk_id(m) + m.mem.write(0x0310, [0x05, 0xFF]) + a, _, _ = m.call(LOAD_FILES, params=[disk_id, 0x0310]) + self.assertEqual(a, 0x01) + + def test_wrong_maker_id(self): + m = self.machine() + disk_id = self.write_disk_id(m) + m.mem[disk_id] = 0x99 + m.mem.write(0x0310, [0x05, 0xFF]) + m.mem[0x0101] = 0x80 + a, _, _ = m.call(LOAD_FILES, params=[disk_id, 0x0310]) + self.assertEqual(a, 0x04) + self.assertEqual(m.mem[0x0101], 0x80, "$0101 not restored after error") + + def test_wildcard_disk_id(self): + m = self.machine() + m.mem.write(0x0300, [0xFF] * 10) + m.mem.write(0x0310, [0x05, 0xFF]) + a, _, y = m.call(LOAD_FILES, params=[0x0300, 0x0310]) + self.assertEqual((a, y), (0, 1)) + + +class LargeFileTest(BiosTest): + def test_loads_large_prg_and_vram_files_without_missing_bytes(self): + prg = [(i * 13 + 1) & 0xFF for i in range(4096)] + chr_data = [(i * 5) & 0xFF if i % 3 else 0 for i in range(2048)] + blocks = build_disk(DISK_ID, 0, [ + dict(id=1, name=b"BIGPRG--", addr=0x6000, data=prg), + dict(id=2, name=b"BIGCHR--", addr=0x0000, type=1, data=chr_data), + ]) + m = self.machine(blocks=blocks) + disk_id = self.write_disk_id(m) + m.mem.write(0x0310, [0x01, 0x02, 0xFF]) + a, _, y = m.call(LOAD_FILES, params=[disk_id, 0x0310]) + self.assertEqual((a, y), (0, 2)) + self.assertEqual(m.mem[0x6000:0x7000], prg) + self.assertEqual(m.vram[0:2048], chr_data) + self.assertNoOverruns(m) + + def test_appends_large_file_from_ram_and_vram(self): + m = self.machine() + disk_id = self.write_disk_id(m) + data = [(i * 11) & 0xFF for i in range(1024)] + m.vram[0x1000:0x1400] = data + header = [9] + list(b"VRAMSAVE") + [0x00, 0x10, 0x00, 0x04, 0x01] + header += [0x00, 0x10, 0x01] # source: VRAM $1000 + m.mem.write(0x0320, header) + a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) + self.assertEqual(a, 0) + self.assertEqual(m.blocks[11], [0x04] + data) + self.assertNoOverruns(m) + + +class GetDiskInfoTest(BiosTest): + def test_reports_disk_id_files_and_size(self): + m = self.machine() + a, _, _ = m.call(GET_DISK_INFO, params=[0x0500]) + self.assertEqual(a, 0) + self.assertEqual(m.mem[0x0500:0x050A], DISK_ID) + self.assertEqual(m.mem[0x050A], 4) + index = 0x050B + for f in files(): + self.assertEqual(m.mem[index], f["id"]) + self.assertEqual(bytes(m.mem[index + 1:index + 9]), f["name"]) + index += 9 + size = sum(len(f["data"]) + 261 for f in files()) + self.assertEqual(m.mem[index], size >> 8) + self.assertEqual(m.mem[index + 1], size & 0xFF) + self.assertNoOverruns(m) + + +class WriteTest(BiosTest): + def header(self, m, file_id=7, addr=0x7100, data=None, source=0x0600): + data = data or [(i * 7) & 0xFF for i in range(32)] + m.mem.write(source, data) + header = [file_id] + list(b"SAVEDATA") + [addr & 0xFF, addr >> 8] + header += [len(data) & 0xFF, len(data) >> 8, 0x00] + header += [source & 0xFF, source >> 8, 0x00] + m.mem.write(0x0320, header) + return data + + def test_append_file(self): + m = self.machine() + disk_id = self.write_disk_id(m) + data = self.header(m) + a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) + self.assertEqual(a, 0) + self.assertEqual(m.file_count(), 5) + self.assertEqual(m.blocks[10][0:3], [0x03, 4, 7]) + self.assertEqual(m.blocks[11], [0x04] + data) + self.assertNoOverruns(m) + + m.mem.write(0x0310, [0x07, 0xFF]) + a, _, y = m.call(LOAD_FILES, params=[disk_id, 0x0310]) + self.assertEqual((a, y), (0, 1)) + self.assertEqual(m.mem[0x7100:0x7120], data) + + def test_write_file_hides_later_files(self): + m = self.machine() + disk_id = self.write_disk_id(m) + data = self.header(m, data=[0x00, 0x01, 0x00, 0x02]) + a, _, _ = m.call(WRITE_FILE, a=1, params=[disk_id, 0x0320]) + self.assertEqual(a, 0) + self.assertEqual(m.file_count(), 2) + self.assertEqual(m.blocks[5], [0x04] + data) + + def test_write_protected(self): + m = self.machine(write_protected=True) + disk_id = self.write_disk_id(m) + self.header(m) + a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) + self.assertEqual(a, 0x03) + self.assertEqual(m.file_count(), 4) + + +class FileCountTest(BiosTest): + def test_set_file_count(self): + m = self.machine() + disk_id = self.write_disk_id(m) + a, _, _ = m.call(SET_FILE_COUNT, a=2, params=[disk_id]) + self.assertEqual((a, m.file_count()), (0, 2)) + + def test_set_file_count1(self): + m = self.machine() + disk_id = self.write_disk_id(m) + a, _, _ = m.call(SET_FILE_COUNT1, a=2, params=[disk_id]) + self.assertEqual((a, m.file_count()), (0, 3)) + + def test_adjust_file_count(self): + m = self.machine() + disk_id = self.write_disk_id(m) + a, _, _ = m.call(ADJUST_FILE_COUNT, a=1, params=[disk_id]) + self.assertEqual((a, m.file_count()), (0, 3)) + + def test_check_file_count(self): + m = self.machine() + disk_id = self.write_disk_id(m) + a, _, _ = m.call(CHECK_FILE_COUNT, a=3, params=[disk_id]) + self.assertEqual((a, m.file_count()), (0, 3)) + + def test_check_file_count_too_large(self): + m = self.machine() + disk_id = self.write_disk_id(m) + a, _, _ = m.call(CHECK_FILE_COUNT, a=9, params=[disk_id]) + self.assertEqual((a, m.file_count()), (0x31, 4)) + + +class KeyboardTest(BiosTest): + def test_no_keyboard(self): + m = self.machine() + a, _, _ = m.call(READ_KEYBOARD) + self.assertEqual(a, 0x00) + + def test_reads_pressed_keys(self): + m = self.machine() + m.keyboard = [[0, 0] for _ in range(9)] + m.keyboard[0] = [0b0001, 0b0000] + m.keyboard[8] = [0b0000, 0b1000] + a, _, _ = m.call(READ_KEYBOARD) + self.assertEqual(a, 0xFF) + self.assertEqual(m.mem[0x08], 0x01) # row 0 + self.assertEqual(m.mem[0x00], 0x80) # row 8 + self.assertEqual(m.mem[0x01:0x08], [0] * 7) + + +class UploadObjectTest(BiosTest): + def obj(self, m, render=0, flags=0): + # 2 wide, 2 tall at Y=$20, X=$30, frame 1, base tile $10, palette 2, OAM $08 + m.mem.write(0x0340, [render, 0x20, 0, 0x30, 0, 1, 0x00, 0x10, flags, 2, 0x22, 0x08]) + m.mem.write(0x00, [0x40, 0x03]) + + def sprites(self, m, count=4): + return [m.mem[0x0208 + i * 4:0x020C + i * 4] for i in range(count)] + + def test_renders_column_by_column(self): + m = self.machine() + self.obj(m) + m.call(UPLOAD_OBJECT) + self.assertEqual(self.sprites(m), [ + [0x20, 0x14, 0x02, 0x30], + [0x28, 0x15, 0x02, 0x30], + [0x20, 0x16, 0x02, 0x38], + [0x28, 0x17, 0x02, 0x38], + ]) + + def test_horizontal_flip(self): + m = self.machine() + self.obj(m, flags=0x10) + m.call(UPLOAD_OBJECT) + self.assertEqual(self.sprites(m)[0], [0x20, 0x14, 0x42, 0x38]) + + def test_hide(self): + m = self.machine() + self.obj(m, render=0x80) + m.call(UPLOAD_OBJECT) + self.assertEqual([s[0] for s in self.sprites(m)], [0xFF] * 4) + + +if __name__ == "__main__": + if len(sys.argv) > 1 and not sys.argv[1].startswith("-"): + ROM_PATH = sys.argv.pop(1) + unittest.main() From 74469d42a7b0878264987f798af5a89f33371584 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:33:57 -0500 Subject: [PATCH 04/19] ci: assemble and test the ROM --- .github/workflows/ci.yml | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ac7eb9f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Build asm6f + run: | + git clone -q https://github.com/freem/asm6f "$RUNNER_TEMP/asm6f" + cc -O2 -o "$RUNNER_TEMP/asm6f/asm6f" "$RUNNER_TEMP/asm6f/asm6f.c" + + - name: Assemble + run: "$RUNNER_TEMP/asm6f/asm6f freedisksys.asm disksys.rom" + + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Test + run: | + pip install py65 + python tests/test_bios.py disksys.rom -v + + - uses: actions/upload-artifact@v4 + with: + name: disksys.rom + path: disksys.rom From af39a5906274cc3c2186e64ab05426adc72fb0f9 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:48:07 -0500 Subject: [PATCH 05/19] fix: write disk blocks the way FCEUmm expects Start each written block with the $80 mark and rewrite $4025 for every written byte. FCEUmm, the EmulatorJS NES core, drops the first byte of a block and only signals the next byte to write after a $4025 write. --- freedisksys.asm | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/freedisksys.asm b/freedisksys.asm index 51df7af..1eb3aa4 100644 --- a/freedisksys.asm +++ b/freedisksys.asm @@ -434,7 +434,7 @@ SetNumFiles: LDA #$02 JSR WriteBlockType PLA - JSR XferByte + JSR Xfer1stByte ; writes rewrite $4025 for every byte, which FCEUmm needs JSR EndOfBlkWrite RTS @@ -687,15 +687,15 @@ WriteBlockType: STA FDSCTRL LDY #$0a JSR Delayms;wait 10ms to make lots of space between the files - LDA #$80 - STA WRITEDATA;write the wake-up bit + STY WRITEDATA;Y is 0 after Delayms, so the gap stays zeros LDA ZP_FDSCTRL ORA #$40 STA ZP_FDSCTRL STA FDSCTRL + LDA #$80 + JSR Xfer1stByte;the start mark that ends the gap PLA - JSR Xfer1stByte - RTS + JMP Xfer1stByte @@ -746,9 +746,8 @@ EndOfBlkWrite: LDA ZP_FDSCTRL ORA #$10 ; transfer the CRC STA ZP_FDSCTRL - STA FDSCTRL - JSR XferByte ; two CRC bytes - JSR XferByte + JSR Xfer1stByte ; two CRC bytes + JSR Xfer1stByte LDA DRIVESTATUS AND #$02 BEQ @ok @@ -989,14 +988,15 @@ ErrorUnwind: JMP EndRead ; Writes A to the disk, or reads a byte and compares it to A, depending on $09. -; The block must already be started, so XferByte is fast enough here. +; Writes go through Xfer1stByte because FCEUmm only signals the next byte to +; write after a $4025 write. Reads use the faster XferByte. ; Parameters: A = byte, $09 = $00 to write, $ff to verify ; Returns: on a mismatch, exits through ErrorOccurred with error $26 ; Affects: A, $08 XferOrVerify: BIT $09 BMI @verify - JMP XferByte + JMP Xfer1stByte @verify: STA $08 JSR XferByte From c375e9efa9157eb5dedefb5acbc942cf9f859b27 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:48:07 -0500 Subject: [PATCH 06/19] test: model the FCEUmm drive and add a demo disk --- tests/fds_sim.py | 155 ++++++++++++++++++++++++++++++++++++++-- tests/make_demo_disk.py | 51 +++++++++++++ tests/test_bios.py | 35 +++++++-- 3 files changed, 230 insertions(+), 11 deletions(-) create mode 100644 tests/make_demo_disk.py diff --git a/tests/fds_sim.py b/tests/fds_sim.py index e226b28..feab72b 100644 --- a/tests/fds_sim.py +++ b/tests/fds_sim.py @@ -57,8 +57,126 @@ def build_disk(disk_id, boot_id, files): return blocks +SIDE_SIZE = 65500 +DSK_INIT, DSK_VOLUME, DSK_FILECNT, DSK_FILEHDR, DSK_FILEDATA = range(5) + + +def flatten(blocks): + side = [b for block in blocks for b in block] + return side + [0] * (SIDE_SIZE - len(side)) + + +def unflatten(side): + """Splits a flat disk side back into blocks, using the block lengths.""" + blocks = [side[0:56], side[56:58]] + pos = 58 + for _ in range(side[57]): + header = side[pos:pos + 16] + size = header[13] | (header[14] << 8) + blocks.append(header) + blocks.append(side[pos + 16:pos + 17 + size]) + pos += 17 + size + return blocks + + +class FceummDrive: + """Models the FDS drive the way the FCEUmm core (used by EmulatorJS) + does in src/fds.c: blocks follow a fixed order with fixed lengths, a byte + becomes ready 150 cycles after the last $4031 read or $4025 write, and the + first $4024 write after a block starts is taken as the start mark.""" + + def __init__(self, machine, blocks): + self.m = machine + self.disk = flatten(blocks) + self.control = 0 + self.block = DSK_INIT + self.start = 0 + self.length = 0 + self.addr = 0 + self.filesize = 0 + self.access = 0 + self.seek = 0 + self.irq = False + self.marks = [] + + def write(self, addr, value): + if addr == 0x4024 and self.m.inserted and not self.control & 0x04: + if self.access == 0: + self.access = 1 + self.marks.append(value) + elif self.addr < self.length: + self.disk[self.start + self.addr] = value + if self.block == DSK_FILEHDR and self.addr in (13, 14): + self._filesize(value) + self.addr += 1 + elif addr == 0x4025: + self.irq = False + if self.m.inserted: + if value & 0x40 and not self.control & 0x40: + self.access = 0 + self.seek = 150 + self.start += self.addr + self.addr = 0 + self.block += 1 + if self.block > DSK_FILEDATA: + self.block = DSK_FILEHDR + self.length = {DSK_VOLUME: 0x38, DSK_FILECNT: 2, DSK_FILEHDR: 0x10, + DSK_FILEDATA: 1 + self.filesize}[self.block] + if value & 0x02: + self.block = DSK_INIT + self.start = self.length = self.addr = 0 + self.seek = 150 + if value & 0x40: + self.seek = 150 + self.control = value + return value + + def _filesize(self, value): + if self.addr == 13: + self.filesize = value + else: + self.filesize |= value << 8 + + def read(self, addr): + if addr == 0x4030: + value = 0x02 if self.irq else 0 + self.irq = False + return value + if addr == 0x4031: + value = 0xFF + if self.m.inserted and self.control & 0x04: + self.access = 1 + value = 0 + if self.addr < self.length: + value = self.disk[self.start + self.addr] + if self.block == DSK_FILEHDR and self.addr in (13, 14): + self._filesize(value) + self.addr += 1 + self.seek = 150 + self.irq = False + return value + if addr == 0x4032: + value = 0x40 + if not self.m.inserted: + value |= 0x05 + if not self.m.inserted or not self.control & 1 or self.control & 2: + value |= 0x02 + if self.m.write_protected: + value |= 0x04 + return value + if addr == 0x4033: + return 0x80 + return 0 + + def tick(self, cycles): + if self.seek > 0: + self.seek -= cycles + if self.seek <= 0 and self.control & 0x80: + self.irq = True + + class Machine: - def __init__(self, rom, blocks=None, inserted=True, write_protected=False): + def __init__(self, rom, blocks=None, inserted=True, write_protected=False, drive="exact"): self.mem = ObservableMemory() self.mem.write(0xE000, list(rom)) # register mirrors and vector flags as left by the BIOS boot @@ -91,6 +209,8 @@ def __init__(self, rom, blocks=None, inserted=True, write_protected=False): self.data = 0 self.next_byte = None self.overruns = 0 + self.marks = [] + self.mark_pending = False self.pending = False # a byte arrived and was not yet read or written self.irq_line = False @@ -98,8 +218,14 @@ def __init__(self, rom, blocks=None, inserted=True, write_protected=False): m.subscribe_to_write(range(0xE000, 0x10000), lambda a, v: m._subject[a]) m.subscribe_to_write(range(0x2000, 0x2008), self._ppu_write) m.subscribe_to_read(range(0x2000, 0x2008), self._ppu_read) - m.subscribe_to_write(range(0x4020, 0x4027), self._fds_write) - m.subscribe_to_read(range(0x4030, 0x4034), self._fds_read) + self.fceumm = FceummDrive(self, self.blocks) if drive == "fceumm" else None + if self.fceumm: + m.subscribe_to_write(range(0x4020, 0x4027), self.fceumm.write) + m.subscribe_to_read(range(0x4030, 0x4034), self.fceumm.read) + else: + m.subscribe_to_write(range(0x4020, 0x4027), self._fds_write) + m.subscribe_to_read(range(0x4030, 0x4034), self._fds_read) + self.last_cycles = 0 m.subscribe_to_read([0x4016, 0x4017], self._pad_read) m.subscribe_to_write([0x4016], self._pad_write) self.kb_row = 0 @@ -174,7 +300,12 @@ def _fds_write(self, addr, value): self._ack() self.pending = False if self.capture is not None and not self.fdsctrl & 0x10: - self.capture.append(value) + if self.mark_pending: + # The first byte of a written block is the start mark. + self.marks.append(value) + self.mark_pending = False + else: + self.capture.append(value) elif addr == 0x4025: old = self.fdsctrl self.fdsctrl = value @@ -197,6 +328,7 @@ def _start_block(self): self.capture = None else: self.capture = [] + self.mark_pending = True self.next_byte = self.mpu.processorCycles + BYTE_CYCLES self.pending = False @@ -280,11 +412,17 @@ def step(self): self.vblank = True if self.ppuctrl & 0x80: self.nmi_pending = True - self._tick_drive() + if self.fceumm: + self.fceumm.tick(mpu.processorCycles - self.last_cycles) + self.last_cycles = mpu.processorCycles + irq = self.fceumm.irq + else: + self._tick_drive() + irq = self.irq_line if self.nmi_pending: self.nmi_pending = False mpu.nmi() - elif self.irq_line and not mpu.p & mpu.INTERRUPT: + elif irq and not mpu.p & mpu.INTERRUPT: mpu.irq() def run_until(self, pc, max_cycles=40_000_000): @@ -316,5 +454,8 @@ def call(self, address, a=0, x=0, params=(), max_cycles=40_000_000): self.run_until(end, max_cycles) return mpu.a, mpu.x, mpu.y + def disk_blocks(self): + return unflatten(self.fceumm.disk) if self.fceumm else self.blocks + def file_count(self): - return self.blocks[1][1] + return self.disk_blocks()[1][1] diff --git a/tests/make_demo_disk.py b/tests/make_demo_disk.py new file mode 100644 index 0000000..1d8abe7 --- /dev/null +++ b/tests/make_demo_disk.py @@ -0,0 +1,51 @@ +"""Writes a one-side .fds demo disk that boots with any FDS BIOS and prints +"FREE BIOS OK" through BIOS routines. Use it to check a BIOS in an emulator. + +Usage: python tests/make_demo_disk.py demo.fds +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from fds_sim import build_disk # noqa: E402 + +SIDE_SIZE = 65500 + +# BIOS font tiles: 0-9 are digits, $0A-$23 are A-Z, $24 is a space. +def text(s): + return [0x24 if c == " " else int(c, 36) for c in s] + +MESSAGE = text("FREE BIOS OK") +CODE = [ + 0xA9, 0x21, # $6000 LDA #$21 + 0xA2, 0xCA, # $6002 LDX #$CA + 0xA0, len(MESSAGE), # $6004 LDY #len + 0x20, 0xD2, 0xE8, # $6006 JSR PrepareVRAMString + 0x1A, 0x60, # $6009 .word message + 0x20, 0xB2, 0xE1, # $600B JSR VINTWait + 0x20, 0x6A, 0xE8, # $600E JSR WriteVRAMBuffers + 0x20, 0xEA, 0xEA, # $6011 JSR SetScroll + 0x4C, 0x0B, 0x60, # $6014 JMP $600B + 0x40, # $6017 RTI, for the game NMI vectors + 0x00, 0x00, # $6018 +] + MESSAGE # $601A +VECTORS = [0x17, 0x60] * 3 + [0x00, 0x60, 0x17, 0x60] # $DFF6-$DFFF + +DISK_ID = [0x00] + list(b"DMO") + [0x20, 0x00, 0x00, 0x00, 0x00, 0x00] + + +def main(path): + blocks = build_disk(DISK_ID, 1, [ + dict(id=0, name=b"DEMOPRG-", addr=0x6000, data=CODE), + dict(id=1, name=b"VECTORS-", addr=0xDFF6, data=VECTORS), + ]) + side = [b for block in blocks for b in block] + side += [0] * (SIDE_SIZE - len(side)) + header = list(b"FDS\x1a") + [1] + [0] * 11 + with open(path, "wb") as f: + f.write(bytes(header + side)) + + +if __name__ == "__main__": + main(sys.argv[1] if len(sys.argv) > 1 else "demo.fds") diff --git a/tests/test_bios.py b/tests/test_bios.py index 0484c8c..62192c3 100644 --- a/tests/test_bios.py +++ b/tests/test_bios.py @@ -52,8 +52,11 @@ def setUpClass(cls): cls.rom = f.read() assert len(cls.rom) == 8192, "ROM must be 8 KiB" + DRIVE = "exact" + def machine(self, **kwargs): kwargs.setdefault("blocks", disk()) + kwargs.setdefault("drive", self.DRIVE) return Machine(self.rom, **kwargs) def write_disk_id(self, m, address=0x0300): @@ -87,6 +90,20 @@ def test_soft_reset_skips_loading(self): self.assertEqual(m.mem[0x0103], 0x53) +class DemoDiskTest(BiosTest): + def test_demo_disk_prints_message(self): + import make_demo_disk as demo + blocks = build_disk(demo.DISK_ID, 1, [ + dict(id=0, name=b"DEMOPRG-", addr=0x6000, data=demo.CODE), + dict(id=1, name=b"VECTORS-", addr=0xDFF6, data=demo.VECTORS), + ]) + m = self.machine(blocks=blocks) + m.reset() + m.run_until(0x600B) + m.run_until(0x6014) + self.assertEqual(m.vram[0x21CA:0x21CA + len(demo.MESSAGE)], demo.MESSAGE) + + class LoadFilesTest(BiosTest): def test_loads_listed_file(self): m = self.machine() @@ -151,7 +168,7 @@ def test_appends_large_file_from_ram_and_vram(self): m.mem.write(0x0320, header) a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) self.assertEqual(a, 0) - self.assertEqual(m.blocks[11], [0x04] + data) + self.assertEqual(m.disk_blocks()[11], [0x04] + data) self.assertNoOverruns(m) @@ -190,8 +207,10 @@ def test_append_file(self): a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) self.assertEqual(a, 0) self.assertEqual(m.file_count(), 5) - self.assertEqual(m.blocks[10][0:3], [0x03, 4, 7]) - self.assertEqual(m.blocks[11], [0x04] + data) + self.assertEqual(m.disk_blocks()[10][0:3], [0x03, 4, 7]) + self.assertEqual(m.disk_blocks()[11], [0x04] + data) + drive = m.fceumm or m + self.assertEqual(set(drive.marks), {0x80}, "blocks must start with an $80 mark") self.assertNoOverruns(m) m.mem.write(0x0310, [0x07, 0xFF]) @@ -206,7 +225,7 @@ def test_write_file_hides_later_files(self): a, _, _ = m.call(WRITE_FILE, a=1, params=[disk_id, 0x0320]) self.assertEqual(a, 0) self.assertEqual(m.file_count(), 2) - self.assertEqual(m.blocks[5], [0x04] + data) + self.assertEqual(m.disk_blocks()[5], [0x04] + data) def test_write_protected(self): m = self.machine(write_protected=True) @@ -300,6 +319,14 @@ def test_hide(self): self.assertEqual([s[0] for s in self.sprites(m)], [0xFF] * 4) +# FCEUmm, the NES core EmulatorJS uses, models the drive differently, so the +# disk tests run against its model too. +for _cls in (BootTest, DemoDiskTest, LoadFilesTest, LargeFileTest, GetDiskInfoTest, + WriteTest, FileCountTest): + _name = "Fceumm" + _cls.__name__ + globals()[_name] = type(_name, (_cls,), {"DRIVE": "fceumm"}) + + if __name__ == "__main__": if len(sys.argv) > 1 and not sys.argv[1].startswith("-"): ROM_PATH = sys.argv.pop(1) From ce07cb684fdf24260b5b067487662a13daa79a29 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 11:48:07 -0500 Subject: [PATCH 07/19] docs: document status, tests, and EmulatorJS use --- README.md | 95 ++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 62 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c85624f..53e2b06 100644 --- a/README.md +++ b/README.md @@ -39,35 +39,35 @@ Modern hardware clones of the FDS RAM Adapter or FPGA re-implementations of the | $e18b | NMI | | :white_check_mark: | | $e1b2 | VINTWait | | :white_check_mark: | | $e1c7 | IRQ | | :white_check_mark: | -| $e1f8 | LoadFiles | | | -| $e237 | AppendFile | | | -| $e239 | WriteFile | | | -| $e2b7 | CheckFileCount | | | -| $e2bb | AdjustFileCount | | | -| $e301 | SetFileCount1 | | | -| $e305 | SetFileCount | | | -| $e32a | GetDiskInfo | | | -| $e3da | AddYtoPtr0A | | | -| $e3e7 | GetHardCodedPointers | | | -| $e3ea | GetHardCodedPointersWriteProtected | | | -| $e445 | CheckDiskHeader | | | -| $e484 | GetNumFiles | | | -| $e492 | SetNumFiles | | | -| $e4a0 | FileMatchTest | 0 | | -| $e4da | SkipFiles | 0 | | -| $e4f9 | LoadData | | | -| $e506 | ReadData | | | -| $e5b5 | SaveData | | | -| $e64d | WaitForDriveReady | | | -| $e685 | StopMotor | | | -| $e68f | CheckBlockType | | | -| $e6b0 | WriteBlockType | | | -| $e6e3 | StartXfer | | | -| $e706 | EndOfBlockRead | | | -| $e729 | EndOfBlkWrite | | | -| $e778 | XferDone | | | -| $e794 | Xfer1stByte | | | -| $e7a3 | XferByte | | | +| $e1f8 | LoadFiles | | :white_check_mark: | +| $e237 | AppendFile | | :white_check_mark: | +| $e239 | WriteFile | | :white_check_mark: | +| $e2b7 | CheckFileCount | | :white_check_mark: | +| $e2bb | AdjustFileCount | | :white_check_mark: | +| $e301 | SetFileCount1 | | :white_check_mark: | +| $e305 | SetFileCount | | :white_check_mark: | +| $e32a | GetDiskInfo | | :white_check_mark: | +| $e3da | AddYtoPtr0A | | :white_check_mark: | +| $e3e7 | GetHardCodedPointers | | :white_check_mark: | +| $e3ea | GetHardCodedPointersWriteProtected | | :white_check_mark: | +| $e445 | CheckDiskHeader | | :white_check_mark: | +| $e484 | GetNumFiles | | :white_check_mark: | +| $e492 | SetNumFiles | | :white_check_mark: | +| $e4a0 | FileMatchTest | 0 | :white_check_mark: | +| $e4da | SkipFiles | 0 | :white_check_mark: | +| $e4f9 | LoadData | | :white_check_mark: | +| $e506 | ReadData | | :white_check_mark: | +| $e5b5 | SaveData | | :white_check_mark: | +| $e64d | WaitForDriveReady | | :white_check_mark: | +| $e685 | StopMotor | | :white_check_mark: | +| $e68f | CheckBlockType | | :white_check_mark: | +| $e6b0 | WriteBlockType | | :white_check_mark: | +| $e6e3 | StartXfer | | :white_check_mark: | +| $e706 | EndOfBlockRead | | :white_check_mark: | +| $e729 | EndOfBlkWrite | | :white_check_mark: | +| $e778 | XferDone | | :white_check_mark: | +| $e794 | Xfer1stByte | | :white_check_mark: | +| $e7a3 | XferByte | | :white_check_mark: | | $e7bb | VRAMStructWrite | | :white_check_mark: | | $e844 | FetchDirectPtr | | :white_check_mark: | | $e86a | WriteVRAMBuffers | | :white_check_mark: | @@ -90,23 +90,52 @@ Modern hardware clones of the FDS RAM Adapter or FPGA re-implementations of the | $ead2 | MemFill | | :white_check_mark: | | $eaea | SetScroll | | :white_check_mark: | | $eafd | JumpEngine | | :white_check_mark: | -| $eb13 | ReadKeyboard | 0 | | +| $eb13 | ReadKeyboard | 0 | :white_check_mark: | | $ebaf | LoadTileset | | :white_check_mark: | -| $ec22 | unk_EC22 | | | -| $ee17 | StartMotor | | | +| $ec22 | UploadObject | | :white_check_mark: | +| $ee17 | StartMotor | | :white_check_mark: | ## Initialization +Every entry point is implemented and covered by the simulator tests below. Not yet done: + +- The license screen check. A free BIOS cannot contain Nintendo's license text, so disks boot without it. +- Retrying a failed write a second time, as the original BIOS does. +- Testing against a broad library of commercial disks. + # Building To build, use [asm6f](https://github.com/freem/asm6f). -```asm6f freedisksys.asm``` +```asm6f freedisksys.asm disksys.rom``` The `-l` flag is very useful for development - it shows the addresses assigned to each instruction, so you can easily see how much room remains for a given subroutine. +# Testing + +`tests/test_bios.py` runs the assembled ROM in a 6502 simulator ([py65](https://github.com/mnaberez/py65)) with a simulated PPU and FDS drive. It covers booting, soft reset, loading files to RAM and VRAM, writing and verifying files, file counts, disk info, error codes, the keyboard, and objects. The disk tests run twice: once against a drive that delivers a byte every 148 CPU cycles, as real hardware does, failing if the BIOS misses a byte; and once against a model of the FCEUmm core's drive, which EmulatorJS uses. + +``` +pip install py65 +python tests/test_bios.py disksys.rom +``` + +# Using with EmulatorJS + +EmulatorJS runs FDS games with its NES core and loads the BIOS from `EJS_biosUrl`: + +```js +EJS_core = 'nes'; +EJS_gameUrl = 'game.fds'; +EJS_biosUrl = 'disksys.rom'; +``` + +Prebuilt `disksys.rom` files are attached to each CI run. + +To check a BIOS in an emulator, `python tests/make_demo_disk.py demo.fds` writes a small disk that prints `FREE BIOS OK` using BIOS routines. + # Contributing Rules: From 633ea8086889596b2f70c2a8fc954aa061a08c67 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 12:08:53 -0500 Subject: [PATCH 08/19] fix: send the last byte of each written block A byte written to $4024 leaves at the next byte event, so EndOfBlkWrite waits one more event before sending the CRC, then waits out the CRC with a delay because drives raise no IRQs during it. The write loop is inlined to stay ahead of the disk. --- freedisksys.asm | 49 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/freedisksys.asm b/freedisksys.asm index 1eb3aa4..aa82fe5 100644 --- a/freedisksys.asm +++ b/freedisksys.asm @@ -146,9 +146,8 @@ AppendFile: ; Same as "Append File", but instead of writing the file to the end of the ; disk, A specifies the sequential position on the disk to write the file (0 -; is the first). This also has the effect of setting the disk's file count to -; the A value, therefore logically hiding any other files that may reside after -; the written one. +; is the first). The disk's file count becomes A + 1, so the written file stays +; visible and any files after it are hidden. ; Parameters: Pointer to Disk ID, Pointer to File Header, A = file # ; Returns: A = error # API_ENTRYPOINT $e239 @@ -613,20 +612,35 @@ SaveData: STA PPUADDR LDA PPUDATA ; VRAM reads are buffered, so discard the first one @begin: - JSR DecPtr0C ; the loop ends when the size underflows - BCC @end + ; This loop is inlined because a byte arrives about every 148 cycles. @dataLoop: - LDY #$00 + LDA $0c ; bytes left + ORA $0d + BEQ @end LDA $0e - BEQ @RAMSource - LDA PPUDATA - JMP @xfer -@RAMSource: + BNE @VRAMSource + LDY #$00 LDA ($0a),y + INC $0a + BNE @xfer + INC $0b + JMP @xfer +@VRAMSource: + LDA PPUDATA @xfer: + BIT $09 + BMI @verify + JSR Xfer1stByte + JMP @next +@verify: JSR XferOrVerify - JSR Inc0ADec0C - BCS @dataLoop +@next: + LDA $0c + BNE + + DEC $0d ++: + DEC $0c + JMP @dataLoop @end: JMP EndOfBlockXfer @@ -743,11 +757,18 @@ EndOfBlockRead: ; Returns: on a full disk, exits through ErrorOccurred with error $30 API_ENTRYPOINT $e729 EndOfBlkWrite: + ; A byte written to $4024 goes out at the next byte event, so wait for one + ; more event before switching to CRC, or the block loses its last byte. + JSR Xfer1stByte LDA ZP_FDSCTRL ORA #$10 ; transfer the CRC STA ZP_FDSCTRL - JSR Xfer1stByte ; two CRC bytes - JSR Xfer1stByte + STA FDSCTRL + ; The drive raises no transfer IRQs while it sends the two CRC bytes + ; (about 300 cycles), so wait them out. + JSR Delay131 + JSR Delay131 + JSR Delay131 LDA DRIVESTATUS AND #$02 BEQ @ok From 822acf066402f7bb21d157a7a98d907328bae3f4 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 12:08:53 -0500 Subject: [PATCH 09/19] fix: keep UploadObject frame offsets in tile IDs --- uploadobject.asm | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/uploadobject.asm b/uploadobject.asm index 83e210a..c61274d 100644 --- a/uploadobject.asm +++ b/uploadobject.asm @@ -104,6 +104,7 @@ UploadObject: LDY #OBJ_TILES LDA ($00),y STA $06 + STA $0B ; the unadjusted high byte picks tile IDs or a tile list INY LDA ($00),y STA $05 @@ -164,7 +165,7 @@ UploadObject: ADC ($00),y STA $0200,x ; tile ID - LDA $06 + LDA $0B BNE @tileFromList LDA $05 CLC From 18e1455e6efa726033c317a3c20a0234d8510cab Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 12:08:53 -0500 Subject: [PATCH 10/19] test: latch drive writes like real hardware --- tests/fds_sim.py | 26 +++++++++++++++++++------- tests/make_demo_disk.py | 5 +++-- tests/test_bios.py | 10 ++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/tests/fds_sim.py b/tests/fds_sim.py index feab72b..8b11f47 100644 --- a/tests/fds_sim.py +++ b/tests/fds_sim.py @@ -211,6 +211,8 @@ def __init__(self, rom, blocks=None, inserted=True, write_protected=False, drive self.overruns = 0 self.marks = [] self.mark_pending = False + self.write_latch = 0 + self.crc_written = 0 self.pending = False # a byte arrived and was not yet read or written self.irq_line = False @@ -299,13 +301,8 @@ def _fds_write(self, addr, value): if addr == 0x4024: self._ack() self.pending = False - if self.capture is not None and not self.fdsctrl & 0x10: - if self.mark_pending: - # The first byte of a written block is the start mark. - self.marks.append(value) - self.mark_pending = False - else: - self.capture.append(value) + # The drive shifts this byte out at the next byte event. + self.write_latch = value elif addr == 0x4025: old = self.fdsctrl self.fdsctrl = value @@ -329,6 +326,7 @@ def _start_block(self): else: self.capture = [] self.mark_pending = True + self.crc_written = 0 self.next_byte = self.mpu.processorCycles + BYTE_CYCLES self.pending = False @@ -381,6 +379,20 @@ def _tick_drive(self): self.next_byte += BYTE_CYCLES if self.pending and not self.fdsctrl & 0x10: self.overruns += 1 + if not self.fdsctrl & 0x04 and self.capture is not None: + if self.fdsctrl & 0x10: + # Sending the CRC: no transfer flag or IRQ while it goes out. + self.crc_written += 1 + self.pending = False + return + value = self.write_latch + if self.mark_pending: + # Zeros form the gap; the $80 start mark begins the block. + if value: + self.marks.append(value) + self.mark_pending = False + else: + self.capture.append(value) self.pending = True if self.fdsctrl & 0x04: if self.stream_pos < len(self.stream): diff --git a/tests/make_demo_disk.py b/tests/make_demo_disk.py index 1d8abe7..0714a6a 100644 --- a/tests/make_demo_disk.py +++ b/tests/make_demo_disk.py @@ -1,5 +1,6 @@ -"""Writes a one-side .fds demo disk that boots with any FDS BIOS and prints -"FREE BIOS OK" through BIOS routines. Use it to check a BIOS in an emulator. +"""Writes a one-side .fds demo disk that prints "FREE BIOS OK" through BIOS +routines. Use it to check FreeDiskSysROM in an emulator. It has no license +file, so the original BIOS refuses it with error $20. Usage: python tests/make_demo_disk.py demo.fds """ diff --git a/tests/test_bios.py b/tests/test_bios.py index 62192c3..4fd3ede 100644 --- a/tests/test_bios.py +++ b/tests/test_bios.py @@ -211,6 +211,8 @@ def test_append_file(self): self.assertEqual(m.disk_blocks()[11], [0x04] + data) drive = m.fceumm or m self.assertEqual(set(drive.marks), {0x80}, "blocks must start with an $80 mark") + if not m.fceumm: + self.assertGreaterEqual(m.crc_written, 2, "last block did not end with 2 CRC bytes") self.assertNoOverruns(m) m.mem.write(0x0310, [0x07, 0xFF]) @@ -312,6 +314,14 @@ def test_horizontal_flip(self): m.call(UPLOAD_OBJECT) self.assertEqual(self.sprites(m)[0], [0x20, 0x14, 0x42, 0x38]) + def test_frame_offset_stays_in_tile_ids(self): + # base tile $F0 plus frame 4 * 4 tiles wraps to $00, not a tile list at $0100 + m = self.machine() + self.obj(m) + m.mem.write(0x0345, [4, 0x00, 0xF0]) + m.call(UPLOAD_OBJECT) + self.assertEqual([s[1] for s in self.sprites(m)], [0x00, 0x01, 0x02, 0x03]) + def test_hide(self): m = self.machine() self.obj(m, render=0x80) From c205d5bd6f0a7f14ca00db83c2b6010fec610b49 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 12:27:21 -0500 Subject: [PATCH 11/19] fix: mask transfer IRQs while writing the CRC --- freedisksys.asm | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/freedisksys.asm b/freedisksys.asm index aa82fe5..06bbd1d 100644 --- a/freedisksys.asm +++ b/freedisksys.asm @@ -762,10 +762,11 @@ EndOfBlkWrite: JSR Xfer1stByte LDA ZP_FDSCTRL ORA #$10 ; transfer the CRC + AND #$7F ; no transfer IRQs: nothing services them during the CRC STA ZP_FDSCTRL STA FDSCTRL - ; The drive raises no transfer IRQs while it sends the two CRC bytes - ; (about 300 cycles), so wait them out. + ; Drives differ on flagging CRC bytes, so wait out the two CRC bytes with + ; a delay: about 450 cycles until the second one finishes shifting out. JSR Delay131 JSR Delay131 JSR Delay131 From 102ad7921c48ea5d1579201a9377462bd7e184b2 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 12:27:21 -0500 Subject: [PATCH 12/19] test: require the CRC to finish before write mode ends --- README.md | 2 +- tests/fds_sim.py | 6 +++++- tests/test_bios.py | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53e2b06..4416937 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ EJS_biosUrl = 'disksys.rom'; Prebuilt `disksys.rom` files are attached to each CI run. -To check a BIOS in an emulator, `python tests/make_demo_disk.py demo.fds` writes a small disk that prints `FREE BIOS OK` using BIOS routines. +To check FreeDiskSysROM in an emulator, `python tests/make_demo_disk.py demo.fds` writes a small disk that prints `FREE BIOS OK` using BIOS routines. It has no license file, so the original BIOS refuses it with error $20. # Contributing diff --git a/tests/fds_sim.py b/tests/fds_sim.py index 8b11f47..5841485 100644 --- a/tests/fds_sim.py +++ b/tests/fds_sim.py @@ -381,9 +381,13 @@ def _tick_drive(self): self.overruns += 1 if not self.fdsctrl & 0x04 and self.capture is not None: if self.fdsctrl & 0x10: - # Sending the CRC: no transfer flag or IRQ while it goes out. + # Sending the CRC. Some drives flag these bytes too, so raise + # the flag and the IRQ if it is enabled. self.crc_written += 1 self.pending = False + self.byte_flag = True + if self.fdsctrl & 0x80: + self.irq_line = True return value = self.write_latch if self.mark_pending: diff --git a/tests/test_bios.py b/tests/test_bios.py index 4fd3ede..c141a15 100644 --- a/tests/test_bios.py +++ b/tests/test_bios.py @@ -212,7 +212,9 @@ def test_append_file(self): drive = m.fceumm or m self.assertEqual(set(drive.marks), {0x80}, "blocks must start with an $80 mark") if not m.fceumm: - self.assertGreaterEqual(m.crc_written, 2, "last block did not end with 2 CRC bytes") + # Byte events while sending the CRC: two start the CRC bytes, and a + # third finishes shifting out the second one. + self.assertGreaterEqual(m.crc_written, 3, "write mode ended before the CRC was out") self.assertNoOverruns(m) m.mem.write(0x0310, [0x07, 0xFF]) From ea45d877ae5e5314753b19917024e6f60ec7853a Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 13:59:28 -0500 Subject: [PATCH 13/19] fix: keep VRAM routines inside their documented zero page Games call VRAMStructWrite, WriteVRAMBuffers, and LoadTileset from their NMI handlers, so these routines must only touch the zero page bytes listed in their Affects lines. They used $02-$06 as scratch, which corrupted Zelda's state. They now keep the pointer in $00/$01 and use the stack. --- freedisksys.asm | 43 +---------- loadtileset.asm | 4 +- vrambuffers.asm | 42 +--------- vramprivate.asm | 184 ++++++++++++++++++++++++++++++++++++++++++++ vramstructwrite.asm | 103 ++----------------------- 5 files changed, 198 insertions(+), 178 deletions(-) create mode 100644 vramprivate.asm diff --git a/freedisksys.asm b/freedisksys.asm index 06bbd1d..f06e3a6 100644 --- a/freedisksys.asm +++ b/freedisksys.asm @@ -1046,48 +1046,7 @@ StartDataBlock: @read: JMP CheckBlockType -; Checks whether the little-endian address provided in ($02) plus the offset in -; $04 is in the range $3Fxx (or one of its mirrors). Checks the current PPU -; increment mode to do the correct arithmetic. If the current PPU address is in -; the palette, reset to $0000. Assumes that the PPUADDR latch is currently -; clear. -; Parameters: $00-$01 = PPU address, $02 = offset -; Affects: A, X, Y -PreventPalettePpuAddr: - LDA #%00000100 ; increment mode flag bit test - AND ZP_PPUCTRL - BEQ @incr1 - LDA $02 ; low address byte - LDY $03 ; high address byte - LDX $04 ; offset - BEQ @check ; if the offset is 0, jump straight to the check -@incr32: - CLC - ADC #32 ; for (X = $04; X != 0; X--) $02,$03 += 32; - BCC @nextiter - INY -@nextiter: - DEX - BNE @incr32 - BEQ @check -@incr1: - LDA $02 ; low address byte - LDY $03 ; high address byte - CLC - ADC $04 ; add length to low address byte - BCC @check - INY ; add C to high address byte -@check: - TYA - AND #$3F ; we might be in the mirror $7Fxx range instead of $3Fxx - CMP #$3F ; now check for exactly $3F - BNE @done - LDA #0 ; reset PPUADDR to 0 to get it out of the palette area - STA PPUADDR - STA PPUADDR -@done: - RTS - +INCLUDE vramprivate.asm INCLUDE reset.asm ; the hard-coded interrupt vectors at the end of ROM diff --git a/loadtileset.asm b/loadtileset.asm index d352742..d0bf491 100644 --- a/loadtileset.asm +++ b/loadtileset.asm @@ -97,7 +97,7 @@ Write8XOR: ; non "data" bitplanes are replaced by dummy reads. Also, mode 3 ONLY works in ; write mode! ; Parameters: A = Low VRAM Address & Flags, Y = Hi VRAM Address, X = # of tiles to transfer to/from VRAM, Direct Pointer = CPU address -; Affects: A, X, Y, $00, $01, $02, $03, $04, $05, $06 +; Affects: A, X, Y, $00, $01, $02, $03, $04, $FF API_ENTRYPOINT $ebaf LoadTileset: TOP PPUSTATUS ; clear PPU address latch @@ -106,7 +106,7 @@ LoadTileset: AND #$F0 STA PPUADDR ; set low byte of VRAM address STX $03 ; store length - JSR FetchDirectPtr + JSR FetchPtr00 ; FetchDirectPtr would touch $05-$06 LDA ZP_PPUCTRL AND #%11111011 ; set increment mode to 1 diff --git a/vrambuffers.asm b/vrambuffers.asm index ec4248e..d970a03 100644 --- a/vrambuffers.asm +++ b/vrambuffers.asm @@ -25,51 +25,17 @@ ; "background palette hack," which occurs whenever rendering is off and the ; PPUADDR is somewhere in the palette. (FWIW, rendering is likely to be off ; when this function is called.) -; To reliably prevent the palette from being drawn to the screen, what this -; implementation does instead is to check whether the address of just the -; last structure PLUS its length is in the $3F00-$3FFF area (or the mirror at -; $7F00-$7FFF). +; This implementation does the same. ; The third byte contains the length of the buffer. ; - There's no check for 0-length buffers. Specifying a length of 0 will cause ; a buffer overflow. ; Before returning, the write buffer is cleared (0 written to $301, $80 written ; to $302.) -; Affects: A, X, Y, $02, $03, $04, $301, $302 +; Games call this from NMI handlers, so it touches only the documented bytes. +; Affects: A, X, Y, $FF, $301, $302 API_ENTRYPOINT $e86a WriteVRAMBuffers: - LDA ZP_PPUCTRL - AND #%11111011 ; Address increment of 1 - STA PPUCTRL - STA ZP_PPUCTRL - LDA PPUSTATUS ; clear PPUADDR latch - LDY #0 ; Start at the beginning of $302 -@structure: - LDA $302,Y ; load high byte of destination PPU Address - BMI @done ; an "opcode" of $80 or more marks the end of the list - STA $03 ; save the address (little endian) so we can check later for PPUADDR in the palette - STA PPUADDR ; set the high byte of the initial address - INY - LDA $302,Y ; load low byte of destination PPU address - STA $02 ; save the low byte of the address (little endian) - STA PPUADDR ; set the low byte of the initial address - INY - LDX $302,Y ; load buffer length from third byte - STX $04 ; save the length so we can check later for PPUADDR in the palette - INY -@loop: - LDA $302,Y - STA PPUDATA - INY - DEX - BNE @loop - BEQ @structure ; this structure is done, so move onto the next one -@done: - STA $302 ; write the $80 "opcode" to the first structure's address to clear the list - LDA #0 ; clear the write buffer, i.e., move the read buffer to the beginning - STA $301 - ; Finally, clear PPUADDR if it's currently in the palette - JSR PreventPalettePpuAddr - RTS + JMP WriteVRAMBuffersImpl ; Read individual bytes from VRAM to the VRAMBuffer. Each byte in the buffer is ; preceded by the source address - (1|32) in VRAM; in other words, it takes 3 diff --git a/vramprivate.asm b/vramprivate.asm new file mode 100644 index 0000000..e79eea4 --- /dev/null +++ b/vramprivate.asm @@ -0,0 +1,184 @@ +; FreeDiskSysROM +; Copyright (c) 2026 rom-weaver contributors +; +; This program is free software: you can redistribute it and/or modify it under +; the terms of the GNU Lesser General Public License version 3 as published by +; the Free Software Foundation. +; +; This program is distributed in the hope that it will be useful, but WITHOUT +; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +; FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +; details. +; +; You should have received a copy of the GNU Lesser General Public License +; along with this program. If not, see . + +; Private VRAM helpers. They live outside the fixed API slots because they do +; not fit in them, and they use only the zero-page bytes the APIs document. + +; Fetch the direct pointer that follows the caller's caller's JSR into $00-$01, +; and fix that return address to skip it. Unlike FetchDirectPtr, it does not +; touch $05-$06. +; Affects: A, X, Y, $00, $01 +FetchPtr00: + TSX + LDA $103,X ; return address of the caller's caller, minus 1 + STA $00 + CLC + ADC #2 + STA $103,X + LDA $104,X + STA $01 + ADC #0 + STA $104,X + LDY #2 + LDA ($00),Y ; high byte of the direct pointer + PHA + DEY + LDA ($00),Y ; low byte + STA $00 + PLA + STA $01 + RTS + +; If the PPU address high byte in A is in the palette, move PPUADDR to $3F00 and +; then $0000, so the PPU does not draw palette colors while rendering is off. +; Affects: A +LeavePalette: + AND #$3F + CMP #$3F + BNE + + STA PPUADDR + LDA #$00 + STA PPUADDR + STA PPUADDR + STA PPUADDR ++: + RTS + +VRAMStructWriteImpl: + LDA ZP_PPUCTRL + AND #%11111011 ; increment by 1 unless a structure asks for 32 + STA ZP_PPUCTRL +@structure: + LDA PPUSTATUS ; clear PPUADDR latch + LDY #0 + LDA ($00),Y ; high byte of the destination PPU address, or a command + BPL + + RTS ; >= $80 ends the structure ++: + CMP #$4C ; "call" a sub-structure + BEQ @call + CMP #$60 ; "return" from a sub-structure + BEQ @return + STA PPUADDR + INY + LDA ($00),Y + STA PPUADDR + INY + LDA ($00),Y ; length and flags + BPL @incr1 + LDA ZP_PPUCTRL + ORA #%00000100 ; increment by 32 + BNE @setincr +@incr1: + LDA ZP_PPUCTRL + AND #%11111011 +@setincr: + STA ZP_PPUCTRL + STA PPUCTRL + LDA ($00),Y + AND #%00111111 ; a length of 0 means 64 + BNE + + LDA #64 ++: + TAX + LDA ($00),Y + AND #%01000000 + BNE @fill +@copy: + INY + LDA ($00),Y + STA PPUDATA + DEX + BNE @copy + BEQ @next +@fill: + INY + LDA ($00),Y +@fillLoop: + STA PPUDATA + DEX + BNE @fillLoop +@next: + ; Y is the offset of this structure's last byte + TYA + PHA + LDY #0 + LDA ($00),Y + JSR LeavePalette + PLA + SEC ; skip past the last byte too + ADC $00 + STA $00 + BCC @structure + INC $01 + JMP @structure +@call: + ; push the address after the call, then continue at the sub-structure + LDA $00 + CLC + ADC #3 + TAX + LDA $01 + ADC #0 + PHA + TXA + PHA + LDY #1 + LDA ($00),Y + TAX + INY + LDA ($00),Y + STA $01 + STX $00 + JMP @structure +@return: + PLA + STA $00 + PLA + STA $01 + JMP @structure + +WriteVRAMBuffersImpl: + LDA ZP_PPUCTRL + AND #%11111011 ; Address increment of 1 + STA PPUCTRL + STA ZP_PPUCTRL + LDA PPUSTATUS ; clear PPUADDR latch + LDY #0 ; Start at the beginning of $302 +@structure: + LDA $302,Y ; high byte of destination PPU address + BMI @done ; an "opcode" of $80 or more marks the end of the list + PHA ; kept for the palette check + STA PPUADDR + INY + LDA $302,Y + STA PPUADDR + INY + LDX $302,Y ; length + INY +@loop: + LDA $302,Y + STA PPUDATA + INY + DEX + BNE @loop + PLA + JSR LeavePalette + JMP @structure +@done: + STA $302 ; write the $80 "opcode" to the first structure's address to clear the list + LDA #0 ; clear the write buffer, i.e., move the read buffer to the beginning + STA $301 + RTS diff --git a/vramstructwrite.asm b/vramstructwrite.asm index f1720fd..7c1334d 100644 --- a/vramstructwrite.asm +++ b/vramstructwrite.asm @@ -13,101 +13,12 @@ ; You should have received a copy of the GNU Lesser General Public License ; along with this program. If not, see . -; Affects: A, X, Y, $00, $01, $02, $03, $04, $FF -; Parameters: Direct Pointer to VRAM buffer to be written +; Transfer a VRAM structure to VRAM. The structure format is described in +; freedisksys.asm. Games call this from NMI handlers, so it touches only the +; documented zero-page bytes. +; Affects: A, X, Y, $00, $01, $FF +; Parameters: Direct Pointer to VRAM structure to be written API_ENTRYPOINT $e7bb VRAMStructWrite: - LDA PPUSTATUS ; clear PPUADDR latch - JSR FetchDirectPtr ; start of the buffer is now in ($00) -@buffer: - LDY #0 -@structure: - LDA ($00),Y ; load high byte of destination PPU Address - BMI @done ; >= $80 is the finish opcode - CMP #$4C ; "call" opcode - BEQ @call - CMP #$60 ; "return" opcode - BEQ @return - STA $03 ; save the high byte of the address (little endian) - STA PPUADDR ; set the high byte of the initial address - INY - - LDA ($00),Y ; load low byte of destination PPU address - STA $02 ; save the low byte of the address (little endian) - STA PPUADDR ; set the low byte of the initial address - INY - - LDX ($00),Y ; load buffer length and flags from third byte - TXA - AND #%00111111 ; if bits 0-5 are all zero (length of 0), then the length is really 64 - BNE @savelength - LDA #64 -@savelength: - STA $04 ; save the length so we can check later for PPUADDR in the palette - INY - TXA - BMI @incr32 ; if bit 7 set, increment mode is 32 - LDA ZP_PPUCTRL - AND #%11111011 ; Address increment of 1 - JMP @setincr -@incr32: - LDA ZP_PPUCTRL - ORA #%00000100 ; Address increment of 32 -@setincr: - STA PPUCTRL - STA ZP_PPUCTRL - TXA - AND #%01000000 ; check the mode flag - BEQ @copy - ; must be fill then - -@fill: - LDX $04 - LDA ($00),Y - INY -@fillloop: - STA PPUDATA - DEX - BNE @fillloop - BEQ @structure ; this structure is done, so move onto the next one - -@copy: - LDX $04 -@copyloop: - LDA ($00),Y - STA PPUDATA - INY - DEX - BNE @copyloop - BEQ @structure ; this structure is done, so move onto the next one - -@call: - ; ($00) will be overwritten and Y will be cleared, so they need to be preserved - LDA $01 - PHA ; preserve the high address byte on the stack - LDA $00 - PHA ; preserve the low address byte on the stack - INY - LDA ($00),Y ; get low address byte of substructure - TAX ; hold onto that low byte - INY - LDA ($00),Y ; get high address byte of substructure - INY - STX $00 ; write the address of the substructure - STA $01 - TYA - PHA ; push the Y index onto the stack - BNE @buffer - -@return: - PLA ; restore the Y index - TAY - PLA ; restore the low address byte - STA $00 - PLA ; restore the high address byte - STA $01 - BNE @structure - -@done: - JSR PreventPalettePpuAddr - RTS + JSR FetchPtr00 ; start of the structure is now in ($00) + JMP VRAMStructWriteImpl From e2b0615f8c59e2250035a49f70d8608bcd0fa19b Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 13:59:29 -0500 Subject: [PATCH 14/19] fix: start the game just after a vblank The BIOS turned NMIs on at a random point in the frame, then jumped to the game. An NMI could fire before the game finished its setup, which crashed Zelda. The BIOS now waits for a vblank first, giving the game a whole frame before its first NMI. NMIs stay on at handoff because Metroid expects them. --- reset.asm | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/reset.asm b/reset.asm index db6b89b..c8a9782 100644 --- a/reset.asm +++ b/reset.asm @@ -93,9 +93,7 @@ RESET: @softReset: LDA #$53 ; the game has already booted once STA RESET_ACTION_2 - LDA #$80 - STA ZP_PPUCTRL - STA PPUCTRL + JSR HandOffPpu JMP (DISK_RESET_VEC) @coldBoot: @@ -165,8 +163,7 @@ RESET: LDA #$80 STA $101 - STA ZP_PPUCTRL - STA PPUCTRL + JSR HandOffPpu LDA #$C0 STA $100 @@ -232,3 +229,14 @@ BootList: .byte $ff,$ff,$ff,$ff,$ff,$ff .byte $00,$00 .byte $ff,$ff + + +; Start the game with NMIs on, as some games expect, but just after a vblank, +; so the game gets a whole frame to set itself up before its first NMI. +HandOffPpu: + JSR VINTWait + LDA PPUSTATUS ; clear the vblank flag so enabling NMIs doesn't fire one now + LDA #$80 + STA ZP_PPUCTRL + STA PPUCTRL + RTS From 8dbcfc2691c8f022881f1a6840e8a7f795ed17a5 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 13:59:29 -0500 Subject: [PATCH 15/19] test: cover VRAM zero page use and handoff timing The simulator now clears the vblank flag at the end of vblank, stops a transfer when it is reset, and has a controller on $4016. --- tests/fds_sim.py | 18 +++++++++++- tests/test_bios.py | 71 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/tests/fds_sim.py b/tests/fds_sim.py index 5841485..6336a17 100644 --- a/tests/fds_sim.py +++ b/tests/fds_sim.py @@ -11,6 +11,7 @@ BYTE_CYCLES = 148 # 96.4 kbit/s at 1.79 MHz is about 148.5 cycles per byte FRAME_CYCLES = 29781 +VBLANK_CYCLES = 2273 # the vblank flag clears at the pre-render line, 20 scanlines in DELAYMS = 0xE153 @@ -187,6 +188,8 @@ def __init__(self, rom, blocks=None, inserted=True, write_protected=False, drive self.inserted = inserted self.write_protected = write_protected self.keyboard = None # None = no keyboard connected + self.buttons = 0 # controller 1: A, B, Select, Start, Up, Down, Left, Right in bits 0-7 + self.pad_shift = 0 # PPU self.vram = [0] * 0x4000 @@ -274,6 +277,8 @@ def _ppu_read(self, addr): # controllers and keyboard def _pad_write(self, addr, value): + if value & 1: + self.pad_shift = self.buttons if value & 1: self.kb_row = 0 self.kb_col = 0 @@ -286,6 +291,10 @@ def _pad_write(self, addr, value): return value def _pad_read(self, addr): + if addr == 0x4016: + bit = self.pad_shift & 1 + self.pad_shift = (self.pad_shift >> 1) | 0x80 + return bit if addr == 0x4017 and self.keyboard is not None and self.kb_enabled: if self.kb_row < 9: pressed = self.keyboard[self.kb_row][self.kb_col] # 4 bits @@ -307,6 +316,10 @@ def _fds_write(self, addr, value): old = self.fdsctrl self.fdsctrl = value if value & 0x02: + # Transfer reset: stop any transfer and rewind to the start. + self.current = None + self.capture = None + self.next_byte = None self.next_block = 0 if not old & 0x40 and value & 0x40 and self.current is None: self._start_block() @@ -428,6 +441,8 @@ def step(self): self.vblank = True if self.ppuctrl & 0x80: self.nmi_pending = True + elif self.vblank and mpu.processorCycles >= self.next_frame - FRAME_CYCLES + VBLANK_CYCLES: + self.vblank = False if self.fceumm: self.fceumm.tick(mpu.processorCycles - self.last_cycles) self.last_cycles = mpu.processorCycles @@ -452,7 +467,7 @@ def reset(self): self.mpu.pc = self.mpu.WordAt(0xFFFC) self.mpu.p |= self.mpu.INTERRUPT - def call(self, address, a=0, x=0, params=(), max_cycles=40_000_000): + def call(self, address, a=0, x=0, y=0, params=(), max_cycles=40_000_000): """Calls a BIOS routine from a stub at $0400, followed by 16-bit parameter words. Returns (A, X, Y).""" stub = [0x20, address & 0xFF, address >> 8] @@ -466,6 +481,7 @@ def call(self, address, a=0, x=0, params=(), max_cycles=40_000_000): mpu.sp = 0xFF mpu.a = a mpu.x = x + mpu.y = y mpu.p = mpu.UNUSED | mpu.INTERRUPT self.run_until(end, max_cycles) return mpu.a, mpu.x, mpu.y diff --git a/tests/test_bios.py b/tests/test_bios.py index c141a15..f308568 100644 --- a/tests/test_bios.py +++ b/tests/test_bios.py @@ -8,7 +8,7 @@ import unittest sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from fds_sim import Machine, build_disk # noqa: E402 +from fds_sim import FRAME_CYCLES, VBLANK_CYCLES, Machine, build_disk # noqa: E402 ROM_PATH = os.environ.get("FDS_ROM", "disksys.rom") @@ -89,6 +89,24 @@ def test_soft_reset_skips_loading(self): m.run_until(GAME_LOOP, max_cycles=200_000) self.assertEqual(m.mem[0x0103], 0x53) + def assertHandsOffJustAfterVblank(self, m): + m.run_until(0x6000) + self.assertTrue(m.ppuctrl & 0x80, "NMIs off at handoff") + into_frame = m.mpu.processorCycles - (m.next_frame - FRAME_CYCLES) + self.assertLess(into_frame, VBLANK_CYCLES, "game started mid-frame, so an NMI could interrupt its setup") + + def test_starts_game_just_after_vblank(self): + m = self.machine() + m.reset() + self.assertHandsOffJustAfterVblank(m) + + def test_soft_reset_starts_game_just_after_vblank(self): + m = self.machine() + m.reset() + m.run_until(GAME_LOOP) + m.reset() + self.assertHandsOffJustAfterVblank(m) + class DemoDiskTest(BiosTest): def test_demo_disk_prints_message(self): @@ -290,6 +308,57 @@ def test_reads_pressed_keys(self): self.assertEqual(m.mem[0x01:0x08], [0] * 7) +VRAM_STRUCT_WRITE = 0xE7BB +WRITE_VRAM_BUFFERS = 0xE86A +LOAD_TILESET = 0xEBAF + + +class VramTest(BiosTest): + """Games call these from NMI handlers, so they must leave the zero-page + bytes outside their documented lists alone.""" + + def fill_zero_page(self, m): + m.mem.write(0x0000, [0xA0 + i for i in range(16)]) + + def test_vram_struct_write(self): + m = self.machine() + long_run = [(i * 3) & 0xFF for i in range(64)] + struct = [] + for row in range(5): # 5 * 67 bytes, past the 256-byte index limit + struct += [0x20, row * 64, 0x00] + long_run + struct += [0x4C, 0x00, 0x05] # call the sub-structure at $0500 + struct += [0x23, 0x00, 0x44, 0x7E] # fill 4 bytes with $7E + struct += [0x24, 0x00, 0x82, 0x11, 0x22] # 2 bytes, incrementing by 32 + struct += [0xFF] + m.mem.write(0x6000, struct) + m.mem.write(0x0500, [0x22, 0x80, 0x02, 0x55, 0x66, 0x60]) + self.fill_zero_page(m) + m.call(VRAM_STRUCT_WRITE, params=[0x6000]) + for row in range(5): + self.assertEqual(m.vram[0x2000 + row * 64:0x2040 + row * 64], long_run) + self.assertEqual(m.vram[0x2280:0x2282], [0x55, 0x66]) + self.assertEqual(m.vram[0x2300:0x2304], [0x7E] * 4) + self.assertEqual((m.vram[0x2400], m.vram[0x2420]), (0x11, 0x22)) + self.assertEqual(m.mem[0x0002:0x0010], [0xA0 + i for i in range(2, 16)]) + + def test_write_vram_buffers(self): + m = self.machine() + m.mem.write(0x0300, [0x7D, 0x08, 0x21, 0x00, 0x03, 0x01, 0x02, 0x03, 0x80]) + self.fill_zero_page(m) + m.call(WRITE_VRAM_BUFFERS) + self.assertEqual(m.vram[0x2100:0x2103], [1, 2, 3]) + self.assertEqual((m.mem[0x0301], m.mem[0x0302]), (0x00, 0x80)) + self.assertEqual(m.mem[0x0000:0x0010], [0xA0 + i for i in range(16)]) + + def test_load_tileset_leaves_05_and_up(self): + m = self.machine() + m.mem.write(0x6000, [0xFF] * 8) + self.fill_zero_page(m) + # one 1-bit-per-pixel tile from $6000, as the boot code loads its font + m.call(LOAD_TILESET, a=0x04, x=1, params=[0x6000]) + self.assertEqual(m.mem[0x0005:0x0010], [0xA0 + i for i in range(5, 16)]) + + class UploadObjectTest(BiosTest): def obj(self, m, render=0, flags=0): # 2 wide, 2 tall at Y=$20, X=$30, frame 1, base tile $10, palette 2, OAM $08 From 669d09f50fd4f31b34c583624bf82c30b1fd6e92 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 13:59:31 -0500 Subject: [PATCH 16/19] docs: list games tested in EmulatorJS --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4416937..1d5c8aa 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,16 @@ Modern hardware clones of the FDS RAM Adapter or FPGA re-implementations of the # Status +## Games + +Tested in EmulatorJS (FCEUmm core) with this BIOS: + +- The Legend of Zelda (Japan): boots, loads side B, and saves a new file to disk. The save survives a console reset. +- Kid Icarus (Japan): boots, creates its save file on first start, and reaches the title screen. +- Metroid, Galaga (Japan): boot to the title screen. + +Also tested in the simulator: Akumajou Dracula, Ice Hockey, Zelda II, and Nazo no Murasame Jou boot and load. + ## APIs | Address | Name | # of Games | Implemented | @@ -115,7 +125,7 @@ subroutine. # Testing -`tests/test_bios.py` runs the assembled ROM in a 6502 simulator ([py65](https://github.com/mnaberez/py65)) with a simulated PPU and FDS drive. It covers booting, soft reset, loading files to RAM and VRAM, writing and verifying files, file counts, disk info, error codes, the keyboard, and objects. The disk tests run twice: once against a drive that delivers a byte every 148 CPU cycles, as real hardware does, failing if the BIOS misses a byte; and once against a model of the FCEUmm core's drive, which EmulatorJS uses. +`tests/test_bios.py` runs the assembled ROM in a 6502 simulator ([py65](https://github.com/mnaberez/py65)) with a simulated PPU and FDS drive. It covers booting, soft reset, loading files to RAM and VRAM, writing and verifying files, file counts, disk info, error codes, the keyboard, the VRAM routines, and objects. The disk tests run twice: once against a drive that delivers a byte every 148 CPU cycles, as real hardware does, failing if the BIOS misses a byte; and once against a model of the FCEUmm core's drive, which EmulatorJS uses. ``` pip install py65 From 4eb7689c2c498736940e72b1617efca713c3ccaa Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 14:19:08 -0500 Subject: [PATCH 17/19] fix: return disk errors with Z clear The error path popped the API's return address with PLP, so the flags took its high byte ($E2 or $E3), which has Z set. Callers that check BNE after LoadFiles or WriteFile took a missing or write-protected disk as success. --- gethardcodedpointers.asm | 8 ++++++-- tests/test_bios.py | 5 +++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/gethardcodedpointers.asm b/gethardcodedpointers.asm index c4edd53..81251d0 100644 --- a/gethardcodedpointers.asm +++ b/gethardcodedpointers.asm @@ -105,7 +105,11 @@ GetHardCodedPointersImpl: BEQ @end lda #WRITE_PROTECTED @error: - PLP;return to user program rather than function in case of error - PLP + ; return to user program rather than function in case of error. PLA, not + ; PLP, so the flags follow the error code and BNE sees the error. + TAX + PLA + PLA + TXA @end: RTS diff --git a/tests/test_bios.py b/tests/test_bios.py index f308568..9eaba89 100644 --- a/tests/test_bios.py +++ b/tests/test_bios.py @@ -63,6 +63,9 @@ def write_disk_id(self, m, address=0x0300): m.mem.write(address, DISK_ID) return address + def assertErrorFlags(self, m): + self.assertFalse(m.mpu.p & m.mpu.ZERO, "Z set on an error, so BNE misses it") + def assertNoOverruns(self, m): self.assertEqual(m.overruns, 0, "BIOS missed disk bytes") @@ -140,6 +143,7 @@ def test_disk_not_set(self): m.mem.write(0x0310, [0x05, 0xFF]) a, _, _ = m.call(LOAD_FILES, params=[disk_id, 0x0310]) self.assertEqual(a, 0x01) + self.assertErrorFlags(m) def test_wrong_maker_id(self): m = self.machine() @@ -255,6 +259,7 @@ def test_write_protected(self): self.header(m) a, _, _ = m.call(APPEND_FILE, params=[disk_id, 0x0320]) self.assertEqual(a, 0x03) + self.assertErrorFlags(m) self.assertEqual(m.file_count(), 4) From 8ca2e58b746bd680f7a150a568711f47536c0236 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 14:19:08 -0500 Subject: [PATCH 18/19] fix: keep the interrupt flag across the boot handoff VINTWait returns with IRQs masked, so games started with I set after the handoff change. Cold boots start with I clear again. --- reset.asm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reset.asm b/reset.asm index c8a9782..8881813 100644 --- a/reset.asm +++ b/reset.asm @@ -234,7 +234,9 @@ BootList: ; Start the game with NMIs on, as some games expect, but just after a vblank, ; so the game gets a whole frame to set itself up before its first NMI. HandOffPpu: + PHP ; VINTWait returns with IRQs masked; keep the caller's I flag JSR VINTWait + PLP LDA PPUSTATUS ; clear the vblank flag so enabling NMIs doesn't fire one now LDA #$80 STA ZP_PPUCTRL From 1fad641bdc5c1899149636e3b48533aea90a47d4 Mon Sep 17 00:00:00 2001 From: brandonocasey Date: Tue, 3 Nov 2026 14:19:08 -0500 Subject: [PATCH 19/19] docs: note that failed reads are not retried --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d5c8aa..911f28f 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Also tested in the simulator: Akumajou Dracula, Ice Hockey, Zelda II, and Nazo n Every entry point is implemented and covered by the simulator tests below. Not yet done: - The license screen check. A free BIOS cannot contain Nintendo's license text, so disks boot without it. -- Retrying a failed write a second time, as the original BIOS does. +- Retrying a failed read or write, as the original BIOS does. A disk error is returned at once. - Testing against a broad library of commercial disks. # Building