├── .gitattributes ├── .gitignore ├── DEPENDENCIES ├── LICENSE ├── README.md ├── disassembler ├── .gitattributes ├── .gitignore └── disassembler.lua ├── emulator ├── README.md ├── meson.build └── src │ ├── Chipset │ ├── CPU.cpp │ ├── CPU.hpp │ ├── CPUArithmetic.cpp │ ├── CPUControl.cpp │ ├── CPULoadStore.cpp │ ├── CPUPushPop.cpp │ ├── Chipset.cpp │ ├── Chipset.hpp │ ├── InterruptSource.cpp │ ├── InterruptSource.hpp │ ├── MMU.cpp │ ├── MMU.hpp │ ├── MMURegion.cpp │ └── MMURegion.hpp │ ├── Config.hpp │ ├── Data │ ├── ColourInfo.hpp │ ├── EventCode.hpp │ ├── ModelInfo.cpp │ ├── ModelInfo.hpp │ └── SpriteInfo.hpp │ ├── Emulator.cpp │ ├── Emulator.hpp │ ├── Logger.cpp │ ├── Logger.hpp │ ├── Peripheral │ ├── BatteryBackedRAM.cpp │ ├── BatteryBackedRAM.hpp │ ├── Keyboard.cpp │ ├── Keyboard.hpp │ ├── Miscellaneous.cpp │ ├── Miscellaneous.hpp │ ├── Peripheral.cpp │ ├── Peripheral.hpp │ ├── ROMWindow.cpp │ ├── ROMWindow.hpp │ ├── Screen.cpp │ ├── Screen.hpp │ ├── StandbyControl.cpp │ ├── StandbyControl.hpp │ ├── Timer.cpp │ └── Timer.hpp │ └── casioemu.cpp └── models └── fx570esplus ├── interface.png ├── interface.svg ├── model.lua └── readme.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | Makefile linguist-vendored 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.log 3 | *.geany 4 | *.sublime-* 5 | models/*/*.bin 6 | models/*/*.asm 7 | models/*/*.names 8 | ignore/ 9 | build/ 10 | test/ 11 | -------------------------------------------------------------------------------- /DEPENDENCIES: -------------------------------------------------------------------------------- 1 | libsdl2-dev 2 | libsdl2-image-dev 3 | liblua5.3-0-dev 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CasioEmu 2 | 3 | I'm too lazy to add a fancy readme. The emulator has its own readme in its 4 | directory `emulator/`, check that one for instructions on building it. 5 | -------------------------------------------------------------------------------- /disassembler/.gitattributes: -------------------------------------------------------------------------------- 1 | *.sh linguist-vendored 2 | -------------------------------------------------------------------------------- /disassembler/.gitignore: -------------------------------------------------------------------------------- 1 | all.sh 2 | -------------------------------------------------------------------------------- /disassembler/disassembler.lua: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env luajit 2 | 3 | if not bit then 4 | bit = {} 5 | 6 | local function normalize(r) 7 | r = r % 0x100000000 8 | if r >= 0x80000000 then 9 | r = r - 0x100000000 10 | end 11 | return r 12 | end 13 | 14 | local function loopfunc(a, b, t, u) 15 | a = a % 0x100000000 16 | b = b % 0x100000000 17 | local r = 0 18 | for ix = 31, 0, -1 do 19 | local v = 2 ^ ix 20 | local m = 0 21 | if a >= v then 22 | a = a - v 23 | m = m + 1 24 | end 25 | if b >= v then 26 | b = b - v 27 | m = m + 1 28 | end 29 | if m == t or m == u then 30 | r = r + v 31 | end 32 | end 33 | return normalize(r) 34 | end 35 | 36 | function bit.band(a, b) 37 | return loopfunc(a, b, 2) 38 | end 39 | 40 | function bit.bor(a, b) 41 | return loopfunc(a, b, 1, 2) 42 | end 43 | 44 | function bit.bxor(a, b) 45 | return loopfunc(a, b, 1) 46 | end 47 | 48 | function bit.lshift(a, b) 49 | return normalize(a * 2 ^ b) 50 | end 51 | 52 | function bit.rshift(a, b) 53 | return normalize(math.floor((a % 0x100000000) / 2 ^ b)) 54 | end 55 | 56 | function bit.arshift(a, b) -- for completeness? 57 | return math.floor(normalize(a) / 2 ^ b) 58 | end 59 | end 60 | 61 | local args_assoc = { 62 | input = "/dev/stdin", 63 | output = "/dev/stdout", 64 | entry = "", 65 | complement_entries = false, 66 | strict = false, 67 | addresses = false, 68 | rom_window = 0 69 | } 70 | 71 | for ix, arg in next, {...} do 72 | local key, value = arg:match("^([^=]+)=(.+)$") 73 | if key then 74 | args_assoc[key] = value 75 | else 76 | args_assoc.input = arg 77 | end 78 | end 79 | 80 | args_assoc.rom_window = tonumber(args_assoc.rom_window) 81 | 82 | local DATA_LABEL_FORMAT = "d_%05X" 83 | local GLOBAL_LABEL_FORMAT = "f_%05X" 84 | local LOCAL_LABEL_FORMAT = ".l_%03X" 85 | 86 | local function print(thing, ...) 87 | io.stderr:write(tostring(thing)) 88 | if ... then 89 | io.stderr:write(", ") 90 | print(...) 91 | else 92 | io.stderr:write("\n") 93 | end 94 | end 95 | 96 | local function printf(...) 97 | print(string.format(...)) 98 | end 99 | 100 | local function panic(...) 101 | io.stderr:write("PANIC: ") 102 | printf(...) 103 | os.exit(1) 104 | end 105 | 106 | local function panic2(...) 107 | io.stderr:write("PANIC: ") 108 | printf(...) 109 | if args_assoc.strict then 110 | os.exit(1) 111 | end 112 | end 113 | 114 | local handle = io.open(args_assoc.input, "rb") 115 | if not handle then 116 | panic("Failed to open \"%s\"", args_assoc.input) 117 | end 118 | local binary_source = handle:read("*a") 119 | handle:close() 120 | 121 | local binary_source_length = #binary_source 122 | printf("Read %i bytes", binary_source_length) 123 | 124 | local formats 125 | do 126 | local condition_names = {"ge", "lt", "gt", "le", "ges", "lts", "gts", "les", "ne", "eq", "nv", "ov", "ps", "ns", "al"} 127 | formats = { 128 | [ "lab"] = {format = function(self, value, instr) 129 | if instr.context ~= value.context and not value.context_head then 130 | if not value.context then 131 | return value.name 132 | end 133 | return value.context.name .. value.name 134 | end 135 | return value.name 136 | end}, 137 | ["dlab"] = {format = function(self, value, instr) 138 | if value.ref_instr then 139 | return ("%s+%i"):format(formats.lab:format(value.ref_instr.under_label, instr), value.address - value.ref_instr.under_label.address) 140 | end 141 | return value.name 142 | end}, 143 | [ "str"] = "%s", 144 | [ "r"] = "r%i", 145 | [ "er"] = "er%i", 146 | [ "xr"] = "xr%i", 147 | [ "qr"] = "qr%i", 148 | [ "cr"] = "cr%i", 149 | [ "cer"] = "cer%i", 150 | [ "cxr"] = "cxr%i", 151 | [ "cqr"] = "cqr%i", 152 | [ "dsr"] = "dsr", 153 | [ "ea"] = "ea", 154 | [ "eap"] = "ea+", 155 | [ "im"] = "%i", 156 | [ "bo"] = "%i", 157 | [ "elr"] = "elr", 158 | [ "lr"] = "lr", 159 | [ "psw"] = "psw", 160 | ["epsw"] = "epsw", 161 | ["ecsr"] = "ecsr", 162 | [ "sp"] = "sp", 163 | [ "pc"] = "pc", 164 | [ "co"] = {format = function(self, value) 165 | return condition_names[value + 1] 166 | end}, 167 | [ "jo"] = {format = function(self, value, instr) 168 | return ("%i"):format((instr.address + instr.length + value * 2) % 0x10000) 169 | end} 170 | } 171 | end 172 | 173 | print("Generating instruction lookup table...") 174 | local instruction_lookup = {} 175 | do 176 | local instruction_source = { 177 | {{ "add", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8001, false, 0}, 178 | {{ "add", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x1000, false, 0}, 179 | {{ "add", { "er", 8, 0x000E}, { "er", 4, 0x000E} }, 0xF006, false, 0}, 180 | {{ "add", { "er", 8, 0x000E}, { "im", 0, -0x007F} }, 0xE080, false, 0}, 181 | {{ "addc", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8006, false, 0}, 182 | {{ "addc", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x6000, false, 0}, 183 | {{ "and", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8002, false, 0}, 184 | {{ "and", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x2000, false, 0}, 185 | {{ "cmp", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8007, false, 0}, 186 | {{ "cmp", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x7000, false, 0}, 187 | {{ "cmpc", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8005, false, 0}, 188 | {{ "cmpc", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x5000, false, 0}, 189 | {{ "mov", { "er", 8, 0x000E}, { "er", 4, 0x000E} }, 0xF005, false, 0}, 190 | {{ "mov", { "er", 8, 0x000E}, { "im", 0, -0x007F} }, 0xE000, false, 0}, 191 | {{ "mov", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8000, false, 0}, 192 | {{ "mov", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x0000, false, 0}, 193 | {{ "or", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8003, false, 0}, 194 | {{ "or", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x3000, false, 0}, 195 | {{ "xor", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8004, false, 0}, 196 | {{ "xor", { "r", 8, 0x000F}, { "im", 0, 0x00FF} }, 0x4000, false, 0}, 197 | {{ "cmp", { "er", 8, 0x000E}, { "er", 4, 0x000E} }, 0xF007, false, 0}, 198 | {{ "sub", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8008, false, 0}, 199 | {{ "subc", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x8009, false, 0}, 200 | {{ "sll", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x800A, false, 0}, 201 | {{ "sll", { "r", 8, 0x000F}, { "im", 4, 0x0007} }, 0x900A, false, 0}, 202 | {{ "sllc", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x800B, false, 0}, 203 | {{ "sllc", { "r", 8, 0x000F}, { "im", 4, 0x0007} }, 0x900B, false, 0}, 204 | {{ "sra", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x800E, false, 0}, 205 | {{ "sra", { "r", 8, 0x000F}, { "im", 4, 0x0007} }, 0x900E, false, 0}, 206 | {{ "srl", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x800C, false, 0}, 207 | {{ "srl", { "r", 8, 0x000F}, { "im", 4, 0x0007} }, 0x900C, false, 0}, 208 | {{ "srlc", { "r", 8, 0x000F}, { "r", 4, 0x000F} }, 0x800D, false, 0}, 209 | {{ "srlc", { "r", 8, 0x000F}, { "im", 4, 0x0007} }, 0x900D, false, 0}, 210 | {{ "l", { "er", 8, 0x000E}, { "ea", 0, 0x0000} }, 0x9032, false, 2}, 211 | {{ "l", { "er", 8, 0x000E}, { "eap", 0, 0x0000} }, 0x9052, false, 2}, 212 | {{ "l", { "er", 8, 0x000E}, { "er", 4, 0x000E} }, 0x9002, false, 2}, 213 | {{ "l", { "er", 8, 0x000E}, { "er", 4, 0x000E}, {"im", 16, 0xFFFF}}, 0xA008, true, 2}, 214 | {{ "l", { "er", 8, 0x000E}, { "er", -1, 0x000C}, {"im", 0, -0x003F}}, 0xB000, false, 2}, 215 | {{ "l", { "er", 8, 0x000E}, { "er", -1, 0x000E}, {"im", 0, -0x003F}}, 0xB040, false, 2}, 216 | {{ "l", { "er", 8, 0x000E}, { "im", 16, 0xFFFF} }, 0x9012, true, 2}, 217 | {{ "l", { "r", 8, 0x000F}, { "ea", 0, 0x0000} }, 0x9030, false, 2}, 218 | {{ "l", { "r", 8, 0x000F}, { "eap", 0, 0x0000} }, 0x9050, false, 2}, 219 | {{ "l", { "r", 8, 0x000F}, { "er", 4, 0x000E} }, 0x9000, false, 2}, 220 | {{ "l", { "r", 8, 0x000F}, { "er", 4, 0x000E}, {"im", 16, 0xFFFF}}, 0x9008, true, 2}, 221 | {{ "l", { "r", 8, 0x000F}, { "er", -1, 0x000C}, {"im", 0, -0x003F}}, 0xD000, false, 2}, 222 | {{ "l", { "r", 8, 0x000F}, { "er", -1, 0x000E}, {"im", 0, -0x003F}}, 0xD040, false, 2}, 223 | {{ "l", { "r", 8, 0x000F}, { "im", 16, 0xFFFF} }, 0x9010, true, 2}, 224 | {{ "l", { "xr", 8, 0x000C}, { "ea", 0, 0x0000} }, 0x9034, false, 2}, 225 | {{ "l", { "xr", 8, 0x000C}, { "eap", 0, 0x0000} }, 0x9054, false, 2}, 226 | {{ "l", { "qr", 8, 0x0008}, { "ea", 0, 0x0000} }, 0x9036, false, 2}, 227 | {{ "l", { "qr", 8, 0x0008}, { "eap", 0, 0x0000} }, 0x9056, false, 2}, 228 | {{ "st", { "er", 8, 0x000E}, { "ea", 0, 0x0000} }, 0x9033, false, 2}, 229 | {{ "st", { "er", 8, 0x000E}, { "eap", 0, 0x0000} }, 0x9053, false, 2}, 230 | {{ "st", { "er", 8, 0x000E}, { "er", 4, 0x000E} }, 0x9003, false, 2}, 231 | {{ "st", { "er", 8, 0x000E}, { "er", 4, 0x000E}, {"im", 16, 0xFFFF}}, 0xA009, true, 2}, 232 | {{ "st", { "er", 8, 0x000E}, { "er", -1, 0x000C}, {"im", 0, -0x003F}}, 0xB080, false, 2}, 233 | {{ "st", { "er", 8, 0x000E}, { "er", -1, 0x000E}, {"im", 0, -0x003F}}, 0xB0C0, false, 2}, 234 | {{ "st", { "er", 8, 0x000E}, { "im", 16, 0xFFFF} }, 0x9013, true, 2}, 235 | {{ "st", { "r", 8, 0x000F}, { "ea", 0, 0x0000} }, 0x9031, false, 2}, 236 | {{ "st", { "r", 8, 0x000F}, { "eap", 0, 0x0000} }, 0x9051, false, 2}, 237 | {{ "st", { "r", 8, 0x000F}, { "er", 4, 0x000E} }, 0x9001, false, 2}, 238 | {{ "st", { "r", 8, 0x000F}, { "er", 4, 0x000E}, {"im", 16, 0xFFFF}}, 0x9009, true, 2}, 239 | {{ "st", { "r", 8, 0x000F}, { "er", -1, 0x000C}, {"im", 0, -0x003F}}, 0xD080, false, 2}, 240 | {{ "st", { "r", 8, 0x000F}, { "er", -1, 0x000E}, {"im", 0, -0x003F}}, 0xD0C0, false, 2}, 241 | {{ "st", { "r", 8, 0x000F}, { "im", 16, 0xFFFF} }, 0x9011, true, 2}, 242 | {{ "st", { "xr", 8, 0x000C}, { "ea", 0, 0x0000} }, 0x9035, false, 2}, 243 | {{ "st", { "xr", 8, 0x000C}, { "eap", 0, 0x0000} }, 0x9055, false, 2}, 244 | {{ "st", { "qr", 8, 0x0008}, { "ea", 0, 0x0000} }, 0x9037, false, 2}, 245 | {{ "st", { "qr", 8, 0x0008}, { "eap", 0, 0x0000} }, 0x9057, false, 2}, 246 | {{ "add", { "sp", 0, 0x0000}, { "im", 0, -0x00FF} }, 0xE100, false, 0}, 247 | {{ "mov", {"ecsr", 0, 0x0000}, { "r", 4, 0x000F} }, 0xA00F, false, 0}, 248 | {{ "mov", { "elr", 0, 0x0000}, { "er", 8, 0x000E} }, 0xA00D, false, 0}, 249 | {{ "mov", {"epsw", 0, 0x0000}, { "r", 4, 0x000F} }, 0xA00C, false, 0}, 250 | {{ "mov", { "er", 8, 0x000E}, { "elr", 0, 0x0000} }, 0xA005, false, 0}, 251 | {{ "mov", { "er", 8, 0x000E}, { "sp", 0, 0x0000} }, 0xA01A, false, 0}, 252 | {{ "mov", { "psw", 0, 0x0000}, { "r", 4, 0x000F} }, 0xA00B, false, 0}, 253 | {{ "mov", { "psw", 0, 0x0000}, { "im", 0, 0x00FF} }, 0xE900, false, 0}, 254 | {{ "mov", { "r", 8, 0x000F}, {"ecsr", 0, 0x0000} }, 0xA007, false, 0}, 255 | {{ "mov", { "r", 8, 0x000F}, {"epsw", 0, 0x0000} }, 0xA004, false, 0}, 256 | {{ "mov", { "r", 8, 0x000F}, { "psw", 0, 0x0000} }, 0xA003, false, 0}, 257 | {{ "mov", { "sp", 0, 0x0000}, { "er", 4, 0x000E} }, 0xA10A, false, 0}, 258 | {{ "push", { "er", 8, 0x000E} }, 0xF05E, false, 0}, 259 | {{ "push", { "qr", 8, 0x0008} }, 0xF07E, false, 0}, 260 | {{ "push", { "r", 8, 0x000F} }, 0xF04E, false, 0}, 261 | {{ "push", { "xr", 8, 0x000C} }, 0xF06E, false, 0}, 262 | {{ "push", {"push", 8, 0x000F} }, 0xF0CE, false, 0}, 263 | {{ "pop", { "er", 8, 0x000E} }, 0xF01E, false, 0}, 264 | {{ "pop", { "qr", 8, 0x0008} }, 0xF03E, false, 0}, 265 | {{ "pop", { "r", 8, 0x000F} }, 0xF00E, false, 0}, 266 | {{ "pop", { "xr", 8, 0x000C} }, 0xF02E, false, 0}, 267 | {{ "pop", { "pop", 8, 0x000F} }, 0xF08E, false, 0}, 268 | {{ "mov", { "cr", 8, 0x000F}, { "r", 4, 0x000F} }, 0xA00E, false, 0}, 269 | {{ "mov", { "cer", 8, 0x000E}, { "ea", 0, 0x0000} }, 0xF02D, false, 2}, 270 | {{ "mov", { "cer", 8, 0x000E}, { "eap", 0, 0x0000} }, 0xF03D, false, 2}, 271 | {{ "mov", { "cr", 8, 0x000F}, { "ea", 0, 0x0000} }, 0xF00D, false, 2}, 272 | {{ "mov", { "cr", 8, 0x000F}, { "eap", 0, 0x0000} }, 0xF01D, false, 2}, 273 | {{ "mov", { "cxr", 8, 0x000C}, { "ea", 0, 0x0000} }, 0xF04D, false, 2}, 274 | {{ "mov", { "cxr", 8, 0x000C}, { "eap", 0, 0x0000} }, 0xF05D, false, 2}, 275 | {{ "mov", { "cqr", 8, 0x0008}, { "ea", 0, 0x0000} }, 0xF06D, false, 2}, 276 | {{ "mov", { "cqr", 8, 0x0008}, { "eap", 0, 0x0000} }, 0xF07D, false, 2}, 277 | {{ "mov", { "r", 4, 0x000F}, { "cr", 8, 0x000F} }, 0xA006, false, 0}, 278 | {{ "mov", { "ea", 0, 0x0000}, { "cer", 8, 0x000E} }, 0xF0AD, false, 1}, 279 | {{ "mov", { "eap", 0, 0x0000}, { "cer", 8, 0x000E} }, 0xF0BD, false, 1}, 280 | {{ "mov", { "ea", 0, 0x0000}, { "cr", 8, 0x000F} }, 0xF08D, false, 1}, 281 | {{ "mov", { "eap", 0, 0x0000}, { "cr", 8, 0x000F} }, 0xF09D, false, 1}, 282 | {{ "mov", { "ea", 0, 0x0000}, { "cxr", 8, 0x000C} }, 0xF0CD, false, 1}, 283 | {{ "mov", { "eap", 0, 0x0000}, { "cxr", 8, 0x000C} }, 0xF0DD, false, 1}, 284 | {{ "mov", { "ea", 0, 0x0000}, { "cqr", 8, 0x0008} }, 0xF0ED, false, 1}, 285 | {{ "mov", { "eap", 0, 0x0000}, { "cqr", 8, 0x0008} }, 0xF0FD, false, 1}, 286 | {{ "lea", { "er", 4, 0x000E} }, 0xF00A, false, 1}, 287 | {{ "lea", { "er", 4, 0x000E}, { "im", 16, 0xFFFF} }, 0xF00B, true, 1}, 288 | {{ "lea", { "im", 16, 0xFFFF} }, 0xF00C, true, 1}, 289 | {{ "daa", { "r", 8, 0x000F} }, 0x801F, false, 0}, 290 | {{ "das", { "r", 8, 0x000F} }, 0x803F, false, 0}, 291 | {{ "neg", { "r", 8, 0x000F} }, 0x805F, false, 0}, 292 | {{ "sb", { "r", 8, 0x000F}, { "bo", 4, 0x0007} }, 0xA000, false, 0}, 293 | {{ "sb", { "im", 16, 0xFFFF}, { "bo", 4, 0x0007} }, 0xA080, true, 1}, 294 | {{ "rb", { "r", 8, 0x000F}, { "bo", 4, 0x0007} }, 0xA002, false, 0}, 295 | {{ "rb", { "im", 16, 0xFFFF}, { "bo", 4, 0x0007} }, 0xA082, true, 1}, 296 | {{ "tb", { "r", 8, 0x000F}, { "bo", 4, 0x0007} }, 0xA001, false, 0}, 297 | {{ "tb", { "im", 16, 0xFFFF}, { "bo", 4, 0x0007} }, 0xA081, true, 1}, 298 | {{ "ei", }, 0xED08, false, 0}, 299 | {{ "di", }, 0xEBF7, false, 0}, 300 | {{ "sc", }, 0xED80, false, 0}, 301 | {{ "rc", }, 0xEB7F, false, 0}, 302 | {{ "clpc", }, 0xFECF, false, 0}, 303 | {{ "bc", { "co", 8, 0x000F}, { "jo", 0, -0x00FF} }, 0xC000, false, 0}, 304 | {{"extbw", { "er", -1, 0x0000} }, 0x810F, false, 0}, 305 | {{"extbw", { "er", -1, 0x0002} }, 0x832F, false, 0}, 306 | {{"extbw", { "er", -1, 0x0004} }, 0x854F, false, 0}, 307 | {{"extbw", { "er", -1, 0x0006} }, 0x876F, false, 0}, 308 | {{"extbw", { "er", -1, 0x0008} }, 0x898F, false, 0}, 309 | {{"extbw", { "er", -1, 0x000A} }, 0x8BAF, false, 0}, 310 | {{"extbw", { "er", -1, 0x000C} }, 0x8DCF, false, 0}, 311 | {{"extbw", { "er", -1, 0x000E} }, 0x8FEF, false, 0}, 312 | {{ "swi", { "im", 0, 0x003F} }, 0xE500, false, 0}, 313 | {{ "brk", }, 0xFFFF, false, 0}, 314 | {{ "b", { "im", 8, 0x000F}, { "im", 16, 0xFFFF} }, 0xF000, true, 0}, 315 | {{ "b", { "er", 4, 0x000E} }, 0xF002, false, 0}, 316 | {{ "bl", { "im", 8, 0x000F}, { "im", 16, 0xFFFF} }, 0xF001, true, 0}, 317 | {{ "bl", { "er", 4, 0x000E} }, 0xF003, false, 0}, 318 | {{ "mul", { "er", 8, 0x000E}, { "r", 4, 0x000F} }, 0xF004, false, 0}, 319 | {{ "div", { "er", 8, 0x000E}, { "r", 4, 0x000F} }, 0xF009, false, 0}, 320 | {{ "inc", { "ea", 0, 0x0000} }, 0xFE2F, false, 1}, 321 | {{ "dec", { "ea", 0, 0x0000} }, 0xFE3F, false, 1}, 322 | {{ "rt", }, 0xFE1F, false, 0}, 323 | {{ "rti", }, 0xFE0F, false, 0}, 324 | {{ "nop", }, 0xFE8F, false, 0}, 325 | {{ "dsr", { "dsr", -1, 0xFFFF} }, 0xFE9F, false, 0}, 326 | {{ "dsr", { "r", 4, 0x000F} }, 0x900F, false, 0}, 327 | {{ "dsr", { "im", 0, 0x00FF} }, 0xE300, false, 0}, 328 | } 329 | 330 | for ix, def in next, instruction_source do 331 | local repr, imask, has_imm, addr = def[1], def[2], def[3], def[4] 332 | local function instruction_emit_func(instruction, imm16) 333 | local params_out = {} 334 | for ix = 2, #repr do 335 | local fmt, shift, pmask = unpack(repr[ix]) 336 | local signed = pmask < 0 337 | pmask = math.abs(pmask) 338 | local fmtvalue = instruction 339 | if shift == 16 then 340 | shift = 0 341 | fmtvalue = imm16 342 | end 343 | if shift < 0 then 344 | shift = 0 345 | fmtvalue = pmask 346 | pmask = -1 347 | end 348 | fmtvalue = bit.band(bit.rshift(fmtvalue, shift), pmask) 349 | if signed then 350 | if bit.band(fmtvalue, bit.rshift(pmask + 1, 1)) ~= 0 then 351 | fmtvalue = bit.bor(bit.bxor(-1, pmask), fmtvalue) 352 | end 353 | end 354 | table.insert(params_out, {fmtvalue, fmt}) 355 | end 356 | local result = { 357 | mnemonic = repr[1], 358 | instruction = instruction, 359 | imm16 = imm16, 360 | params = params_out, 361 | offsetable = addr 362 | } 363 | return result 364 | end 365 | local vmask = 0 366 | for ix = 2, #repr do 367 | local shift, pmask = repr[ix][2], math.abs(repr[ix][3]) 368 | if shift >= 0 then 369 | vmask = bit.bor(vmask, bit.lshift(pmask, shift)) 370 | end 371 | end 372 | local maskvariants = {[0] = true} 373 | for ix = 0, 15 do 374 | local cbit = bit.lshift(1, ix) 375 | if bit.band(vmask, cbit) ~= 0 then 376 | local newmaskvariants = {} 377 | for key in next, maskvariants do 378 | newmaskvariants[key] = true 379 | newmaskvariants[bit.bor(key, cbit)] = true 380 | end 381 | maskvariants = newmaskvariants 382 | end 383 | end 384 | local instruction_stub = { 385 | has_imm, 386 | instruction_emit_func 387 | } 388 | for key in next, maskvariants do 389 | local lkey = bit.bor(imask, key) + 1 390 | if instruction_lookup[lkey] then 391 | printf("%04X, %04X, %04X", imask, key, lkey - 1) 392 | panic("lookupgen: clash") 393 | end 394 | instruction_lookup[lkey] = instruction_stub 395 | end 396 | end 397 | do 398 | local instruction_stub = { 399 | false, 400 | function(instruction, imm16) 401 | return { 402 | mnemonic = "?", 403 | instruction = instruction, 404 | imm16 = imm16, 405 | params = {}, 406 | offsetable = 0, 407 | opcode = {instruction} 408 | } 409 | end 410 | } 411 | for ix = 0x0000, 0xFFFF do 412 | if not instruction_lookup[ix + 1] then 413 | instruction_lookup[ix + 1] = instruction_stub 414 | end 415 | end 416 | end 417 | end 418 | print(" Done.") 419 | 420 | local function fetch(address) 421 | return binary_source:byte(address + 1) + 0x100 * binary_source:byte(address + 2) 422 | end 423 | 424 | local instruction_by_address = {} 425 | local function disassemble(segment, address) 426 | local full_address = segment + address 427 | local fetch_addr = address 428 | if instruction_by_address[full_address] then 429 | if instruction_by_address[full_address].head then 430 | panic("disassemble: requesting tail at %01X:%04X", bit.rshift(segment, 16), address) 431 | end 432 | return instruction_by_address[full_address], true 433 | end 434 | local instruction_data = {} 435 | 436 | local state = {} 437 | local instruction_stub 438 | 439 | local length = 0 440 | local opcode, imm16, dsr, result 441 | local opcode_data = {} 442 | while true do 443 | local word = fetch(segment + fetch_addr) 444 | table.insert(opcode_data, word) 445 | fetch_addr = bit.band(fetch_addr + 2, 0xFFFF) 446 | length = length + 2 447 | if imm16 == true then 448 | imm16 = word 449 | end 450 | if not opcode then 451 | opcode = word 452 | instruction_stub = instruction_lookup[opcode + 1] 453 | if instruction_stub[1] then 454 | imm16 = true 455 | end 456 | end 457 | if imm16 ~= true then 458 | result = instruction_stub[2](opcode, imm16) 459 | end 460 | if result then 461 | if result.mnemonic == "dsr" then 462 | if dsr then 463 | panic("disassemble: double dsr at %01X:%04X", bit.rshift(segment, 16), address) 464 | end 465 | dsr = result.params[1] 466 | opcode = false 467 | imm16 = false 468 | result = false 469 | elseif result.mnemonic == "push" and result.params[1][2] == "push" then 470 | local mask = result.params[1][1] 471 | result.params = {} 472 | if bit.band(mask, 2) ~= 0 then table.insert(result.params, {0, "elr"}) end 473 | if bit.band(mask, 4) ~= 0 then table.insert(result.params, {0, "epsw"}) end 474 | if bit.band(mask, 8) ~= 0 then table.insert(result.params, {0, "lr"}) end 475 | if bit.band(mask, 1) ~= 0 then table.insert(result.params, {0, "ea"}) end 476 | elseif result.mnemonic == "pop" and result.params[1][2] == "pop" then 477 | local mask = result.params[1][1] 478 | result.params = {} 479 | if bit.band(mask, 1) ~= 0 then table.insert(result.params, {0, "ea"}) end 480 | if bit.band(mask, 8) ~= 0 then table.insert(result.params, {0, "lr"}) end 481 | if bit.band(mask, 4) ~= 0 then table.insert(result.params, {0, "psw"}) end 482 | if bit.band(mask, 2) ~= 0 then table.insert(result.params, {0, "pc"}) end 483 | end 484 | end 485 | if result then 486 | break 487 | end 488 | end 489 | result.address = full_address 490 | result.dsr = dsr 491 | result.length = length 492 | result.opcode = opcode_data 493 | instruction_by_address[full_address] = result 494 | for ix = 2, length - 2 do 495 | instruction_by_address[full_address + ix] = { 496 | head = result 497 | } 498 | end 499 | return result 500 | end 501 | 502 | local datalabel_by_address = {} 503 | local function add_data_label(address, xref) 504 | local label_obj = datalabel_by_address[address] 505 | if not label_obj then 506 | label_obj = { 507 | address = address, 508 | name = DATA_LABEL_FORMAT:format(address), 509 | xrefs = {} 510 | } 511 | datalabel_by_address[address] = label_obj 512 | end 513 | if xref then 514 | label_obj.xrefs[xref] = true 515 | end 516 | return label_obj 517 | end 518 | 519 | local label_by_address = {} 520 | local function add_label(streak, address, xref) 521 | local label_obj = label_by_address[address] 522 | if not label_obj then 523 | label_obj = { 524 | address = address, 525 | name = GLOBAL_LABEL_FORMAT:format(address), 526 | xrefs = {}, 527 | streak = streak 528 | } 529 | label_by_address[address] = label_obj 530 | end 531 | if xref then 532 | label_obj.xrefs[xref] = true 533 | end 534 | return label_obj 535 | end 536 | 537 | local comments_by_address = {} 538 | local function add_comment(address, comment) 539 | comments_by_address[address] = comments_by_address[address] or {} 540 | table.insert(comments_by_address[address], comment) 541 | end 542 | local function add_jt_comment(address, ix, label_obj) 543 | add_comment(address, { 544 | type = "jt", 545 | ix = ix, 546 | label = label_obj 547 | }) 548 | end 549 | 550 | local function make_streak() 551 | return { 552 | friends = {} 553 | } 554 | end 555 | 556 | local image_iterator 557 | do 558 | local function image_next(st, address) 559 | if address >= st.length then 560 | return 561 | end 562 | local instr = st.store[address] 563 | local next_address 564 | if instr then 565 | next_address = address + instr.length 566 | else 567 | next_address = address + 2 568 | end 569 | return next_address, address, instr, st.label[address] 570 | end 571 | 572 | function image_iterator() 573 | return image_next, { 574 | length = binary_source_length, 575 | store = instruction_by_address, 576 | label = label_by_address 577 | }, 0 578 | end 579 | end 580 | 581 | print("Disassembling binary...") 582 | local to_disassemble = {} 583 | do 584 | local entry_ords_in = {} 585 | for entry in args_assoc.entry:gmatch("[^,]+") do 586 | local entry_ord = tonumber(entry) 587 | if not entry_ord then 588 | panic("invalid entry ordinal %s", entry) 589 | end 590 | entry_ords_in[entry_ord] = true 591 | end 592 | if args_assoc.complement_entries then 593 | for entry_ord = 1, 127 do 594 | entry_ords_in[entry_ord] = not entry_ords_in[entry_ord] and true or nil 595 | end 596 | end 597 | for entry_ord in next, entry_ords_in do 598 | local address = fetch(math.floor(2 * entry_ord)) 599 | if address % 2 == 0 then 600 | local new_streak = make_streak() 601 | local label_obj = add_label(new_streak, address) 602 | to_disassemble[{0, address, new_streak}] = true 603 | else 604 | printf("ignoring entry %s (%04X)", entry_ord, address) 605 | end 606 | end 607 | end 608 | 609 | local resolve_variable_branch 610 | do 611 | local function prev_instr(instr) 612 | local result = instruction_by_address[bit.band(instr.address, 0xF0000) + bit.band(instr.address - 2, 0xFFFF)] 613 | if not result then 614 | return 615 | end 616 | return result.head or result 617 | end 618 | 619 | local function instruction_match(instr, mnemonic, ...) 620 | if not instr then 621 | return 622 | end 623 | if instr.mnemonic ~= mnemonic then 624 | return 625 | end 626 | return true 627 | end 628 | 629 | function resolve_variable_branch(bl_instr, new_to_disassemble, streak) 630 | --[[ 631 | cmp A, B 632 | cmpc A, B 633 | bc A 634 | b A 635 | ( 636 | cmp A, B 637 | cmpc A, B 638 | bc A 639 | b A 640 | )? 641 | ( 642 | add A, B 643 | addc A, B 644 | )? 645 | sllc A 646 | sll A 647 | l A, (B:)?C[D] 648 | ]] 649 | 650 | local l_instr = prev_instr(bl_instr) 651 | if not instruction_match(l_instr, "l") then 652 | return 653 | end 654 | if l_instr.dsr then 655 | return 656 | end 657 | if not l_instr.params[3] or l_instr.params[3][2] ~= "dlab" then 658 | return 659 | end 660 | local map_base = l_instr.params[3][1].address 661 | 662 | local sll_instr = prev_instr(l_instr) 663 | if not instruction_match(sll_instr, "sll") then 664 | return 665 | end 666 | local sllc_instr = prev_instr(sll_instr) 667 | if not instruction_match(sllc_instr, "sllc") then 668 | return 669 | end 670 | local offset_instr = prev_instr(sllc_instr) 671 | 672 | local offset = 0 673 | 674 | local offset_instr_2 = prev_instr(offset_instr) 675 | if instruction_match(offset_instr, "addc") then 676 | offset = offset + bit.lshift(offset_instr.params[2][1], 8) 677 | else 678 | offset_instr_2 = offset_instr 679 | end 680 | 681 | local branch_4 = prev_instr(offset_instr_2) 682 | if instruction_match(offset_instr_2, "add") then 683 | offset = offset + offset_instr_2.params[2][1] 684 | else 685 | branch_4 = offset_instr_2 686 | end 687 | 688 | local branch_3, branch_1, cmp_1, cmpc_1, cmp_2, cmpc_2 689 | repeat 690 | branch_3 = prev_instr(branch_4) 691 | if not instruction_match(branch_4, "b") then 692 | branch_3 = branch_4 693 | end 694 | if not instruction_match(branch_3, "bc") then 695 | return 696 | end 697 | cmpc_2 = prev_instr(branch_3) 698 | 699 | if not instruction_match(cmpc_2, "cmpc") then 700 | return 701 | end 702 | cmp_2 = prev_instr(cmpc_2) 703 | if not instruction_match(cmp_2, "cmp") then 704 | return 705 | end 706 | local branch_2 = prev_instr(cmp_2) 707 | 708 | branch_1 = prev_instr(branch_2) 709 | if not instruction_match(branch_2, "b") then 710 | branch_1 = branch_2 711 | end 712 | if not instruction_match(branch_1, "bc") then 713 | break 714 | end 715 | if branch_1.params[1][1] > 3 then 716 | break 717 | end 718 | cmpc_1 = prev_instr(branch_1) 719 | 720 | if not instruction_match(cmpc_1, "cmpc") then 721 | return 722 | end 723 | cmp_1 = prev_instr(cmpc_1) 724 | if not instruction_match(cmp_1, "cmp") then 725 | return 726 | end 727 | until true 728 | 729 | local cmp_value, cmp_cond = {}, {} 730 | if cmp_1 then 731 | cmp_value[1] = cmp_1.params[2][1] + bit.lshift(cmpc_1.params[2][1], 8) 732 | cmp_cond[1] = branch_1.params[1][1] 733 | end 734 | cmp_value[2] = cmp_2.params[2][1] + bit.lshift(cmpc_2.params[2][1], 8) 735 | cmp_cond[2] = branch_3.params[1][1] 736 | 737 | local min, max 738 | for ix = 1, 2 do 739 | if cmp_cond[ix] then 740 | if cmp_cond[ix] == 0 then 741 | min = cmp_value[ix] 742 | end 743 | if cmp_cond[ix] == 1 then 744 | max = cmp_value[ix] - 1 745 | end 746 | if cmp_cond[ix] == 2 then 747 | min = cmp_value[ix] + 1 748 | end 749 | if cmp_cond[ix] == 3 then 750 | max = cmp_value[ix] 751 | end 752 | end 753 | end 754 | 755 | if not max and min then 756 | max = min - 1 757 | min = 0 758 | end 759 | if not min and max then 760 | min = 0 761 | end 762 | 763 | if not min or not max then 764 | printf("fail %05X", bl_instr.address) 765 | return 766 | end 767 | min = min + offset 768 | max = max + offset 769 | 770 | if max < min then 771 | min, max = max + 1, min - 1 772 | end 773 | 774 | min, max = bit.band(min, 0xFFFF), bit.band(max, 0xFFFF) 775 | 776 | add_comment(bl_instr.address, "Jump table") 777 | local td_segment = bit.band(bl_instr.address, 0xF0000) 778 | for ix = min, max do 779 | local td_address = fetch(bit.band(map_base + ix * 2, 0xFFFF)) 780 | new_to_disassemble[{td_segment, td_address, streak}] = true 781 | local label_obj = add_label(streak, td_segment + td_address, bl_instr) 782 | add_jt_comment(bl_instr.address, ix, label_obj) 783 | end 784 | 785 | return true 786 | end 787 | end 788 | 789 | while next(to_disassemble) do 790 | local variable_branches = {} 791 | while next(to_disassemble) do 792 | local new_to_disassemble = {} 793 | for address_tuple in next, to_disassemble do 794 | local segment, address, streak = unpack(address_tuple) 795 | if segment + address >= binary_source_length then 796 | panic2("runloop: out of data at %01X:%04X", bit.rshift(segment, 16), address) 797 | break 798 | end 799 | while true do 800 | local instr, seen = disassemble(segment, address) 801 | if seen then 802 | break 803 | end 804 | if instr.mnemonic == "?" then 805 | panic2("runloop: unknown instruction at %01X:%04X", bit.rshift(segment, 16), address) 806 | break 807 | end 808 | address = bit.band(address + instr.length, 0xFFFF) 809 | if instr.mnemonic == "rt" 810 | or instr.mnemonic == "rti" 811 | or (instr.mnemonic == "pop" and ( 812 | (instr.params[1] and instr.params[1][2] == "pc") or 813 | (instr.params[2] and instr.params[2][2] == "pc") or 814 | (instr.params[3] and instr.params[3][2] == "pc") or 815 | (instr.params[4] and instr.params[4][2] == "pc") 816 | )) then 817 | instr.break_streak = true 818 | end 819 | if instr.mnemonic == "bc" then 820 | local td_segment = segment 821 | local td_address = bit.band(address + instr.params[2][1] * 2, 0xFFFF) 822 | local label_obj = add_label(streak, td_segment + td_address, instr) 823 | new_to_disassemble[{td_segment, td_address, streak}] = true 824 | instr.params[2] = {label_obj, "lab"} 825 | if instr.params[1][1] == 0x000E then 826 | instr.break_streak = true 827 | end 828 | end 829 | if instr.mnemonic == "b" or instr.mnemonic == "bl" then 830 | if instr.params[1][2] == "im" then 831 | local td_segment = bit.lshift(instr.params[1][1], 16) 832 | local td_address = instr.params[2][1] 833 | local new_streak = make_streak() 834 | local label_obj = add_label(new_streak, td_segment + td_address, instr) 835 | new_to_disassemble[{td_segment, td_address, new_streak}] = true 836 | instr.params[2] = nil 837 | instr.params[1] = {label_obj, "lab"} 838 | else 839 | variable_branches[instr] = streak 840 | end 841 | if instr.mnemonic == "b" then 842 | instr.break_streak = true 843 | end 844 | end 845 | if (instr.mnemonic == "l" 846 | or instr.mnemonic == "st" 847 | or instr.mnemonic == "lea" 848 | or instr.mnemonic == "sb" 849 | or instr.mnemonic == "tb" 850 | or instr.mnemonic == "rb") 851 | and (not instr.dsr or (instr.dsr and instr.dsr[2] == "im")) then 852 | local td_segment = instr.dsr and instr.dsr[1] or 0 853 | for ix = 1, #instr.params do 854 | if instr.params[ix][2] == "im" and instr.params[ix][1] >= 0x100 and instr.params[ix][1] < 0xFF00 then 855 | local td_address = instr.params[ix][1] 856 | local label_obj = add_data_label(td_segment + td_address, instr) 857 | instr.params[ix] = {label_obj, "dlab"} 858 | end 859 | end 860 | end 861 | if instr.break_streak then 862 | break 863 | end 864 | end 865 | end 866 | to_disassemble = new_to_disassemble 867 | end 868 | 869 | for instr, streak in next, variable_branches do 870 | local segment = bit.band(instr.address, 0xF0000) 871 | local address = bit.band(instr.address, 0xFFFF) 872 | if not resolve_variable_branch(instr, to_disassemble, streak) then 873 | printf("runloop: failed to resolve variable branch at %01X:%04X", bit.rshift(segment, 16), address) 874 | add_comment(instr.address, "Failed to resolve variable branch") 875 | end 876 | end 877 | end 878 | print(" Done.") 879 | 880 | print("Discovering contexts...") 881 | do 882 | local function make_streak_friends(one, other) 883 | if other.streak ~= one.streak then 884 | one.streak.friends[other.streak] = true 885 | other.streak.friends[one.streak] = true 886 | end 887 | end 888 | 889 | local streaks = {} 890 | local last_label 891 | for next_address, address, instr, label_obj in image_iterator() do 892 | if instr and label_obj then 893 | if last_label then 894 | make_streak_friends(last_label, label_obj) 895 | end 896 | last_label = label_obj 897 | streaks[last_label.streak] = true 898 | end 899 | if instr then 900 | if instr.mnemonic == "bc" or (instr.mnemonic == "b" and instr.params[1][2] == "lab") then 901 | local other_label_obj = instr.params[2] and instr.params[2][1] or instr.params[1][1] 902 | make_streak_friends(other_label_obj, last_label) 903 | end 904 | if instr.break_streak then 905 | last_label = nil 906 | end 907 | end 908 | end 909 | for streak in next, streaks do 910 | if not streak.seen then 911 | local friend_streaks = {} 912 | local streaks_to_check = {[streak] = true} 913 | streak.seen = true 914 | while next(streaks_to_check) do 915 | local new_streaks_to_check = {} 916 | for next_streak in next, streaks_to_check do 917 | friend_streaks[next_streak] = true 918 | for friend_streak in next, next_streak.friends do 919 | if not friend_streak.seen then 920 | new_streaks_to_check[friend_streak] = true 921 | friend_streak.seen = true 922 | end 923 | end 924 | end 925 | streaks_to_check = new_streaks_to_check 926 | end 927 | local new_context = {} 928 | for streak in next, friend_streaks do 929 | streak.context = new_context 930 | end 931 | end 932 | end 933 | end 934 | for next_address, address, instr, label in image_iterator() do 935 | if instr and label then 936 | label.context = label.streak.context 937 | label.streak = nil 938 | end 939 | end 940 | do 941 | local contexts_seen = {} 942 | local rewrite_from, rewrite_to 943 | local last_label 944 | for next_address, address, instr, label in image_iterator() do 945 | if instr and label then 946 | if last_label and label.context ~= last_label.context and contexts_seen[label.context] then 947 | if label.context ~= rewrite_from then 948 | rewrite_from, rewrite_to = label.context, {} 949 | end 950 | label.context = rewrite_to 951 | else 952 | rewrite_from = nil 953 | end 954 | contexts_seen[label.context] = true 955 | last_label = label 956 | end 957 | end 958 | end 959 | do 960 | local last_label 961 | for next_address, address, instr, label in image_iterator() do 962 | if instr and label then 963 | last_label = label 964 | if label.context.name then 965 | label.name = LOCAL_LABEL_FORMAT:format(label.address - label.context.head.address) 966 | else 967 | label.context.name = label.name 968 | label.context.head = label 969 | label.context_head = true 970 | end 971 | end 972 | if instr then 973 | instr.context = last_label.context 974 | instr.under_label = last_label 975 | end 976 | end 977 | for address, datalabel in next, datalabel_by_address do 978 | if address >= 0x10000 or address < args_assoc.rom_window then 979 | local instr = instruction_by_address[address] 980 | instr = instr and instr.head or instr 981 | if instr then 982 | datalabel.ref_instr = instr 983 | printf("context: warning: data label pointing into code at %01X:%04X", bit.rshift(address, 16), bit.band(address, 0xFFFF)) 984 | end 985 | end 986 | end 987 | end 988 | print(" Done.") 989 | 990 | if args_assoc.names then 991 | print("Renaming labels...") 992 | local handle = io.open(args_assoc.names, "r") 993 | if not handle then 994 | panic("Failed to open \"%s\"", args_assoc.names) 995 | end 996 | local name_content = handle:read("*a") 997 | handle:close() 998 | local raw_to_real = {} 999 | local last_global_label 1000 | for line in name_content:gmatch("[^\n]+") do 1001 | local raw, real = line:match("([%w_%.]+)%s+([%w_%.]+)") 1002 | if raw then 1003 | if raw:find("^%.") then 1004 | if not last_global_label then 1005 | panic("rename: fix that rename list pls") 1006 | end 1007 | raw_to_real[last_global_label .. raw] = real 1008 | else 1009 | last_global_label = raw 1010 | raw_to_real[raw] = real 1011 | end 1012 | end 1013 | end 1014 | for address, label in next, label_by_address do 1015 | local raw = label.name:find("^%.") and (label.context.name .. label.name) or label.name 1016 | local real = raw_to_real[raw] 1017 | if real then 1018 | label.name = real 1019 | end 1020 | end 1021 | for address, datalabel in next, datalabel_by_address do 1022 | local raw = datalabel.name 1023 | local real = raw_to_real[raw] 1024 | if real then 1025 | datalabel.name = real 1026 | end 1027 | end 1028 | print(" Done.") 1029 | end 1030 | 1031 | print("Writing disassembly...") 1032 | local handle = io.open(args_assoc.output, "w") 1033 | if not handle then 1034 | panic("Failed to open \"%s\"", args_assoc.output) 1035 | end 1036 | do 1037 | local last_instr 1038 | for next_address, address, instr, label in image_iterator() do 1039 | local instr = instruction_by_address[address] 1040 | if ((not last_instr) ~= (not instr)) or (last_instr and instr and last_instr.context ~= instr.context) then 1041 | handle:write("\n\n\n") 1042 | end 1043 | 1044 | local comments = comments_by_address[address] 1045 | if comments then 1046 | for ix = 1, #comments do 1047 | handle:write("; ") 1048 | if comments[ix].type == "jt" then 1049 | handle:write((" %4i | %s"):format(comments[ix].ix, formats.lab:format(comments[ix].label, instr))) 1050 | else 1051 | handle:write(comments[ix]) 1052 | end 1053 | handle:write("\n") 1054 | end 1055 | end 1056 | if label then 1057 | handle:write(("%s:\n"):format(label.name)) 1058 | end 1059 | 1060 | local out_head = {} 1061 | local out_body = {} 1062 | local out_tail 1063 | if args_assoc.addresses then 1064 | out_tail = {("; %05X |"):format(address)} 1065 | end 1066 | 1067 | if instr then 1068 | table.insert(out_head, instr.mnemonic) 1069 | for ix = 1, #instr.params do 1070 | if instr.offsetable ~= 0 and instr.offsetable == ix - 1 and (instr.params[ix][2] == "dlab" or instr.params[ix][2] == "im") then 1071 | if instr.params[ix][2] == "im" and instr.params[ix][1] >= 0xFF00 then 1072 | instr.params[ix][1] = instr.params[ix][1] - 0x10000 1073 | end 1074 | out_body[#out_body] = out_body[#out_body]:gsub("%[", formats[instr.params[ix][2]]:format(instr.params[ix][1], instr) .. "[") 1075 | else 1076 | local paramtbl = {} 1077 | if instr.offsetable == ix then 1078 | if instr.dsr then 1079 | table.insert(paramtbl, formats[instr.dsr[2]]:format(instr.dsr[1], instr)) 1080 | table.insert(paramtbl, ":") 1081 | end 1082 | table.insert(paramtbl, "[") 1083 | end 1084 | table.insert(paramtbl, formats[instr.params[ix][2]]:format(instr.params[ix][1], instr)) 1085 | if instr.offsetable == ix then 1086 | table.insert(paramtbl, "]") 1087 | end 1088 | table.insert(out_body, table.concat(paramtbl)) 1089 | end 1090 | end 1091 | if args_assoc.addresses then 1092 | for ix = 1, instr.length / 2 do 1093 | table.insert(out_tail, ("%04X"):format(instr.opcode[ix])) 1094 | end 1095 | end 1096 | else 1097 | if address >= 0x10000 or address < args_assoc.rom_window then 1098 | local datalabel = datalabel_by_address[address] 1099 | if datalabel then 1100 | handle:write(("%s:\n"):format(datalabel.name)) 1101 | end 1102 | end 1103 | table.insert(out_head, "dw") 1104 | local data = fetch(address) 1105 | table.insert(out_body, ("0x%04X"):format(data)) 1106 | if args_assoc.addresses then 1107 | table.insert(out_tail, ("%04X"):format(data)) 1108 | end 1109 | end 1110 | 1111 | table.insert(out_head, table.concat(out_body, ", ")) 1112 | 1113 | if args_assoc.addresses then 1114 | handle:write(("\t%-30s %s\n"):format( 1115 | table.concat(out_head, " "), 1116 | table.concat(out_tail, " ") 1117 | )) 1118 | else 1119 | handle:write(("\t%s\n"):format( 1120 | table.concat(out_head, " ") 1121 | )) 1122 | end 1123 | 1124 | 1125 | last_instr = instr 1126 | end 1127 | end 1128 | handle:close() 1129 | print(" Done.") 1130 | 1131 | 1132 | 1133 | 1134 | -------------------------------------------------------------------------------- /emulator/README.md: -------------------------------------------------------------------------------- 1 | # Emulator 2 | 3 | Assuming your current directory is this one, you have 4 | [meson](https://mesonbuild.com/) and [ninja](https://ninja-build.org/) installed 5 | and you have the proper ROM in `../../models/fx570esplus`: 6 | 7 | ``` 8 | $ meson build && cd build 9 | $ meson configure -Dwerror=true -Dwarning_level=3 -Dcpp_std=c++11 10 | $ ninja 11 | $ ./emulator ../../models/fx570esplus 12 | ``` 13 | 14 | Unlike the previous, terrible excuse of a build system, this one is likely to 15 | work well on platforms other than unices with coreutils and other shady stuff 16 | installed. 17 | -------------------------------------------------------------------------------- /emulator/meson.build: -------------------------------------------------------------------------------- 1 | project('emulator', 'cpp', version: '1.0.0') 2 | 3 | executable('emulator', sources: [ 4 | 'src/Logger.cpp', 5 | 'src/Peripheral/ROMWindow.cpp', 6 | 'src/Peripheral/Timer.cpp', 7 | 'src/Peripheral/Screen.cpp', 8 | 'src/Peripheral/StandbyControl.cpp', 9 | 'src/Peripheral/Keyboard.cpp', 10 | 'src/Peripheral/Miscellaneous.cpp', 11 | 'src/Peripheral/Peripheral.cpp', 12 | 'src/Peripheral/BatteryBackedRAM.cpp', 13 | 'src/Data/ModelInfo.cpp', 14 | 'src/casioemu.cpp', 15 | 'src/Emulator.cpp', 16 | 'src/Chipset/CPUPushPop.cpp', 17 | 'src/Chipset/CPU.cpp', 18 | 'src/Chipset/InterruptSource.cpp', 19 | 'src/Chipset/Chipset.cpp', 20 | 'src/Chipset/CPUArithmetic.cpp', 21 | 'src/Chipset/MMU.cpp', 22 | 'src/Chipset/CPUControl.cpp', 23 | 'src/Chipset/MMURegion.cpp', 24 | 'src/Chipset/CPULoadStore.cpp', 25 | ], dependencies: [ 26 | dependency('threads'), 27 | dependency('SDL2'), 28 | dependency('SDL2_image'), 29 | dependency('lua53'), 30 | ]) 31 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPU.cpp: -------------------------------------------------------------------------------- 1 | #include "CPU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | #include "../Logger.hpp" 7 | 8 | #include 9 | 10 | namespace casioemu 11 | { 12 | CPU::OpcodeSource CPU::opcode_sources[] = { 13 | // function, hints, main mask, operand {size, mask, shift} x2 14 | // * Arithmetic Instructions 15 | {&CPU::OP_ADD , H_WB , 0x8001, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 16 | {&CPU::OP_ADD , H_WB , 0x1000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 17 | {&CPU::OP_ADD16 , H_WB , 0xF006, {{2, 0x000E, 8}, {2, 0x000E, 4}}}, 18 | {&CPU::OP_ADD16 , H_WB | H_IE, 0xE080, {{2, 0x000E, 8}, {0, 0x007F, 0}}}, 19 | {&CPU::OP_ADDC , H_WB , 0x8006, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 20 | {&CPU::OP_ADDC , H_WB , 0x6000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 21 | {&CPU::OP_AND , H_WB , 0x8002, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 22 | {&CPU::OP_AND , H_WB , 0x2000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 23 | {&CPU::OP_SUB , 0, 0x8007, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 24 | {&CPU::OP_SUB , 0, 0x7000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 25 | {&CPU::OP_SUBC , 0, 0x8005, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 26 | {&CPU::OP_SUBC , 0, 0x5000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 27 | {&CPU::OP_MOV16 , H_WB , 0xF005, {{2, 0x000E, 8}, {2, 0x000E, 4}}}, 28 | {&CPU::OP_MOV16 , H_WB | H_IE, 0xE000, {{2, 0x000E, 8}, {0, 0x007F, 0}}}, 29 | {&CPU::OP_MOV , H_WB , 0x8000, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 30 | {&CPU::OP_MOV , H_WB , 0x0000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 31 | {&CPU::OP_OR , H_WB , 0x8003, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 32 | {&CPU::OP_OR , H_WB , 0x3000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 33 | {&CPU::OP_XOR , H_WB , 0x8004, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 34 | {&CPU::OP_XOR , H_WB , 0x4000, {{1, 0x000F, 8}, {0, 0x00FF, 0}}}, 35 | {&CPU::OP_CMP16 , 0, 0xF007, {{2, 0x000E, 8}, {2, 0x000E, 4}}}, 36 | {&CPU::OP_SUB , H_WB , 0x8008, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 37 | {&CPU::OP_SUBC , H_WB , 0x8009, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 38 | // * Shift Instructions 39 | {&CPU::OP_SLL , H_WB , 0x800A, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 40 | {&CPU::OP_SLL , H_WB , 0x900A, {{1, 0x000F, 8}, {0, 0x0007, 4}}}, 41 | {&CPU::OP_SLLC , H_WB , 0x800B, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 42 | {&CPU::OP_SLLC , H_WB , 0x900B, {{1, 0x000F, 8}, {0, 0x0007, 4}}}, 43 | {&CPU::OP_SRA , H_WB , 0x800E, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 44 | {&CPU::OP_SRA , H_WB , 0x900E, {{1, 0x000F, 8}, {0, 0x0007, 4}}}, 45 | {&CPU::OP_SRL , H_WB , 0x800C, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 46 | {&CPU::OP_SRL , H_WB , 0x900C, {{1, 0x000F, 8}, {0, 0x0007, 4}}}, 47 | {&CPU::OP_SRLC , H_WB , 0x800D, {{1, 0x000F, 8}, {1, 0x000F, 4}}}, 48 | {&CPU::OP_SRLC , H_WB , 0x900D, {{1, 0x000F, 8}, {0, 0x0007, 4}}}, 49 | // * Load/Store Instructions 50 | {&CPU::OP_LS_EA , 2 << 8 , 0x9032, {{0, 0x000E, 8}, {0, 0, 0}}}, 51 | {&CPU::OP_LS_EA , 2 << 8 | H_IA , 0x9052, {{0, 0x000E, 8}, {0, 0, 0}}}, 52 | {&CPU::OP_LS_R , 2 << 8 , 0x9002, {{0, 0x000E, 8}, {2, 0x000E, 4}}}, 53 | {&CPU::OP_LS_I_R , 2 << 8 | H_TI , 0xA008, {{0, 0x000E, 8}, {2, 0x000E, 4}}}, 54 | {&CPU::OP_LS_BP , 2 << 8 | 0, 0xB000, {{0, 0x000E, 8}, {0, 0x003F, 0}}}, 55 | {&CPU::OP_LS_FP , 2 << 8 | 0, 0xB040, {{0, 0x000E, 8}, {0, 0x003F, 0}}}, 56 | {&CPU::OP_LS_I , 2 << 8 | H_TI , 0x9012, {{0, 0x000E, 8}, {0, 0, 0}}}, 57 | {&CPU::OP_LS_EA , 1 << 8 , 0x9030, {{0, 0x000F, 8}, {0, 0, 0}}}, 58 | {&CPU::OP_LS_EA , 1 << 8 | H_IA , 0x9050, {{0, 0x000F, 8}, {0, 0, 0}}}, 59 | {&CPU::OP_LS_R , 1 << 8 , 0x9000, {{0, 0x000F, 8}, {2, 0x000E, 4}}}, 60 | {&CPU::OP_LS_I_R , 1 << 8 | H_TI , 0x9008, {{0, 0x000F, 8}, {2, 0x000E, 4}}}, 61 | {&CPU::OP_LS_BP , 1 << 8 | 0, 0xD000, {{0, 0x000F, 8}, {0, 0x003F, 0}}}, 62 | {&CPU::OP_LS_FP , 1 << 8 | 0, 0xD040, {{0, 0x000F, 8}, {0, 0x003F, 0}}}, 63 | {&CPU::OP_LS_I , 1 << 8 | H_TI , 0x9010, {{0, 0x000F, 8}, {0, 0, 0}}}, 64 | {&CPU::OP_LS_EA , 4 << 8 , 0x9034, {{0, 0x000C, 8}, {0, 0, 0}}}, 65 | {&CPU::OP_LS_EA , 4 << 8 | H_IA , 0x9054, {{0, 0x000C, 8}, {0, 0, 0}}}, 66 | {&CPU::OP_LS_EA , 8 << 8 , 0x9036, {{0, 0x0008, 8}, {0, 0, 0}}}, 67 | {&CPU::OP_LS_EA , 8 << 8 | H_IA , 0x9056, {{0, 0x0008, 8}, {0, 0, 0}}}, 68 | {&CPU::OP_LS_EA , 2 << 8 | H_ST, 0x9033, {{0, 0x000E, 8}, {0, 0, 0}}}, 69 | {&CPU::OP_LS_EA , 2 << 8 | H_IA | H_ST, 0x9053, {{0, 0x000E, 8}, {0, 0, 0}}}, 70 | {&CPU::OP_LS_R , 2 << 8 | H_ST, 0x9003, {{0, 0x000E, 8}, {2, 0x000E, 4}}}, 71 | {&CPU::OP_LS_I_R , 2 << 8 | H_TI | H_ST, 0xA009, {{0, 0x000E, 8}, {2, 0x000E, 4}}}, 72 | {&CPU::OP_LS_BP , 2 << 8 | H_ST, 0xB080, {{0, 0x000E, 8}, {0, 0x003F, 0}}}, 73 | {&CPU::OP_LS_FP , 2 << 8 | H_ST, 0xB0C0, {{0, 0x000E, 8}, {0, 0x003F, 0}}}, 74 | {&CPU::OP_LS_I , 2 << 8 | H_TI | H_ST, 0x9013, {{0, 0x000E, 8}, {0, 0, 0}}}, 75 | {&CPU::OP_LS_EA , 1 << 8 | H_ST, 0x9031, {{0, 0x000F, 8}, {0, 0, 0}}}, 76 | {&CPU::OP_LS_EA , 1 << 8 | H_IA | H_ST, 0x9051, {{0, 0x000F, 8}, {0, 0, 0}}}, 77 | {&CPU::OP_LS_R , 1 << 8 | H_ST, 0x9001, {{0, 0x000F, 8}, {2, 0x000E, 4}}}, 78 | {&CPU::OP_LS_I_R , 1 << 8 | H_TI | H_ST, 0x9009, {{0, 0x000F, 8}, {2, 0x000E, 4}}}, 79 | {&CPU::OP_LS_BP , 1 << 8 | H_ST, 0xD080, {{0, 0x000F, 8}, {0, 0x003F, 0}}}, 80 | {&CPU::OP_LS_FP , 1 << 8 | H_ST, 0xD0C0, {{0, 0x000F, 8}, {0, 0x003F, 0}}}, 81 | {&CPU::OP_LS_I , 1 << 8 | H_TI | H_ST, 0x9011, {{0, 0x000F, 8}, {0, 0, 0}}}, 82 | {&CPU::OP_LS_EA , 4 << 8 | H_ST, 0x9035, {{0, 0x000C, 8}, {0, 0, 0}}}, 83 | {&CPU::OP_LS_EA , 4 << 8 | H_IA | H_ST, 0x9055, {{0, 0x000C, 8}, {0, 0, 0}}}, 84 | {&CPU::OP_LS_EA , 8 << 8 | H_ST, 0x9037, {{0, 0x0008, 8}, {0, 0, 0}}}, 85 | {&CPU::OP_LS_EA , 8 << 8 | H_IA | H_ST, 0x9057, {{0, 0x0008, 8}, {0, 0, 0}}}, 86 | // * Control Register Access Instructions 87 | {&CPU::OP_ADDSP , 0, 0xE100, {{0, 0x00FF, 0}, {0, 0, 0}}}, 88 | {&CPU::OP_CTRL , 1 << 8, 0xA00F, {{0, 0, 0}, {1, 0x000F, 4}}}, 89 | {&CPU::OP_CTRL , 2 << 8, 0xA00D, {{0, 0, 0}, {2, 0x000E, 8}}}, 90 | {&CPU::OP_CTRL , 3 << 8, 0xA00C, {{0, 0, 0}, {1, 0x000F, 4}}}, 91 | {&CPU::OP_CTRL , H_WB | 4 << 8, 0xA005, {{2, 0x000E, 8}, {0, 0, 0}}}, 92 | {&CPU::OP_CTRL , H_WB | 5 << 8, 0xA01A, {{2, 0x000E, 8}, {0, 0, 0}}}, 93 | {&CPU::OP_CTRL , 6 << 8, 0xA00B, {{0, 0, 0}, {1, 0x000F, 4}}}, 94 | {&CPU::OP_CTRL , 7 << 8, 0xE900, {{0, 0, 0}, {0, 0x00FF, 0}}}, 95 | {&CPU::OP_CTRL , H_WB | 8 << 8, 0xA007, {{1, 0x000F, 8}, {0, 0, 0}}}, 96 | {&CPU::OP_CTRL , H_WB | 9 << 8, 0xA004, {{1, 0x000F, 8}, {0, 0, 0}}}, 97 | {&CPU::OP_CTRL , H_WB | 10 << 8, 0xA003, {{1, 0x000F, 8}, {0, 0, 0}}}, 98 | {&CPU::OP_CTRL , 11 << 8, 0xA10A, {{0, 0, 0}, {2, 0x000E, 4}}}, 99 | // * PUSH/POP Instructions 100 | {&CPU::OP_PUSH , 0, 0xF05E, {{0, 0, 0}, {2, 0x000E, 8}}}, 101 | {&CPU::OP_PUSH , 0, 0xF07E, {{0, 0, 0}, {8, 0x0008, 8}}}, 102 | {&CPU::OP_PUSH , 0, 0xF04E, {{0, 0, 0}, {1, 0x000F, 8}}}, 103 | {&CPU::OP_PUSH , 0, 0xF06E, {{0, 0, 0}, {4, 0x000C, 8}}}, 104 | {&CPU::OP_PUSHL , 0, 0xF0CE, {{0, 0, 0}, {0, 0x000F, 8}}}, 105 | {&CPU::OP_POP , H_WB , 0xF01E, {{2, 0x000E, 8}, {0, 0, 0}}}, 106 | {&CPU::OP_POP , H_WB , 0xF03E, {{8, 0x0008, 8}, {0, 0, 0}}}, 107 | {&CPU::OP_POP , H_WB , 0xF00E, {{1, 0x000F, 8}, {0, 0, 0}}}, 108 | {&CPU::OP_POP , H_WB , 0xF02E, {{4, 0x000C, 8}, {0, 0, 0}}}, 109 | {&CPU::OP_POPL , 0, 0xF08E, {{0, 0x000F, 8}, {0, 0, 0}}}, 110 | // * Coprocessor Data Transfer Instructions 111 | {&CPU::OP_CR_R , 0, 0xA00E, {{0, 0x000F, 8}, {0, 0x000F, 4}}}, 112 | {&CPU::OP_CR_EA , 2 << 8 | 0, 0xF02D, {{0, 0, 0}, {0, 0x000E, 8}}}, 113 | {&CPU::OP_CR_EA , 2 << 8 | H_IA , 0xF03D, {{0, 0, 0}, {0, 0x000E, 8}}}, 114 | {&CPU::OP_CR_EA , 1 << 8 | 0, 0xF00D, {{0, 0, 0}, {0, 0x000F, 8}}}, 115 | {&CPU::OP_CR_EA , 1 << 8 | H_IA , 0xF01D, {{0, 0, 0}, {0, 0x000F, 8}}}, 116 | {&CPU::OP_CR_EA , 4 << 8 | 0, 0xF04D, {{0, 0, 0}, {0, 0x000C, 8}}}, 117 | {&CPU::OP_CR_EA , 4 << 8 | H_IA , 0xF05D, {{0, 0, 0}, {0, 0x000C, 8}}}, 118 | {&CPU::OP_CR_EA , 8 << 8 | 0, 0xF06D, {{0, 0, 0}, {0, 0x0008, 8}}}, 119 | {&CPU::OP_CR_EA , 8 << 8 | H_IA , 0xF07D, {{0, 0, 0}, {0, 0x0008, 8}}}, 120 | {&CPU::OP_CR_R , H_ST, 0xA006, {{0, 0x000F, 8}, {0, 0x000F, 4}}}, 121 | {&CPU::OP_CR_EA , 2 << 8 | H_ST, 0xF0AD, {{0, 0x000E, 8}, {0, 0, 0}}}, 122 | {&CPU::OP_CR_EA , 2 << 8 | H_IA | H_ST, 0xF0BD, {{0, 0x000E, 8}, {0, 0, 0}}}, 123 | {&CPU::OP_CR_EA , 1 << 8 | H_ST, 0xF08D, {{0, 0x000F, 8}, {0, 0, 0}}}, 124 | {&CPU::OP_CR_EA , 1 << 8 | H_IA | H_ST, 0xF09D, {{0, 0x000F, 8}, {0, 0, 0}}}, 125 | {&CPU::OP_CR_EA , 4 << 8 | H_ST, 0xF0CD, {{0, 0x000C, 8}, {0, 0, 0}}}, 126 | {&CPU::OP_CR_EA , 4 << 8 | H_IA | H_ST, 0xF0DD, {{0, 0x000C, 8}, {0, 0, 0}}}, 127 | {&CPU::OP_CR_EA , 8 << 8 | H_ST, 0xF0ED, {{0, 0x0008, 8}, {0, 0, 0}}}, 128 | {&CPU::OP_CR_EA , 8 << 8 | H_IA | H_ST, 0xF0FD, {{0, 0x0008, 8}, {0, 0, 0}}}, 129 | // * EA Register Data Transfer Instructions 130 | {&CPU::OP_LEA , 0, 0xF00A, {{0, 0, 0}, {2, 0x000E, 4}}}, 131 | {&CPU::OP_LEA , H_TI , 0xF00B, {{0, 0, 0}, {2, 0x000E, 4}}}, 132 | {&CPU::OP_LEA , H_TI , 0xF00C, {{0, 0, 0}, {0, 0, 0}}}, 133 | // * ALU Instructions 134 | {&CPU::OP_DAA , H_WB , 0x801F, {{1, 0x000F, 8}, {0, 0, 0}}}, 135 | {&CPU::OP_DAS , H_WB , 0x803F, {{1, 0x000F, 8}, {0, 0, 0}}}, 136 | {&CPU::OP_NEG , H_WB , 0x805F, {{1, 0x000F, 8}, {0, 0, 0}}}, 137 | // * Bit Access Instructions 138 | {&CPU::OP_BITMOD , 0, 0xA000, {{0, 0x000F, 8}, {0, 0x0007, 4}}}, 139 | {&CPU::OP_BITMOD , H_TI , 0xA080, {{0, 0, 0}, {0, 0x0007, 4}}}, 140 | {&CPU::OP_BITMOD , 0, 0xA002, {{0, 0x000F, 8}, {0, 0x0007, 4}}}, 141 | {&CPU::OP_BITMOD , H_TI , 0xA082, {{0, 0, 0}, {0, 0x0007, 4}}}, 142 | {&CPU::OP_BITMOD , 0, 0xA001, {{0, 0x000F, 8}, {0, 0x0007, 4}}}, 143 | {&CPU::OP_BITMOD , H_TI , 0xA081, {{0, 0, 0}, {0, 0x0007, 4}}}, 144 | // * PSW Access Instructions 145 | {&CPU::OP_PSW_OR , 0, 0xED08, {{0, 0, 0}, {0, 0, 0}}}, 146 | {&CPU::OP_PSW_AND , 0, 0xEBF7, {{0, 0, 0}, {0, 0, 0}}}, 147 | {&CPU::OP_PSW_OR , 0, 0xED80, {{0, 0, 0}, {0, 0, 0}}}, 148 | {&CPU::OP_PSW_AND , 0, 0xEB7F, {{0, 0, 0}, {0, 0, 0}}}, 149 | {&CPU::OP_CPLC , 0, 0xFECF, {{0, 0, 0}, {0, 0, 0}}}, 150 | // * Conditional Relative Branch Instructions 151 | {&CPU::OP_BC , 0, 0xC000, {{0, 0x00FF, 0}, {0, 0, 0}}}, 152 | {&CPU::OP_BC , 0, 0xC100, {{0, 0x00FF, 0}, {0, 0, 0}}}, 153 | {&CPU::OP_BC , 0, 0xC200, {{0, 0x00FF, 0}, {0, 0, 0}}}, 154 | {&CPU::OP_BC , 0, 0xC300, {{0, 0x00FF, 0}, {0, 0, 0}}}, 155 | {&CPU::OP_BC , 0, 0xC400, {{0, 0x00FF, 0}, {0, 0, 0}}}, 156 | {&CPU::OP_BC , 0, 0xC500, {{0, 0x00FF, 0}, {0, 0, 0}}}, 157 | {&CPU::OP_BC , 0, 0xC600, {{0, 0x00FF, 0}, {0, 0, 0}}}, 158 | {&CPU::OP_BC , 0, 0xC700, {{0, 0x00FF, 0}, {0, 0, 0}}}, 159 | {&CPU::OP_BC , 0, 0xC800, {{0, 0x00FF, 0}, {0, 0, 0}}}, 160 | {&CPU::OP_BC , 0, 0xC900, {{0, 0x00FF, 0}, {0, 0, 0}}}, 161 | {&CPU::OP_BC , 0, 0xCA00, {{0, 0x00FF, 0}, {0, 0, 0}}}, 162 | {&CPU::OP_BC , 0, 0xCB00, {{0, 0x00FF, 0}, {0, 0, 0}}}, 163 | {&CPU::OP_BC , 0, 0xCC00, {{0, 0x00FF, 0}, {0, 0, 0}}}, 164 | {&CPU::OP_BC , 0, 0xCD00, {{0, 0x00FF, 0}, {0, 0, 0}}}, 165 | {&CPU::OP_BC , 0, 0xCE00, {{0, 0x00FF, 0}, {0, 0, 0}}}, 166 | // * Sign Extension Instruction 167 | {&CPU::OP_EXTBW , 0, 0x810F, {{0, 0, 0}, {0, 0, 0}}}, 168 | {&CPU::OP_EXTBW , 0, 0x832F, {{0, 0, 0}, {0, 0, 0}}}, 169 | {&CPU::OP_EXTBW , 0, 0x854F, {{0, 0, 0}, {0, 0, 0}}}, 170 | {&CPU::OP_EXTBW , 0, 0x876F, {{0, 0, 0}, {0, 0, 0}}}, 171 | {&CPU::OP_EXTBW , 0, 0x898F, {{0, 0, 0}, {0, 0, 0}}}, 172 | {&CPU::OP_EXTBW , 0, 0x8BAF, {{0, 0, 0}, {0, 0, 0}}}, 173 | {&CPU::OP_EXTBW , 0, 0x8DCF, {{0, 0, 0}, {0, 0, 0}}}, 174 | {&CPU::OP_EXTBW , 0, 0x8FEF, {{0, 0, 0}, {0, 0, 0}}}, 175 | // * Software Interrupt Instructions 176 | {&CPU::OP_SWI , 0, 0xE500, {{0, 0x003F, 0}, {0, 0, 0}}}, 177 | {&CPU::OP_BRK , 0, 0xFFFF, {{0, 0, 0}, {0, 0, 0}}}, 178 | // * Branch Instructions 179 | {&CPU::OP_B , H_TI , 0xF000, {{0, 0, 0}, {0, 0x000F, 8}}}, 180 | {&CPU::OP_B , 0, 0xF002, {{0, 0, 0}, {2, 0x000E, 4}}}, 181 | {&CPU::OP_BL , H_TI , 0xF001, {{0, 0, 0}, {0, 0x000F, 8}}}, 182 | {&CPU::OP_BL , 0, 0xF003, {{0, 0, 0}, {2, 0x000E, 4}}}, 183 | // * Multiplication and Division Instructions 184 | {&CPU::OP_MUL , H_WB , 0xF004, {{2, 0x000E, 8}, {1, 0x000F, 4}}}, 185 | {&CPU::OP_DIV , H_WB , 0xF009, {{2, 0x000E, 8}, {1, 0x000F, 4}}}, 186 | // * Miscellaneous Instructions 187 | {&CPU::OP_INC_EA , 0, 0xFE2F, {{0, 0, 0}, {0, 0, 0}}}, 188 | {&CPU::OP_DEC_EA , 0, 0xFE3F, {{0, 0, 0}, {0, 0, 0}}}, 189 | {&CPU::OP_RT , 0, 0xFE1F, {{0, 0, 0}, {0, 0, 0}}}, 190 | {&CPU::OP_RTI , 0, 0xFE0F, {{0, 0, 0}, {0, 0, 0}}}, 191 | {&CPU::OP_NOP , 0, 0xFE8F, {{0, 0, 0}, {0, 0, 0}}}, 192 | {&CPU::OP_DSR , H_DS , 0xFE9F, {{0, 0, 0}, {0, 0, 0}}}, 193 | {&CPU::OP_DSR , H_DS | H_DW, 0xE300, {{0, 0x00FF, 0}, {0, 0, 0}}}, 194 | {&CPU::OP_DSR , H_DS | H_DW, 0x900F, {{1, 0x000F, 4}, {0, 0, 0}}} 195 | }; 196 | 197 | CPU::RegisterRecord CPU::register_record_sources[] = { 198 | { "r", 16, 0, nullptr, (RegisterStubArrayPointer)&CPU::reg_r}, 199 | { "cr", 16, 0, nullptr, (RegisterStubArrayPointer)&CPU::reg_cr}, 200 | { "pc", 1, 0, (RegisterStubPointer)&CPU::reg_pc, nullptr}, 201 | { "csr", 1, 0, (RegisterStubPointer)&CPU::reg_csr, nullptr}, 202 | { "lr", 1, 0, nullptr, (RegisterStubArrayPointer)&CPU::reg_elr}, 203 | { "elr1", 1, 1, nullptr, (RegisterStubArrayPointer)&CPU::reg_elr}, 204 | { "elr2", 1, 2, nullptr, (RegisterStubArrayPointer)&CPU::reg_elr}, 205 | { "elr3", 1, 3, nullptr, (RegisterStubArrayPointer)&CPU::reg_elr}, 206 | { "lcsr", 1, 0, nullptr, (RegisterStubArrayPointer)&CPU::reg_ecsr}, 207 | {"ecsr1", 1, 1, nullptr, (RegisterStubArrayPointer)&CPU::reg_ecsr}, 208 | {"ecsr2", 1, 2, nullptr, (RegisterStubArrayPointer)&CPU::reg_ecsr}, 209 | {"ecsr3", 1, 3, nullptr, (RegisterStubArrayPointer)&CPU::reg_ecsr}, 210 | { "psw", 1, 0, nullptr, (RegisterStubArrayPointer)&CPU::reg_epsw}, 211 | {"epsw1", 1, 1, nullptr, (RegisterStubArrayPointer)&CPU::reg_epsw}, 212 | {"epsw2", 1, 2, nullptr, (RegisterStubArrayPointer)&CPU::reg_epsw}, 213 | {"epsw3", 1, 3, nullptr, (RegisterStubArrayPointer)&CPU::reg_epsw}, 214 | { "sp", 1, 0, (RegisterStubPointer)&CPU::reg_sp, nullptr}, 215 | { "ea", 1, 0, (RegisterStubPointer)&CPU::reg_ea, nullptr}, 216 | { "dsr", 1, 0, (RegisterStubPointer)&CPU::reg_dsr, nullptr} 217 | }; 218 | 219 | void CPU::OP_NOP() 220 | { 221 | } 222 | 223 | void CPU::OP_DSR() 224 | { 225 | if (impl_hint & H_DW) 226 | impl_last_dsr = impl_operands[0].value; 227 | 228 | reg_dsr = impl_last_dsr; 229 | } 230 | 231 | CPU::CPU(Emulator &_emulator) : emulator(_emulator), reg_lr(reg_elr[0]), reg_lcsr(reg_ecsr[0]), reg_psw(reg_epsw[0]) 232 | { 233 | opcode_dispatch = new OpcodeSource *[0x10000]; 234 | for (size_t ix = 0; ix != 0x10000; ++ix) 235 | opcode_dispatch[ix] = nullptr; 236 | } 237 | 238 | CPU::~CPU() 239 | { 240 | delete[] opcode_dispatch; 241 | } 242 | 243 | void CPU::SetupInternals() 244 | { 245 | SetupOpcodeDispatch(); 246 | SetupRegisterProxies(); 247 | 248 | impl_csr_mask = emulator.GetModelInfo("csr_mask"); 249 | } 250 | 251 | void CPU::SetupOpcodeDispatch() 252 | { 253 | uint16_t *permutation_buffer = new uint16_t[0x10000]; 254 | for (size_t ix = 0; ix != sizeof(opcode_sources) / sizeof(opcode_sources[0]); ++ix) 255 | { 256 | OpcodeSource &handler_stub = opcode_sources[ix]; 257 | 258 | uint16_t varying_bits = 0; 259 | for (size_t ox = 0; ox != sizeof(impl_operands) / sizeof(impl_operands[0]); ++ox) 260 | varying_bits |= handler_stub.operands[ox].mask << handler_stub.operands[ox].shift; 261 | 262 | size_t permutation_count = 1; 263 | permutation_buffer[0] = handler_stub.opcode; 264 | for (uint16_t checkbit = 0x8000; checkbit; checkbit >>= 1) 265 | { 266 | if (varying_bits & checkbit) 267 | { 268 | for (size_t px = 0; px != permutation_count; ++px) 269 | permutation_buffer[px + permutation_count] = permutation_buffer[px] | checkbit; 270 | permutation_count <<= 1; 271 | } 272 | } 273 | 274 | for (size_t px = 0; px != permutation_count; ++px) 275 | { 276 | if (opcode_dispatch[permutation_buffer[px]]) 277 | PANIC("clashing opcode %04X\n", permutation_buffer[px]); 278 | opcode_dispatch[permutation_buffer[px]] = &handler_stub; 279 | } 280 | } 281 | delete[] permutation_buffer; 282 | } 283 | 284 | void CPU::SetupRegisterProxies() 285 | { 286 | for (size_t ix = 0; ix != sizeof(register_record_sources) / sizeof(register_record_sources[0]); ++ix) 287 | { 288 | RegisterRecord &record = register_record_sources[ix]; 289 | 290 | if (record.stub) 291 | { 292 | RegisterStub *register_stub = &(this->*record.stub); 293 | register_stub->name = record.name; 294 | register_proxies[record.name] = register_stub; 295 | } 296 | 297 | if (record.stub_array) 298 | { 299 | if (record.array_size == 1) 300 | { 301 | RegisterStub *register_stub = &(this->*record.stub_array)[record.array_base]; 302 | register_stub->name = record.name; 303 | register_proxies[record.name] = register_stub; 304 | } 305 | else 306 | { 307 | for (size_t rx = 0; rx != record.array_size; ++rx) 308 | { 309 | std::stringstream ss; 310 | ss << record.name << rx; 311 | RegisterStub *register_stub = &(this->*record.stub_array)[rx]; 312 | register_stub->name = ss.str(); 313 | register_proxies[ss.str()] = register_stub; 314 | } 315 | } 316 | } 317 | } 318 | 319 | *(CPU **)lua_newuserdata(emulator.lua_state, sizeof(CPU *)) = this; 320 | lua_newtable(emulator.lua_state); 321 | lua_pushcfunction(emulator.lua_state, [](lua_State *lua_state) { 322 | CPU *cpu = *(CPU **)lua_topointer(lua_state, 1); 323 | auto it = cpu->register_proxies.find(lua_tostring(lua_state, 2)); 324 | if (it == cpu->register_proxies.end()) 325 | return 0; 326 | RegisterStub *reg_stub = it->second; 327 | if (reg_stub->type_size == 1) 328 | lua_pushinteger(lua_state, (uint8_t)reg_stub->raw); 329 | else 330 | lua_pushinteger(lua_state, (uint16_t)reg_stub->raw); 331 | return 1; 332 | }); 333 | lua_setfield(emulator.lua_state, -2, "__index"); 334 | lua_pushcfunction(emulator.lua_state, [](lua_State *lua_state) { 335 | CPU *cpu = *(CPU **)lua_topointer(lua_state, 1); 336 | auto it = cpu->register_proxies.find(lua_tostring(lua_state, 2)); 337 | if (it == cpu->register_proxies.end()) 338 | return 0; 339 | RegisterStub *reg_stub = it->second; 340 | if (reg_stub->type_size == 1) 341 | reg_stub->raw = (uint8_t)lua_tointeger(lua_state, 3); 342 | else 343 | reg_stub->raw = (uint16_t)lua_tointeger(lua_state, 3); 344 | return 0; 345 | }); 346 | lua_setfield(emulator.lua_state, -2, "__newindex"); 347 | lua_setmetatable(emulator.lua_state, -2); 348 | lua_setglobal(emulator.lua_state, "cpu"); 349 | } 350 | 351 | uint16_t CPU::Fetch() 352 | { 353 | if (reg_csr.raw & ~impl_csr_mask) 354 | { 355 | logger::Info("warning: CSR masked bits set\n"); 356 | reg_csr.raw &= impl_csr_mask; 357 | } 358 | if (reg_pc.raw & 1) 359 | { 360 | logger::Info("warning: PC LSB set\n"); 361 | reg_pc.raw &= ~1; 362 | } 363 | uint16_t opcode = emulator.chipset.mmu.ReadCode((reg_csr.raw << 16) | reg_pc.raw); 364 | reg_pc.raw = (uint16_t)(reg_pc.raw + 2); 365 | return opcode; 366 | } 367 | 368 | void CPU::Next() 369 | { 370 | /** 371 | * `reg_dsr` only affects the current instruction. The old DSR is stored in 372 | * `impl_last_dsr` and is recalled every time a DSR instruction is encountered 373 | * that activates DSR addressing without actually changing DSR. 374 | */ 375 | reg_dsr = 0; 376 | 377 | for (auto &proxy : register_proxies) 378 | { 379 | proxy.second->read = false; 380 | proxy.second->written = false; 381 | } 382 | 383 | while (1) 384 | { 385 | impl_opcode = Fetch(); 386 | OpcodeSource *handler = opcode_dispatch[impl_opcode]; 387 | 388 | if (!handler) 389 | PANIC("unrecognized instruction %04X at %06zX\n", impl_opcode, (((size_t)reg_csr.raw) << 16) | (reg_pc.raw - 2)); 390 | 391 | impl_long_imm = 0; 392 | if (handler->hint & H_TI) 393 | impl_long_imm = Fetch(); 394 | 395 | for (size_t ix = 0; ix != sizeof(impl_operands) / sizeof(impl_operands[0]); ++ix) 396 | { 397 | impl_operands[ix].value = (impl_opcode >> handler->operands[ix].shift) & handler->operands[ix].mask; 398 | impl_operands[ix].register_index = impl_operands[ix].value; 399 | impl_operands[ix].register_size = handler->operands[ix].register_size; 400 | 401 | if (impl_operands[ix].register_size) 402 | { 403 | impl_operands[ix].value = 0; 404 | for (size_t bx = 0; bx != impl_operands[ix].register_size; ++bx) 405 | impl_operands[ix].value |= (uint64_t)(reg_r[impl_operands[ix].register_index + bx]) << (bx * 8); 406 | } 407 | } 408 | impl_hint = handler->hint; 409 | 410 | impl_flags_changed = 0; 411 | impl_flags_in = reg_psw; 412 | /** 413 | * Yes, Z is always set to 1. While `impl_flags_changed` may not have 414 | * PSW_Z set, `impl_flags_out` does as most of the time Z is calculated 415 | * by one or more calls to `ZSCheck`. `ZSCheck` only changes Z if the 416 | * value it checks is non-zero, otherwise it leaves it alone. 417 | */ 418 | impl_flags_out = PSW_Z; 419 | (this->*(handler->handler_function))(); 420 | reg_psw &= ~impl_flags_changed; 421 | reg_psw |= impl_flags_out & impl_flags_changed; 422 | 423 | if (handler->hint & H_WB && impl_operands[0].register_size) 424 | for (size_t bx = 0; bx != impl_operands[0].register_size; ++bx) 425 | reg_r[impl_operands[0].register_index + bx] = (uint8_t)(impl_operands[0].value >> (bx * 8)); 426 | 427 | if (!(handler->hint & H_DS)) 428 | break; 429 | } 430 | } 431 | 432 | void CPU::SetMemoryModel(MemoryModel _memory_model) 433 | { 434 | memory_model = _memory_model; 435 | } 436 | 437 | void CPU::Reset() 438 | { 439 | reg_sp = emulator.chipset.mmu.ReadCode(0); 440 | reg_dsr = 0; 441 | reg_psw = 0; 442 | } 443 | 444 | void CPU::Raise(size_t exception_level, size_t index) 445 | { 446 | if (exception_level == 1) 447 | reg_psw.raw &= ~PSW_MIE; 448 | reg_psw.raw = (reg_psw.raw & ~PSW_ELEVEL) | exception_level; 449 | 450 | reg_elr[exception_level].raw = reg_pc.raw; 451 | reg_ecsr[exception_level].raw = reg_csr.raw; 452 | 453 | reg_csr.raw = 0; 454 | reg_pc.raw = emulator.chipset.mmu.ReadCode(index * 2); 455 | } 456 | 457 | size_t CPU::GetExceptionLevel() 458 | { 459 | return reg_psw.raw & PSW_ELEVEL; 460 | } 461 | 462 | bool CPU::GetMasterInterruptEnable() 463 | { 464 | return reg_psw & PSW_MIE; 465 | } 466 | } 467 | 468 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPU.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "../Logger.hpp" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | namespace casioemu 11 | { 12 | class Emulator; 13 | 14 | class CPU 15 | { 16 | Emulator &emulator; 17 | 18 | private: 19 | struct RegisterStub 20 | { 21 | size_t type_size; 22 | std::string name; 23 | bool read, written; 24 | 25 | uint16_t raw; 26 | }; 27 | 28 | template 29 | struct Register : public RegisterStub 30 | { 31 | Register() 32 | { 33 | type_size = sizeof(value_type); 34 | name = "?"; 35 | } 36 | 37 | operator value_type() 38 | { 39 | read = true; 40 | return raw; 41 | } 42 | 43 | Register &operator =(value_type value) 44 | { 45 | written = true; 46 | raw = value; 47 | return *this; 48 | } 49 | 50 | Register &operator &=(value_type value) 51 | { 52 | return *this = raw & value; 53 | } 54 | 55 | Register &operator |=(value_type value) 56 | { 57 | return *this = raw | value; 58 | } 59 | 60 | Register &operator ^=(value_type value) 61 | { 62 | return *this = raw ^ value; 63 | } 64 | 65 | Register &operator +=(value_type value) 66 | { 67 | return *this = raw + value; 68 | } 69 | 70 | Register &operator -=(value_type value) 71 | { 72 | return *this = raw - value; 73 | } 74 | }; 75 | 76 | typedef Register reg8_t; 77 | typedef Register reg16_t; 78 | 79 | uint8_t impl_last_dsr; 80 | uint8_t impl_flags_changed, impl_flags_out, impl_flags_in; 81 | uint8_t impl_shift_buffer; 82 | uint16_t impl_opcode, impl_long_imm; 83 | struct { 84 | uint64_t value; 85 | size_t register_index, register_size; 86 | } impl_operands[2]; 87 | size_t impl_hint; 88 | uint16_t impl_csr_mask; 89 | 90 | void SetupOpcodeDispatch(); 91 | void SetupRegisterProxies(); 92 | 93 | public: 94 | CPU(Emulator &emulator); 95 | ~CPU(); 96 | void SetupInternals(); 97 | 98 | /** 99 | * See 1.2.2.1 in the nX-U8 manual. 100 | */ 101 | enum StatusFlag 102 | { 103 | PSW_C = 0x80, 104 | PSW_Z = 0x40, 105 | PSW_S = 0x20, 106 | PSW_OV = 0x10, 107 | PSW_MIE = 0x8, 108 | PSW_HC = 0x4, 109 | PSW_ELEVEL = 0x3 110 | }; 111 | 112 | /** 113 | * See 1.3.6 in the nX-U8 manual. 114 | */ 115 | enum MemoryModel 116 | { 117 | MM_SMALL, 118 | MM_LARGE 119 | } memory_model; 120 | 121 | /** 122 | * See 1.2.1 in the nX-U8 manual. 123 | */ 124 | reg8_t reg_r[16], reg_cr[16]; 125 | reg16_t reg_pc, reg_elr[4], ®_lr; 126 | reg16_t reg_csr, reg_ecsr[4], ®_lcsr; 127 | reg8_t reg_epsw[4], ®_psw; 128 | reg16_t reg_sp, reg_ea; 129 | reg8_t reg_dsr; 130 | 131 | void SetMemoryModel(MemoryModel memory_model); 132 | void Next(); 133 | void Reset(); 134 | void Raise(size_t exception_level, size_t index); 135 | size_t GetExceptionLevel(); 136 | bool GetMasterInterruptEnable(); 137 | 138 | private: 139 | uint16_t Fetch(); 140 | 141 | enum OpcodeHint 142 | { 143 | H_IE = 0x0001, // * Extend Immediate flag for arithmetic instructions. 144 | H_ST = 0x0002, // * Store flag for load/store/coprocessor instructions. 145 | H_DW = 0x0004, // * Store a new DSR value. 146 | H_DS = 0x0008, // * Instruction is a DSR prefix. 147 | H_IA = 0x0010, // * Increment EA flag for load/store/coprocessor instructions. 148 | H_TI = 0x0020, // * Instruction takes an external long immediate value. 149 | H_WB = 0x0040 // * Register Writeback flag for a lot of instructions to make life easier. 150 | }; 151 | 152 | struct OpcodeSource 153 | { 154 | void (CPU::*handler_function)(); 155 | /** 156 | * I know this should be an OpcodeHint, but the damn C++ initializer lists 157 | * convert literally everything to int if it's more than a single enum 158 | * value. Even binary OR'd values and 0. Pain in the ass. 159 | */ 160 | size_t hint; 161 | uint16_t opcode; 162 | struct OperandMask 163 | { 164 | /** 165 | * `register_size` determines whether an operand is a register 166 | * or an immediate. If it's 0, the operand is an immediate. Otherwise 167 | * the operand is a register of size `register_size`. 168 | */ 169 | size_t register_size; 170 | uint16_t mask, shift; 171 | } operands[2]; 172 | }; 173 | static OpcodeSource opcode_sources[]; 174 | OpcodeSource **opcode_dispatch; 175 | 176 | typedef RegisterStub CPU::*RegisterStubPointer; 177 | typedef RegisterStub (CPU::*RegisterStubArrayPointer)[]; 178 | struct RegisterRecord 179 | { 180 | std::string name; 181 | size_t array_size, array_base; 182 | RegisterStubPointer stub; 183 | RegisterStubArrayPointer stub_array; 184 | }; 185 | static RegisterRecord register_record_sources[]; 186 | std::map register_proxies; 187 | 188 | // * Arithmetic Instructions 189 | void OP_ADD(); 190 | void OP_ADD16(); 191 | void OP_ADDC(); 192 | void OP_AND(); 193 | void OP_MOV16(); 194 | void OP_MOV(); 195 | void OP_OR(); 196 | void OP_XOR(); 197 | void OP_CMP16(); 198 | void OP_SUB(); 199 | void OP_SUBC(); 200 | void Add8(); 201 | void ZSCheck(); 202 | void ShiftLeft8(); 203 | void ShiftRight8(); 204 | // * Shift Instructions 205 | void OP_SLL(); 206 | void OP_SLLC(); 207 | void OP_SRA(); 208 | void OP_SRL(); 209 | void OP_SRLC(); 210 | // * Load/Store Instructions 211 | void OP_LS_EA(); 212 | void OP_LS_R(); 213 | void OP_LS_I_R(); 214 | void OP_LS_BP(); 215 | void OP_LS_FP(); 216 | void OP_LS_I(); 217 | void LoadStore(uint16_t offset, size_t length); 218 | // * Control Register Access Instructions 219 | void OP_ADDSP(); 220 | void OP_CTRL(); 221 | // * PUSH/POP Instructions 222 | void OP_PUSH(); 223 | void OP_PUSHL(); 224 | void OP_POP(); 225 | void OP_POPL(); 226 | void Push16(uint16_t data); 227 | uint16_t Pop16(); 228 | // * Coprocessor Data Transfer Instructions 229 | void OP_CR_R(); 230 | void OP_CR_EA(); 231 | void BumpEA(size_t value_size); 232 | // * EA Register Data Transfer Instructions 233 | void OP_LEA(); 234 | // * ALU Instructions 235 | void OP_DAA(); 236 | void OP_DAS(); 237 | void OP_NEG(); 238 | // * Bit Access Instructions 239 | void OP_BITMOD(); 240 | // * PSW Access Instructions 241 | void OP_PSW_OR(); 242 | void OP_PSW_AND(); 243 | void OP_CPLC(); 244 | // * Conditional Relative Branch Instructions 245 | void OP_BC(); 246 | // * Sign Extension Instruction 247 | void OP_EXTBW(); 248 | // * Software Interrupt Instructions 249 | void OP_SWI(); 250 | void OP_BRK(); 251 | // * Branch Instructions 252 | void OP_B(); 253 | void OP_BL(); 254 | // * Multiplication and Division Instructions 255 | void OP_MUL(); 256 | void OP_DIV(); 257 | // * Miscellaneous Instructions 258 | void OP_INC_EA(); 259 | void OP_DEC_EA(); 260 | void OP_RT(); 261 | void OP_RTI(); 262 | void OP_NOP(); 263 | void OP_DSR(); 264 | }; 265 | } 266 | 267 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPUArithmetic.cpp: -------------------------------------------------------------------------------- 1 | #include "CPU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | 7 | namespace casioemu 8 | { 9 | // * Arithmetic Instructions 10 | void CPU::OP_ADD() 11 | { 12 | impl_flags_in &= ~PSW_C; 13 | impl_flags_in |= PSW_Z; 14 | OP_ADDC(); 15 | } 16 | 17 | void CPU::OP_ADD16() 18 | { 19 | if (impl_hint & H_IE) 20 | impl_operands[1].value |= (impl_operands[1].value & 0x40) ? 0xFF80 : 0; 21 | 22 | impl_flags_in &= ~PSW_C; 23 | 24 | uint8_t op_high_0 = impl_operands[0].value >> 8; 25 | uint8_t op_high_1 = impl_operands[1].value >> 8; 26 | Add8(); 27 | ZSCheck(); 28 | 29 | impl_flags_in = (impl_flags_in & ~PSW_C) | (impl_flags_out & PSW_C); 30 | 31 | uint8_t op_low_0 = impl_operands[0].value; 32 | impl_operands[0].value = op_high_0; 33 | impl_operands[1].value = op_high_1; 34 | Add8(); 35 | ZSCheck(); 36 | 37 | impl_operands[0].value = (impl_operands[0].value << 8) | op_low_0; 38 | } 39 | 40 | void CPU::OP_ADDC() 41 | { 42 | Add8(); 43 | if (!(impl_flags_in & PSW_Z)) 44 | impl_flags_out &= ~PSW_Z; 45 | ZSCheck(); 46 | } 47 | 48 | void CPU::OP_AND() 49 | { 50 | impl_operands[0].value &= impl_operands[1].value & 0xFF; 51 | ZSCheck(); 52 | } 53 | 54 | void CPU::OP_MOV16() 55 | { 56 | if (impl_hint & H_IE) 57 | impl_operands[1].value |= (impl_operands[1].value & 0x40) ? 0xFF80 : 0; 58 | 59 | impl_operands[0].value = impl_operands[1].value & 0xFF; 60 | ZSCheck(); 61 | 62 | uint8_t op_low_0 = impl_operands[0].value; 63 | impl_operands[0].value = (impl_operands[1].value >> 8) & 0xFF; 64 | ZSCheck(); 65 | 66 | impl_operands[0].value = (impl_operands[0].value << 8) | op_low_0; 67 | } 68 | 69 | void CPU::OP_MOV() 70 | { 71 | impl_operands[0].value = impl_operands[1].value & 0xFF; 72 | ZSCheck(); 73 | } 74 | 75 | void CPU::OP_OR() 76 | { 77 | impl_operands[0].value |= impl_operands[1].value & 0xFF; 78 | ZSCheck(); 79 | } 80 | 81 | void CPU::OP_XOR() 82 | { 83 | impl_operands[0].value ^= impl_operands[1].value & 0xFF; 84 | ZSCheck(); 85 | } 86 | 87 | void CPU::OP_CMP16() 88 | { 89 | impl_flags_in &= ~PSW_C; 90 | 91 | uint8_t op_high_0 = impl_operands[0].value >> 8; 92 | uint8_t op_high_1 = impl_operands[1].value >> 8; 93 | impl_operands[0].value ^= 0xFF; 94 | Add8(); 95 | impl_operands[0].value ^= 0xFF; 96 | ZSCheck(); 97 | 98 | impl_flags_in = (impl_flags_in & ~PSW_C) | (impl_flags_out & PSW_C); 99 | 100 | uint8_t op_low_0 = impl_operands[0].value; 101 | impl_operands[0].value = op_high_0; 102 | impl_operands[1].value = op_high_1; 103 | impl_operands[0].value ^= 0xFF; 104 | Add8(); 105 | impl_operands[0].value ^= 0xFF; 106 | ZSCheck(); 107 | 108 | impl_operands[0].value = (impl_operands[0].value << 8) | op_low_0; 109 | } 110 | 111 | void CPU::OP_SUB() 112 | { 113 | impl_flags_in &= ~PSW_C; 114 | impl_flags_in |= PSW_Z; 115 | OP_SUBC(); 116 | } 117 | 118 | void CPU::OP_SUBC() 119 | { 120 | impl_operands[0].value ^= 0xFF; 121 | Add8(); 122 | impl_operands[0].value ^= 0xFF; 123 | if (!(impl_flags_in & PSW_Z)) 124 | impl_flags_out &= ~PSW_Z; 125 | ZSCheck(); 126 | } 127 | 128 | // * Shift Instructions 129 | void CPU::OP_SLL() 130 | { 131 | impl_shift_buffer = 0; 132 | ShiftLeft8(); 133 | } 134 | 135 | void CPU::OP_SLLC() 136 | { 137 | size_t external_reg_index = (impl_operands[0].register_index - 1) & 15; 138 | impl_shift_buffer = reg_r[external_reg_index]; 139 | ShiftLeft8(); 140 | } 141 | 142 | void CPU::OP_SRA() 143 | { 144 | size_t shift_by = impl_operands[1].value & 7; 145 | uint64_t msb = impl_operands[0].value & 0x80; 146 | impl_shift_buffer = 0; 147 | ShiftRight8(); 148 | if (msb) 149 | impl_operands[0].value |= (0xFF >> shift_by) ^ 0xFF; 150 | } 151 | 152 | void CPU::OP_SRL() 153 | { 154 | impl_shift_buffer = 0; 155 | ShiftRight8(); 156 | } 157 | 158 | void CPU::OP_SRLC() 159 | { 160 | size_t external_reg_index = (impl_operands[0].register_index + 1) & 15; 161 | impl_shift_buffer = reg_r[external_reg_index]; 162 | ShiftRight8(); 163 | } 164 | 165 | // * ALU Instructions 166 | void CPU::OP_DAA() 167 | { 168 | impl_operands[1].value = 0; 169 | if ((impl_operands[0].value & 0x0F) > 0x09 || (impl_flags_in & PSW_HC)) impl_operands[1].value |= 0x06; 170 | if ((impl_operands[0].value & 0xF0) > 0x90 || (impl_flags_in & PSW_C)) impl_operands[1].value |= 0x60; 171 | if ((impl_operands[0].value & 0xF0) == 0x90 && (impl_operands[0].value & 0x0F) > 0x09 && !(impl_flags_in & PSW_HC)) impl_operands[1].value |= 0x60; 172 | uint8_t flags_in_backup = impl_flags_in; 173 | OP_ADD(); 174 | impl_flags_out |= flags_in_backup & PSW_C; 175 | impl_flags_changed &= ~PSW_OV; 176 | } 177 | 178 | void CPU::OP_DAS() 179 | { 180 | impl_operands[1].value = 0; 181 | if ((impl_operands[0].value & 0x0F) > 0x09 || (impl_flags_in & PSW_HC)) impl_operands[1].value |= 0x06; 182 | if ((impl_operands[0].value & 0xF0) > 0x90 || (impl_flags_in & PSW_C)) impl_operands[1].value |= 0x60; 183 | uint8_t flags_in_backup = impl_flags_in; 184 | OP_SUB(); 185 | impl_flags_out |= flags_in_backup & PSW_C; 186 | impl_flags_changed &= ~PSW_OV; 187 | } 188 | 189 | void CPU::OP_NEG() 190 | { 191 | impl_operands[1].value = impl_operands[0].value; 192 | impl_operands[0].value = 0; 193 | OP_SUB(); 194 | } 195 | 196 | // * Bit Access Instructions 197 | void CPU::OP_BITMOD() 198 | { 199 | size_t src_index; 200 | uint64_t bit_in = 1 << impl_operands[1].value; 201 | if (impl_hint & H_TI) 202 | { 203 | src_index = impl_long_imm; 204 | impl_operands[0].value = emulator.chipset.mmu.ReadData((((size_t)reg_dsr) << 16) | src_index); 205 | } 206 | else 207 | { 208 | src_index = impl_operands[0].value; 209 | impl_operands[0].value = reg_r[src_index]; 210 | } 211 | 212 | impl_flags_changed |= PSW_Z; 213 | impl_flags_out = (impl_operands[0].value & bit_in) ? 0 : PSW_Z; 214 | 215 | switch (impl_opcode & 0x000F) 216 | { 217 | case 0: 218 | impl_operands[0].value |= bit_in; 219 | break; 220 | case 2: 221 | impl_operands[0].value &= ~bit_in; 222 | break; 223 | } 224 | 225 | if ((impl_opcode & 0x000F) != 1) 226 | { 227 | if (impl_hint & H_TI) 228 | emulator.chipset.mmu.WriteData((((size_t)reg_dsr) << 16) | src_index, impl_operands[0].value); 229 | else 230 | reg_r[src_index] = impl_operands[0].value; 231 | } 232 | } 233 | 234 | // * Sign Extension Instruction 235 | void CPU::OP_EXTBW() 236 | { 237 | size_t index = (impl_opcode & 0x00E0) >> 4; 238 | impl_operands[0].value = (reg_r[index] & 0x80) ? 0xFF : 0x00; 239 | reg_r[index + 1] = impl_operands[0].value; 240 | ZSCheck(); 241 | } 242 | 243 | // * Multiplication and Division Instructions 244 | void CPU::OP_MUL() 245 | { 246 | impl_operands[0].value &= 0xFF; 247 | impl_operands[0].value *= impl_operands[1].value; 248 | 249 | impl_flags_changed |= PSW_Z; 250 | impl_flags_out = impl_operands[0].value ? 0 : PSW_Z; 251 | } 252 | 253 | void CPU::OP_DIV() 254 | { 255 | impl_flags_changed |= PSW_Z | PSW_C; 256 | if (!impl_operands[1].value) 257 | { 258 | impl_flags_out |= PSW_C; 259 | return; 260 | } 261 | 262 | uint16_t quotient = impl_operands[0].value / impl_operands[1].value; 263 | uint16_t remainder = impl_operands[0].value % impl_operands[1].value; 264 | 265 | impl_operands[0].value = quotient; 266 | if (impl_operands[0].value) 267 | impl_flags_out &= ~PSW_Z; 268 | 269 | size_t remainder_reg_index = (impl_opcode >> 4) & 0x000F; 270 | reg_r[remainder_reg_index] = remainder; 271 | } 272 | 273 | // * Miscellaneous Instructions 274 | void CPU::OP_INC_EA() 275 | { 276 | impl_operands[0].value = emulator.chipset.mmu.ReadData((((size_t)reg_dsr) << 16) | reg_ea); 277 | impl_operands[1].value = 1; 278 | OP_ADD(); 279 | impl_flags_changed &= ~PSW_C; 280 | emulator.chipset.mmu.WriteData((((size_t)reg_dsr) << 16) | reg_ea, impl_operands[0].value); 281 | } 282 | 283 | void CPU::OP_DEC_EA() 284 | { 285 | impl_operands[0].value = emulator.chipset.mmu.ReadData((((size_t)reg_dsr) << 16) | reg_ea); 286 | impl_operands[1].value = 1; 287 | OP_SUB(); 288 | impl_flags_changed &= ~PSW_C; 289 | emulator.chipset.mmu.WriteData((((size_t)reg_dsr) << 16) | reg_ea, impl_operands[0].value); 290 | } 291 | 292 | void CPU::Add8() 293 | { 294 | uint8_t op8[2] = {(uint8_t)impl_operands[0].value, (uint8_t)impl_operands[1].value}; 295 | uint16_t c_in = (impl_flags_in & PSW_C) ? 1 : 0; 296 | 297 | bool carry_8 = (((uint16_t)op8[0] & 0xFF) + (op8[1] & 0xFF) + c_in) >> 8; 298 | bool carry_7 = (((uint16_t)op8[0] & 0x7F) + (op8[1] & 0x7F) + c_in) >> 7; 299 | bool carry_4 = (((uint16_t)op8[0] & 0x0F) + (op8[1] & 0x0F) + c_in) >> 4; 300 | 301 | impl_flags_changed |= PSW_C | PSW_OV | PSW_HC; 302 | impl_flags_out = (impl_flags_out & ~PSW_C) | (carry_8 ? PSW_C : 0); 303 | impl_flags_out = (impl_flags_out & ~PSW_OV) | ((carry_8 ^ carry_7) ? PSW_OV : 0); 304 | impl_flags_out = (impl_flags_out & ~PSW_HC) | (carry_4 ? PSW_HC : 0); 305 | 306 | impl_operands[0].value = (uint8_t)(op8[0] + op8[1] + c_in); 307 | } 308 | 309 | void CPU::ZSCheck() 310 | { 311 | impl_flags_changed |= PSW_Z | PSW_S; 312 | if (impl_operands[0].value & 0xFF) 313 | impl_flags_out &= ~PSW_Z; 314 | impl_flags_out = (impl_flags_out & ~PSW_S) | ((impl_operands[0].value & 0x80) ? PSW_S : 0); 315 | } 316 | 317 | void CPU::ShiftLeft8() 318 | { 319 | impl_operands[0].value &= 0xFF; 320 | size_t shift_by = impl_operands[1].value & 7; 321 | uint16_t result = (uint16_t)impl_operands[0].value << shift_by; 322 | result |= impl_shift_buffer >> (8 - shift_by); 323 | impl_flags_changed |= PSW_C; 324 | if (result & 0x100) 325 | impl_flags_out |= PSW_C; 326 | impl_operands[0].value = (uint8_t)result; 327 | } 328 | 329 | void CPU::ShiftRight8() 330 | { 331 | impl_operands[0].value &= 0xFF; 332 | size_t shift_by = impl_operands[1].value & 7; 333 | uint16_t result = (uint16_t)impl_operands[0].value << (8 - shift_by); 334 | result |= (uint16_t)impl_shift_buffer << (16 - shift_by); 335 | impl_flags_changed |= PSW_C; 336 | if (result & 0x80) 337 | impl_flags_out |= PSW_C; 338 | impl_operands[0].value = (uint8_t)(result >> 8); 339 | } 340 | } 341 | 342 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPUControl.cpp: -------------------------------------------------------------------------------- 1 | #include "CPU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | 7 | namespace casioemu 8 | { 9 | // * Control Register Access Instructions 10 | void CPU::OP_ADDSP() 11 | { 12 | impl_operands[0].value |= (impl_operands[0].value & 0x80) ? 0xFF00 : 0; 13 | reg_sp += impl_operands[0].value; 14 | } 15 | 16 | void CPU::OP_CTRL() 17 | { 18 | switch (impl_hint >> 8) 19 | { 20 | case 1: 21 | reg_ecsr[reg_psw & PSW_ELEVEL] = impl_operands[1].value; 22 | break; 23 | case 2: 24 | reg_elr[reg_psw & PSW_ELEVEL] = impl_operands[1].value; 25 | break; 26 | case 3: 27 | if (reg_psw & PSW_ELEVEL) 28 | reg_epsw[reg_psw & PSW_ELEVEL] = impl_operands[1].value; 29 | break; 30 | case 4: 31 | impl_operands[0].value = reg_elr[reg_psw & PSW_ELEVEL]; 32 | break; 33 | case 5: 34 | impl_operands[0].value = reg_sp; 35 | break; 36 | case 6: 37 | case 7: 38 | reg_psw = impl_operands[1].value; 39 | break; 40 | case 8: 41 | impl_operands[0].value = reg_ecsr[reg_psw & PSW_ELEVEL]; 42 | break; 43 | case 9: 44 | if (reg_psw & PSW_ELEVEL) 45 | impl_operands[0].value = reg_epsw[reg_psw & PSW_ELEVEL]; 46 | break; 47 | case 10: 48 | impl_operands[0].value = reg_psw; 49 | break; 50 | case 11: 51 | reg_sp = impl_operands[1].value; 52 | break; 53 | } 54 | } 55 | 56 | // * EA Register Data Transfer Instructions 57 | void CPU::OP_LEA() 58 | { 59 | reg_ea = 0; 60 | if (impl_operands[1].register_size) 61 | reg_ea += impl_operands[1].value; 62 | if (impl_hint & H_TI) 63 | reg_ea += impl_long_imm; 64 | } 65 | 66 | // * Coprocessor Data Transfer Instructions 67 | void CPU::OP_CR_R() 68 | { 69 | size_t op0_index = (impl_opcode >> 8) & 0x000F; 70 | size_t op1_index = (impl_opcode >> 4) & 0x000F; 71 | if (impl_hint & H_ST) 72 | reg_r[op0_index] = reg_cr[op1_index]; 73 | else 74 | reg_cr[op0_index] = reg_r[op1_index]; 75 | } 76 | 77 | void CPU::OP_CR_EA() 78 | { 79 | size_t op0_index = (impl_opcode >> 8) & 0x000F; 80 | size_t register_size = impl_opcode >> 8; 81 | 82 | if (impl_hint & H_ST) 83 | for (size_t ix = register_size - 1; ix != (size_t)-1; --ix) 84 | emulator.chipset.mmu.WriteData((((size_t)reg_dsr) << 16) | (uint16_t)(reg_ea + ix), reg_cr[op0_index + ix] 85 | ); 86 | else 87 | for (size_t ix = 0; ix != register_size; ++ix) 88 | reg_cr[op0_index + ix] = emulator.chipset.mmu.ReadData((((size_t)reg_dsr) << 16) | (uint16_t)(reg_ea + ix)); 89 | 90 | if (impl_hint & H_IA) 91 | BumpEA(register_size); 92 | } 93 | 94 | void CPU::BumpEA(size_t value_size) 95 | { 96 | reg_ea += value_size; 97 | if (value_size != 1) 98 | reg_ea &= ~1; 99 | } 100 | 101 | // * PSW Access Instructions 102 | void CPU::OP_PSW_OR() 103 | { 104 | reg_psw |= (impl_opcode & 0xFF); 105 | } 106 | 107 | void CPU::OP_PSW_AND() 108 | { 109 | reg_psw &= (impl_opcode & 0xFF); 110 | } 111 | 112 | void CPU::OP_CPLC() 113 | { 114 | reg_psw ^= PSW_C; 115 | } 116 | 117 | // * Conditional Relative Branch Instructions 118 | void CPU::OP_BC() 119 | { 120 | bool c = impl_flags_in & PSW_C; 121 | bool z = impl_flags_in & PSW_Z; 122 | bool s = impl_flags_in & PSW_S; 123 | bool ov = impl_flags_in & PSW_OV; 124 | bool le = z | c; 125 | bool lts = ov ^ s; 126 | bool les = lts | z; 127 | 128 | bool branch; 129 | switch ((impl_opcode >> 8) & 0x000F) 130 | { 131 | case 0: branch = !c; break; 132 | case 1: branch = c; break; 133 | case 2: branch = !le; break; 134 | case 3: branch = le; break; 135 | case 4: branch = !lts; break; 136 | case 5: branch = lts; break; 137 | case 6: branch = !les; break; 138 | case 7: branch = les; break; 139 | case 8: branch = !z; break; 140 | case 9: branch = z; break; 141 | case 10: branch = !ov; break; 142 | case 11: branch = ov; break; 143 | case 12: branch = !s; break; 144 | case 13: branch = s; break; 145 | default: branch = true; break; 146 | } 147 | 148 | if (branch) 149 | { 150 | impl_operands[0].value |= (impl_operands[0].value & 0x80) ? 0x7F00 : 0; 151 | reg_pc += impl_operands[0].value << 1; 152 | } 153 | } 154 | 155 | // * Software Interrupt Instructions 156 | void CPU::OP_SWI() 157 | { 158 | emulator.chipset.RaiseSoftware(impl_operands[0].value); 159 | } 160 | 161 | void CPU::OP_BRK() 162 | { 163 | emulator.chipset.Break(); 164 | } 165 | 166 | // * Branch Instructions 167 | void CPU::OP_B() 168 | { 169 | if (impl_hint & H_TI) 170 | { 171 | reg_csr = impl_operands[1].value; 172 | reg_pc = impl_long_imm; 173 | } 174 | else 175 | reg_pc = impl_operands[1].value; 176 | } 177 | 178 | void CPU::OP_BL() 179 | { 180 | reg_lr = reg_pc; 181 | reg_lcsr = reg_csr; 182 | OP_B(); 183 | } 184 | 185 | // * Miscellaneous Instructions 186 | void CPU::OP_RT() 187 | { 188 | reg_csr = reg_lcsr; 189 | reg_pc = reg_lr; 190 | } 191 | 192 | void CPU::OP_RTI() 193 | { 194 | reg_csr = reg_ecsr[reg_psw & PSW_ELEVEL]; 195 | reg_pc = reg_elr[reg_psw & PSW_ELEVEL]; 196 | reg_psw = reg_epsw[reg_psw & PSW_ELEVEL]; 197 | } 198 | } 199 | 200 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPULoadStore.cpp: -------------------------------------------------------------------------------- 1 | #include "CPU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | 7 | namespace casioemu 8 | { 9 | // * Load/Store Instructions 10 | void CPU::OP_LS_EA() 11 | { 12 | LoadStore(reg_ea, impl_hint >> 8); 13 | } 14 | 15 | void CPU::OP_LS_R() 16 | { 17 | LoadStore(impl_operands[1].value, impl_hint >> 8); 18 | } 19 | 20 | void CPU::OP_LS_I_R() 21 | { 22 | LoadStore(impl_operands[1].value + impl_long_imm, impl_hint >> 8); 23 | } 24 | 25 | void CPU::OP_LS_BP() 26 | { 27 | impl_operands[1].value |= (impl_operands[1].value & 0x20) ? 0xFFC0 : 0; 28 | impl_operands[1].value += reg_r[12] | (((uint16_t)reg_r[13]) << 8); 29 | LoadStore(impl_operands[1].value, impl_hint >> 8); 30 | } 31 | 32 | void CPU::OP_LS_FP() 33 | { 34 | impl_operands[1].value |= (impl_operands[1].value & 0x20) ? 0xFFC0 : 0; 35 | impl_operands[1].value += reg_r[14] | (((uint16_t)reg_r[15]) << 8); 36 | LoadStore(impl_operands[1].value, impl_hint >> 8); 37 | } 38 | 39 | void CPU::OP_LS_I() 40 | { 41 | LoadStore(impl_long_imm, impl_hint >> 8); 42 | } 43 | 44 | void CPU::LoadStore(uint16_t offset, size_t length) 45 | { 46 | size_t reg_base = impl_operands[0].value; 47 | if (impl_hint & H_ST) 48 | { 49 | for (size_t ix = length - 1; ix != (size_t)-1; --ix) 50 | emulator.chipset.mmu.WriteData((((size_t)reg_dsr) << 16) | (uint16_t)(offset + ix), reg_r[reg_base + ix]); 51 | } 52 | else 53 | { 54 | for (size_t ix = 0; ix != length; ++ix) 55 | { 56 | impl_operands[0].value = emulator.chipset.mmu.ReadData((((size_t)reg_dsr) << 16) | (uint16_t)(offset + ix)); 57 | ZSCheck(); // * defined in CPUArithmetic.cpp 58 | reg_r[reg_base + ix] = impl_operands[0].value; 59 | } 60 | } 61 | 62 | if (impl_hint & H_IA) 63 | BumpEA(length); // * defined in CPUControl.cpp 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /emulator/src/Chipset/CPUPushPop.cpp: -------------------------------------------------------------------------------- 1 | #include "CPU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | 7 | namespace casioemu 8 | { 9 | // * PUSH/POP Instructions 10 | void CPU::OP_PUSH() 11 | { 12 | size_t push_size = impl_operands[1].register_size; 13 | if (push_size == 1) 14 | push_size = 2; 15 | reg_sp -= push_size; 16 | for (size_t ix = impl_operands[1].register_size - 1; ix != (size_t)-1; --ix) 17 | emulator.chipset.mmu.WriteData(reg_sp + ix, impl_operands[1].value >> (8 * ix)); 18 | } 19 | 20 | void CPU::OP_PUSHL() 21 | { 22 | if (impl_operands[1].value & 2) 23 | { 24 | if (memory_model == MM_LARGE) 25 | Push16(reg_ecsr[reg_psw & PSW_ELEVEL]); 26 | Push16(reg_elr[reg_psw & PSW_ELEVEL]); 27 | } 28 | if (impl_operands[1].value & 4) 29 | Push16(reg_epsw[reg_psw & PSW_ELEVEL]); 30 | if (impl_operands[1].value & 8) 31 | { 32 | if (memory_model == MM_LARGE) 33 | Push16(reg_lcsr); 34 | Push16(reg_lr); 35 | } 36 | if (impl_operands[1].value & 1) 37 | Push16(reg_ea); 38 | } 39 | 40 | void CPU::OP_POP() 41 | { 42 | size_t pop_size = impl_operands[0].register_size; 43 | if (pop_size == 1) 44 | pop_size = 2; 45 | impl_operands[0].value = 0; 46 | for (size_t ix = 0; ix != impl_operands[0].register_size; ++ix) 47 | impl_operands[0].value |= ((uint64_t)emulator.chipset.mmu.ReadData(reg_sp + ix)) << (8 * ix); 48 | reg_sp += pop_size; 49 | } 50 | 51 | void CPU::OP_POPL() 52 | { 53 | if (impl_operands[0].value & 1) 54 | reg_ea = Pop16(); 55 | if (impl_operands[0].value & 8) 56 | { 57 | reg_lr = Pop16(); 58 | if (memory_model == MM_LARGE) 59 | reg_lcsr = Pop16() & 0x000F; 60 | } 61 | if (impl_operands[0].value & 4) 62 | reg_psw = Pop16(); 63 | if (impl_operands[0].value & 2) 64 | { 65 | reg_pc = Pop16(); 66 | if (memory_model == MM_LARGE) 67 | reg_csr = Pop16() & 0x000F; 68 | } 69 | } 70 | 71 | void CPU::Push16(uint16_t data) 72 | { 73 | reg_sp -= 2; 74 | emulator.chipset.mmu.WriteData(reg_sp + 1, data >> 8); 75 | emulator.chipset.mmu.WriteData(reg_sp, data & 0xFF); 76 | } 77 | 78 | uint16_t CPU::Pop16() 79 | { 80 | uint16_t result = emulator.chipset.mmu.ReadData(reg_sp) | (((uint16_t)emulator.chipset.mmu.ReadData(reg_sp + 1)) << 8); 81 | reg_sp += 2; 82 | return result; 83 | } 84 | } 85 | 86 | -------------------------------------------------------------------------------- /emulator/src/Chipset/Chipset.cpp: -------------------------------------------------------------------------------- 1 | #include "Chipset.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "../Logger.hpp" 5 | #include "CPU.hpp" 6 | #include "MMU.hpp" 7 | 8 | #include "../Peripheral/ROMWindow.hpp" 9 | #include "../Peripheral/BatteryBackedRAM.hpp" 10 | #include "../Peripheral/Screen.hpp" 11 | #include "../Peripheral/Keyboard.hpp" 12 | #include "../Peripheral/StandbyControl.hpp" 13 | #include "../Peripheral/Miscellaneous.hpp" 14 | #include "../Peripheral/Timer.hpp" 15 | 16 | #include 17 | #include 18 | 19 | namespace casioemu 20 | { 21 | Chipset::Chipset(Emulator &_emulator) : emulator(_emulator), cpu(*new CPU(emulator)), mmu(*new MMU(emulator)) 22 | { 23 | for (size_t ix = 0; ix != INT_COUNT; ++ix) 24 | interrupts_active[ix] = false; 25 | pending_interrupt_count = 0; 26 | 27 | cpu.SetMemoryModel(CPU::MM_LARGE); 28 | 29 | for (auto &segment_index : mmu_segments) 30 | mmu.GenerateSegmentDispatch(segment_index); 31 | 32 | ConstructPeripherals(); 33 | } 34 | 35 | Chipset::~Chipset() 36 | { 37 | DestructPeripherals(); 38 | DestructInterruptSFR(); 39 | 40 | delete &mmu; 41 | delete &cpu; 42 | } 43 | 44 | void Chipset::ConstructInterruptSFR() 45 | { 46 | region_int_mask.Setup(0xF010, 2, "Chipset/InterruptMask", &data_int_mask, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 47 | 48 | region_int_pending.Setup(0xF014, 2, "Chipset/InterruptPending", &data_int_pending, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 49 | } 50 | 51 | void Chipset::DestructInterruptSFR() 52 | { 53 | region_int_pending.Kill(); 54 | region_int_mask.Kill(); 55 | } 56 | 57 | void Chipset::ConstructPeripherals() 58 | { 59 | peripherals.push_front(new ROMWindow(emulator)); 60 | peripherals.push_front(new BatteryBackedRAM(emulator)); 61 | peripherals.push_front(new Screen(emulator)); 62 | peripherals.push_front(new Keyboard(emulator)); 63 | peripherals.push_front(new StandbyControl(emulator)); 64 | peripherals.push_front(new Miscellaneous(emulator)); 65 | peripherals.push_front(new Timer(emulator)); 66 | } 67 | 68 | void Chipset::DestructPeripherals() 69 | { 70 | for (auto &peripheral : peripherals) 71 | { 72 | peripheral->Uninitialise(); 73 | delete peripheral; 74 | } 75 | } 76 | 77 | void Chipset::SetupInternals() 78 | { 79 | std::ifstream rom_handle(emulator.GetModelFilePath(emulator.GetModelInfo("rom_path")), std::ifstream::binary); 80 | if (rom_handle.fail()) 81 | PANIC("std::ifstream failed: %s\n", strerror(errno)); 82 | rom_data = std::vector((std::istreambuf_iterator(rom_handle)), std::istreambuf_iterator()); 83 | 84 | for (auto &peripheral : peripherals) 85 | peripheral->Initialise(); 86 | 87 | ConstructInterruptSFR(); 88 | 89 | cpu.SetupInternals(); 90 | mmu.SetupInternals(); 91 | } 92 | 93 | void Chipset::Reset() 94 | { 95 | data_int_mask = 0; 96 | data_int_pending = 0; 97 | 98 | for (auto &peripheral : peripherals) 99 | peripheral->Reset(); 100 | 101 | cpu.Reset(); 102 | 103 | interrupts_active[INT_RESET] = true; 104 | pending_interrupt_count = 1; 105 | 106 | run_mode = RM_RUN; 107 | } 108 | 109 | void Chipset::Break() 110 | { 111 | if (cpu.GetExceptionLevel() > 1) 112 | { 113 | Reset(); 114 | return; 115 | } 116 | 117 | if (interrupts_active[INT_BREAK]) 118 | return; 119 | interrupts_active[INT_BREAK] = true; 120 | pending_interrupt_count++; 121 | } 122 | 123 | void Chipset::Halt() 124 | { 125 | run_mode = RM_HALT; 126 | } 127 | 128 | void Chipset::Stop() 129 | { 130 | run_mode = RM_STOP; 131 | } 132 | 133 | void Chipset::RaiseEmulator() 134 | { 135 | if (interrupts_active[INT_EMULATOR]) 136 | return; 137 | interrupts_active[INT_EMULATOR] = true; 138 | pending_interrupt_count++; 139 | } 140 | 141 | void Chipset::RaiseNonmaskable() 142 | { 143 | if (interrupts_active[INT_NONMASKABLE]) 144 | return; 145 | interrupts_active[INT_NONMASKABLE] = true; 146 | pending_interrupt_count++; 147 | } 148 | 149 | void Chipset::RaiseMaskable(size_t index) 150 | { 151 | if (index < INT_MASKABLE || index >= INT_SOFTWARE) 152 | PANIC("%zu is not a valid maskable interrupt index\n", index); 153 | if (interrupts_active[index]) 154 | return; 155 | interrupts_active[index] = true; 156 | pending_interrupt_count++; 157 | } 158 | 159 | void Chipset::RaiseSoftware(size_t index) 160 | { 161 | index += 0x40; 162 | if (interrupts_active[index]) 163 | return; 164 | interrupts_active[index] = true; 165 | pending_interrupt_count++; 166 | } 167 | 168 | void Chipset::AcceptInterrupt() 169 | { 170 | size_t old_exception_level = cpu.GetExceptionLevel(); 171 | 172 | size_t index = 0; 173 | // * Reset has priority over everything. 174 | if (interrupts_active[INT_RESET]) 175 | index = INT_RESET; 176 | // * Software interrupts are immediately accepted. 177 | if (!index) 178 | for (size_t ix = INT_SOFTWARE; ix != INT_COUNT; ++ix) 179 | if (interrupts_active[ix]) 180 | { 181 | if (old_exception_level > 1) 182 | PANIC("software interrupt while exception level was greater than 1\n"); 183 | index = ix; 184 | break; 185 | } 186 | // * No need to check the old exception level as NMICI has an exception level of 3. 187 | if (!index && interrupts_active[INT_EMULATOR]) 188 | index = INT_EMULATOR; 189 | // * No need to check the old exception level as BRK initiates a reset if 190 | // the currect exception level is greater than 1. 191 | if (!index && interrupts_active[INT_BREAK]) 192 | index = INT_BREAK; 193 | if (!index && interrupts_active[INT_NONMASKABLE] && old_exception_level <= 2) 194 | index = INT_NONMASKABLE; 195 | if (!index && old_exception_level <= 1) 196 | for (size_t ix = INT_MASKABLE; ix != INT_SOFTWARE; ++ix) 197 | if (interrupts_active[ix]) 198 | { 199 | index = ix; 200 | break; 201 | } 202 | 203 | size_t exception_level; 204 | switch (index) 205 | { 206 | case INT_RESET: 207 | exception_level = 0; 208 | break; 209 | 210 | case INT_BREAK: 211 | case INT_NONMASKABLE: 212 | exception_level = 2; 213 | break; 214 | 215 | case INT_EMULATOR: 216 | exception_level = 3; 217 | break; 218 | 219 | default: 220 | exception_level = 1; 221 | break; 222 | } 223 | 224 | if (index >= INT_MASKABLE && index < INT_SOFTWARE) 225 | { 226 | if (InterruptEnabledBySFR(index)) 227 | { 228 | SetInterruptPendingSFR(index); 229 | if (cpu.GetMasterInterruptEnable()) 230 | cpu.Raise(exception_level, index); 231 | } 232 | } 233 | else 234 | { 235 | cpu.Raise(exception_level, index); 236 | } 237 | 238 | run_mode = RM_RUN; 239 | 240 | // * TODO: introduce delay 241 | 242 | interrupts_active[index] = false; 243 | pending_interrupt_count--; 244 | } 245 | 246 | bool Chipset::InterruptEnabledBySFR(size_t index) 247 | { 248 | return data_int_mask & (1 << (index - managed_interrupt_base)); 249 | } 250 | 251 | bool Chipset::GetInterruptPendingSFR(size_t index) 252 | { 253 | return data_int_pending & (1 << (index - managed_interrupt_base)); 254 | } 255 | 256 | void Chipset::SetInterruptPendingSFR(size_t index) 257 | { 258 | data_int_pending |= (1 << (index - managed_interrupt_base)); 259 | } 260 | 261 | bool Chipset::GetRequireFrame() 262 | { 263 | return std::any_of(peripherals.begin(), peripherals.end(), [](Peripheral *peripheral){ 264 | return peripheral->GetRequireFrame(); 265 | }); 266 | } 267 | 268 | void Chipset::Frame() 269 | { 270 | for (auto peripheral : peripherals) 271 | peripheral->Frame(); 272 | } 273 | 274 | void Chipset::Tick() 275 | { 276 | // * TODO: decrement delay counter, return if it's not 0 277 | 278 | for (auto peripheral : peripherals) 279 | peripheral->Tick(); 280 | 281 | if (pending_interrupt_count) 282 | AcceptInterrupt(); 283 | 284 | for (auto peripheral : peripherals) 285 | peripheral->TickAfterInterrupts(); 286 | 287 | if (run_mode == RM_RUN) 288 | cpu.Next(); 289 | } 290 | 291 | void Chipset::UIEvent(SDL_Event &event) 292 | { 293 | for (auto peripheral : peripherals) 294 | peripheral->UIEvent(event); 295 | } 296 | } 297 | 298 | -------------------------------------------------------------------------------- /emulator/src/Chipset/Chipset.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "MMURegion.hpp" 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace casioemu 12 | { 13 | class Emulator; 14 | class CPU; 15 | class MMU; 16 | class Peripheral; 17 | 18 | class Chipset 19 | { 20 | enum InterruptIndex 21 | { 22 | INT_CHECKFLAG, 23 | INT_RESET, 24 | INT_BREAK, 25 | INT_EMULATOR, 26 | INT_NONMASKABLE, 27 | INT_MASKABLE, 28 | INT_SOFTWARE = 64, 29 | INT_COUNT = 128 30 | }; 31 | 32 | enum RunMode 33 | { 34 | RM_STOP, 35 | RM_HALT, 36 | RM_RUN 37 | }; 38 | RunMode run_mode; 39 | 40 | std::forward_list peripherals; 41 | 42 | /** 43 | * A bunch of internally used methods for encapsulation purposes. 44 | */ 45 | size_t pending_interrupt_count; 46 | bool interrupts_active[INT_COUNT]; 47 | void AcceptInterrupt(); 48 | void RaiseSoftware(size_t index); 49 | 50 | const size_t mmu_segments[3] = {0, 1, 8}; 51 | 52 | void ConstructPeripherals(); 53 | void DestructPeripherals(); 54 | 55 | void ConstructInterruptSFR(); 56 | void DestructInterruptSFR(); 57 | MMURegion region_int_mask, region_int_pending; 58 | uint16_t data_int_mask, data_int_pending; 59 | static const size_t managed_interrupt_base = 4, managed_interrupt_amount = 13; 60 | static const uint16_t interrupt_bitfield_mask = (1 << managed_interrupt_amount) - 1; 61 | 62 | public: 63 | Chipset(Emulator &emulator); 64 | ~Chipset(); 65 | 66 | Emulator &emulator; 67 | CPU &cpu; 68 | MMU &mmu; 69 | std::vector rom_data; 70 | 71 | /** 72 | * This exists because the Emulator that owns this Chipset is not ready 73 | * to supply a ROM path upon construction. It has to call `LoadROM` later 74 | * in its constructor. 75 | */ 76 | void SetupInternals(); 77 | 78 | /** 79 | * See 1.3.7 in the nX-U8 manual. 80 | */ 81 | void Reset(); 82 | void Break(); 83 | void Halt(); 84 | void Stop(); 85 | void RaiseEmulator(); 86 | void RaiseNonmaskable(); 87 | void RaiseMaskable(size_t index); 88 | bool InterruptEnabledBySFR(size_t index); 89 | void SetInterruptPendingSFR(size_t index); 90 | bool GetInterruptPendingSFR(size_t index); 91 | 92 | void Tick(); 93 | bool GetRequireFrame(); 94 | void Frame(); 95 | void UIEvent(SDL_Event &event); 96 | 97 | friend class CPU; 98 | }; 99 | } 100 | 101 | -------------------------------------------------------------------------------- /emulator/src/Chipset/InterruptSource.cpp: -------------------------------------------------------------------------------- 1 | #include "InterruptSource.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | 6 | namespace casioemu 7 | { 8 | InterruptSource::InterruptSource() 9 | { 10 | setup_done = false; 11 | } 12 | 13 | void InterruptSource::Setup(size_t _interrupt_index, Emulator &_emulator) 14 | { 15 | if (setup_done) 16 | PANIC("Setup invoked twice\n"); 17 | 18 | interrupt_index = _interrupt_index; 19 | emulator = &_emulator; 20 | 21 | setup_done = true; 22 | } 23 | 24 | bool InterruptSource::Enabled() 25 | { 26 | if (!setup_done) 27 | PANIC("Setup not invoked\n"); 28 | 29 | return emulator->chipset.InterruptEnabledBySFR(interrupt_index); 30 | } 31 | 32 | bool InterruptSource::TryRaise() 33 | { 34 | if (!setup_done) 35 | PANIC("Setup not invoked\n"); 36 | 37 | if (!emulator->chipset.InterruptEnabledBySFR(interrupt_index) || emulator->chipset.GetInterruptPendingSFR(interrupt_index)) 38 | { 39 | raise_success = false; 40 | } 41 | else 42 | { 43 | emulator->chipset.RaiseMaskable(interrupt_index); 44 | raise_success = true; 45 | } 46 | 47 | return raise_success; 48 | } 49 | 50 | bool InterruptSource::Success() 51 | { 52 | if (!setup_done) 53 | PANIC("Setup not invoked\n"); 54 | 55 | return raise_success && emulator->chipset.GetInterruptPendingSFR(interrupt_index); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /emulator/src/Chipset/InterruptSource.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | namespace casioemu 5 | { 6 | class Emulator; 7 | 8 | class InterruptSource 9 | { 10 | Emulator *emulator; 11 | bool raise_success, setup_done; 12 | size_t interrupt_index; 13 | 14 | public: 15 | InterruptSource(); 16 | void Setup(size_t interrupt_index, Emulator &_emulator); 17 | bool Enabled(); 18 | bool TryRaise(); 19 | bool Success(); 20 | }; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /emulator/src/Chipset/MMU.cpp: -------------------------------------------------------------------------------- 1 | #include "MMU.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "../Logger.hpp" 6 | 7 | namespace casioemu 8 | { 9 | MMU::MMU(Emulator &_emulator) : emulator(_emulator) 10 | { 11 | segment_dispatch = new MMURegion **[0x100]; 12 | for (size_t ix = 0; ix != 0x100; ++ix) 13 | segment_dispatch[ix] = nullptr; 14 | } 15 | 16 | MMU::~MMU() 17 | { 18 | for (size_t ix = 0; ix != 0x100; ++ix) 19 | if (segment_dispatch[ix]) 20 | delete[] segment_dispatch[ix]; 21 | 22 | delete[] segment_dispatch; 23 | } 24 | 25 | void MMU::GenerateSegmentDispatch(size_t segment_index) 26 | { 27 | segment_dispatch[segment_index] = new MMURegion *[0x10000]; 28 | for (size_t ix = 0; ix != 0x10000; ++ix) 29 | segment_dispatch[segment_index][ix] = nullptr; 30 | } 31 | 32 | void MMU::SetupInternals() 33 | { 34 | *(MMU **)lua_newuserdata(emulator.lua_state, sizeof(MMU *)) = this; 35 | lua_newtable(emulator.lua_state); 36 | lua_pushcfunction(emulator.lua_state, [](lua_State *lua_state) { 37 | MMU *mmu = *(MMU **)lua_topointer(lua_state, 1); 38 | lua_pushinteger(lua_state, mmu->ReadCode(lua_tointeger(lua_state, 2))); 39 | return 1; 40 | }); 41 | lua_setfield(emulator.lua_state, -2, "__index"); 42 | lua_pushcfunction(emulator.lua_state, [](lua_State *) { 43 | return 0; 44 | }); 45 | lua_setfield(emulator.lua_state, -2, "__newindex"); 46 | lua_setmetatable(emulator.lua_state, -2); 47 | lua_setglobal(emulator.lua_state, "code"); 48 | 49 | *(MMU **)lua_newuserdata(emulator.lua_state, sizeof(MMU *)) = this; 50 | lua_newtable(emulator.lua_state); 51 | lua_pushcfunction(emulator.lua_state, [](lua_State *lua_state) { 52 | MMU *mmu = *(MMU **)lua_topointer(lua_state, 1); 53 | lua_pushinteger(lua_state, mmu->ReadData(lua_tointeger(lua_state, 2))); 54 | return 1; 55 | }); 56 | lua_setfield(emulator.lua_state, -2, "__index"); 57 | lua_pushcfunction(emulator.lua_state, [](lua_State *lua_state) { 58 | MMU *mmu = *(MMU **)lua_topointer(lua_state, 1); 59 | mmu->WriteData(lua_tointeger(lua_state, 2), lua_tointeger(lua_state, 3)); 60 | return 0; 61 | }); 62 | lua_setfield(emulator.lua_state, -2, "__newindex"); 63 | lua_setmetatable(emulator.lua_state, -2); 64 | lua_setglobal(emulator.lua_state, "data"); 65 | } 66 | 67 | uint16_t MMU::ReadCode(size_t offset) 68 | { 69 | if (offset >= (1 << 20)) 70 | PANIC("offset doesn't fit 20 bits\n"); 71 | if (offset & 1) 72 | PANIC("offset has LSB set\n"); 73 | 74 | size_t segment_index = offset >> 16; 75 | size_t segment_offset = offset & 0xFFFF; 76 | 77 | if (!segment_index) 78 | return (((uint16_t)emulator.chipset.rom_data[segment_offset + 1]) << 8) | emulator.chipset.rom_data[segment_offset]; 79 | 80 | MMURegion **segment = segment_dispatch[segment_index]; 81 | if (!segment) 82 | { 83 | logger::Info("code read from offset %04zX of unmapped segment %02zX\n", segment_offset, segment_index); 84 | emulator.HandleMemoryError(); 85 | return 0; 86 | } 87 | 88 | MMURegion *region = segment[segment_offset]; 89 | if (!region) 90 | { 91 | logger::Info("code read from unmapped offset %04zX of segment %02zX\n", segment_offset, segment_index); 92 | emulator.HandleMemoryError(); 93 | return 0; 94 | } 95 | 96 | return (((uint16_t)region->read(region, offset + 1)) << 8) | region->read(region, offset); 97 | } 98 | 99 | uint8_t MMU::ReadData(size_t offset) 100 | { 101 | if (offset >= (1 << 24)) 102 | PANIC("offset doesn't fit 24 bits\n"); 103 | 104 | size_t segment_index = offset >> 16; 105 | size_t segment_offset = offset & 0xFFFF; 106 | 107 | MMURegion **segment = segment_dispatch[segment_index]; 108 | if (!segment) 109 | { 110 | logger::Info("read from offset %04zX of unmapped segment %02zX\n", segment_offset, segment_index); 111 | emulator.HandleMemoryError(); 112 | return 0; 113 | } 114 | 115 | MMURegion *region = segment[segment_offset]; 116 | if (!region) 117 | { 118 | logger::Info("read from unmapped offset %04zX of segment %02zX\n", segment_offset, segment_index); 119 | emulator.HandleMemoryError(); 120 | return 0; 121 | } 122 | 123 | return region->read(region, offset); 124 | } 125 | 126 | void MMU::WriteData(size_t offset, uint8_t data) 127 | { 128 | if (offset >= (1 << 24)) 129 | PANIC("offset doesn't fit 24 bits\n"); 130 | 131 | size_t segment_index = offset >> 16; 132 | size_t segment_offset = offset & 0xFFFF; 133 | 134 | MMURegion **segment = segment_dispatch[segment_index]; 135 | if (!segment) 136 | { 137 | logger::Info("write to offset %04zX of unmapped segment %02zX (%02zX)\n", segment_offset, segment_index, data); 138 | emulator.HandleMemoryError(); 139 | return; 140 | } 141 | 142 | MMURegion *region = segment[segment_offset]; 143 | if (!region) 144 | { 145 | logger::Info("write to unmapped offset %04zX of segment %02zX (%02zX)\n", segment_offset, segment_index, data); 146 | emulator.HandleMemoryError(); 147 | return; 148 | } 149 | 150 | region->write(region, offset, data); 151 | } 152 | 153 | void MMU::RegisterRegion(MMURegion *region) 154 | { 155 | for (size_t ix = region->base; ix != region->base + region->size; ++ix) 156 | { 157 | if (segment_dispatch[ix >> 16][ix & 0xFFFF]) 158 | PANIC("MMU region overlap at %06zX\n", ix); 159 | segment_dispatch[ix >> 16][ix & 0xFFFF] = region; 160 | } 161 | } 162 | 163 | void MMU::UnregisterRegion(MMURegion *region) 164 | { 165 | for (size_t ix = region->base; ix != region->base + region->size; ++ix) 166 | { 167 | if (!segment_dispatch[ix >> 16][ix & 0xFFFF]) 168 | PANIC("MMU region double-hole at %06zX\n", ix); 169 | segment_dispatch[ix >> 16][ix & 0xFFFF] = nullptr; 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /emulator/src/Chipset/MMU.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "MMURegion.hpp" 5 | 6 | #include 7 | #include 8 | 9 | namespace casioemu 10 | { 11 | class Emulator; 12 | 13 | class MMU 14 | { 15 | private: 16 | Emulator &emulator; 17 | 18 | MMURegion ***segment_dispatch; 19 | 20 | public: 21 | MMU(Emulator &emulator); 22 | ~MMU(); 23 | void SetupInternals(); 24 | void GenerateSegmentDispatch(size_t segment_index); 25 | uint16_t ReadCode(size_t offset); 26 | uint8_t ReadData(size_t offset); 27 | void WriteData(size_t offset, uint8_t data); 28 | 29 | void RegisterRegion(MMURegion *region); 30 | void UnregisterRegion(MMURegion *region); 31 | }; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /emulator/src/Chipset/MMURegion.cpp: -------------------------------------------------------------------------------- 1 | #include "MMURegion.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "Chipset.hpp" 5 | #include "MMU.hpp" 6 | 7 | namespace casioemu 8 | { 9 | MMURegion::MMURegion() 10 | { 11 | setup_done = false; 12 | } 13 | 14 | MMURegion::~MMURegion() 15 | { 16 | if (setup_done) 17 | Kill(); 18 | } 19 | 20 | void MMURegion::Setup(size_t _base, size_t _size, std::string _description, void *_userdata, ReadFunction _read, WriteFunction _write, Emulator &_emulator) 21 | { 22 | if (setup_done) 23 | PANIC("Setup invoked twice\n"); 24 | 25 | emulator = &_emulator; 26 | base = _base; 27 | size = _size; 28 | description = _description; 29 | userdata = _userdata; 30 | read = _read; 31 | write = _write; 32 | 33 | emulator->chipset.mmu.RegisterRegion(this); 34 | setup_done = true; 35 | } 36 | 37 | void MMURegion::Kill() 38 | { 39 | emulator->chipset.mmu.UnregisterRegion(this); 40 | setup_done = false; 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /emulator/src/Chipset/MMURegion.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "../Logger.hpp" 5 | 6 | #include 7 | #include 8 | 9 | namespace casioemu 10 | { 11 | class Emulator; 12 | 13 | struct MMURegion 14 | { 15 | typedef uint8_t (*ReadFunction)(MMURegion *, size_t); 16 | typedef void (*WriteFunction)(MMURegion *, size_t, uint8_t); 17 | 18 | size_t base, size; 19 | std::string description; 20 | void *userdata; 21 | ReadFunction read; 22 | WriteFunction write; 23 | bool setup_done; 24 | Emulator *emulator; 25 | 26 | MMURegion(); 27 | ~MMURegion(); 28 | void Setup(size_t base, size_t size, std::string description, void *userdata, ReadFunction read, WriteFunction write, Emulator &emulator); 29 | void Kill(); 30 | 31 | template 32 | static uint8_t IgnoreRead(MMURegion *, size_t) 33 | { 34 | return read_value; 35 | } 36 | 37 | static void IgnoreWrite(MMURegion *, size_t, uint8_t) 38 | { 39 | } 40 | 41 | template 42 | static uint8_t DefaultRead(MMURegion *region, size_t offset) 43 | { 44 | value_type *value = (value_type *)(region->userdata); 45 | return ((*value) & mask) >> ((offset - region->base) * 8); 46 | } 47 | 48 | template 49 | static void DefaultWrite(MMURegion *region, size_t offset, uint8_t data) 50 | { 51 | value_type *value = (value_type *)(region->userdata); 52 | *value &= ~(((value_type)0xFF) << ((offset - region->base) * 8)); 53 | *value |= ((value_type)data) << ((offset - region->base) * 8); 54 | *value &= mask; 55 | } 56 | 57 | template 58 | static uint8_t DefaultReadLog(MMURegion *region, size_t offset) 59 | { 60 | logger::Info("SFR read from %06X\n", offset); 61 | value_type *value = (value_type *)(region->userdata); 62 | return ((*value) & mask) >> ((offset - region->base) * 8); 63 | } 64 | 65 | template 66 | static void DefaultWriteLog(MMURegion *region, size_t offset, uint8_t data) 67 | { 68 | value_type *value = (value_type *)(region->userdata); 69 | *value &= ~(((value_type)0xFF) << ((offset - region->base) * 8)); 70 | *value |= ((value_type)data) << ((offset - region->base) * 8); 71 | *value &= mask; 72 | logger::Info("SFR write to %06X (%02X)\n", offset, data); 73 | } 74 | }; 75 | } 76 | -------------------------------------------------------------------------------- /emulator/src/Config.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #ifdef __GNUG__ 7 | # define FUNCTION_NAME __PRETTY_FUNCTION__ 8 | #else 9 | # define FUNCTION_NAME __func__ 10 | #endif 11 | #define PANIC(...) (fprintf(stderr, "%s:%i: in %s: ", __FILE__, __LINE__, FUNCTION_NAME), fprintf(stderr, __VA_ARGS__), exit(1)) 12 | 13 | #define MODEL_DEF_NAME "model.def" 14 | 15 | -------------------------------------------------------------------------------- /emulator/src/Data/ColourInfo.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | struct ColourInfo 9 | { 10 | int r, g, b; 11 | }; 12 | } 13 | -------------------------------------------------------------------------------- /emulator/src/Data/EventCode.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace casioemu 4 | { 5 | enum EventCode 6 | { 7 | CE_EVENT_INPUT, 8 | CE_FRAME_REQUEST 9 | }; 10 | } 11 | 12 | -------------------------------------------------------------------------------- /emulator/src/Data/ModelInfo.cpp: -------------------------------------------------------------------------------- 1 | #include "ModelInfo.hpp" 2 | 3 | #include "../Emulator.hpp" 4 | #include "SpriteInfo.hpp" 5 | #include "ColourInfo.hpp" 6 | 7 | namespace casioemu 8 | { 9 | ModelInfo Emulator::GetModelInfo(std::string key) 10 | { 11 | return ModelInfo(*this, key); 12 | } 13 | 14 | ModelInfo::ModelInfo(Emulator &_emulator, std::string _key) : emulator(_emulator) 15 | { 16 | key = _key; 17 | } 18 | 19 | ModelInfo::operator std::string() 20 | { 21 | lua_geti(emulator.lua_state, LUA_REGISTRYINDEX, emulator.lua_model_ref); 22 | if (lua_getfield(emulator.lua_state, -1, key.c_str()) != LUA_TSTRING) 23 | PANIC("key '%s' is not a string\n", key.c_str()); 24 | const char *value = lua_tostring(emulator.lua_state, -1); 25 | lua_pop(emulator.lua_state, 2); 26 | return std::string(value); 27 | } 28 | 29 | ModelInfo::operator int() 30 | { 31 | lua_geti(emulator.lua_state, LUA_REGISTRYINDEX, emulator.lua_model_ref); 32 | if (lua_getfield(emulator.lua_state, -1, key.c_str()) != LUA_TNUMBER) 33 | PANIC("key '%s' is not a number\n", key.c_str()); 34 | int value = lua_tointeger(emulator.lua_state, -1); 35 | lua_pop(emulator.lua_state, 2); 36 | return value; 37 | } 38 | 39 | ModelInfo::operator SpriteInfo() 40 | { 41 | lua_geti(emulator.lua_state, LUA_REGISTRYINDEX, emulator.lua_model_ref); 42 | if (lua_getfield(emulator.lua_state, -1, key.c_str()) != LUA_TTABLE) 43 | PANIC("key '%s' is not a table\n", key.c_str()); 44 | 45 | for (int ix = 0; ix != 6; ++ix) 46 | if (lua_geti(emulator.lua_state, -1 - ix, ix + 1) != LUA_TNUMBER) 47 | PANIC("key '%s'[%i] is not a number\n", key.c_str(), ix + 1); 48 | 49 | SpriteInfo sprite_info; 50 | sprite_info.src.x = lua_tointeger(emulator.lua_state, -6); 51 | sprite_info.src.y = lua_tointeger(emulator.lua_state, -5); 52 | sprite_info.src.w = lua_tointeger(emulator.lua_state, -4); 53 | sprite_info.src.h = lua_tointeger(emulator.lua_state, -3); 54 | sprite_info.dest.x = lua_tointeger(emulator.lua_state, -2); 55 | sprite_info.dest.y = lua_tointeger(emulator.lua_state, -1); 56 | sprite_info.dest.w = sprite_info.src.w; 57 | sprite_info.dest.h = sprite_info.src.h; 58 | 59 | lua_pop(emulator.lua_state, 7); 60 | return sprite_info; 61 | } 62 | 63 | ModelInfo::operator ColourInfo() 64 | { 65 | lua_geti(emulator.lua_state, LUA_REGISTRYINDEX, emulator.lua_model_ref); 66 | if (lua_getfield(emulator.lua_state, -1, key.c_str()) != LUA_TTABLE) 67 | PANIC("key '%s' is not a table\n", key.c_str()); 68 | 69 | for (int ix = 0; ix != 3; ++ix) 70 | if (lua_geti(emulator.lua_state, -1 - ix, ix + 1) != LUA_TNUMBER) 71 | PANIC("key '%s'[%i] is not a number\n", key.c_str(), ix + 1); 72 | 73 | ColourInfo colour_info; 74 | colour_info.r = lua_tointeger(emulator.lua_state, -3); 75 | colour_info.g = lua_tointeger(emulator.lua_state, -2); 76 | colour_info.b = lua_tointeger(emulator.lua_state, -1); 77 | 78 | lua_pop(emulator.lua_state, 4); 79 | return colour_info; 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /emulator/src/Data/ModelInfo.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | class Emulator; 9 | class SpriteInfo; 10 | class ColourInfo; 11 | 12 | struct ModelInfo 13 | { 14 | ModelInfo(Emulator &emulator, std::string key); 15 | Emulator &emulator; 16 | std::string key; 17 | 18 | operator std::string(); 19 | operator int(); 20 | operator SpriteInfo(); 21 | operator ColourInfo(); 22 | }; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /emulator/src/Data/SpriteInfo.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | struct SpriteInfo 9 | { 10 | SDL_Rect src, dest; 11 | }; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /emulator/src/Emulator.cpp: -------------------------------------------------------------------------------- 1 | #include "Emulator.hpp" 2 | 3 | #include "Chipset/Chipset.hpp" 4 | #include "Logger.hpp" 5 | #include "Data/EventCode.hpp" 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | namespace casioemu 13 | { 14 | Emulator::Emulator(std::map &_argv_map, unsigned int _timer_interval, unsigned int _cycles_per_second, bool _paused) : paused(_paused), argv_map(_argv_map), cycles(_cycles_per_second, _timer_interval), chipset(*new Chipset(*this)) 15 | { 16 | std::lock_guard access_lock(access_mx); 17 | 18 | running = true; 19 | timer_interval = _timer_interval; 20 | model_path = argv_map["model"]; 21 | 22 | lua_state = luaL_newstate(); 23 | luaL_openlibs(lua_state); 24 | 25 | SetupLuaAPI(); 26 | LoadModelDefition(); 27 | 28 | interface_background = GetModelInfo("rsd_interface"); 29 | 30 | window = SDL_CreateWindow( 31 | std::string(GetModelInfo("model_name")).c_str(), 32 | SDL_WINDOWPOS_UNDEFINED, 33 | SDL_WINDOWPOS_UNDEFINED, 34 | interface_background.src.w, 35 | interface_background.src.h, 36 | SDL_WINDOW_SHOWN 37 | ); 38 | if (!window) 39 | PANIC("SDL_CreateWindow failed: %s\n", SDL_GetError()); 40 | renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); 41 | if (!renderer) 42 | PANIC("SDL_CreateRenderer failed: %s\n", SDL_GetError()); 43 | 44 | SDL_Surface *loaded_surface = IMG_Load(GetModelFilePath(GetModelInfo("interface_image_path")).c_str()); 45 | if (!loaded_surface) 46 | PANIC("IMG_Load failed: %s\n", IMG_GetError()); 47 | interface_texture = SDL_CreateTextureFromSurface(renderer, loaded_surface); 48 | SDL_FreeSurface(loaded_surface); 49 | 50 | SetupInternals(); 51 | cycles.Reset(); 52 | 53 | tick_thread = new std::thread([this] { 54 | while (1) 55 | { 56 | { 57 | std::lock_guard access_lock(access_mx); 58 | if (!Running()) 59 | break; 60 | TimerCallback(); 61 | } 62 | 63 | std::this_thread::sleep_for(std::chrono::milliseconds(timer_interval)); 64 | } 65 | }); 66 | 67 | RunStartupScript(); 68 | 69 | chipset.Reset(); 70 | 71 | if (argv_map.find("paused") != argv_map.end()) 72 | SetPaused(true); 73 | 74 | pause_on_mem_error = argv_map.find("pause_on_mem_error") != argv_map.end(); 75 | } 76 | 77 | Emulator::~Emulator() 78 | { 79 | if (tick_thread->joinable()) 80 | tick_thread->join(); 81 | delete tick_thread; 82 | 83 | std::lock_guard access_lock(access_mx); 84 | 85 | SDL_DestroyTexture(interface_texture); 86 | SDL_DestroyRenderer(renderer); 87 | SDL_DestroyWindow(window); 88 | 89 | luaL_unref(lua_state, LUA_REGISTRYINDEX, lua_model_ref); 90 | lua_close(lua_state); 91 | delete &chipset; 92 | } 93 | 94 | void Emulator::HandleMemoryError() 95 | { 96 | if (pause_on_mem_error) 97 | { 98 | logger::Info("execution paused due to memory error\n"); 99 | SetPaused(true); 100 | } 101 | } 102 | 103 | void Emulator::UIEvent(SDL_Event &event) 104 | { 105 | std::lock_guard access_lock(access_mx); 106 | 107 | chipset.UIEvent(event); 108 | } 109 | 110 | void Emulator::RunStartupScript() 111 | { 112 | if (argv_map.find("script") == argv_map.end()) 113 | return; 114 | 115 | if (luaL_loadfile(lua_state, argv_map["script"].c_str()) != LUA_OK) 116 | { 117 | logger::Info("%s\n", lua_tostring(lua_state, -1)); 118 | lua_pop(lua_state, 1); 119 | return; 120 | } 121 | 122 | if (lua_pcall(lua_state, 0, 1, 0) != LUA_OK) 123 | { 124 | logger::Info("%s\n", lua_tostring(lua_state, -1)); 125 | lua_pop(lua_state, 1); 126 | return; 127 | } 128 | } 129 | 130 | void Emulator::SetupLuaAPI() 131 | { 132 | *(Emulator **)lua_newuserdata(lua_state, sizeof(Emulator *)) = this; 133 | lua_newtable(lua_state); 134 | lua_newtable(lua_state); 135 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 136 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 137 | emu->Tick(); 138 | return 0; 139 | }); 140 | lua_setfield(lua_state, -2, "tick"); 141 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 142 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 143 | emu->Shutdown(); 144 | return 0; 145 | }); 146 | lua_setfield(lua_state, -2, "shutdown"); 147 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 148 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 149 | emu->SetPaused(lua_toboolean(lua_state, 2)); 150 | return 0; 151 | }); 152 | lua_setfield(lua_state, -2, "set_paused"); 153 | lua_model_ref = LUA_REFNIL; 154 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 155 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 156 | if (emu->lua_model_ref != LUA_REFNIL) 157 | PANIC("emu.model invoked twice\n"); 158 | emu->lua_model_ref = luaL_ref(lua_state, LUA_REGISTRYINDEX); 159 | return 0; 160 | }); 161 | lua_setfield(lua_state, -2, "model"); 162 | lua_pre_tick_ref = LUA_REFNIL; 163 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 164 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 165 | luaL_unref(lua_state, LUA_REGISTRYINDEX, emu->lua_pre_tick_ref); 166 | emu->lua_pre_tick_ref = luaL_ref(lua_state, LUA_REGISTRYINDEX); 167 | return 0; 168 | }); 169 | lua_setfield(lua_state, -2, "pre_tick"); 170 | lua_post_tick_ref = LUA_REFNIL; 171 | lua_pushcfunction(lua_state, [](lua_State *lua_state) { 172 | Emulator *emu = *(Emulator **)lua_topointer(lua_state, 1); 173 | luaL_unref(lua_state, LUA_REGISTRYINDEX, emu->lua_post_tick_ref); 174 | emu->lua_post_tick_ref = luaL_ref(lua_state, LUA_REGISTRYINDEX); 175 | return 0; 176 | }); 177 | lua_setfield(lua_state, -2, "post_tick"); 178 | lua_setfield(lua_state, -2, "__index"); 179 | lua_pushcfunction(lua_state, [](lua_State *) { 180 | return 0; 181 | }); 182 | lua_setfield(lua_state, -2, "__newindex"); 183 | lua_setmetatable(lua_state, -2); 184 | lua_setglobal(lua_state, "emu"); 185 | } 186 | 187 | void Emulator::SetupInternals() 188 | { 189 | chipset.SetupInternals(); 190 | } 191 | 192 | void Emulator::LoadModelDefition() 193 | { 194 | if (luaL_loadfile(lua_state, (model_path + "/model.lua").c_str()) != LUA_OK) 195 | PANIC("LoadModelDefition failed: %s\n", lua_tostring(lua_state, -1)); 196 | 197 | if (lua_pcall(lua_state, 0, 0, 0) != LUA_OK) 198 | PANIC("LoadModelDefition failed: %s\n", lua_tostring(lua_state, -1)); 199 | 200 | if (lua_model_ref == LUA_REFNIL) 201 | PANIC("LoadModelDefition failed: model failed to call emu.model\n"); 202 | } 203 | 204 | std::string Emulator::GetModelFilePath(std::string relative_path) 205 | { 206 | return model_path + "/" + relative_path; 207 | } 208 | 209 | void Emulator::TimerCallback() 210 | { 211 | std::lock_guard access_lock(access_mx); 212 | 213 | Uint64 cycles_to_emulate = cycles.GetDelta(); 214 | for (Uint64 ix = 0; ix != cycles_to_emulate; ++ix) 215 | if (!paused) 216 | Tick(); 217 | 218 | SDL_Event event; 219 | SDL_zero(event); 220 | event.type = SDL_USEREVENT; 221 | event.user.code = CE_FRAME_REQUEST; 222 | SDL_PushEvent(&event); 223 | } 224 | 225 | void Emulator::Frame() 226 | { 227 | std::lock_guard access_lock(access_mx); 228 | if (chipset.GetRequireFrame()) 229 | { 230 | SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); 231 | SDL_RenderClear(renderer); 232 | SDL_SetTextureColorMod(interface_texture, 255, 255, 255); 233 | SDL_SetTextureAlphaMod(interface_texture, 255); 234 | SDL_RenderCopy(renderer, interface_texture, &interface_background.src, &interface_background.dest); 235 | chipset.Frame(); 236 | SDL_RenderPresent(renderer); 237 | } 238 | } 239 | 240 | void Emulator::Tick() 241 | { 242 | if (lua_pre_tick_ref != LUA_REFNIL) 243 | { 244 | lua_geti(lua_state, LUA_REGISTRYINDEX, lua_pre_tick_ref); 245 | if (lua_pcall(lua_state, 0, 0, 0) != LUA_OK) 246 | { 247 | logger::Info("pre-tick hook failed: %s\n", lua_tostring(lua_state, -1)); 248 | lua_pop(lua_state, 1); 249 | luaL_unref(lua_state, LUA_REGISTRYINDEX, lua_pre_tick_ref); 250 | lua_pre_tick_ref = LUA_REFNIL; 251 | logger::Info(" pre-tick hook unregistered\n"); 252 | } 253 | } 254 | 255 | chipset.Tick(); 256 | 257 | if (lua_post_tick_ref != LUA_REFNIL) 258 | { 259 | lua_geti(lua_state, LUA_REGISTRYINDEX, lua_post_tick_ref); 260 | if (lua_pcall(lua_state, 0, 0, 0) != LUA_OK) 261 | { 262 | logger::Info("post-tick hook failed: %s\n", lua_tostring(lua_state, -1)); 263 | lua_pop(lua_state, 1); 264 | luaL_unref(lua_state, LUA_REGISTRYINDEX, lua_post_tick_ref); 265 | lua_post_tick_ref = LUA_REFNIL; 266 | logger::Info(" post-tick hook unregistered\n"); 267 | } 268 | } 269 | } 270 | 271 | bool Emulator::Running() 272 | { 273 | return running; 274 | } 275 | 276 | bool Emulator::GetPaused() 277 | { 278 | return paused; 279 | } 280 | 281 | void Emulator::Shutdown() 282 | { 283 | std::lock_guard access_lock(access_mx); 284 | 285 | running = false; 286 | } 287 | 288 | void Emulator::ExecuteCommand(std::string command) 289 | { 290 | std::lock_guard access_lock(access_mx); 291 | 292 | const char *ugly_string_data_ptr = command.c_str(); 293 | if (lua_load(lua_state, [](lua_State *, void *data, size_t *size) { 294 | char **ugly_string_data_ptr_ptr = (char **)data; 295 | if (!*ugly_string_data_ptr_ptr) 296 | return (const char *)nullptr; 297 | const char *result = *ugly_string_data_ptr_ptr; 298 | *size = strlen(result); 299 | *ugly_string_data_ptr_ptr = nullptr; 300 | return result; 301 | }, &ugly_string_data_ptr, "stdin", "t") != LUA_OK) 302 | { 303 | logger::Info("%s\n", lua_tostring(lua_state, -1)); 304 | lua_pop(lua_state, 1); 305 | return; 306 | } 307 | 308 | if (lua_pcall(lua_state, 0, 0, 0) != LUA_OK) 309 | { 310 | logger::Info("%s\n", lua_tostring(lua_state, -1)); 311 | lua_pop(lua_state, 1); 312 | return; 313 | } 314 | } 315 | 316 | void Emulator::SetPaused(bool _paused) 317 | { 318 | paused = _paused; 319 | } 320 | 321 | Emulator::Cycles::Cycles(Uint64 _cycles_per_second, unsigned int _timer_interval) 322 | { 323 | cycles_per_second = _cycles_per_second; 324 | timer_interval = _timer_interval; 325 | diff_cap = cycles_per_second * timer_interval / 1000; 326 | performance_frequency = SDL_GetPerformanceFrequency(); 327 | } 328 | 329 | void Emulator::Cycles::Reset() 330 | { 331 | ticks_at_reset = SDL_GetPerformanceCounter(); 332 | cycles_emulated = 0; 333 | } 334 | 335 | Uint64 Emulator::Cycles::GetDelta() 336 | { 337 | Uint64 ticks_now = SDL_GetPerformanceCounter(); 338 | Uint64 cycles_to_have_been_emulated_by_now = (double)(ticks_now - ticks_at_reset) / performance_frequency * cycles_per_second; 339 | Uint64 diff = cycles_to_have_been_emulated_by_now - cycles_emulated; 340 | if (diff > diff_cap) 341 | diff = diff_cap; 342 | cycles_emulated = cycles_to_have_been_emulated_by_now; 343 | return diff; 344 | } 345 | 346 | SDL_Renderer *Emulator::GetRenderer() 347 | { 348 | return renderer; 349 | } 350 | 351 | SDL_Texture *Emulator::GetInterfaceTexture() 352 | { 353 | return interface_texture; 354 | } 355 | 356 | unsigned int Emulator::GetCyclesPerSecond() 357 | { 358 | return cycles.cycles_per_second; 359 | } 360 | } 361 | -------------------------------------------------------------------------------- /emulator/src/Emulator.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Config.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "Data/ModelInfo.hpp" 13 | #include "Data/SpriteInfo.hpp" 14 | 15 | namespace casioemu 16 | { 17 | class Chipset; 18 | class CPU; 19 | class MMU; 20 | 21 | class Emulator 22 | { 23 | SDL_Window *window; 24 | SDL_Renderer *renderer; 25 | SDL_Texture *interface_texture; 26 | unsigned int timer_interval; 27 | bool running, paused; 28 | unsigned int last_frame_tick_count; 29 | std::string model_path; 30 | bool pause_on_mem_error; 31 | 32 | std::thread *tick_thread; 33 | 34 | SpriteInfo interface_background; 35 | 36 | /** 37 | * A bunch of internally used methods for encapsulation purposes. 38 | */ 39 | void LoadModelDefition(); 40 | void TimerCallback(); 41 | void SetupLuaAPI(); 42 | void SetupInternals(); 43 | void RunStartupScript(); 44 | 45 | public: 46 | Emulator(std::map &argv_map, unsigned int timer_interval, unsigned int cycles_per_second, bool paused = false); 47 | ~Emulator(); 48 | 49 | std::recursive_mutex access_mx; 50 | lua_State *lua_state; 51 | int lua_model_ref, lua_pre_tick_ref, lua_post_tick_ref; 52 | std::map &argv_map; 53 | 54 | private: 55 | /** 56 | * The cycle manager structure. This structure is reset every time the 57 | * emulator starts emulating CPU cycles and in every timer callback 58 | * it's queried for the number of cycles that need to be emulated in the 59 | * callback. This ensures that only as many cycles are emulated in a period 60 | * of time as many would be in real life. 61 | */ 62 | struct Cycles 63 | { 64 | Cycles(Uint64 cycles_per_second, unsigned int timer_interval); 65 | void Reset(); 66 | Uint64 GetDelta(); 67 | Uint64 ticks_at_reset, cycles_emulated, cycles_per_second, performance_frequency, diff_cap; 68 | unsigned int timer_interval; 69 | } cycles; 70 | 71 | public: 72 | /** 73 | * A reference to the emulator chipset. This object holds all CPU, MMU, memory and 74 | * peripheral state. The emulator interfaces with the chipset by issuing interrupts 75 | * and rendering the screen buffer. It may also read internal state for testing purposes. 76 | */ 77 | Chipset &chipset; 78 | 79 | bool Running(); 80 | void HandleMemoryError(); 81 | void Shutdown(); 82 | void Tick(); 83 | void Frame(); 84 | void ExecuteCommand(std::string command); 85 | unsigned int GetCyclesPerSecond(); 86 | bool GetPaused(); 87 | void SetPaused(bool paused); 88 | void UIEvent(SDL_Event &event); 89 | SDL_Renderer *GetRenderer(); 90 | SDL_Texture *GetInterfaceTexture(); 91 | ModelInfo GetModelInfo(std::string key); 92 | std::string GetModelFilePath(std::string relative_path); 93 | 94 | friend class ModelInfo; 95 | friend class CPU; 96 | friend class MMU; 97 | }; 98 | } 99 | -------------------------------------------------------------------------------- /emulator/src/Logger.cpp: -------------------------------------------------------------------------------- 1 | #include "Logger.hpp" 2 | 3 | #include 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | namespace logger 9 | { 10 | void Info(const char *format, ...) 11 | { 12 | va_list args; 13 | va_start(args, format); 14 | vprintf(format, args); 15 | va_end(args); 16 | } 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /emulator/src/Logger.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Config.hpp" 3 | 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | namespace logger 9 | { 10 | void Info(const char *format, ...); 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/BatteryBackedRAM.cpp: -------------------------------------------------------------------------------- 1 | #include "BatteryBackedRAM.hpp" 2 | 3 | #include "../Chipset/MMU.hpp" 4 | #include "../Emulator.hpp" 5 | #include "../Chipset/Chipset.hpp" 6 | #include "../Logger.hpp" 7 | 8 | #include 9 | 10 | namespace casioemu 11 | { 12 | void BatteryBackedRAM::Initialise() 13 | { 14 | ram_buffer = new uint8_t[0xE00]; 15 | for (size_t ix = 0; ix != 0xE00; ++ix) 16 | ram_buffer[ix] = 0; 17 | 18 | ram_file_requested = false; 19 | if (emulator.argv_map.find("ram") != emulator.argv_map.end()) 20 | { 21 | ram_file_requested = true; 22 | 23 | if (emulator.argv_map.find("clean_ram") == emulator.argv_map.end()) 24 | LoadRAMImage(); 25 | } 26 | 27 | region.Setup(0x8000, 0x0E00, "BatteryBackedRAM", ram_buffer, [](MMURegion *region, size_t offset) { 28 | return ((uint8_t *)region->userdata)[offset - region->base]; 29 | }, [](MMURegion *region, size_t offset, uint8_t data) { 30 | ((uint8_t *)region->userdata)[offset - region->base] = data; 31 | }, emulator); 32 | } 33 | 34 | void BatteryBackedRAM::Uninitialise() 35 | { 36 | if (ram_file_requested && emulator.argv_map.find("preserve_ram") == emulator.argv_map.end()) 37 | SaveRAMImage(); 38 | 39 | delete[] ram_buffer; 40 | } 41 | 42 | void BatteryBackedRAM::SaveRAMImage() 43 | { 44 | std::ofstream ram_handle(emulator.argv_map["ram"], std::ofstream::binary); 45 | if (ram_handle.fail()) 46 | { 47 | logger::Info("[BatteryBackedRAM] std::ofstream failed: %s\n", strerror(errno)); 48 | return; 49 | } 50 | ram_handle.write((char *)ram_buffer, 0xE00); 51 | if (ram_handle.fail()) 52 | { 53 | logger::Info("[BatteryBackedRAM] std::ofstream failed: %s\n", strerror(errno)); 54 | return; 55 | } 56 | } 57 | 58 | void BatteryBackedRAM::LoadRAMImage() 59 | { 60 | std::ifstream ram_handle(emulator.argv_map["ram"], std::ifstream::binary); 61 | if (ram_handle.fail()) 62 | { 63 | logger::Info("[BatteryBackedRAM] std::ifstream failed: %s\n", strerror(errno)); 64 | return; 65 | } 66 | ram_handle.read((char *)ram_buffer, 0xE00); 67 | if (ram_handle.fail()) 68 | { 69 | logger::Info("[BatteryBackedRAM] std::ifstream failed: %s\n", strerror(errno)); 70 | return; 71 | } 72 | } 73 | } 74 | 75 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/BatteryBackedRAM.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | 7 | namespace casioemu 8 | { 9 | class BatteryBackedRAM : public Peripheral 10 | { 11 | MMURegion region; 12 | uint8_t *ram_buffer; 13 | bool ram_file_requested; 14 | 15 | public: 16 | using Peripheral::Peripheral; 17 | 18 | void Initialise(); 19 | void Uninitialise(); 20 | void SaveRAMImage(); 21 | void LoadRAMImage(); 22 | }; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Keyboard.cpp: -------------------------------------------------------------------------------- 1 | #include "Keyboard.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Chipset/MMU.hpp" 5 | #include "../Emulator.hpp" 6 | #include "../Chipset/Chipset.hpp" 7 | 8 | #include 9 | #include 10 | 11 | namespace casioemu 12 | { 13 | void Keyboard::Initialise() 14 | { 15 | renderer = emulator.GetRenderer(); 16 | require_frame = true; 17 | 18 | interrupt_source.Setup(5, emulator); 19 | 20 | region_ki.Setup(0xF040, 1, "Keyboard/KI", &keyboard_in, MMURegion::DefaultRead, MMURegion::IgnoreWrite, emulator); 21 | 22 | region_input_filter.Setup(0xF042, 1, "Keyboard/InputFilter", &input_filter, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 23 | 24 | region_ko_mask.Setup(0xF044, 2, "Keyboard/KOMask", this, [](MMURegion *region, size_t offset) { 25 | offset -= region->base; 26 | Keyboard *keyboard = ((Keyboard *)region->userdata); 27 | return (uint8_t)((keyboard->keyboard_out_mask & 0x03FF) >> (offset * 8)); 28 | }, [](MMURegion *region, size_t offset, uint8_t data) { 29 | offset -= region->base; 30 | Keyboard *keyboard = ((Keyboard *)region->userdata); 31 | keyboard->keyboard_out_mask &= ~(((uint16_t)0xFF) << (offset * 8)); 32 | keyboard->keyboard_out_mask |= ((uint16_t)data) << (offset * 8); 33 | keyboard->keyboard_out_mask &= 0x03FF; 34 | if (!offset) 35 | keyboard->RecalculateKI(); 36 | }, emulator); 37 | 38 | region_ko.Setup(0xF046, 2, "Keyboard/KO", this, [](MMURegion *region, size_t offset) { 39 | offset -= region->base; 40 | Keyboard *keyboard = ((Keyboard *)region->userdata); 41 | return (uint8_t)((keyboard->keyboard_out & 0x03FF) >> (offset * 8)); 42 | }, [](MMURegion *region, size_t offset, uint8_t data) { 43 | offset -= region->base; 44 | Keyboard *keyboard = ((Keyboard *)region->userdata); 45 | keyboard->keyboard_out &= ~(((uint16_t)0xFF) << (offset * 8)); 46 | keyboard->keyboard_out |= ((uint16_t)data) << (offset * 8); 47 | keyboard->keyboard_out &= 0x03FF; 48 | if (!offset) 49 | keyboard->RecalculateKI(); 50 | }, emulator); 51 | 52 | { 53 | for (auto &button : buttons) 54 | button.type = Button::BT_NONE; 55 | 56 | const char *key = "button_map"; 57 | lua_geti(emulator.lua_state, LUA_REGISTRYINDEX, emulator.lua_model_ref); 58 | if (lua_getfield(emulator.lua_state, -1, key) != LUA_TTABLE) 59 | PANIC("key '%s' is not a table\n", key); 60 | lua_len(emulator.lua_state, -1); 61 | size_t buttons_size = lua_tointeger(emulator.lua_state, -1); 62 | lua_pop(emulator.lua_state, 1); 63 | 64 | for (size_t ix = 0; ix != buttons_size; ++ix) 65 | { 66 | if (lua_geti(emulator.lua_state, -1, ix + 1) != LUA_TTABLE) 67 | PANIC("key '%s'[%zu] is not a table\n", key, ix + 1); 68 | 69 | if (lua_geti(emulator.lua_state, -1, 6) != LUA_TSTRING) 70 | PANIC("key '%s'[%zu][6] is not a string\n", key, ix + 1); 71 | 72 | size_t button_name_len; 73 | const char *button_name = lua_tolstring(emulator.lua_state, -1, &button_name_len); 74 | if (strlen(button_name) != button_name_len) 75 | PANIC("Key name '%.*s' contains null byte\n", (int) button_name_len, button_name); 76 | 77 | SDL_Keycode button_key; 78 | if (button_name_len == 0) 79 | { 80 | button_key = SDLK_UNKNOWN; 81 | } 82 | else 83 | { 84 | button_key = SDL_GetKeyFromName(button_name); 85 | if (button_key == SDLK_UNKNOWN) 86 | PANIC("Key name '%s' is invalid\n", button_name); 87 | } 88 | lua_pop(emulator.lua_state, 1); // Pop the key name 89 | 90 | for (int kx = 0; kx != 5; ++kx) 91 | if (lua_geti(emulator.lua_state, -1 - kx, kx + 1) != LUA_TNUMBER) 92 | PANIC("key '%s'[%zu][%i] is not a number\n", key, ix + 1, kx + 1); 93 | 94 | uint8_t code = lua_tointeger(emulator.lua_state, -1); 95 | size_t button_ix; 96 | if (code == 0xFF) 97 | { 98 | button_ix = 63; 99 | } 100 | else 101 | { 102 | button_ix = ((code >> 1) & 0x38) | (code & 0x07); 103 | if (button_ix >= 64) 104 | PANIC("button index doesn't fit 6 bits\n"); 105 | } 106 | 107 | if (button_key != SDLK_UNKNOWN) 108 | { 109 | bool insert_success = keyboard_map.emplace(button_key, button_ix).second; 110 | if (!insert_success) 111 | PANIC("Key '%s' is used twice\n", button_name); 112 | } 113 | 114 | Button &button = buttons[button_ix]; 115 | 116 | if (code == 0xFF) 117 | button.type = Button::BT_POWER; 118 | else 119 | button.type = Button::BT_BUTTON; 120 | button.rect.x = lua_tointeger(emulator.lua_state, -5); 121 | button.rect.y = lua_tointeger(emulator.lua_state, -4); 122 | button.rect.w = lua_tointeger(emulator.lua_state, -3); 123 | button.rect.h = lua_tointeger(emulator.lua_state, -2); 124 | button.ko_bit = 1 << ((code >> 4) & 0xF); 125 | button.ki_bit = 1 << (code & 0xF); 126 | 127 | lua_pop(emulator.lua_state, 6); 128 | 129 | button.pressed = false; 130 | button.stuck = false; 131 | } 132 | 133 | lua_pop(emulator.lua_state, 2); 134 | } 135 | } 136 | 137 | void Keyboard::Reset() 138 | { 139 | p0 = false; 140 | p1 = false; 141 | p146 = false; 142 | keyboard_out = 0; 143 | keyboard_out_mask = 0; 144 | 145 | RecalculateGhost(); 146 | } 147 | 148 | void Keyboard::Tick() 149 | { 150 | if (has_input && interrupt_source.Enabled()) 151 | interrupt_source.TryRaise(); 152 | } 153 | 154 | void Keyboard::Frame() 155 | { 156 | require_frame = false; 157 | 158 | SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); 159 | for (auto &button : buttons) 160 | { 161 | if (button.type != Button::BT_NONE && button.pressed) 162 | { 163 | if (button.stuck) 164 | SDL_SetRenderDrawColor(renderer, 127, 0, 0, 127); 165 | else 166 | SDL_SetRenderDrawColor(renderer, 0, 0, 0, 127); 167 | SDL_RenderFillRect(renderer, &button.rect); 168 | } 169 | } 170 | } 171 | 172 | void Keyboard::UIEvent(SDL_Event &event) 173 | { 174 | switch (event.type) 175 | { 176 | case SDL_MOUSEBUTTONDOWN: 177 | case SDL_MOUSEBUTTONUP: 178 | switch (event.button.button) 179 | { 180 | case SDL_BUTTON_LEFT: 181 | if (event.button.state == SDL_PRESSED) 182 | PressAt(event.button.x, event.button.y, false); 183 | else 184 | ReleaseAll(); 185 | break; 186 | 187 | case SDL_BUTTON_RIGHT: 188 | if (event.button.state == SDL_PRESSED) 189 | PressAt(event.button.x, event.button.y, true); 190 | break; 191 | } 192 | break; 193 | 194 | case SDL_KEYDOWN: 195 | case SDL_KEYUP: 196 | SDL_Keycode keycode = event.key.keysym.sym; 197 | auto iterator = keyboard_map.find(keycode); 198 | if (iterator == keyboard_map.end()) 199 | break; 200 | if (event.key.state == SDL_PRESSED) 201 | PressButton(buttons[iterator->second], false); 202 | else 203 | ReleaseAll(); 204 | break; 205 | } 206 | } 207 | 208 | void Keyboard::PressButton(Button& button, bool stick) 209 | { 210 | bool old_pressed = button.pressed; 211 | 212 | if (stick) 213 | { 214 | button.stuck = !button.stuck; 215 | button.pressed = button.stuck; 216 | } 217 | else 218 | button.pressed = true; 219 | 220 | require_frame = true; 221 | 222 | if (button.type == Button::BT_POWER && button.pressed && !old_pressed) 223 | emulator.chipset.Reset(); 224 | if (button.type == Button::BT_BUTTON && button.pressed != old_pressed) 225 | RecalculateGhost(); 226 | } 227 | 228 | void Keyboard::PressAt(int x, int y, bool stick) 229 | { 230 | for (auto &button : buttons) 231 | { 232 | if (button.rect.x <= x && button.rect.y <= y && button.rect.x + button.rect.w > x && button.rect.y + button.rect.h > y) 233 | { 234 | PressButton(button, stick); 235 | break; 236 | } 237 | } 238 | } 239 | 240 | void Keyboard::RecalculateGhost() 241 | { 242 | struct KOColumn 243 | { 244 | uint8_t connections; 245 | bool seen; 246 | } columns[8]; 247 | 248 | has_input = 0; 249 | for (auto &button : buttons) 250 | if (button.type == Button::BT_BUTTON && button.pressed && button.ki_bit & input_filter) 251 | has_input |= button.ki_bit; 252 | 253 | for (size_t cx = 0; cx != 8; ++cx) 254 | { 255 | columns[cx].seen = false; 256 | columns[cx].connections = 0; 257 | for (size_t rx = 0; rx != 8; ++rx) 258 | { 259 | Button &button = buttons[cx * 8 + rx]; 260 | if (button.type == Button::BT_BUTTON && button.pressed) 261 | { 262 | for (size_t ax = 0; ax != 8; ++ax) 263 | { 264 | Button &sibling = buttons[ax * 8 + rx]; 265 | if (sibling.type == Button::BT_BUTTON && sibling.pressed) 266 | columns[cx].connections |= 1 << ax; 267 | } 268 | } 269 | } 270 | } 271 | 272 | for (size_t cx = 0; cx != 8; ++cx) 273 | { 274 | if (!columns[cx].seen) 275 | { 276 | uint8_t to_visit = 1 << cx; 277 | uint8_t ghost_mask = 1 << cx; 278 | columns[cx].seen = true; 279 | 280 | while (to_visit) 281 | { 282 | uint8_t new_to_visit = 0; 283 | for (size_t vx = 0; vx != 8; ++vx) 284 | { 285 | if (to_visit & (1 << vx)) 286 | { 287 | for (size_t sx = 0; sx != 8; ++sx) 288 | { 289 | if (columns[vx].connections & (1 << sx) && !columns[sx].seen) 290 | { 291 | new_to_visit |= 1 << sx; 292 | ghost_mask |= 1 << sx; 293 | columns[sx].seen = true; 294 | } 295 | } 296 | } 297 | } 298 | to_visit = new_to_visit; 299 | } 300 | 301 | for (size_t gx = 0; gx != 8; ++gx) 302 | if (ghost_mask & (1 << gx)) 303 | keyboard_ghost[gx] = ghost_mask; 304 | } 305 | } 306 | 307 | RecalculateKI(); 308 | } 309 | 310 | void Keyboard::RecalculateKI() 311 | { 312 | uint8_t keyboard_out_ghosted = 0; 313 | for (size_t ix = 0; ix != 7; ++ix) 314 | if (keyboard_out & ~keyboard_out_mask & (1 << ix)) 315 | keyboard_out_ghosted |= keyboard_ghost[ix]; 316 | 317 | keyboard_in = 0xFF; 318 | for (auto &button : buttons) 319 | if (button.type == Button::BT_BUTTON && button.pressed && button.ko_bit & keyboard_out_ghosted) 320 | keyboard_in &= ~button.ki_bit; 321 | 322 | if (keyboard_out & ~keyboard_out_mask & (1 << 7) && p0) 323 | keyboard_in &= 0x7F; 324 | if (keyboard_out & ~keyboard_out_mask & (1 << 8) && p1) 325 | keyboard_in &= 0x7F; 326 | if (keyboard_out & ~keyboard_out_mask & (1 << 9) && p146) 327 | keyboard_in &= 0x7F; 328 | } 329 | 330 | void Keyboard::ReleaseAll() 331 | { 332 | bool had_effect = false; 333 | for (auto &button : buttons) 334 | { 335 | if (!button.stuck && button.pressed) 336 | { 337 | button.pressed = false; 338 | if (button.type == Button::BT_BUTTON) 339 | had_effect = true; 340 | } 341 | } 342 | if (had_effect) 343 | { 344 | require_frame = true; 345 | RecalculateGhost(); 346 | } 347 | } 348 | } 349 | 350 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Keyboard.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | #include "../Chipset/InterruptSource.hpp" 7 | 8 | #include 9 | 10 | namespace casioemu 11 | { 12 | class Keyboard : public Peripheral 13 | { 14 | MMURegion region_ko_mask, region_ko, region_ki, region_input_filter; 15 | uint16_t keyboard_out, keyboard_out_mask; 16 | uint8_t keyboard_in, input_filter, keyboard_ghost[8]; 17 | 18 | uint8_t has_input; 19 | InterruptSource interrupt_source; 20 | 21 | SDL_Renderer *renderer; 22 | 23 | struct Button 24 | { 25 | enum ButtonType 26 | { 27 | BT_NONE, 28 | BT_BUTTON, 29 | BT_POWER 30 | } type; 31 | SDL_Rect rect; 32 | uint8_t ko_bit, ki_bit; 33 | bool pressed, stuck; 34 | } buttons[64]; 35 | 36 | // Maps from keycode to an index to (buttons). 37 | std::unordered_map keyboard_map; 38 | 39 | bool p0, p1, p146; 40 | 41 | public: 42 | using Peripheral::Peripheral; 43 | 44 | void Initialise(); 45 | void Reset(); 46 | void Tick(); 47 | void Frame(); 48 | void UIEvent(SDL_Event &event); 49 | void PressButton(Button& button, bool stick); 50 | void PressAt(int x, int y, bool stick); 51 | void ReleaseAll(); 52 | void RecalculateKI(); 53 | void RecalculateGhost(); 54 | }; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Miscellaneous.cpp: -------------------------------------------------------------------------------- 1 | #include "Miscellaneous.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Emulator.hpp" 5 | #include "../Chipset/Chipset.hpp" 6 | #include "../Chipset/CPU.hpp" 7 | 8 | namespace casioemu 9 | { 10 | void Miscellaneous::Initialise() 11 | { 12 | region_dsr.Setup(0xF000, 1, "Miscellaneous/DSR", this, [](MMURegion *region, size_t) { 13 | return (uint8_t)((Miscellaneous *)region->userdata)->emulator.chipset.cpu.reg_dsr; 14 | }, [](MMURegion *region, size_t, uint8_t data) { 15 | ((Miscellaneous *)region->userdata)->emulator.chipset.cpu.reg_dsr = data; 16 | }, emulator); 17 | 18 | // * TODO: figure out what these are 19 | region_F00A.Setup(0xF00A, 1, "Miscellaneous/Unknown/F00A*1", &data_F00A, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 20 | region_F018.Setup(0xF018, 1, "Miscellaneous/Unknown/F018*1", &data_F018, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 21 | region_F033.Setup(0xF033, 1, "Miscellaneous/Unknown/F033*1", &data_F033, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 22 | region_F034.Setup(0xF034, 1, "Miscellaneous/Unknown/F034*1", &data_F034, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 23 | region_F041.Setup(0xF041, 1, "Miscellaneous/Unknown/F041*1", &data_F041, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 24 | region_F048.Setup(0xF048, 8, "Miscellaneous/Unknown/F048*8", &data_F048, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 25 | region_F220.Setup(0xF220, 4, "Miscellaneous/Unknown/F220*4", &data_F220, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Miscellaneous.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | 7 | namespace casioemu 8 | { 9 | class Miscellaneous : public Peripheral 10 | { 11 | MMURegion region_dsr, region_F048, region_F220; 12 | uint64_t data_F048; 13 | uint32_t data_F220; 14 | 15 | MMURegion region_F00A, region_F018, region_F041, region_F033, region_F034; 16 | uint8_t data_F00A, data_F018, data_F041, data_F033, data_F034; 17 | 18 | public: 19 | using Peripheral::Peripheral; 20 | 21 | void Initialise(); 22 | }; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Peripheral.cpp: -------------------------------------------------------------------------------- 1 | #include "Peripheral.hpp" 2 | 3 | namespace casioemu 4 | { 5 | Peripheral::Peripheral(Emulator &_emulator) : emulator(_emulator), require_frame(false) 6 | { 7 | } 8 | 9 | Peripheral::~Peripheral() 10 | { 11 | } 12 | 13 | void Peripheral::Initialise() 14 | { 15 | } 16 | 17 | void Peripheral::Uninitialise() 18 | { 19 | } 20 | 21 | void Peripheral::Tick() 22 | { 23 | } 24 | 25 | void Peripheral::TickAfterInterrupts() 26 | { 27 | } 28 | 29 | void Peripheral::Frame() 30 | { 31 | require_frame = false; 32 | } 33 | 34 | void Peripheral::UIEvent(SDL_Event &) 35 | { 36 | } 37 | 38 | void Peripheral::Reset() 39 | { 40 | } 41 | 42 | bool Peripheral::GetRequireFrame() 43 | { 44 | return require_frame; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Peripheral.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include 5 | 6 | namespace casioemu 7 | { 8 | class Emulator; 9 | 10 | class Peripheral 11 | { 12 | protected: 13 | Emulator &emulator; 14 | 15 | /** 16 | * This should be true if the state of this peripheral changed 17 | * so that it requires a call to Frame(). 18 | * It should not directly call Frame() because otherwise it may 19 | * call it more than required (once per timer_interval) 20 | */ 21 | bool require_frame; 22 | 23 | public: 24 | Peripheral(Emulator &emulator); 25 | virtual void Initialise(); 26 | virtual void Uninitialise(); 27 | virtual void Tick(); 28 | virtual void TickAfterInterrupts(); 29 | virtual void Frame(); 30 | virtual void UIEvent(SDL_Event &event); 31 | virtual void Reset(); 32 | virtual bool GetRequireFrame(); 33 | virtual ~Peripheral(); 34 | }; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/ROMWindow.cpp: -------------------------------------------------------------------------------- 1 | #include "ROMWindow.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Chipset/MMU.hpp" 5 | #include "../Emulator.hpp" 6 | #include "../Chipset/Chipset.hpp" 7 | 8 | namespace casioemu 9 | { 10 | void ROMWindow::Initialise() 11 | { 12 | region_0.Setup(0x00000, 0x08000, "ROM/Segment0", this, [](MMURegion *region, size_t offset) { 13 | return ((ROMWindow *)(region->userdata))->emulator.chipset.rom_data[offset]; 14 | }, [](MMURegion *region, size_t offset, uint8_t data) { 15 | ROMWindow *rom_window = (ROMWindow *)(region->userdata); 16 | if (rom_window->strict_memory) 17 | { 18 | logger::Info("ROM::[region write lambda]: attempt to write %02hhX to %06zX\n", data, offset); 19 | rom_window->emulator.HandleMemoryError(); 20 | } 21 | }, emulator); 22 | 23 | region_1.Setup(0x10000, 0x10000, "ROM/Segment1", this, [](MMURegion *region, size_t offset) { 24 | return ((ROMWindow *)(region->userdata))->emulator.chipset.rom_data[offset]; 25 | }, [](MMURegion *region, size_t offset, uint8_t data) { 26 | ROMWindow *rom_window = (ROMWindow *)(region->userdata); 27 | if (rom_window->strict_memory) 28 | { 29 | logger::Info("ROM::[region write lambda]: attempt to write %02hhX to %06zX\n", data, offset); 30 | rom_window->emulator.HandleMemoryError(); 31 | } 32 | }, emulator); 33 | 34 | region_8.Setup(0x80000, 0x10000, "ROM/Segment8", this, [](MMURegion *region, size_t offset) { 35 | return ((ROMWindow *)(region->userdata))->emulator.chipset.rom_data[offset - 0x80000]; 36 | }, [](MMURegion *region, size_t offset, uint8_t data) { 37 | ROMWindow *rom_window = (ROMWindow *)(region->userdata); 38 | if (rom_window->strict_memory) 39 | { 40 | logger::Info("ROM::[region write lambda]: attempt to write %02hhX to %06zX\n", data, offset); 41 | rom_window->emulator.HandleMemoryError(); 42 | } 43 | }, emulator); 44 | 45 | strict_memory = emulator.argv_map.find("strict_memory") != emulator.argv_map.end(); 46 | } 47 | 48 | void ROMWindow::Uninitialise() 49 | { 50 | } 51 | 52 | void ROMWindow::Tick() 53 | { 54 | } 55 | 56 | void ROMWindow::Frame() 57 | { 58 | } 59 | 60 | void ROMWindow::UIEvent(SDL_Event &) 61 | { 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/ROMWindow.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | 7 | namespace casioemu 8 | { 9 | class ROMWindow : public Peripheral 10 | { 11 | MMURegion region_0, region_1, region_8; 12 | bool strict_memory; 13 | 14 | public: 15 | using Peripheral::Peripheral; 16 | 17 | void Initialise(); 18 | void Uninitialise(); 19 | void Tick(); 20 | void Frame(); 21 | void UIEvent(SDL_Event &event); 22 | }; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Screen.cpp: -------------------------------------------------------------------------------- 1 | #include "Screen.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Chipset/MMU.hpp" 5 | #include "../Emulator.hpp" 6 | #include "../Chipset/Chipset.hpp" 7 | 8 | namespace casioemu 9 | { 10 | Screen::SpriteBitmap Screen::sprite_bitmap[] = { 11 | {"rsd_pixel", 0, 0}, 12 | {"rsd_s", 0x10, 0x00}, 13 | {"rsd_a", 0x04, 0x00}, 14 | {"rsd_m", 0x10, 0x01}, 15 | {"rsd_sto", 0x02, 0x01}, 16 | {"rsd_rcl", 0x40, 0x02}, 17 | {"rsd_stat", 0x40, 0x03}, 18 | {"rsd_cmplx", 0x80, 0x04}, 19 | {"rsd_mat", 0x40, 0x05}, 20 | {"rsd_vct", 0x01, 0x05}, 21 | {"rsd_d", 0x20, 0x07}, 22 | {"rsd_r", 0x02, 0x07}, 23 | {"rsd_g", 0x10, 0x08}, 24 | {"rsd_fix", 0x01, 0x08}, 25 | {"rsd_sci", 0x20, 0x09}, 26 | {"rsd_math", 0x40, 0x0A}, 27 | {"rsd_down", 0x08, 0x0A}, 28 | {"rsd_up", 0x80, 0x0B}, 29 | {"rsd_disp", 0x10, 0x0B} 30 | }; 31 | 32 | void Screen::Initialise() 33 | { 34 | static_assert(SPR_MAX == (sizeof(sprite_bitmap) / sizeof(sprite_bitmap[0])), "SPR_MAX and sizeof(sprite_bitmap) don't match"); 35 | 36 | renderer = emulator.GetRenderer(); 37 | interface_texture = emulator.GetInterfaceTexture(); 38 | for (int ix = 0; ix != SPR_MAX; ++ix) 39 | sprite_info[ix] = emulator.GetModelInfo(sprite_bitmap[ix].name); 40 | 41 | ink_colour = emulator.GetModelInfo("ink_colour"); 42 | require_frame = true; 43 | 44 | screen_buffer = new uint8_t[0x0200]; 45 | 46 | region_buffer.Setup(0xF800, 0x0200, "Screen/Buffer", this, [](MMURegion *region, size_t offset) { 47 | offset -= region->base; 48 | if ((offset & 0x000F) >= 0x000C) 49 | return (uint8_t)0; 50 | return ((Screen *)region->userdata)->screen_buffer[offset]; 51 | }, [](MMURegion *region, size_t offset, uint8_t data) { 52 | offset -= region->base; 53 | if ((offset & 0x000F) >= 0x000C) 54 | return; 55 | 56 | auto this_obj = (Screen *)region->userdata; 57 | // * Set require_frame to true only if the value changed. 58 | this_obj->require_frame |= this_obj->screen_buffer[offset] != data; 59 | this_obj->screen_buffer[offset] = data; 60 | }, emulator); 61 | 62 | region_range.Setup(0xF030, 1, "Screen/Range", this, MMURegion::DefaultRead, SetRequireFrameWrite, emulator); 63 | 64 | region_mode.Setup(0xF031, 1, "Screen/Mode", this, MMURegion::DefaultRead, SetRequireFrameWrite, emulator); 65 | 66 | region_contrast.Setup(0xF032, 1, "Screen/Contrast", this, MMURegion::DefaultRead, SetRequireFrameWrite, emulator); 67 | } 68 | 69 | void Screen::Uninitialise() 70 | { 71 | delete[] screen_buffer; 72 | } 73 | 74 | void Screen::Frame() 75 | { 76 | require_frame = false; 77 | 78 | int ink_alpha_on = 20 + screen_contrast * 16; 79 | if (ink_alpha_on > 255) 80 | ink_alpha_on = 255; 81 | int ink_alpha_off = (screen_contrast - 8) * 7; 82 | if (ink_alpha_off < 0) 83 | ink_alpha_off = 0; 84 | 85 | bool enable_status, enable_dotmatrix, clear_dots; 86 | 87 | switch (screen_mode) 88 | { 89 | case 4: 90 | enable_dotmatrix = true; 91 | clear_dots = true; 92 | enable_status = false; 93 | break; 94 | 95 | case 5: 96 | enable_dotmatrix = true; 97 | clear_dots = false; 98 | enable_status = true; 99 | break; 100 | 101 | case 6: 102 | enable_dotmatrix = true; 103 | clear_dots = true; 104 | enable_status = true; 105 | ink_alpha_on = 80; 106 | ink_alpha_off = 20; 107 | break; 108 | 109 | default: 110 | return; 111 | } 112 | 113 | SDL_SetTextureColorMod(interface_texture, ink_colour.r, ink_colour.g, ink_colour.b); 114 | 115 | if (enable_status) 116 | { 117 | for (int ix = SPR_PIXEL + 1; ix != SPR_MAX; ++ix) 118 | { 119 | if (screen_buffer[sprite_bitmap[ix].offset] & sprite_bitmap[ix].mask) 120 | SDL_SetTextureAlphaMod(interface_texture, ink_alpha_on); 121 | else 122 | SDL_SetTextureAlphaMod(interface_texture, ink_alpha_off); 123 | SDL_RenderCopy(renderer, interface_texture, &sprite_info[ix].src, &sprite_info[ix].dest); 124 | } 125 | } 126 | 127 | if (enable_dotmatrix) 128 | { 129 | SDL_Rect dest = sprite_info[SPR_PIXEL].dest; 130 | for (int iy = 0; iy != 31; ++iy) 131 | { 132 | dest.x = sprite_info[SPR_PIXEL].dest.x; 133 | dest.y = sprite_info[SPR_PIXEL].dest.y + iy * sprite_info[SPR_PIXEL].src.h; 134 | for (int ix = 0; ix != 12; ++ix) 135 | { 136 | for (uint8_t mask = 0x80; mask; mask >>= 1, dest.x += sprite_info[SPR_PIXEL].src.w) 137 | { 138 | if (!clear_dots && screen_buffer[(iy << 4) + 0x10 + ix] & mask) 139 | SDL_SetTextureAlphaMod(interface_texture, ink_alpha_on); 140 | else 141 | SDL_SetTextureAlphaMod(interface_texture, ink_alpha_off); 142 | SDL_RenderCopy(renderer, interface_texture, &sprite_info[SPR_PIXEL].src, &dest); 143 | } 144 | } 145 | } 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Screen.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | #include "../Data/SpriteInfo.hpp" 7 | #include "../Data/ColourInfo.hpp" 8 | 9 | namespace casioemu 10 | { 11 | class Screen : public Peripheral 12 | { 13 | MMURegion region_buffer, region_contrast, region_mode, region_range; 14 | uint8_t *screen_buffer, screen_contrast, screen_mode, screen_range; 15 | 16 | SDL_Renderer *renderer; 17 | SDL_Texture *interface_texture; 18 | 19 | enum Sprite 20 | { 21 | SPR_PIXEL, 22 | SPR_S, 23 | SPR_A, 24 | SPR_M, 25 | SPR_STO, 26 | SPR_RCL, 27 | SPR_STAT, 28 | SPR_CMPLX, 29 | SPR_MAT, 30 | SPR_VCT, 31 | SPR_D, 32 | SPR_R, 33 | SPR_G, 34 | SPR_FIX, 35 | SPR_SCI, 36 | SPR_MATH, 37 | SPR_DOWN, 38 | SPR_UP, 39 | SPR_DISP, 40 | SPR_MAX 41 | }; 42 | 43 | struct SpriteBitmap 44 | { 45 | const char *name; 46 | uint8_t mask, offset; 47 | }; 48 | 49 | static SpriteBitmap sprite_bitmap[]; 50 | SpriteInfo sprite_info[SPR_MAX]; 51 | ColourInfo ink_colour; 52 | 53 | /** 54 | * Similar to MMURegion::DefaultWrite, except this also set the 55 | * (require_frame) flag of (Peripheral) class. 56 | * If (only_on_change) is true, (require_frame) is not set if the new value 57 | * is the same as the old value. 58 | * (region->userdata) should be a pointer to a (Screen) instance. 59 | * 60 | * TODO: Probably this should be a member of Peripheral class instead. 61 | * (in that case (Screen) class needs to be parameterized) 62 | */ 63 | template 65 | static void SetRequireFrameWrite(MMURegion *region, size_t offset, uint8_t data) 66 | { 67 | auto this_obj = (Screen *)(region->userdata); 68 | value_type &value = this_obj->*member_ptr; 69 | 70 | value_type old_value; 71 | if (only_on_change) 72 | old_value = value; 73 | 74 | // This part is identical to MMURegion::DefaultWrite. 75 | // * TODO Try to avoid duplication? 76 | value &= ~(((value_type)0xFF) << ((offset - region->base) * 8)); 77 | value |= ((value_type)data) << ((offset - region->base) * 8); 78 | value &= mask; 79 | 80 | if (only_on_change && old_value == value) 81 | return; 82 | this_obj->require_frame = true; 83 | } 84 | 85 | public: 86 | using Peripheral::Peripheral; 87 | 88 | void Initialise(); 89 | void Uninitialise(); 90 | void Frame(); 91 | }; 92 | } 93 | 94 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/StandbyControl.cpp: -------------------------------------------------------------------------------- 1 | #include "StandbyControl.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Chipset/MMU.hpp" 5 | #include "../Emulator.hpp" 6 | #include "../Chipset/Chipset.hpp" 7 | 8 | namespace casioemu 9 | { 10 | void StandbyControl::Initialise() 11 | { 12 | region_stpacp.Setup(0xF008, 1, "StandbyControl/STPACP", this, MMURegion::IgnoreRead<0x00>, [](MMURegion *region, size_t, uint8_t data) { 13 | StandbyControl *self = (StandbyControl *)(region->userdata); 14 | if ((data & 0xF0) == 0xA0 && (self->stpacp_last & 0xF0) == 0x50) 15 | self->stop_acceptor_enabled = true; 16 | self->stpacp_last = data; 17 | }, emulator); 18 | 19 | region_sbycon.Setup(0xF009, 1, "StandbyControl/SBYCON", this, MMURegion::IgnoreRead<0x00>, [](MMURegion *region, size_t, uint8_t data) { 20 | StandbyControl *self = (StandbyControl *)(region->userdata); 21 | 22 | if (data & 0x01) 23 | { 24 | self->emulator.chipset.Halt(); 25 | return; 26 | } 27 | 28 | if (data & 0x02 && self->stop_acceptor_enabled) 29 | { 30 | self->stop_acceptor_enabled = false; 31 | self->emulator.chipset.Stop(); 32 | return; 33 | } 34 | }, emulator); 35 | } 36 | 37 | void StandbyControl::Reset() 38 | { 39 | stpacp_last = 0; 40 | stop_acceptor_enabled = false; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/StandbyControl.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | 7 | namespace casioemu 8 | { 9 | class StandbyControl : public Peripheral 10 | { 11 | MMURegion region_stpacp, region_sbycon; 12 | uint8_t stpacp_last; 13 | bool stop_acceptor_enabled; 14 | 15 | public: 16 | using Peripheral::Peripheral; 17 | 18 | void Initialise(); 19 | void Reset(); 20 | }; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Timer.cpp: -------------------------------------------------------------------------------- 1 | #include "Timer.hpp" 2 | 3 | #include "../Logger.hpp" 4 | #include "../Chipset/MMU.hpp" 5 | #include "../Emulator.hpp" 6 | #include "../Chipset/Chipset.hpp" 7 | 8 | namespace casioemu 9 | { 10 | void Timer::Initialise() 11 | { 12 | interrupt_source.Setup(9, emulator); 13 | 14 | region_interval.Setup(0xF020, 2, "Timer/Interval", &data_interval, MMURegion::DefaultRead, [](MMURegion *region, size_t offset, uint8_t data) { 15 | uint16_t *value = (uint16_t *)(region->userdata); 16 | *value &= ~(((uint16_t)0xFF) << ((offset - region->base) * 8)); 17 | *value |= ((uint16_t)data) << ((offset - region->base) * 8); 18 | if (!*value) 19 | *value = 1; 20 | }, emulator); 21 | 22 | region_counter.Setup(0xF022, 2, "Timer/Counter", &data_counter, MMURegion::DefaultRead, [](MMURegion *region, size_t, uint8_t) { 23 | *((uint16_t *)region->userdata) = 0; 24 | }, emulator); 25 | 26 | region_control.Setup(0xF025, 1, "Timer/Control", this, [](MMURegion *region, size_t) { 27 | Timer *timer = (Timer *)region->userdata; 28 | return (uint8_t)(timer->data_control & 0x01); 29 | }, [](MMURegion *region, size_t, uint8_t data) { 30 | Timer *timer = (Timer *)region->userdata; 31 | timer->data_control = data & 0x01; 32 | timer->raise_required = false; 33 | }, emulator); 34 | 35 | region_F024.Setup(0xF024, 1, "Timer/Unknown/F024*1", &data_F024, MMURegion::DefaultRead, MMURegion::DefaultWrite, emulator); 36 | } 37 | 38 | void Timer::Reset() 39 | { 40 | ext_to_int_counter = 0; 41 | ext_to_int_next = 0; 42 | ext_to_int_int_done = 0; 43 | DivideTicks(); 44 | 45 | raise_required = false; 46 | data_control = 0; 47 | } 48 | 49 | void Timer::Tick() 50 | { 51 | if (ext_to_int_counter == ext_to_int_next) 52 | DivideTicks(); 53 | ++ext_to_int_counter; 54 | 55 | if (raise_required) 56 | interrupt_source.TryRaise(); 57 | } 58 | 59 | void Timer::TickAfterInterrupts() 60 | { 61 | if (raise_required && interrupt_source.Success()) 62 | raise_required = false; 63 | } 64 | 65 | void Timer::DivideTicks() 66 | { 67 | ++ext_to_int_int_done; 68 | if (ext_to_int_int_done == ext_to_int_frequency) 69 | { 70 | ext_to_int_int_done = 0; 71 | ext_to_int_counter = 0; 72 | } 73 | ext_to_int_next = emulator.GetCyclesPerSecond() * (ext_to_int_int_done + 1) / ext_to_int_frequency; 74 | 75 | if (data_control & 0x01) 76 | { 77 | if (data_counter == data_interval) 78 | { 79 | data_counter = 0; 80 | if (interrupt_source.Enabled()) 81 | raise_required = true; 82 | } 83 | ++data_counter; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /emulator/src/Peripheral/Timer.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Config.hpp" 3 | 4 | #include "Peripheral.hpp" 5 | #include "../Chipset/MMURegion.hpp" 6 | #include "../Chipset/InterruptSource.hpp" 7 | 8 | namespace casioemu 9 | { 10 | class Timer : public Peripheral 11 | { 12 | MMURegion region_counter, region_interval, region_F024, region_control; 13 | uint16_t data_counter, data_interval; 14 | uint8_t data_F024, data_control; 15 | 16 | InterruptSource interrupt_source; 17 | 18 | bool raise_required; 19 | unsigned int ext_to_int_counter, ext_to_int_next, ext_to_int_int_done; 20 | const unsigned int ext_to_int_frequency = 10000; 21 | 22 | public: 23 | using Peripheral::Peripheral; 24 | 25 | void Initialise(); 26 | void Reset(); 27 | void Tick(); 28 | void TickAfterInterrupts(); 29 | void DivideTicks(); 30 | }; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /emulator/src/casioemu.cpp: -------------------------------------------------------------------------------- 1 | #include "Config.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "Emulator.hpp" 13 | #include "Logger.hpp" 14 | #include "Data/EventCode.hpp" 15 | 16 | using namespace casioemu; 17 | 18 | std::mutex input_mx; 19 | int main(int argc, char *argv[]) 20 | { 21 | std::map argv_map; 22 | for (int ix = 1; ix != argc; ++ix) 23 | { 24 | std::string key, value; 25 | char *eq_pos = strchr(argv[ix], '='); 26 | if (eq_pos) 27 | { 28 | key = std::string(argv[ix], eq_pos); 29 | value = eq_pos + 1; 30 | } 31 | else 32 | { 33 | key = "model"; 34 | value = argv[ix]; 35 | } 36 | 37 | if (argv_map.find(key) == argv_map.end()) 38 | argv_map[key] = value; 39 | else 40 | logger::Info("[argv] #%i: key '%s' already set\n", ix, key.c_str()); 41 | } 42 | 43 | if (argv_map.find("model") == argv_map.end()) 44 | { 45 | printf("No model path supplied\n"); 46 | exit(2); 47 | } 48 | 49 | int sdlFlags = SDL_INIT_VIDEO & SDL_INIT_TIMER; 50 | if (SDL_Init(sdlFlags) != sdlFlags) 51 | PANIC("SDL_Init failed: %s\n", SDL_GetError()); 52 | 53 | int imgFlags = IMG_INIT_PNG; 54 | if (IMG_Init(imgFlags) != imgFlags) 55 | PANIC("IMG_Init failed: %s\n", IMG_GetError()); 56 | 57 | { 58 | Emulator emulator(argv_map, 20, 128 * 1024); 59 | 60 | std::condition_variable input_cv; 61 | bool input_processed; 62 | std::string console_input_str; 63 | std::thread console_input_thread([&] { 64 | while (1) 65 | { 66 | std::cout << "> "; 67 | std::getline(std::cin, console_input_str); 68 | if (std::cin.fail()) 69 | { 70 | logger::Info("Console thread shutting down\n"); 71 | break; 72 | } 73 | 74 | input_processed = false; 75 | SDL_Event event; 76 | SDL_zero(event); 77 | event.type = SDL_USEREVENT; 78 | event.user.code = CE_EVENT_INPUT; 79 | SDL_PushEvent(&event); 80 | 81 | std::unique_lock input_lock(input_mx); 82 | input_cv.wait(input_lock, [&] { 83 | return input_processed; 84 | }); 85 | } 86 | }); 87 | console_input_thread.detach(); 88 | 89 | while (emulator.Running()) 90 | { 91 | SDL_Event event; 92 | if (!SDL_WaitEvent(&event)) 93 | PANIC("SDL_WaitEvent failed: %s\n", SDL_GetError()); 94 | 95 | switch (event.type) 96 | { 97 | case SDL_USEREVENT: 98 | switch (event.user.code) 99 | { 100 | case CE_EVENT_INPUT: 101 | { 102 | std::lock_guard input_lock(input_mx); 103 | emulator.ExecuteCommand(console_input_str); 104 | input_processed = true; 105 | } 106 | input_cv.notify_one(); 107 | break; 108 | 109 | case CE_FRAME_REQUEST: 110 | emulator.Frame(); 111 | break; 112 | } 113 | break; 114 | 115 | case SDL_WINDOWEVENT: 116 | switch (event.window.event) 117 | { 118 | case SDL_WINDOWEVENT_CLOSE: 119 | emulator.Shutdown(); 120 | break; 121 | } 122 | break; 123 | 124 | case SDL_MOUSEBUTTONDOWN: 125 | case SDL_MOUSEBUTTONUP: 126 | case SDL_KEYDOWN: 127 | case SDL_KEYUP: 128 | emulator.UIEvent(event); 129 | break; 130 | } 131 | } 132 | 133 | input_mx.lock(); 134 | } 135 | 136 | IMG_Quit(); 137 | SDL_Quit(); 138 | 139 | return 0; 140 | } 141 | -------------------------------------------------------------------------------- /models/fx570esplus/interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LBPHacker/CasioEmu/4ee2287dbbf163bf407e3b7540b3368663ce7d32/models/fx570esplus/interface.png -------------------------------------------------------------------------------- /models/fx570esplus/model.lua: -------------------------------------------------------------------------------- 1 | do 2 | local buttons = {} 3 | local function generate(px, py, w, h, nx, ny, sx, sy, code) 4 | local cp = 1 5 | for iy = 0, ny - 1 do 6 | for ix = 0, nx - 1 do 7 | table.insert(buttons, {px + ix*sx, py + iy*sy, w, h, code[cp], code[cp+1]}) 8 | cp = cp + 2 9 | end 10 | end 11 | end 12 | -- Refer to https://wiki.libsdl.org/SDL_Keycode for key names. 13 | generate(46, 544, 58, 41, 5, 4, 65, 57, { 14 | 0x02, '7', 0x12, '8', 0x22, '9', 0x32, 'Backspace', 0x42, 'Space', 15 | 0x01, '4', 0x11, '5', 0x21, '6', 0x31, '' , 0x41, '/', 16 | 0x00, '1', 0x10, '2', 0x20, '3', 0x30, '=', 0x40, '-', 17 | 0x64, '0', 0x63, '.', 0x62, 'E', 0x61, '' , 0x60, 'Return', 18 | }) 19 | generate(46, 406, 48, 31, 6, 3, 54, 46, { 20 | 0x05, '', 0x15, '', 0x25, '', 0x35, '', 0x45, '', 0x55, '', 21 | 0x04, '', 0x14, '', 0x24, '', 0x34, '', 0x44, '', 0x54, '', 22 | 0x03, '', 0x13, '', 0x23, '', 0x33, '', 0x43, '', 0x53, '', 23 | }) 24 | generate( 40, 359, 48, 31, 2, 1, 54, 0, {0x06, 'F5', 0x16, 'F6',}) 25 | generate(268, 359, 48, 31, 2, 1, 54, 0, {0x46, 'F7', 0x56, 'F8',}) 26 | generate( 44, 290, 49, 39, 2, 1, 273, 0, {0x07, 'F1', 0xFF, 'F4',}) 27 | generate(100, 298, 48, 38, 2, 1, 162, 0, {0x17, 'F2', 0x47, 'F3',}) 28 | generate(155, 319, 33, 32, 2, 1, 67, 0, {0x26, 'Left', 0x37, 'Right',}) 29 | generate(188, 289, 34, 30, 1, 2, 0, 62, {0x27, 'Up', 0x36, 'Down',}) 30 | 31 | emu:model({ 32 | model_name = "fx-570ES PLUS", 33 | interface_image_path = "interface.png", 34 | rom_path = "rom.bin", 35 | csr_mask = 0x0001, 36 | rsd_interface = {0, 0, 410, 810, 0, 0}, 37 | rsd_pixel = {410, 252, 3, 3, 61, 141}, 38 | rsd_s = {410, 0, 10, 14, 61, 127}, 39 | rsd_a = {410, 14, 11, 14, 70, 127}, 40 | rsd_m = {410, 28, 10, 14, 81, 127}, 41 | rsd_sto = {410, 42, 20, 14, 91, 127}, 42 | rsd_rcl = {410, 56, 19, 14, 110, 127}, 43 | rsd_stat = {410, 70, 24, 14, 130, 127}, 44 | rsd_cmplx = {410, 84, 32, 14, 154, 127}, 45 | rsd_mat = {410, 98, 20, 14, 186, 127}, 46 | rsd_vct = {410, 112, 20, 14, 205, 127}, 47 | rsd_d = {410, 126, 12, 14, 225, 127}, 48 | rsd_r = {410, 140, 10, 14, 236, 127}, 49 | rsd_g = {410, 154, 11, 14, 246, 127}, 50 | rsd_fix = {410, 168, 17, 14, 257, 127}, 51 | rsd_sci = {410, 182, 16, 14, 273, 127}, 52 | rsd_math = {410, 196, 24, 14, 289, 127}, 53 | rsd_down = {410, 210, 10, 14, 313, 127}, 54 | rsd_up = {410, 224, 10, 14, 319, 127}, 55 | rsd_disp = {410, 238, 20, 14, 329, 127}, 56 | ink_colour = {30, 52, 90}, 57 | button_map = buttons 58 | }) 59 | end 60 | 61 | local break_targets = {} 62 | 63 | local function get_real_pc() 64 | return (cpu.csr << 16) | cpu.pc 65 | end 66 | 67 | function break_at(addr) 68 | if not addr then 69 | addr = get_real_pc() 70 | end 71 | break_targets[addr] = true 72 | end 73 | 74 | function unbreak_at(addr) 75 | if not addr then 76 | addr = get_real_pc() 77 | end 78 | break_targets[addr] = nil 79 | end 80 | 81 | function cont() 82 | emu:set_paused(false) 83 | end 84 | 85 | emu:post_tick(function() 86 | local real_pc = get_real_pc() 87 | if break_targets[real_pc] then 88 | printf("********** breakpoint reached at %05X **********", real_pc) 89 | emu:set_paused(true) 90 | end 91 | end) 92 | 93 | function printf(...) 94 | print(string.format(...)) 95 | end 96 | 97 | function ins() 98 | printf("%02X %02X %02X %02X | %01X:%04X | %02X %01X:%04X", cpu.r0, cpu.r1, cpu.r2, cpu.r3, cpu.csr, cpu.pc, cpu.psw, cpu.lcsr, cpu.lr) 99 | printf("%02X %02X %02X %02X | S %04X | %02X %01X:%04X", cpu.r4, cpu.r5, cpu.r6, cpu.r7, cpu.sp, cpu.epsw1, cpu.ecsr1, cpu.elr1) 100 | printf("%02X %02X %02X %02X | A %04X | %02X %01X:%04X", cpu.r8, cpu.r9, cpu.r10, cpu.r11, cpu.ea, cpu.epsw2, cpu.ecsr2, cpu.elr2) 101 | printf("%02X %02X %02X %02X | ELVL %01X | %02X %01X:%04X", cpu.r12, cpu.r13, cpu.r14, cpu.r15, cpu.psw & 3, cpu.epsw3, cpu.ecsr3, cpu.elr3) 102 | end 103 | 104 | -------------------------------------------------------------------------------- /models/fx570esplus/readme.txt: -------------------------------------------------------------------------------- 1 | For running the emulator, you'll need the ROM of a real fx-570ES PLUS. 2 | It's not provided here due to copyright reasons, but if you own a Casio calculator, hashes of the ROM file (which you can find yourself) are given below. 3 | 4 | MD5: 117085f99ed9a392ee63adafab46a2de 5 | SHA1: 9517e696295363ee0fc79e7c90e52655ab5ea6ca 6 | SHA256: 1a1b575f130b3fa4c79a598881181f5a137edb45e398cd9b78ae5baf9b071071 7 | --------------------------------------------------------------------------------