From 4c530bf7a78730901635f42196c82d79c46a29e0 Mon Sep 17 00:00:00 2001 From: steve Date: Thu, 12 Apr 2018 12:17:44 +0100 Subject: [PATCH] o initial commit - 6502 implementation is basically correct but does not handle - interrupts - pre-fetch cycle - anything less fine grained than instruction stepping - memory sub-system sketched in o retroactive adding of GPL copyright notice --- COPYING | 674 +++++++++++++++++++++++++++++++++ LICENCE | 674 +++++++++++++++++++++++++++++++++ hardware/cpu/cpu.go | 605 +++++++++++++++++++++++++++++ hardware/cpu/cpu_test.go | 450 ++++++++++++++++++++++ hardware/cpu/definitions.csv | 234 ++++++++++++ hardware/cpu/definitions.go | 202 ++++++++++ hardware/cpu/helpers_test.go | 108 ++++++ hardware/cpu/registers.go | 193 ++++++++++ hardware/cpu/registers_bits.go | 141 +++++++ hardware/cpu/registers_test.go | 107 ++++++ hardware/cpu/statusregister.go | 97 +++++ hardware/cpu/stepresult.go | 105 +++++ hardware/memory/memory.go | 7 + 13 files changed, 3597 insertions(+) create mode 100644 COPYING create mode 100644 LICENCE create mode 100644 hardware/cpu/cpu.go create mode 100644 hardware/cpu/cpu_test.go create mode 100644 hardware/cpu/definitions.csv create mode 100644 hardware/cpu/definitions.go create mode 100644 hardware/cpu/helpers_test.go create mode 100644 hardware/cpu/registers.go create mode 100644 hardware/cpu/registers_bits.go create mode 100644 hardware/cpu/registers_test.go create mode 100644 hardware/cpu/statusregister.go create mode 100644 hardware/cpu/stepresult.go create mode 100644 hardware/memory/memory.go diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..f288702d --- /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/LICENCE b/LICENCE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENCE @@ -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/hardware/cpu/cpu.go b/hardware/cpu/cpu.go new file mode 100644 index 00000000..fc531806 --- /dev/null +++ b/hardware/cpu/cpu.go @@ -0,0 +1,605 @@ +package cpu + +// TODO List +// --------- +// . concurrency: yield control back to the clock manager after every cycle +// . NMOS indexed addressing extra read when crossing page boundaries +// . Binary Decimal Mode + +import ( + "fmt" + "headless/hardware/memory" + "log" +) + +// CPU is the main container structure for the package +type CPU struct { + PC Register + A Register + X Register + Y Register + SP Register + Status StatusRegister + + memory memory.Memory + + opCodes definitionsTable +} + +// NewCPU is the constructor for the CPU type +func NewCPU(memory memory.Memory) *CPU { + mc := new(CPU) + mc.memory = memory + + var err error + + mc.opCodes, err = getInstructionDefinitions() + if err != nil { + log.Fatalln(err) + } + + mc.PC = make(Register, 16) + mc.A = make(Register, 8) + mc.X = make(Register, 8) + mc.Y = make(Register, 8) + mc.SP = make(Register, 8) + mc.Status = *new(StatusRegister) + + mc.Reset() + + return mc +} + +// Reset reinitialises all registers +func (mc *CPU) Reset() { + mc.PC.Load(0) + mc.A.Load(0) + mc.X.Load(0) + mc.Y.Load(0) + mc.SP.Load(255) + mc.Status.FromUint8(0) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + mc.Status.InterruptDisable = true + mc.Status.Break = true +} + +func (mc *CPU) read8Bit(address uint16) uint8 { + val, err := mc.memory.Read(address) + if err != nil { + log.Fatalln(err) + } + + return val +} + +func (mc *CPU) read16Bit(address uint16) uint16 { + lo, err := mc.memory.Read(address) + if err != nil { + log.Fatalln(err) + } + + hi, err := mc.memory.Read(address + 1) + if err != nil { + log.Fatalln(err) + } + + var val uint16 + val = uint16(hi) << 8 + val |= uint16(lo) + + return val +} + +func (mc *CPU) read8BitPC() uint8 { + op := mc.read8Bit(mc.PC.ToUint16()) + mc.PC.Add(1, false) + return op +} + +func (mc *CPU) read16BitPC() uint16 { + val := mc.read16Bit(mc.PC.ToUint16()) + mc.PC.Add(2, false) + return val +} + +// Step executes the next instruction in the program +func (mc *CPU) Step() (*StepResult, error) { + // read next instruction + operator := mc.read8BitPC() + defn, found := mc.opCodes[operator] + if !found { + return nil, fmt.Errorf("unimplemented instruction (0x%x)", operator) + } + + var address uint16 + var value uint8 + var err error + + // prepare StepResult structure + result := new(StepResult) + result.ProgramCounter = mc.PC.ToUint16() + result.Defn = defn + result.ActualCycles = defn.Cycles + + // get address to use when reading/writing from/to memory (note that in the + // case of immediate addressing, we are actually getting the value to use in + // the instruction, not the address). we also take the opportuinity to set + // the InstructionData value for the StepResult and whether a page fault has + // occured + switch defn.AddressingMode { + case Implied: + // do nothing for implied addressing + + case Immediate: + // for immediate mode, the value is the next byte in the program + // therefore, we don't set the address and we read the value through the PC + value = mc.read8BitPC() + result.InstructionData = value + + case Relative: + // relative addressing is only used for branch instructions, the address + // is an offset value from the current PC position + address = uint16(mc.read8BitPC()) + result.InstructionData = address + + case Absolute: + address = mc.read16BitPC() + result.InstructionData = address + + case ZeroPage: + address = uint16(mc.read8BitPC()) + result.InstructionData = address + + case Indirect: + // indirect addressing (without indexing) is only used for the JMP command + indirectAddress := mc.read16BitPC() + + // implement NMOS 6502 Indirect JMP bug + if indirectAddress&0x00ff == 0x00ff { + lo, err := mc.memory.Read(indirectAddress) + if err != nil { + log.Fatalln(err) + } + hi, err := mc.memory.Read(indirectAddress & 0xff00) + if err != nil { + log.Fatalln(err) + } + address = uint16(hi) << 8 + address |= uint16(lo) + + result.InstructionData = indirectAddress + result.Bug = fmt.Sprintf("Indirect JMP Bug") + + } else { + // normal, non-buggy behaviour + address = mc.read16Bit(indirectAddress) + result.InstructionData = indirectAddress + } + + case PreIndexedIndirect: + indirectAddress := mc.read8BitPC() + adder, err := generateRegister(indirectAddress, 8) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.X, false) + address = mc.read16Bit(adder.ToUint16()) + + result.InstructionData = indirectAddress + // never a page fault wth pre-index indirect addressing because the we only + // ever read from the first page - we discard any carry from the addition + // and allow the indexing to "wrap around" + + case PostIndexedIndirect: + indirectAddress := mc.read8BitPC() + indexedAddress := mc.read16Bit(uint16(indirectAddress)) + adder, err := generateRegister(indexedAddress, 16) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.Y, false) + address = adder.ToUint16() + + result.InstructionData = indirectAddress + result.PageFault = defn.PageSensitive && (address&0xFF00 != indexedAddress&0xFF00) + + case AbsoluteIndexedX: + indirectAddress := mc.read16BitPC() + adder, err := generateRegister(indirectAddress, 16) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.X, false) + address = adder.ToUint16() + + result.InstructionData = indirectAddress + result.PageFault = defn.PageSensitive && (address&0xFF00 != indirectAddress&0xFF00) + + case AbsoluteIndexedY: + indirectAddress := mc.read16BitPC() + adder, err := generateRegister(indirectAddress, 16) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.Y, false) + address = adder.ToUint16() + + result.InstructionData = indirectAddress + result.PageFault = defn.PageSensitive && (address&0xFF00 != indirectAddress&0xFF00) + + case IndexedZeroPageX: + indirectAddress := mc.read8BitPC() + adder, err := generateRegister(indirectAddress, 8) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.X, false) + address = adder.ToUint16() + + result.InstructionData = indirectAddress + + case IndexedZeroPageY: + // used exclusively for LDX ZeroPage,y + indirectAddress := mc.read8BitPC() + adder, err := generateRegister(indirectAddress, 8) + if err != nil { + log.Fatalln(err) + } + adder.Add(mc.Y, false) + address = adder.ToUint16() + + result.InstructionData = indirectAddress + + default: + log.Printf("unknown addressing mode for %s", defn.Mnemonic) + } + + // adjust number of cycles used if there has been a page fault + if result.PageFault { + result.ActualCycles++ + } + + // read value from memory using address found in AddressingMode switch above only when: + // a) addressing mode is not 'implied' or 'immediate' + // - for immediate modes, we already have the value in lieu of an address + // - for implied modes, we don't need a value + // b) instruction is 'Read' OR 'ReadWrite' + // - for write modes, we only use the address to write a value we already have + // - for flow modes, the use of the address is very specific + if !(defn.AddressingMode == Implied || defn.AddressingMode == Immediate) { + if defn.Effect == Read || defn.Effect == RMW { + value = mc.read8Bit(address) + } + } + + // actually perform instruction based on mnemonic + switch defn.Mnemonic { + case "NOP": + // does nothing + + case "CLI": + mc.Status.InterruptDisable = false + + case "SEI": + mc.Status.InterruptDisable = true + + case "CLC": + mc.Status.Carry = false + + case "SEC": + mc.Status.Carry = true + + case "CLD": + mc.Status.DecimalMode = false + + case "SED": + mc.Status.DecimalMode = true + + case "CLV": + mc.Status.Overflow = false + + case "PHA": + err = mc.memory.Write(mc.SP.ToUint16(), mc.A.ToUint8()) + if err != nil { + log.Fatalln(err) + } + mc.SP.Add(255, false) + + case "PLA": + mc.SP.Add(1, false) + value = mc.read8Bit(mc.SP.ToUint16()) + mc.A.Load(value) + + case "PHP": + err = mc.memory.Write(mc.SP.ToUint16(), mc.Status.ToUint8()) + if err != nil { + log.Fatalln(err) + } + mc.SP.Add(255, false) + + case "PLP": + mc.SP.Add(1, false) + value = mc.read8Bit(mc.SP.ToUint16()) + mc.Status.FromUint8(value) + + case "TXA": + mc.A.Load(mc.X) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "TAX": + mc.X.Load(mc.A) + mc.Status.Zero = mc.X.IsZero() + mc.Status.Sign = mc.X.IsNegative() + + case "TAY": + mc.Y.Load(mc.A) + mc.Status.Zero = mc.Y.IsZero() + mc.Status.Sign = mc.Y.IsNegative() + + case "TYA": + mc.A.Load(mc.Y) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "TSX": + mc.X.Load(mc.SP) + mc.Status.Zero = mc.X.IsZero() + mc.Status.Sign = mc.X.IsNegative() + + case "TXS": + mc.SP.Load(mc.X) + // does not affect status register + + case "EOR": + mc.A.EOR(value) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "ORA": + mc.A.ORA(value) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "AND": + mc.A.AND(value) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "LDA": + mc.A.Load(value) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "LDX": + mc.X.Load(value) + mc.Status.Zero = mc.X.IsZero() + mc.Status.Sign = mc.X.IsNegative() + + case "LDY": + mc.Y.Load(value) + mc.Status.Zero = mc.Y.IsZero() + mc.Status.Sign = mc.Y.IsNegative() + + case "STA": + err = mc.memory.Write(address, mc.A.ToUint8()) + if err != nil { + log.Fatalln(err) + } + + case "STX": + err = mc.memory.Write(address, mc.X.ToUint8()) + if err != nil { + log.Fatalln(err) + } + + case "STY": + err = mc.memory.Write(address, mc.Y.ToUint8()) + if err != nil { + log.Fatalln(err) + } + + case "INX": + mc.X.Add(1, false) + mc.Status.Zero = mc.X.IsZero() + mc.Status.Sign = mc.X.IsNegative() + + case "INY": + mc.Y.Add(1, false) + mc.Status.Zero = mc.Y.IsZero() + mc.Status.Sign = mc.Y.IsNegative() + + case "DEX": + mc.X.Add(255, false) + mc.Status.Zero = mc.X.IsZero() + mc.Status.Sign = mc.X.IsNegative() + + case "DEY": + mc.Y.Add(255, false) + mc.Status.Zero = mc.Y.IsZero() + mc.Status.Sign = mc.Y.IsNegative() + + case "ASL": + mc.Status.Carry = mc.A.ASL() + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "LSR": + mc.Status.Carry = mc.A.LSR() + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "ADC": + mc.Status.Carry, mc.Status.Overflow = mc.A.Add(value, mc.Status.Carry) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "SBC": + mc.Status.Carry, mc.Status.Overflow = mc.A.Subtract(value, mc.Status.Carry) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "ROR": + mc.Status.Carry = mc.A.ROR(mc.Status.Carry) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "ROL": + mc.Status.Carry = mc.A.ROL(mc.Status.Carry) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + + case "INC": + r, err := generateRegister(value, 8) + if err != nil { + log.Fatalln(err) + } + r.Add(1, false) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + err = mc.memory.Write(address, r.ToUint8()) + if err != nil { + log.Fatalln(err) + } + + case "DEC": + r, err := generateRegister(value, 8) + if err != nil { + log.Fatalln(err) + } + r.Add(255, false) + mc.Status.Zero = mc.A.IsZero() + mc.Status.Sign = mc.A.IsNegative() + err = mc.memory.Write(address, r.ToUint8()) + if err != nil { + log.Fatalln(err) + } + + case "CMP": + cmp, err := generateRegister(&mc.A, len(mc.A)) + if err != nil { + log.Fatalln(err) + } + mc.Status.Carry, _ = cmp.Subtract(value, true) + mc.Status.Zero = cmp.IsZero() + mc.Status.Sign = cmp.IsNegative() + + case "CPX": + cmp, err := generateRegister(&mc.X, len(mc.X)) + if err != nil { + log.Fatalln(err) + } + mc.Status.Carry, _ = cmp.Subtract(value, true) + mc.Status.Zero = cmp.IsZero() + mc.Status.Sign = cmp.IsNegative() + + case "CPY": + cmp, err := generateRegister(&mc.Y, len(mc.Y)) + if err != nil { + log.Fatalln(err) + } + mc.Status.Carry, _ = cmp.Subtract(value, true) + mc.Status.Zero = cmp.IsZero() + mc.Status.Sign = cmp.IsNegative() + + case "BIT": + cmp, err := generateRegister(&mc.A, len(mc.A)) + if err != nil { + log.Fatalln(err) + } + cmp.AND(value) + mc.Status.Zero = cmp.IsZero() + mc.Status.Sign = cmp.IsNegative() + mc.Status.Overflow = bool(cmp[1]) + + case "JMP": + mc.PC.Load(address) + + case "BCC": + if mc.Status.Carry == false { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BCS": + if mc.Status.Carry == true { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BEQ": + if mc.Status.Zero == true { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BMI": + if mc.Status.Sign == true { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BNE": + if mc.Status.Zero == false { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BPL": + if mc.Status.Sign == false { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BVC": + if mc.Status.Overflow == false { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "BVS": + if mc.Status.Overflow == true { + mc.PC.Add(address, false) + result.ActualCycles++ + } + + case "JSR": + rtsAddress, err := generateRegister(&mc.PC, len(mc.PC)) + if err != nil { + log.Fatalln(err) + } + rtsAddress.Add(65535, false) + v := rtsAddress.ToUint16() + err = mc.memory.Write(mc.SP.ToUint16(), uint8((v&0xFF00)>>8)) + if err != nil { + log.Fatalln(err) + } + mc.SP.Add(255, false) + err = mc.memory.Write(mc.SP.ToUint16(), uint8(v&0x00FF)) + if err != nil { + log.Fatalln(err) + } + mc.SP.Add(255, false) + mc.PC.Load(address) + + case "RTS": + mc.SP.Add(1, false) + rtsAddress := mc.read16Bit(mc.SP.ToUint16()) + mc.SP.Add(1, false) + mc.PC.Load(rtsAddress) + mc.PC.Add(1, false) + + case "BRK": + // TODO: implement BRK + + case "RTI": + // TODO: implement RTI + + default: + // this should never, ever happen + log.Fatalf("WTF! unknown mnemonic! (%s)", defn.Mnemonic) + } + + return result, nil +} diff --git a/hardware/cpu/cpu_test.go b/hardware/cpu/cpu_test.go new file mode 100644 index 00000000..9d46cd28 --- /dev/null +++ b/hardware/cpu/cpu_test.go @@ -0,0 +1,450 @@ +package cpu_test + +import ( + "fmt" + "headless/hardware/cpu" + "testing" +) + +func step(t *testing.T, mc *cpu.CPU) *cpu.StepResult { + sr, err := mc.Step() + if err != nil { + t.Errorf("error during CPU step (%v)\n", err) + return nil + } + + err = sr.IsValid() + if err != nil { + t.Errorf("error during CPU step (%v)\n", err) + return nil + } else { + fmt.Println(sr) + } + + return sr +} + +func testStatusInstructions(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // SEC; CLC; CLI; SEI; SED; CLD; CLV + origin = mem.putInstructions(origin, 0x38, 0x18, 0x58, 0x78, 0xf8, 0xd8, 0xb8) + step(t, mc) // SEC + assert(t, mc.Status, "sv-BdIZC") + step(t, mc) // CLC + assert(t, mc.Status, "sv-BdIZc") + step(t, mc) // CLI + assert(t, mc.Status, "sv-BdiZc") + step(t, mc) // SEI + assert(t, mc.Status, "sv-BdIZc") + step(t, mc) // SED + assert(t, mc.Status, "sv-BDIZc") + step(t, mc) // CLD + assert(t, mc.Status, "sv-BdIZc") + step(t, mc) // CLV + assert(t, mc.Status, "sv-BdIZc") + + // PHP; PLP + origin = mem.putInstructions(origin, 0x08, 0x28) + step(t, mc) // PHP + assert(t, mc.Status, "sv-BdIZc") + assert(t, mc.SP, 254) + + // mangle status register + mc.Status.Sign = true + mc.Status.Overflow = true + mc.Status.Break = false + + // restore status register + step(t, mc) // PLP + assert(t, mc.SP, 255) + assert(t, mc.Status, "sv-BdIZc") +} + +func testRegsiterArithmetic(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // LDA immediate; ADC immediate + origin = mem.putInstructions(origin, 0xa9, 1, 0x69, 10) + step(t, mc) // LDA #1 + step(t, mc) // ADC #1 + assert(t, mc.A, 11) + + // SEC; SBC immediate + origin = mem.putInstructions(origin, 0x38, 0xe9, 8) + step(t, mc) // SEC + step(t, mc) // SBC #8 + assert(t, mc.A, 3) +} + +func testRegsiterBitwiseInstructions(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // ORA immediate; EOR immediate; AND immediate + origin = mem.putInstructions(origin, 0x09, 0xff, 0x49, 0xf0, 0x29, 0x01) + assert(t, mc.A, 0) + step(t, mc) // ORA #$FF + assert(t, mc.A, 255) + step(t, mc) // EOR #$F0 + assert(t, mc.A, 15) + step(t, mc) // AND #$01 + assert(t, mc.A, 1) + + // ASL implied; LSR implied; LSR implied + origin = mem.putInstructions(origin, 0x0a, 0x4a, 0x4a) + step(t, mc) // ASL + assert(t, mc.A, 2) + assert(t, mc.Status, "sv-BdIzc") + step(t, mc) // LSR + assert(t, mc.A, 1) + assert(t, mc.Status, "sv-BdIzc") + step(t, mc) // LSR + assert(t, mc.A, 0) + assert(t, mc.Status, "sv-BdIZC") + + // ROL implied; ROR implied; ROR implied; ROR implied + origin = mem.putInstructions(origin, 0x2a, 0x6a, 0x6a, 0x6a) + step(t, mc) // ROL + assert(t, mc.A, 1) + assert(t, mc.Status, "sv-BdIzc") + step(t, mc) // ROR + assert(t, mc.A, 0) + assert(t, mc.Status, "sv-BdIZC") + step(t, mc) // ROR + assert(t, mc.A, 128) + assert(t, mc.Status, "Sv-BdIzc") + step(t, mc) // ROR + assert(t, mc.A, 64) + assert(t, mc.Status, "sv-BdIzc") +} + +func testImmediateImplied(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // LDX immediate; INX; DEX + origin = mem.putInstructions(origin, 0xa2, 5, 0xe8, 0xca) + step(t, mc) // LDX #5 + assert(t, mc.X, 5) + step(t, mc) // INX + assert(t, mc.X, 6) + step(t, mc) // DEX + assert(t, mc.X, 5) + assert(t, mc.Status, "sv-BdIzc") + + // PHA; LDA immediate; PLA + origin = mem.putInstructions(origin, 0xa9, 5, 0x48, 0xa9, 0, 0x68) + step(t, mc) // LDA #5 + step(t, mc) // PHA + assert(t, mc.SP, 254) + step(t, mc) // LDA #0 + assert(t, mc.A, 0) + assert(t, mc.Status.Zero, true) + step(t, mc) // PLA + assert(t, mc.A, 5) + + // TAX; TAY; LDX immediate; TXA; LDY immediate; TYA; INY; DEY + origin = mem.putInstructions(origin, 0xaa, 0xa8, 0xa2, 1, 0x8a, 0xa0, 2, 0x98, 0xc8, 0x88) + step(t, mc) // TAX + assert(t, mc.X, 5) + step(t, mc) // TAY + assert(t, mc.Y, 5) + step(t, mc) // LDX #1 + step(t, mc) // TXA + assert(t, mc.A, 1) + step(t, mc) // LDY #2 + step(t, mc) // TYA + assert(t, mc.A, 2) + step(t, mc) // INY + assert(t, mc.Y, 3) + step(t, mc) // DEY + assert(t, mc.Y, 2) + + // TSX; LDX immediate; TXS + origin = mem.putInstructions(origin, 0xba, 0xa2, 100, 0x9a) + step(t, mc) // TSX + assert(t, mc.X, 255) + step(t, mc) // LDX #100 + step(t, mc) // TXS + assert(t, mc.SP, 100) +} + +func testOtherAddressingModes(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + mem.putInstructions(0x0100, 123, 43) + mem.putInstructions(0x01a2, 47) + + // LDA zero page + origin = mem.putInstructions(origin, 0xa5, 0x00) + step(t, mc) // LDA $00 + assert(t, mc.A, 0xa5) + + // LDX immediate; LDA zero page,X + origin = mem.putInstructions(origin, 0xa2, 1, 0xb5, 0x01) + step(t, mc) // LDX #1 + step(t, mc) // LDA 01,X + assert(t, mc.A, 0xa2) + + // LDY immediate; LDX zero page,Y + origin = mem.putInstructions(origin, 0xa0, 3, 0xb6, 0x01) + step(t, mc) // LDX #3 + step(t, mc) // LDA 01,Y + assert(t, mc.A, 0xa2) + + // LDA absolute + origin = mem.putInstructions(origin, 0xad, 0x00, 0x01) + step(t, mc) // LDA $0100 + assert(t, mc.A, 123) + + // LDX immediate; LDA absolute,X + origin = mem.putInstructions(origin, 0xa2, 1, 0xbd, 0x01, 0x00) + step(t, mc) // LDX #1 + assert(t, mc.X, 1) + step(t, mc) // LDA $0001,X + assert(t, mc.A, 0xa2) + + // LDY immediate; LDA absolute,Y + origin = mem.putInstructions(origin, 0xa0, 1, 0xb9, 0x01, 0x00) + step(t, mc) // LDY #1 + assert(t, mc.X, 1) + step(t, mc) // LDA $0001,Y + assert(t, mc.A, 0xa2) + + // pre-indexed indirect + // X = 1 + // INX; LDA (Indirect, X) + origin = mem.putInstructions(origin, 0xe8, 0xa1, 0x0b) + step(t, mc) // INX (x equals 2) + step(t, mc) // LDA (0x0b,X) + assert(t, mc.A, 47) + + // post-indexed indirect + // Y = 1 + // LDA (Indirect), Y + origin = mem.putInstructions(origin, 0xb1, 0x0b) + step(t, mc) // LDA (0x0b),Y + assert(t, mc.A, 43) + + // pre-indexed indirect (with wraparound) + // X = 1 + // INX; LDA (Indirect, X) + origin = mem.putInstructions(origin, 0xe8, 0xa1, 0xff) + step(t, mc) // INX (x equals 2) + step(t, mc) // LDA (0xff,X) + assert(t, mc.A, 47) + + // post-indexed indirect (with page-fault) + // Y = 1 + // INY; INY; LDA (Indirect), Y + mem.putInstructions(0xc0, 0xfd, 0x00) + origin = mem.putInstructions(origin, 0xc8, 0xc8, 0xb1, 0xc0) + step(t, mc) // INY (y = 2) + step(t, mc) // INY (y = 2) + sr := step(t, mc) // LDA (0x0b),Y + assert(t, mc.A, 123) + assert(t, sr.PageFault, true) +} + +func testStorageInstructions(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // LDA immediate; STA absolute + origin = mem.putInstructions(origin, 0xa9, 0x54, 0x8d, 0x00, 0x01) + step(t, mc) // LDA 0x54 + step(t, mc) // STA 0x0100 + mem.assert(t, 0x0100, 0x54) + + // LDX immediate; STX absolute + origin = mem.putInstructions(origin, 0xa2, 0x63, 0x8e, 0x01, 0x01) + step(t, mc) // LDX 0x63 + step(t, mc) // STX 0x0101 + mem.assert(t, 0x0101, 0x63) + + // LDY immediate; STY absolute + origin = mem.putInstructions(origin, 0xa0, 0x72, 0x8c, 0x02, 0x01) + step(t, mc) // LDY 0x72 + step(t, mc) // STY 0x0102 + mem.assert(t, 0x0101, 0x63) + + // INC zero page + origin = mem.putInstructions(origin, 0xe6, 0x01) + step(t, mc) // INC $01 + mem.assert(t, 0x01, 0x55) + + // DEC absolute + origin = mem.putInstructions(origin, 0xce, 0x00, 0x01) + step(t, mc) // DEC 0x0100 + mem.assert(t, 0x0100, 0x53) +} + +func testBranching(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0x10, 0x10) + step(t, mc) // BPL $10 + assert(t, mc.PC, 0x12) + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0x50, 0x10) + step(t, mc) // BVC $10 + assert(t, mc.PC, 0x12) + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0x90, 0x10) + step(t, mc) // BCC $10 + assert(t, mc.PC, 0x12) + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0x38, 0xb0, 0x10) + step(t, mc) // SEC + step(t, mc) // BCS $10 + assert(t, mc.PC, 0x13) + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0xe8, 0xd0, 0x10) + step(t, mc) // INX + step(t, mc) // BNE $10 + assert(t, mc.PC, 0x13) + + origin = mem.clear() + mc.Reset() + origin = mem.putInstructions(origin, 0xca, 0x30, 0x10) + step(t, mc) // DEX + step(t, mc) // BMI $10 + assert(t, mc.PC, 0x13) + + origin = mem.putInstructions(0x13, 0xe8, 0xf0, 0x10) + step(t, mc) // INX + step(t, mc) // BEQ $10 + assert(t, mc.PC, 0x26) + + origin = mem.clear() + mc.Reset() + // fudging overflow test + mc.Status.Overflow = true + origin = mem.putInstructions(origin, 0x70, 0x10) + step(t, mc) // BVS $10 + assert(t, mc.PC, 0x12) +} + +func testJumps(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // JMP absolute + origin = mem.putInstructions(origin, 0x4c, 0x00, 0x01) + step(t, mc) // JMP $100 + assert(t, mc.PC, 0x0100) + + // JMP indirect + origin = mem.clear() + mc.Reset() + + mem.putInstructions(0x0050, 0x49, 0x01) + origin = mem.putInstructions(origin, 0x6c, 0x50, 0x00) + step(t, mc) // JMP ($50) + assert(t, mc.PC, 0x0149) + + // JMP indirect (bug) + origin = mem.clear() + mc.Reset() + + mem.putInstructions(0x01FF, 0x03) + mem.putInstructions(0x0100, 0x00) + origin = mem.putInstructions(origin, 0x6c, 0xFF, 0x01) + step(t, mc) // JMP ($0x01FF) + assert(t, mc.PC, 0x0003) +} + +func testComparisonInstructions(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // CMP immediate (equality) + origin = mem.putInstructions(origin, 0xc9, 0x00) + step(t, mc) // CMP $00 + assert(t, mc.Status, "sv-BdIZc") + + // LDA immediate; CMP immediate + origin = mem.putInstructions(origin, 0xa9, 0xf6, 0xc9, 0x18) + step(t, mc) // LDA $F6 + step(t, mc) // CMP $10 + assert(t, mc.Status, "Sv-BdIzC") + + // LDX immediate; CMP immediate + origin = mem.putInstructions(origin, 0xa2, 0xf6, 0xe0, 0x18) + step(t, mc) // LDX $F6 + step(t, mc) // CMP $10 + assert(t, mc.Status, "Sv-BdIzC") + + // LDY immediate; CMP immediate + origin = mem.putInstructions(origin, 0xa0, 0xf6, 0xc0, 0x18) + step(t, mc) // LDY $F6 + step(t, mc) // CMP $10 + assert(t, mc.Status, "Sv-BdIzC") + + // LDA immediate; CMP immediate + origin = mem.putInstructions(origin, 0xa9, 0x18, 0xc9, 0xf6) + step(t, mc) // LDA $F6 + step(t, mc) // CMP $10 + assert(t, mc.Status, "sv-BdIzc") + + // BIT zero page + origin = mem.putInstructions(origin, 0x24, 0x01) + step(t, mc) // BIT $01 + assert(t, mc.Status, "sv-BdIZc") + + // BIT zero page + origin = mem.putInstructions(origin, 0x24, 0x0e) + step(t, mc) // BIT $01 + assert(t, mc.Status, "sv-BdIzc") +} + +func testSubroutineInstructions(t *testing.T, mc *cpu.CPU, mem *MockMem) { + origin := mem.clear() + mc.Reset() + + // JSR absolute + origin = mem.putInstructions(origin, 0x20, 0x00, 0x01) + step(t, mc) // JSR $0100 + assert(t, mc.PC, 0x0100) + mem.assert(t, 255, 0x00) + mem.assert(t, 254, 0x02) + assert(t, mc.SP, 253) + + origin = mem.putInstructions(0x100, 0x60) + step(t, mc) // RTS + assert(t, mc.PC, 0x0003) + mem.assert(t, 255, 0x00) + mem.assert(t, 254, 0x02) + assert(t, mc.SP, 255) +} + +func TestCPU(t *testing.T) { + mem := NewMockMem() + mc := cpu.NewCPU(mem) + + testStatusInstructions(t, mc, mem) + testRegsiterArithmetic(t, mc, mem) + testRegsiterBitwiseInstructions(t, mc, mem) + testImmediateImplied(t, mc, mem) + testOtherAddressingModes(t, mc, mem) + testStorageInstructions(t, mc, mem) + testBranching(t, mc, mem) + testJumps(t, mc, mem) + testComparisonInstructions(t, mc, mem) + testSubroutineInstructions(t, mc, mem) +} diff --git a/hardware/cpu/definitions.csv b/hardware/cpu/definitions.csv new file mode 100644 index 00000000..0a999ad8 --- /dev/null +++ b/hardware/cpu/definitions.csv @@ -0,0 +1,234 @@ +# instructions are defined with the following fields: +# +# opcode, mnemonic, cycles, addressing mode, page sensitivity, [effect category] +# +# +# effect category can be one of three types (READ is the default if no effect category is given) +# +# 1. READ (instruction only reads from memory - or not at all in the case of IMPLIED instructions +# 2. WRITE (instruction changes memory) +# 3. RMW (instruction reads, modifies and writes to memory) +# 4. FLOW (instruction explicitely affects the program counter) +# 5. SUB-ROUTINE (like FLOW but also writes to the stack) +# +# in the 6502 all instructions are considered to read from memory, even register only +# instructions (the IMPLIED addressing mode). in the hardware, this meant that the chip could forego +# a "read" pin - the electrical connection that switched on access to memory - and thereby save +# on manufacturing costs. +# +# only some instructions however, ever *write* to memory. in the 6502 this is accomplished with a +# "read/write" pin - an electrical connection to memory that causes bits to be written +# as well as read. in our emulation, we mark the instructions that write to memory by specifying +# the WRITE effect category +# +# a small class of instructions read AND write to memory (using the same address), these +# are the RMW class of instructions. +# +# +# note that the addressing mode /implies/ the number of bytes each instruction requires: +# (including the 1 byte required for the opcode) +# +# IMPLIED = 1 +# IMMEDIATE = 2 +# ZERO PAGE = 2 +# all others = 3 +# +# TODO: maybe the number of cycles can be inferred in a similar way + +# no operation +0xea, NOP, 2, IMPLIED, False +0x04, NOP, 3, ZERO_PAGE, False + +# status flags +0x58, CLI, 2, IMPLIED, False +0x78, SEI, 2, IMPLIED, False +0x18, CLC, 2, IMPLIED, False +0x38, SEC, 2, IMPLIED, False +0xd8, CLD, 2, IMPLIED, False +0xf8, SED, 2, IMPLIED, False +0xb8, CLV, 2, IMPLIED, False + +# stack +0x48, PHA, 2, IMPLIED, False, WRITE +0x68, PLA, 3, IMPLIED, False +0x08, PHP, 2, IMPLIED, False, WRITE +0x28, PLP, 3, IMPLIED, False + +# register transfer +0x8a, TXA, 2, IMPLIED, False +0xaa, TAX, 2, IMPLIED, False +0xa8, TAY, 2, IMPLIED, False +0x98, TYA, 2, IMPLIED, False +0xba, TSX, 2, IMPLIED, False +0x9a, TXS, 2, IMPLIED, False + +# bitwise operations +0x49, EOR, 2, IMMEDIATE, False +0x45, EOR, 3, ZERO_PAGE, False +0x55, EOR, 4, INDEXED_ZERO_PAGE_X, False +0x4d, EOR, 4, ABSOLUTE, False +0x5d, EOR, 4, ABSOLUTE_INDEXED_X, True +0x59, EOR, 4, ABSOLUTE_INDEXED_Y, True +0x41, EOR, 6, PRE_INDEX_INDIRECT, False +0x51, EOR, 5, POST_INDEX_INDIRECT, True + +0x09, ORA, 2, IMMEDIATE, False +0x05, ORA, 3, ZERO_PAGE, False +0x15, ORA, 4, INDEXED_ZERO_PAGE_X, False +0x0d, ORA, 4, ABSOLUTE, False +0x1d, ORA, 4, ABSOLUTE_INDEXED_X, True +0x10, ORA, 4, ABSOLUTE_INDEXED_Y, True +0x01, ORA, 6, PRE_INDEX_INDIRECT, False +0x11, ORA, 5, POST_INDEX_INDIRECT, True + +0x29, AND, 2, IMMEDIATE, False +0x25, AND, 3, ZERO_PAGE, False +0x35, AND, 4, INDEXED_ZERO_PAGE_X, False +0x2d, AND, 4, ABSOLUTE, False +0x3d, AND, 4, ABSOLUTE_INDEXED_X, True +0x39, AND, 4, ABSOLUTE_INDEXED_Y, True +0x21, AND, 6, PRE_INDEX_INDIRECT, False +0x31, AND, 5, POST_INDEX_INDIRECT, True + +# load register +0xa9, LDA, 2, IMMEDIATE, False +0xa5, LDA, 3, ZERO_PAGE, False +0xb5, LDA, 4, INDEXED_ZERO_PAGE_X, False +0xad, LDA, 4, ABSOLUTE, False +0xbd, LDA, 4, ABSOLUTE_INDEXED_X, True +0xb9, LDA, 4, ABSOLUTE_INDEXED_Y, True +0xa1, LDA, 6, PRE_INDEX_INDIRECT, False +0xb1, LDA, 5, POST_INDEX_INDIRECT, True + +0xa2, LDX, 2, IMMEDIATE, False +0xa6, LDX, 3, ZERO_PAGE, False +0xb6, LDX, 4, INDEXED_ZERO_PAGE_Y, False +0xae, LDX, 4, ABSOLUTE, False +0xbe, LDX, 4, ABSOLUTE_INDEXED_Y, True + +0xa0, LDY, 2, IMMEDIATE, False +0xa4, LDY, 3, ZERO_PAGE, False +0xb4, LDY, 4, INDEXED_ZERO_PAGE_X, False +0xac, LDY, 4, ABSOLUTE, False +0xbc, LDY, 4, ABSOLUTE_INDEXED_X, True + +# register operations +0xe8, INX, 2, IMPLIED, False +0xc8, INY, 2, IMPLIED, False +0xca, DEX, 2, IMPLIED, False +0x88, DEY, 2, IMPLIED, False + +0x0a, ASL, 2, IMPLIED, False +0x06, ASL, 5, ZERO_PAGE, False +0x16, ASL, 6, INDEXED_ZERO_PAGE_X, False +0x0e, ASL, 6, ABSOLUTE, False +0x1e, ASL, 7, ABSOLUTE_INDEXED_X, False + +0x4a, LSR, 2, IMPLIED, False +0x46, LSR, 5, ZERO_PAGE, False +0x56, LSR, 6, INDEXED_ZERO_PAGE_X, False +0x4e, LSR, 6, ABSOLUTE, False +0x5e, LSR, 7, ABSOLUTE_INDEXED_X, False + +0x69, ADC, 2, IMMEDIATE, False +0x65, ADC, 3, ZERO_PAGE, False +0x75, ADC, 4, INDEXED_ZERO_PAGE_X, False +0x6d, ADC, 4, ABSOLUTE, False +0x7d, ADC, 4, ABSOLUTE_INDEXED_X, True +0x79, ADC, 4, ABSOLUTE_INDEXED_Y, True +0x61, ADC, 6, PRE_INDEX_INDIRECT, False +0x71, ADC, 5, POST_INDEX_INDIRECT, True + +0xe9, SBC, 2, IMMEDIATE, False +0xe5, SBC, 3, ZERO_PAGE, False +0xf5, SBC, 4, INDEXED_ZERO_PAGE_X, False +0xed, SBC, 4, ABSOLUTE, False +0xfd, SBC, 4, ABSOLUTE_INDEXED_X, True +0xf9, SBC, 4, ABSOLUTE_INDEXED_Y, True +0xe1, SBC, 6, PRE_INDEX_INDIRECT, False +0xf1, SBC, 5, POST_INDEX_INDIRECT, True + +0x6a, ROR, 2, IMPLIED, False +0x66, ROR, 5, ZERO_PAGE, False +0x76, ROR, 6, INDEXED_ZERO_PAGE_X, False +0x6e, ROR, 6, ABSOLUTE, False +0x7e, ROR, 7, ABSOLUTE_INDEXED_X, False + +0x2a, ROL, 2, IMPLIED, False +0x26, ROL, 5, ZERO_PAGE, False +0x36, ROL, 6, INDEXED_ZERO_PAGE_X, False +0x2e, ROL, 6, ABSOLUTE, False +0x3e, ROL, 7, ABSOLUTE_INDEXED_X, False + +# compare instructions +0xc9, CMP, 3, IMMEDIATE, False +0xc5, CMP, 3, ZERO_PAGE, False +0xd5, CMP, 4, INDEXED_ZERO_PAGE_X, False +0xcd, CMP, 4, ABSOLUTE, False +0xdd, CMP, 4, ABSOLUTE_INDEXED_X, True +0xd9, CMP, 4, ABSOLUTE_INDEXED_Y, True +0xc1, CMP, 6, PRE_INDEX_INDIRECT, False +0xd1, CMP, 5, POST_INDEX_INDIRECT, True + +0xe0, CPX, 2, IMMEDIATE, False +0xe4, CPX, 3, ZERO_PAGE, False +0xec, CPX, 4, ABSOLUTE, False + +0xc0, CPY, 2, IMMEDIATE, False +0xc4, CPY, 3, ZERO_PAGE, False +0xcc, CPY, 4, ABSOLUTE, False + +0x24, BIT, 3, ZERO_PAGE, False +0x2c, BIT, 4, ABSOLUTE, False + +# store register +0x85, STA, 3, ZERO_PAGE, False, WRITE +0x95, STA, 4, INDEXED_ZERO_PAGE_X, False, WRITE +0x8d, STA, 4, ABSOLUTE, False, WRITE +0x9d, STA, 5, ABSOLUTE_INDEXED_X, False, WRITE +0x99, STA, 5, ABSOLUTE_INDEXED_Y, False, WRITE +0x81, STA, 6, PRE_INDEX_INDIRECT, False, WRITE +0x91, STA, 6, POST_INDEX_INDIRECT, False, WRITE + +0x86, STX, 3, ZERO_PAGE, False, WRITE +0x96, STX, 4, INDEXED_ZERO_PAGE_Y, False, WRITE +0x8e, STX, 4, ABSOLUTE, False, WRITE + +0x84, STY, 3, ZERO_PAGE, False, WRITE +0x94, STY, 4, INDEXED_ZERO_PAGE_X, False, WRITE +0x8c, STY, 4, ABSOLUTE, False, WRITE + +# memory instructions +0xe6, INC, 5, ZERO_PAGE, False, RMW +0xf6, INC, 6, INDEXED_ZERO_PAGE_X, False, RMW +0xee, INC, 6, ABSOLUTE, False, RMW +0xfe, INC, 7, ABSOLUTE_INDEXED_X, False, RMW + +0xc6, DEC, 5, ZERO_PAGE, False, RMW +0xd6, DEC, 6, INDEXED_ZERO_PAGE_X, False, RMW +0xce, DEC, 6, ABSOLUTE, False, RMW +0xde, DEC, 7, ABSOLUTE_INDEXED_X, False, RMW + +# flow control +0x4c, JMP, 3, ABSOLUTE, False, FLOW +0x6c, JMP, 5, INDIRECT, False, FLOW + +# flow control (branch instructions) -- machine cycles count column is the fail count +# ie. when the branch condition isfalse and the PC allowed to advance as normal. if the +# branch succeeds then the PC is adjusted, taking an additional cycle. +0x90, BCC, 2, RELATIVE, False, FLOW +0xb0, BCS, 2, RELATIVE, False, FLOW +0xf0, BEQ, 2, RELATIVE, False, FLOW +0x30, BMI, 2, RELATIVE, False, FLOW +0xd0, BNE, 2, RELATIVE, False, FLOW +0x10, BPL, 2, RELATIVE, False, FLOW +0x50, BVC, 2, RELATIVE, False, FLOW +0x70, BVS, 2, RELATIVE, False, FLOW + +0x20, JSR, 2, ABSOLUTE, False, SUB-ROUTINE +0x60, RTS, 3, IMPLIED, False, SUB-ROUTINE + +# interrupts +0x00, BRK, 7, IMPLIED, False, WRITE +0x40, RTI, 6, IMPLIED, False + diff --git a/hardware/cpu/definitions.go b/hardware/cpu/definitions.go new file mode 100644 index 00000000..b6bf86f9 --- /dev/null +++ b/hardware/cpu/definitions.go @@ -0,0 +1,202 @@ +package cpu + +import ( + "encoding/csv" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +const definitionsCSVFile = "./definitions.csv" + +// AddressingMode describes the method by which an instruction receives data +// on which to operate +type AddressingMode int + +// enumeration of supported addressing modes +const ( + Implied AddressingMode = iota + Immediate + Relative // relative addressing is used for branch instructions + + Absolute // sometimes called absolute addressing + ZeroPage + Indirect // indirect addressing (with no indexing) is only for JMP instructions + + PreIndexedIndirect // uses X register + PostIndexedIndirect // uses Y register + AbsoluteIndexedX + AbsoluteIndexedY + IndexedZeroPageX + IndexedZeroPageY // only used for LDX +) + +// EffectCategory - categorises an instruction by the effect it has +type EffectCategory int + +// enumeration of instruction effect categories +const ( + Read EffectCategory = iota + Write + RMW + Flow + Subroutine +) + +// InstructionDefinition type is the property list for each instruction +type InstructionDefinition struct { + ObjectCode uint8 + Mnemonic string + Bytes int + Cycles int + AddressingMode AddressingMode + PageSensitive bool + Effect EffectCategory +} + +type definitionsTable map[uint8]InstructionDefinition + +func getInstructionDefinitions() (definitionsTable, error) { + df, err := os.Open(definitionsCSVFile) + if err != nil { + return nil, fmt.Errorf("error opening instruction definitions (%s)", err) + } + defer func() { + _ = df.Close() + }() + + // treat the file as a CSV file + csvr := csv.NewReader(df) + csvr.Comment = rune('#') + csvr.TrimLeadingSpace = true + csvr.ReuseRecord = true + + // csv file can have a variable number of fields per record + csvr.FieldsPerRecord = -1 + + // create new definitions table + definitions := make(definitionsTable) + + for { + rec, err := csvr.Read() + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + + // check for valid record length + if !(len(rec) == 5 || len(rec) == 6) { + return nil, fmt.Errorf("wrong number of fields in instruction definition (%s)", rec) + } + + newDef := InstructionDefinition{} + + // parse object code -- we'll use this for the hash key too + objectCode := rec[0] + if objectCode[:2] == "0x" { + objectCode = objectCode[2:] + } + objectCode = strings.ToUpper(objectCode) + + // store the decimal number in the hash table + n, err := strconv.ParseInt(objectCode, 16, 16) + if err != nil { + return nil, fmt.Errorf("invalid object code (0x%s)", objectCode) + } + newDef.ObjectCode = uint8(n) + + // instruction mnemonic + newDef.Mnemonic = rec[1] + + // cycle count + newDef.Cycles, err = strconv.Atoi(rec[2]) + if err != nil { + return nil, fmt.Errorf("invalid cycle count for 0x%s (%s)", objectCode, rec[2]) + } + + // addressing Mode - also taking the opportunity to record the number of bytes used + // by the instruction - inferred from the addressing mode + am := strings.ToUpper(rec[3]) + switch am { + default: + return nil, fmt.Errorf("invalid addressing mode for 0x%s (%s)", objectCode, rec[3]) + case "IMPLIED": + newDef.AddressingMode = Implied + newDef.Bytes = 1 + case "IMMEDIATE": + newDef.AddressingMode = Immediate + newDef.Bytes = 2 + case "RELATIVE": + newDef.AddressingMode = Relative + newDef.Bytes = 2 + case "ABSOLUTE": + newDef.AddressingMode = Absolute + newDef.Bytes = 3 + case "ZERO_PAGE": + newDef.AddressingMode = ZeroPage + newDef.Bytes = 2 + case "INDIRECT": + newDef.AddressingMode = Indirect + newDef.Bytes = 3 + case "PRE_INDEX_INDIRECT": + newDef.AddressingMode = PreIndexedIndirect + newDef.Bytes = 2 + case "POST_INDEX_INDIRECT": + newDef.AddressingMode = PostIndexedIndirect + newDef.Bytes = 2 + case "ABSOLUTE_INDEXED_X": + newDef.AddressingMode = AbsoluteIndexedX + newDef.Bytes = 3 + case "ABSOLUTE_INDEXED_Y": + newDef.AddressingMode = AbsoluteIndexedY + newDef.Bytes = 3 + case "INDEXED_ZERO_PAGE_X": + newDef.AddressingMode = IndexedZeroPageX + newDef.Bytes = 2 + case "INDEXED_ZERO_PAGE_Y": + newDef.AddressingMode = IndexedZeroPageY + newDef.Bytes = 2 + } + + // page sensitive + ps := strings.ToUpper(rec[4]) + switch ps { + default: + return nil, fmt.Errorf("invalid page sensitivity switch for 0x%s (%s)", objectCode, rec[4]) + case "TRUE": + newDef.PageSensitive = true + case "FALSE": + newDef.PageSensitive = false + } + + // effect category + if len(rec) == 5 { + // default category + newDef.Effect = Read + } else { + switch rec[5] { + default: + return nil, fmt.Errorf("unknown category for 0x%s (%s)", objectCode, rec[5]) + case "READ": + newDef.Effect = Read + case "WRITE": + newDef.Effect = Write + case "RMW": + newDef.Effect = RMW + case "FLOW": + newDef.Effect = Flow + case "SUB-ROUTINE": + newDef.Effect = Subroutine + } + } + + // insert new definition into the table + definitions[newDef.ObjectCode] = newDef + } + + return definitions, nil +} diff --git a/hardware/cpu/helpers_test.go b/hardware/cpu/helpers_test.go new file mode 100644 index 00000000..4101e23e --- /dev/null +++ b/hardware/cpu/helpers_test.go @@ -0,0 +1,108 @@ +package cpu_test + +// helpers_test.go contains the all the support code required for the cpu_test package +// it includes: +// +// o assert - used to test for equality between values +// +// o MockMem - a simple memory implementation satisfying the memory.Memory interface +// - includes putInstructions(), a variadic function to place a sequence of bytes +// into memory +// - a clear method and and an assert method + +import ( + "fmt" + "headless/hardware/cpu" + "testing" +) + +func assert(t *testing.T, r, x interface{}) { + switch r := r.(type) { + case cpu.StatusRegister: + if fmt.Sprintf("%s", r) != x.(string) { + t.Errorf("assert StatusRegister failed (%s - wanted %s)", r, x.(string)) + } + case cpu.Register: + switch x := x.(type) { + case int: + if r.ToUint16() != uint16(x) { + t.Errorf("assert Register failed (%d - wanted %d", r.ToUint16(), x) + } + case string: + if r.ToBits() != x { + t.Errorf("assert Register failed (%s - wanted %s", r.ToBits(), x) + } + } + case bool: + if r != x.(bool) { + t.Errorf("assert Bool failed (%v - wanted %v", r, x.(bool)) + } + case int: + if r != x.(int) { + t.Errorf("assert Int failed (%d - wanted %d)", r, x.(int)) + } + } +} + +type MockMem struct { + data []uint8 +} + +func (mem *MockMem) String() string { + s := "0000 " + i := 0 + j := 16 + for _, d := range mem.data { + s = fmt.Sprintf("%s%02x ", s, d) + i++ + if i == 16 { + s = fmt.Sprintf("%s\n%04d ", s, j) + i = 0 + j += 16 + } + } + return s +} + +func NewMockMem() *MockMem { + mock := new(MockMem) + mock.data = make([]uint8, 512) + return mock +} + +func (mem *MockMem) Read(address uint16) (uint8, error) { + if int(address) > len(mem.data) { + return 0, fmt.Errorf("address out of range (%d)", address) + } + return mem.data[address], nil +} + +func (mem *MockMem) Write(address uint16, data uint8) error { + if int(address) > len(mem.data) { + return fmt.Errorf("address out of range (%d)", address) + } + mem.data[address] = data + return nil +} + +func (mem *MockMem) clear() uint16 { + fmt.Println("\nclearing memory\n---------------") + for i := 0; i < len(mem.data); i++ { + mem.data[i] = 0x00 + } + return 0 +} + +func (mem *MockMem) putInstructions(origin uint16, bytes ...uint8) uint16 { + for i, b := range bytes { + mem.data[i+int(origin)] = b + } + return origin + uint16(len(bytes)) +} + +func (mem *MockMem) assert(t *testing.T, address uint16, value uint8) { + t.Helper() + if mem.data[address] != value { + t.Errorf("assertMockMem failed (%v - wanted %v at address %04x", mem.data[address], value, address) + } +} diff --git a/hardware/cpu/registers.go b/hardware/cpu/registers.go new file mode 100644 index 00000000..c3e26c5c --- /dev/null +++ b/hardware/cpu/registers.go @@ -0,0 +1,193 @@ +package cpu + +import ( + "fmt" + "log" +) + +// Register is the bit representation of the all CPU registers (with the exception of +// the status register. +type Register []bit + +// note that in the 6502, all arithmetic and bitwise operations are carried out on 8 bit +// registers, with a special increment for the PC register. for this emulation, those +// operations can be performed on 16 bit registers too, for convenience. principally, this +// means the PC register, but we also perform 16 bit addition on temporary registers when +// indexing. in the latter case, care must be taken to detect 8 bit overflow, or page-faults +// as we call them, manually. +// +// pageFault = indexedAddress & 0xFF00 != preIndexedAddress & 0xFF00 + +func (r Register) String() string { + return fmt.Sprintf("%s (%d)", r.ToBits(), r.ToUint()) +} + +// Load value into register +func (r Register) Load(v interface{}) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + copy(r, b) +} + +// Add value to register. Returns carry and overflow states +func (r Register) Add(v interface{}, carry bool) (bool, bool) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + sign := r[0] + + i := len(b) - 1 + + for i >= 0 { + if r[i] == false && b[i] == false && carry == false { // 0 0 0 + r[i] = false + carry = false + } else if r[i] == false && b[i] == false && carry == true { // 0 0 1 + r[i] = true + carry = false + } else if r[i] == false && b[i] == true && carry == false { // 0 1 0 + r[i] = true + carry = false + } else if r[i] == false && b[i] == true && carry == true { // 0 1 1 + r[i] = false + carry = true + } else if r[i] == true && b[i] == false && carry == false { // 1 0 0 + r[i] = true + carry = false + } else if r[i] == true && b[i] == false && carry == true { // 1 0 1 + r[i] = false + carry = true + } else if r[i] == true && b[i] == true && carry == false { // 1 1 0 + r[i] = false + carry = true + } else if r[i] == true && b[i] == true && carry == true { // 1 1 1 + r[i] = true + carry = true + } + + i-- + } + + overflow := sign == true && b[0] == true && r[0] == false + + return carry, overflow +} + +// Subtract value from register. Returns carry and overflow states +// +// Note that carry flag is opposite of what you might expect when subtracting +// on the 6502/6507 +func (r Register) Subtract(v interface{}, carry bool) (bool, bool) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + // generate two's complement + i := 0 + for i < len(b) { + b[i] = !b[i] + i++ + } + b.Add(1, false) + + return r.Add(b, !carry) +} + +// EOR - XOR Register with value +func (r Register) EOR(v interface{}) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + i := 0 + for i < len(r) { + r[i] = (r[i] || b[i]) && r[i] != b[i] + i++ + } +} + +// ORA - OR Register with value +func (r Register) ORA(v interface{}) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + i := 0 + for i < len(r) { + r[i] = r[i] || b[i] + i++ + } +} + +// AND register with value +func (r Register) AND(v interface{}) { + b, err := generateRegister(v, len(r)) + if err != nil { + log.Fatalln(err) + } + + i := 0 + for i < len(r) { + r[i] = r[i] && b[i] + i++ + } +} + +// ROR rotates register 1 bit to the right. Returns new carry status. +func (r Register) ROR(carry bool) bool { + rcarry := bool(r[len(r)-1]) + copy(r[1:], r[:len(r)-1]) + r[0] = bit(carry) + return rcarry +} + +// ROL rotates register 1 bit to the left. Returns new carry status. +func (r Register) ROL(carry bool) bool { + rcarry := bool(r[0]) + copy(r[:len(r)-1], r[1:]) + r[len(r)-1] = bit(carry) + return rcarry +} + +// ASL (Arithmetic shift Left) shifts register one bit to the left. Returns +// the most significant bit as it was before the shift. If we think of the +// ASL operation as a multiply by two then the return value is the carry bit. +func (r Register) ASL() bool { + rcarry := bool(r[0]) + copy(r[:len(r)-1], r[1:]) + r[len(r)-1] = bit(false) + return rcarry +} + +// LSR (Logical Shift Right) shifts register one bit to the rigth. +// the least significant bit as it was before the shift. If we think of +// the ASL operation as a division by two then the return value is the carry bit. +func (r Register) LSR() bool { + rcarry := bool(r[len(r)-1]) + copy(r[1:], r[:len(r)-1]) + r[0] = bit(false) + return rcarry +} + +// IsNegative checks the sign bit of the register +func (r Register) IsNegative() bool { + return bool(r[0]) +} + +// IsZero checks if register is all zero bits +func (r Register) IsZero() bool { + for b := range r { + if r[b] == true { + return false + } + } + return true +} diff --git a/hardware/cpu/registers_bits.go b/hardware/cpu/registers_bits.go new file mode 100644 index 00000000..8b2c265e --- /dev/null +++ b/hardware/cpu/registers_bits.go @@ -0,0 +1,141 @@ +package cpu + +import ( + "fmt" + "log" + "strings" +) + +type bit bool + +// bitVals is a lookup table for pow(2,n) +var bitVals = [...]int{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536} + +func max(a int, b int) int { + if a < b { + return b + } + return a +} + +// ToUint returns value as type uint, regardless of register size +func (r Register) ToUint() uint { + var v uint + + i := len(r) - 1 + j := 0 + for i >= 0 { + if r[i] != false { + v += uint(bitVals[j]) + } + i-- + j++ + } + + return v +} + +// ToBits returns the register as bit pattern (of '0' and '1') +func (r Register) ToBits() string { + s := make([]string, len(r)) + i := 0 + for i < len(r) { + if r[i] { + s[i] = "1" + } else { + s[i] = "0" + } + i++ + } + return strings.Join(s, "") +} + +// ToUint16 returns value of size uint16, regardless of register size +func (r Register) ToUint16() uint16 { + if len(r) > 16 { + log.Print("ToUint16: register wider than 16 bits. information may be lost") + } + return uint16(r.ToUint()) +} + +// ToUint8 returns value of size uint8, regardless of register size +func (r Register) ToUint8() uint8 { + if len(r) > 8 { + log.Print("ToUint8: register wider than 8 bits. information may be lost") + } + return uint8(r.ToUint()) +} + +// generateRegister is used to create a register using a value (v) to initialise it +// v can be another register or an integer type (int) or uint8 or uint16. if v is nil +// then a unitialised register of length bitlen is created; although it is suggested that +// a plain "make(Register, bitlen)" is used instead +// +// when a register is supplied, the register will be reused unless the bit length is wrong +// a pointer to a register indicates that you definitely want a new copy of the register +// regardless of bit length +func generateRegister(v interface{}, bitlen int) (Register, error) { + var r Register + var val uint16 + + if v == nil { + r := make(Register, bitlen) + return r, nil + } + + switch v := v.(type) { + default: + return nil, fmt.Errorf("value is of an unsupported type") + case *Register: + r = make(Register, bitlen) + val = v.ToUint16() + case Register: + // reuse register if possible + if len(v) == bitlen { + return v, nil + } + + // if register is not of length 'bitlen' then recurse this with a the numeric value of 'v' + // this will create a register of the correct length + r = make(Register, max(16, bitlen)) + val = v.ToUint16() + case uint16: + if int(v) >= bitVals[bitlen] { + return nil, fmt.Errorf("(1) value is too big (%d) for bit length of register (%d)", v, bitlen) + } + val = uint16(v) + r = make(Register, max(16, bitlen)) + case uint8: + if int(v) >= bitVals[bitlen] { + return nil, fmt.Errorf("(2) value is too big (%d) for bit length of register (%d)", v, bitlen) + } + val = uint16(v) + r = make(Register, max(8, bitlen)) + case int: + if v >= bitVals[bitlen] { + return nil, fmt.Errorf("(3) value is too big (%d) for bit length of register (%d)", v, bitlen) + } + val = uint16(v) + r = make(Register, max(8, bitlen)) + } + + // create bit pattern + i := 0 + j := len(r) - 1 + for j >= 0 { + bv := uint16(bitVals[j]) + if val/bv != 0 { + r[i] = true + val = val - bv + } + i++ + j-- + } + + // belt & braces test + if val != 0 { + return nil, fmt.Errorf("(2) value is too big (%d) for bit length of register (%d)", v, bitlen) + } + + return r, nil +} diff --git a/hardware/cpu/registers_test.go b/hardware/cpu/registers_test.go new file mode 100644 index 00000000..fa61bb11 --- /dev/null +++ b/hardware/cpu/registers_test.go @@ -0,0 +1,107 @@ +package cpu_test + +import ( + "headless/hardware/cpu" + "testing" +) + +func TestRegister(t *testing.T) { + r8 := make(cpu.Register, 8) + r16 := make(cpu.Register, 16) + + var carry, overflow bool + + // register loading + r8.Load(127) + assert(t, r8, "01111111") + assert(t, r8, 127) + + r8.Load(r8) + assert(t, r8, "01111111") + + r16.Load(1) + assert(t, r16, "0000000000000001") + assert(t, r16, 1) + + r16.Load(256) + assert(t, r16, "0000000100000000") + assert(t, r16, 256) + + r16.Load(1024) + assert(t, r16, "0000010000000000") + assert(t, r16, 1024) + + // arithemtic + r16.Add(2, false) + assert(t, r16, "0000010000000010") + assert(t, r16, 1026) + + r16.Subtract(2, true) + assert(t, r16, "0000010000000000") + assert(t, r16, 1024) + + r8.Add(1, false) + r8.Subtract(1, true) + assert(t, r8, "01111111") + + // arithmetic - carry/overflow + r8.Load(255) + assert(t, r8, 255) + carry, overflow = r8.Add(1, false) + assert(t, r8, 0) + assert(t, carry, true) + assert(t, overflow, false) + carry, overflow = r8.Subtract(1, true) + assert(t, r8, 255) + assert(t, carry, false) + assert(t, overflow, false) + carry, overflow = r8.Subtract(1, true) + assert(t, r8, 254) + assert(t, carry, true) + assert(t, overflow, false) + + // bitwise + r16.EOR(65535) + assert(t, r16, "1111101111111111") + + r16.ORA(65535) + assert(t, r16, "1111111111111111") + + r16.AND(253) + assert(t, r16, "0000000011111101") + + r8.Load(1) + assert(t, r8, "00000001") + + // rotation + r8.ROL(false) + assert(t, r8, "00000010") + + r8.ROL(true) + assert(t, r8, "00000101") + + r8.ROR(true) + assert(t, r8, "10000010") + + r8.ROR(false) + assert(t, r8, "01000001") + + // cpu flags + assert(t, r8.IsZero(), false) + assert(t, r8.IsNegative(), false) + r8.ROL(false) + assert(t, r8.IsNegative(), true) + r8.Load(0) + assert(t, r8.IsZero(), true) + + r8.Load(255) + carry, overflow = r8.Add(2, false) + assert(t, carry, true) + assert(t, overflow, false) + + // addition of different sized registers + r8.Load(1) + r16.Load(255) + r16.Add(r8, false) + assert(t, r16, 256) +} diff --git a/hardware/cpu/statusregister.go b/hardware/cpu/statusregister.go new file mode 100644 index 00000000..7e6cd0b1 --- /dev/null +++ b/hardware/cpu/statusregister.go @@ -0,0 +1,97 @@ +package cpu + +// StatusRegister is the special purpose register that stores the flags of the CPU +type StatusRegister struct { + Sign bool + Overflow bool + Break bool + DecimalMode bool + InterruptDisable bool + Zero bool + Carry bool +} + +func (sr StatusRegister) String() string { + var v string + + if sr.Sign { + v += "S" + } else { + v += "s" + } + if sr.Overflow { + v += "V" + } else { + v += "v" + } + v += "-" + if sr.Break { + v += "B" + } else { + v += "b" + } + if sr.DecimalMode { + v += "D" + } else { + v += "d" + } + if sr.InterruptDisable { + v += "I" + } else { + v += "i" + } + if sr.Zero { + v += "Z" + } else { + v += "z" + } + if sr.Carry { + v += "C" + } else { + v += "c" + } + + return v +} + +// ToUint8 converts the StatusRegister struct into a value suitable for pushing +// onto the stack +func (sr *StatusRegister) ToUint8() uint8 { + var v uint8 + + if sr.Sign { + v |= 0x80 + } + if sr.Overflow { + v |= 0x40 + } + if sr.Break { + v |= 0x10 + } + if sr.DecimalMode { + v |= 0x08 + } + if sr.InterruptDisable { + v |= 0x04 + } + if sr.Zero { + v |= 0x02 + } + if sr.Carry { + v |= 0x01 + } + + return v +} + +// FromUint8 converts an 8 bit integer (taken from the stack, for example) to +// the StatusRegister struct receiver +func (sr *StatusRegister) FromUint8(v uint8) { + sr.Sign = v&0x80 == 0x80 + sr.Overflow = v&0x40 == 0x40 + sr.Break = v&0x10 == 0x10 + sr.DecimalMode = v&0x08 == 0x08 + sr.InterruptDisable = v&0x04 == 0x04 + sr.Zero = v&0x02 == 0x02 + sr.Carry = v&0x01 == 0x01 +} diff --git a/hardware/cpu/stepresult.go b/hardware/cpu/stepresult.go new file mode 100644 index 00000000..d45eccc1 --- /dev/null +++ b/hardware/cpu/stepresult.go @@ -0,0 +1,105 @@ +package cpu + +import ( + "fmt" + "reflect" +) + +// StepResult contains all the interesting information from a CPU step. +type StepResult struct { + ProgramCounter uint16 + Defn InstructionDefinition + InstructionData interface{} + ActualCycles int + + // whether an extra cycle was required because of 8 bit adder overflow + PageFault bool + + // whether a buggy (CPU) code path was triggered + Bug string +} + +func (sr StepResult) String() string { + var data string + var pf, bug string + + if sr.Defn.Bytes == 2 { + data = fmt.Sprintf("$%02x", sr.InstructionData) + } else if sr.Defn.Bytes == 3 { + data = fmt.Sprintf("$%04x", sr.InstructionData) + } + + switch sr.Defn.AddressingMode { + case Implied: + case Immediate: + data = fmt.Sprintf("#%s", data) + case Relative: + case Absolute: + case ZeroPage: + case Indirect: + data = fmt.Sprintf("(%s)", data) + case PreIndexedIndirect: + data = fmt.Sprintf("(%s,X)", data) + case PostIndexedIndirect: + data = fmt.Sprintf("(%s),Y", data) + case AbsoluteIndexedX: + data = fmt.Sprintf("%s,X", data) + case AbsoluteIndexedY: + data = fmt.Sprintf("%s,Y", data) + case IndexedZeroPageX: + data = fmt.Sprintf("%s,X", data) + case IndexedZeroPageY: + data = fmt.Sprintf("%s,Y", data) + default: + } + + if sr.PageFault { + pf = " page-fault" + } + + if sr.Bug != "" { + bug = fmt.Sprintf(" * %s *", sr.Bug) + } + + return fmt.Sprintf("0x%04x\t%s\t%s\t[%d]%s%s", sr.ProgramCounter, sr.Defn.Mnemonic, data, sr.ActualCycles, pf, bug) +} + +// IsValid checks whether the instance of StepResult contains consistent data. +// +// Intended to be used during development of the CPU pacakge, to make sure +// implementation hasn't gone off the rails. +func (sr StepResult) IsValid() error { + // check that InstructionData is broadly sensible - is either nil, a uint16 or uint8 + if sr.InstructionData != nil { + ot := reflect.TypeOf(sr.InstructionData).Kind() + if ot != reflect.Uint16 && ot != reflect.Uint8 { + return fmt.Errorf("instruction data is bad (%s)", ot) + } + } + + // is PageFault valid given content of Defn + if !sr.Defn.PageSensitive && sr.PageFault { + return fmt.Errorf("unexpected page fault") + } + + // if a bug has been triggered, don't perform the number of cycles check + if sr.Bug != "" { + if sr.Defn.AddressingMode == Relative { + if sr.ActualCycles != sr.Defn.Cycles && sr.ActualCycles != sr.Defn.Cycles+1 { + return fmt.Errorf("number of cycles wrong (%d instead of %d or %d)", sr.ActualCycles, sr.Defn.Cycles, sr.Defn.Cycles+1) + } + } else { + if sr.Defn.PageSensitive { + if sr.PageFault && sr.ActualCycles != sr.Defn.Cycles && sr.ActualCycles != sr.Defn.Cycles+1 { + return fmt.Errorf("number of cycles wrong (%d instead of %d or %d)", sr.ActualCycles, sr.Defn.Cycles, sr.Defn.Cycles+1) + } + } else { + if sr.ActualCycles != sr.Defn.Cycles { + return fmt.Errorf("number of cycles wrong (%d instead of %d", sr.ActualCycles, sr.Defn.Cycles) + } + } + } + } + + return nil +} diff --git a/hardware/memory/memory.go b/hardware/memory/memory.go new file mode 100644 index 00000000..8f3a3be6 --- /dev/null +++ b/hardware/memory/memory.go @@ -0,0 +1,7 @@ +package memory + +// Memory defines the operations for a memory system +type Memory interface { + Read(address uint16) (uint8, error) + Write(address uint16, data uint8) error +}