Compare commits

..
215 Commits
Author SHA1 Message Date
dingusdev 882b5f3ff3 Temporary fix for command line args
Set the values for two booleans to prevent potential conflicts when compiling DingusPPC
2021-03-22 21:19:08 -07:00
dingusdev 2d08ded9f4 viacuda: Getting and setting ADB device mask 2021-03-04 08:01:42 -07:00
dingusdev 2767257f2d viacuda: Getting and setting 6805 address 2021-03-04 07:59:52 -07:00
dingusdev b30c54e1c5 viacuda: Started implementing power commands 2021-03-04 07:58:13 -07:00
dingusdev a5a2a12df4 viacuda: Further fixing set real time 2021-02-23 19:59:22 -07:00
dingusdev 0ff4fe3cd6 Cuda - File server flag added 2021-02-23 07:50:54 -07:00
dingusdev f24039b821 Fixed parameters for CUDA time 2021-02-23 07:31:55 -07:00
dingusdev 03a3a0369a Added getting and setting time for CUDA 2021-02-23 07:16:18 -07:00
dingusdev e7e28b4497 Compilation fix for Raspberry Pi 2021-02-14 08:41:48 -07:00
Maxim Poliakovski baa7f8b211 atirage: use standard names for common pixel formats. 2021-02-08 22:25:36 +01:00
Maxim Poliakovski 2f4a3b955e atirage: calculation of display parameters. 2021-02-08 02:20:55 +01:00
dingusdev 19ca37c4ba Started refactoring fctiw and fctiwz 2021-02-05 12:45:57 -07:00
Maxim Poliakovski a4eb658309 atirage: increase PLL registers count to 64. 2021-02-05 02:01:31 +01:00
Maxim Poliakovski 508ef2eaa9 atirage: increase registers array and add boundary checks. 2021-02-05 01:23:04 +01:00
Maxim Poliakovski a5ef814ec4 atirage: add reading and writing of PLL registers. 2021-02-05 01:23:04 +01:00
Maxim Poliakovski ace19c0bdf atirage: clean up register names. 2021-02-05 01:11:23 +01:00
Maxim Poliakovski 3a9ed2671c atirage: remove obsolete memaccess code. 2021-02-04 19:05:39 +01:00
Maxim Poliakovski 3c787a87cd atirage: add ASIC ID for Rage Pro. 2021-02-04 19:01:55 +01:00
dingusdev ce70b0f096 Removed obseleted function declarations 2021-02-03 20:01:02 -07:00
Maxim Poliakovski a0b43754a7 atirage: fix and clean up PCI interface. 2021-02-04 01:03:23 +01:00
Maxim Poliakovski 1adbf90e21 MPC106: use memaccess thoroughly. 2021-02-03 23:39:19 +01:00
Maxim Poliakovski aa0f43d89f memaccess: generic functions for accessing memory. 2021-02-03 23:36:32 +01:00
Maxim Poliakovski 478ca1065f MPC106: fix RAM size calculation. 2021-02-03 23:29:48 +01:00
Maxim Poliakovski 7628ec92c0 Rename memreadwrite.h to memaccess.h 2021-02-03 12:19:18 +01:00
dingusdev 7f0acaf3d3 Load and store instruction clean-up 2021-01-25 21:03:17 -07:00
Maxim Poliakovski 5961552ed9 ppcfpopcodes: fix register stores. 2021-01-25 17:19:32 +01:00
Maxim Poliakovski 2141a72b87 ppcfpopcodes: finish RFC of the loading helpers. 2021-01-25 02:27:58 +01:00
Maxim Poliakovski 9683c660bc ppcfpopcodes: RFC loading helpers, part 2.
Fix lfdx emulation along the way.
2021-01-25 01:30:19 +01:00
Maxim Poliakovski d8397906c2 ppcfpopcodes: start refactoring of loading helpers. 2021-01-24 23:06:33 +01:00
Maxim Poliakovski fd0f8e2ef5 ppcopcodes: revert inlining of helper functions. 2021-01-24 22:50:07 +01:00
dingusdev 60f84ef0d9 Refactoring interpreter value storage 2021-01-24 11:59:16 -07:00
Maxim Poliakovski 2f8694e57c Revert enabling PPC tests by default. 2021-01-24 11:45:12 +01:00
dingusdev 593230f326 Disassembler - floating point instruction fixes 2021-01-23 22:44:14 -07:00
dingusdev 680b437b74 Fixed disassembly for fctiwz, frsp, and fctiw 2021-01-23 21:30:29 -07:00
Maxim Poliakovski 3189876d41 ppcfpopcodes: fix fmul emulation. 2021-01-24 04:53:19 +01:00
dingusdev 2539faef7e Small typo fixes 2021-01-23 15:10:08 -07:00
Maxim Poliakovski 42184213e9 ppcexec: fix RC flag for subgroup 63. 2021-01-23 03:21:50 +01:00
Maxim Poliakovski bb3f4e596e ppcexec: fix subopcode 59 dispatching. 2021-01-23 03:12:39 +01:00
Maxim Poliakovski 014eefdf7e ppcdisasm: fix frsp and add tests for it. 2021-01-23 02:32:30 +01:00
Maxim Poliakovski d8f7588693 debugger: some fixes and improvements. 2021-01-12 15:17:51 +01:00
dingusdev 2bac606365 Added to Heathrow
Plus some debugging stuff to help figure out what register 0x34 is responsible for.
2021-01-08 15:29:43 -07:00
dingusdev df8ea1b276 Code clean-up for interpreter 2021-01-08 14:34:01 -07:00
dingusdev 9210244c0c Further ATI Rage registers 2021-01-08 14:32:06 -07:00
Maxim Poliakovski 358f018815 ppcopcodes: fix mcrf. 2021-01-08 21:59:18 +01:00
dingusdev 14d3874382 More ATI Rage register names added 2021-01-08 13:12:06 -07:00
Maxim Poliakovski b230299076 Make building of tests and benchmarks optional. 2021-01-08 20:38:40 +01:00
dingusdev 79e3d398ba mcrf implemented 2021-01-07 20:38:32 -07:00
Maxim Poliakovski 2f3938c23f ppcopcodes: fix dcbz. 2021-01-07 04:25:27 +01:00
Maxim Poliakovski dbbaf13a78 ppcopcodes: fix cntlzw to compile properly with Clang.
Enable USE_GCC_BUILTINS by default.
2020-12-18 18:33:00 +01:00
Maxim Poliakovski 99641b1b5e ppcopcodes: fix cntlzw with __builtin_clz.
The result of __builtin_clz is undefined when the source operand
is zero. Add a check for this case and handle it accordingly.
2020-12-07 14:37:20 +01:00
dingusdev 5cba9c1dae Merge branch 'cpu-refactor' 2020-12-04 11:01:34 -07:00
Maxim Poliakovski 180cb0d25f Make 68k debugger optional and disabled by default. 2020-12-03 02:18:13 +01:00
Maxim Poliakovski df39a59190 Build Capstone as static library. 2020-12-03 01:39:39 +01:00
Maxim Poliakovski f0315e98ee Add Capstone submodule. 2020-12-03 00:53:28 +01:00
Maxim Poliakovski 6c6247b94f Clean up program exceptions. 2020-11-30 20:59:36 +01:00
Maxim Poliakovski f61277e46d README.md: minor corrections. 2020-11-30 14:47:22 +01:00
Maxim Poliakovski da3a6c71fd README.md: add C++11 compiler requirement. 2020-11-30 14:45:03 +01:00
Maxim Poliakovski acfa09af65 Illegal opcodes raise program exception. 2020-11-29 23:54:10 +01:00
dingusdev 54fcfca8e9 Fixed floating point loading and storing instructions 2020-11-29 06:52:01 -07:00
Maxim Poliakovski a775007d3a MMU: implement misaligned cross-page accesses. 2020-11-29 00:23:30 +01:00
Maxim Poliakovski 2be8e7b542 Set minimum Capstone version to 4.0.2
This version has fixed a bug with Capstone's main header.
2020-11-28 02:23:47 +01:00
Maxim Poliakovski 0e83ffe435 Fix broken CMakeLists.txt to work on MacOS. 2020-11-28 01:08:34 +01:00
dingusdev 0c202b0c2d Merging the 68k debugger from another branch 2020-11-26 20:00:08 -07:00
Maxim Poliakovski 81b3c3c4a0 Default initialization of Heathrow registers. 2020-11-26 03:03:52 +01:00
Maxim Poliakovski 7be6cb30ac README: fix submodules update command. 2020-11-22 00:17:09 +01:00
Maxim Poliakovski 6124dfd897 Add virtual CPU benchmarking code. 2020-11-14 03:05:41 +01:00
Maxim Poliakovski b81de4af48 ppcexec: initialize interpreter lookup tables. 2020-11-14 03:05:41 +01:00
Maxim Poliakovski 2b19b0b237 ppcmmu: better initialization of last used entries. 2020-11-14 02:57:36 +01:00
dingusdev f417df0630 Fixes Issue #18
Courtesy of webspacecreations
2020-10-25 16:23:53 -07:00
dingusdev 1fe9ffe3e5 Further refactoring to clean up the interpreter 2020-10-17 21:46:38 -07:00
dingusdev dc58386237 Started re-refactoring opcode retrieval 2020-10-17 14:30:37 -07:00
dingusdev 6cc88d3b02 Started a timing mechanism 2020-10-15 21:10:17 -07:00
dingusdev 5d2f3ca3c0 Fixed an issue with a command line arg description 2020-10-14 08:02:34 -07:00
Maxim Poliakovski 3b29ff9514 atirage: fix monitor identification. 2020-10-14 16:55:38 +02:00
dingusdev fc50e3c4f6 Some fix-ups and updates for readme.md 2020-10-14 07:45:18 -07:00
Maxim Poliakovski 2df2d089d7 list properties now prints out valid values. 2020-10-14 16:19:11 +02:00
dingusdev 4c0c32c02c Initial cleanup for the help print-outs 2020-10-13 20:20:44 -07:00
Maxim Poliakovski 90b2eb712a Implement CLI list subcommand. 2020-10-13 04:24:54 +02:00
Maxim Poliakovski 27f5d981da Remove more unused code. 2020-10-13 04:01:37 +02:00
Maxim Poliakovski ce9e8e7244 Fix valid values for gfxmem_size. 2020-10-09 16:33:17 +02:00
Maxim Poliakovski a3b17d46ce Attach value checks to properties. 2020-10-09 15:58:47 +02:00
Maxim Poliakovski 246a7f2082 Remove unused machineconfig source. 2020-10-09 14:28:28 +02:00
Maxim Poliakovski 2eba8acc23 Fix MSVC compilation. 2020-10-09 12:39:31 +02:00
Maxim Poliakovski c81c00f918 Make properties overridable from the command line. 2020-10-09 12:25:12 +02:00
dingusdev 0ca03be001 Fixed booting up to emulator 2020-10-04 09:58:21 -07:00
dingusdev 55ea643974 Full directory name
Makes VS2019 happier
2020-09-25 17:54:14 -07:00
Maxim Poliakovski 599659495b Initial CLI11 integration. 2020-09-26 02:38:22 +02:00
dingusdev 9efea80e43 Removed janky functions
This still compiles in VS2019
2020-09-08 07:46:54 -07:00
dingusdev 4ccfb5d527 Finished the proof-of-concept machine presets 2020-08-31 22:20:47 -07:00
dingusdev 4f59407cd0 Repair code for powermacg3 presets 2020-08-30 16:14:58 -07:00
dingusdev 2f2c9aadcb Typo fix 2020-08-29 17:49:50 -07:00
dingusdev d21515d964 Fixed RAM check and help prompts 2020-08-29 16:20:22 -07:00
dingusdev b28549825d Started work on machine-specific configs 2020-08-29 11:11:06 -07:00
dingusdev 14ef7564cd CLI fixes - RAM and GFXMEM work better 2020-08-25 20:07:02 -07:00
dingusdev f04ce09a7d Clean-up + further command line options 2020-08-23 09:24:52 -07:00
dingusdev 2869755819 Initial work for configuration 2020-08-22 11:05:08 -07:00
Maxim Poliakovski 353035e9ca Prevent clobbering during debugging. 2020-07-20 23:02:07 +02:00
Maxim Poliakovski 660d227ac7 debugger: fix string formatting. 2020-07-20 18:00:04 +02:00
Maxim Poliakovski b9dcfef551 debugger: debugging commands for 68k code. 2020-07-16 14:26:34 +02:00
Maxim Poliakovski 6b74e358dc WIP: basic 68k debugging environment. 2020-07-15 02:19:05 +02:00
Maxim Poliakovski 8094fb30f6 atirage: add access to internal DAC palette. 2020-06-11 01:30:10 +02:00
Maxim Poliakovski f753bb1911 atirage: replace magic numbers with named constants. 2020-06-11 00:49:00 +02:00
Maxim Poliakovski 67596ca49c Merge pull request #17 from Waqar144/fix-linux-build
Fix compilation on Linux.
2020-06-04 12:43:45 +02:00
Waqar Ahmed 59da71884e Fix linux build 2020-06-04 13:29:36 +05:00
Maxim Poliakovski 5d57086795 Add one more missing include. 2020-06-03 20:28:57 +02:00
Maxim Poliakovski 3be46aa44d Add missing includes. 2020-06-03 20:21:52 +02:00
Maxim Poliakovski 39a643aff6 Merge branch 'machines'
Also disable SDL for now because it produces build errors.
2020-06-03 18:21:51 +02:00
Maxim Poliakovski 2cd002cffa ppcexec: remove dead code. 2020-06-03 15:33:32 +02:00
Maxim Poliakovski 6ef0f0baae Fix CPU cycles counter to play nicely with setjmp.
setjmp clobbers non-volatile local variables. bb_start_la is such
a local variable that is used for counting of virtual CPU cycles.
To make cycles counting work after setjmp, the global variable
glob_bb_start_la is used to preserve content of bb_start_la accross
interpreter pipeline.
2020-06-03 15:21:19 +02:00
Maxim Poliakovski d21fdb25d1 Remove unused variable grab_branch. 2020-06-01 23:12:18 +02:00
Maxim Poliakovski f204caa907 ppcexec: new TBR/DEC updating code. 2020-06-01 00:46:00 +02:00
Maxim Poliakovski 07340d82dd atirage: add video RAM. 2020-05-28 23:47:20 +02:00
Maxim Poliakovski 55a14ca28f atirage: fix big memory aperture registration. 2020-05-28 22:36:55 +02:00
Maxim Poliakovski 4dcdeb095d Cubeb library is now a submodule. 2020-05-19 19:14:32 +02:00
Maxim Poliakovski bcc0e38e9f More sound fixes and cleanups. 2020-05-18 20:45:37 +02:00
Maxim Poliakovski ae78a1f04f Fix AWACs sound playback with WASAPI. 2020-05-18 03:02:30 +02:00
Maxim Poliakovski e59939541e WIP: initial Cubeb integration. 2020-05-15 02:44:00 +02:00
dingusdev f8bde236b8 Merge pull request #14 from Waqar144/clang-format
clang-format everything
2020-05-12 14:04:01 -07:00
Waqar Ahmed 0ab9380be3 clang-format everything 2020-05-12 23:55:45 +05:00
Maxim Poliakovski 0fcb1fda72 Merge pull request #12 from Waqar144/machines
Fix build on linux
2020-05-12 18:57:04 +02:00
Waqar Ahmed 286897398c Fix build on linux 2020-05-12 21:20:57 +05:00
Maxim Poliakovski d4c39f13af Changes related to Windows build. 2020-05-09 14:29:37 +02:00
Maxim Poliakovski ba81094fa2 CMakeLists.txt: enable static linkage to libsoundio. 2020-05-08 23:48:02 +02:00
Maxim Poliakovski f7d67a91e0 New AWAC and sound server implementation. 2020-05-08 23:12:04 +02:00
Maxim Poliakovski a5c63c1b09 viacuda: fix autopoll control commands. 2020-04-27 02:50:53 +02:00
dingusdev d24a71528b Slightly readjusted key mappings 2020-04-25 11:02:47 -07:00
Maxim Poliakovski 3b98dee232 adb.cpp: fix indentation. 2020-04-25 03:01:16 +02:00
dingusdev f2ab933884 Slightly clean-up and expansion for future uses 2020-04-23 18:22:47 -07:00
dingusdev c0d0187190 ADB Refactoring, Pt. 2 2020-04-23 18:08:27 -07:00
dingusdev d0f03f722e ADB Refactoring Pt. 1 2020-04-22 14:14:49 -07:00
dingusdev a5b740eafc Slightly reworked ADB work so far 2020-04-21 19:45:59 -07:00
dingusdev 70f5b45e71 Started work on ADB input 2020-04-21 15:23:55 -07:00
Maxim Poliakovski 64d74228c2 ppcopcodes: fix STMW emulation. 2020-04-21 04:58:21 +02:00
Maxim Poliakovski 3d13bc1ca6 ppcopcodes: fix TWI emulation. 2020-04-21 04:58:21 +02:00
Maxim Poliakovski 7154e51d86 Make debugger standalone component. 2020-04-20 20:32:09 +02:00
dingusdev add11ecc62 Adding further Heathrow registers 2020-04-19 11:28:51 -07:00
dingusdev 8fb2e851d7 Started work for ADB polling 2020-04-17 17:23:50 -07:00
Maxim Poliakovski 3461f2e353 displayid.cpp: fix indentation. 2020-04-14 13:03:43 +02:00
Maxim Poliakovski 54a86972cd Basic support for display identification. 2020-04-14 01:04:37 +02:00
dingusdev 925bcdfe9f Getting most I/O Space registers in. 2020-04-01 22:31:29 -07:00
Maxim Poliakovski 9f95fde279 ATI Rage: partial register access implemented. 2020-04-01 03:24:39 +02:00
Maxim Poliakovski b6fcd289a3 ATI Rage: basic register access via PCI I/O space. 2020-03-31 21:19:10 +02:00
Maxim Poliakovski a243c79d0f Add support for PCI I/O space. 2020-03-31 21:12:06 +02:00
Maxim Poliakovski cc5261cfa9 Update gitignore to ignore VS configs. 2020-03-31 18:48:04 +02:00
Maxim Poliakovski a8c6298545 devices: skeleton for ATI Rage emulation. 2020-03-31 18:48:04 +02:00
Maxim Poliakovski 695044cf0e Support more than one I/O region per device. 2020-03-31 18:48:04 +02:00
Maxim Poliakovski ec384fb5ea More little-endian memreadwrite macros. 2020-03-31 18:35:24 +02:00
dingusdev 1744f13fb4 Fixed build issues 2020-03-27 12:52:48 -07:00
dingusdev f50f719b02 Started connecting ATI Rage 2020-03-27 12:43:29 -07:00
dingusdev 17200d5f35 Started work on ATI Rage 2020-03-27 10:54:25 -07:00
dingusdev c1dec68afd Update README.md 2020-03-26 23:36:43 -07:00
dingusdev 13e90b9cb9 Updating this slightly for the GitHub Page 2020-03-26 23:36:02 -07:00
dingusdev b16d1c43ef Set theme jekyll-theme-minimal 2020-03-26 23:30:27 -07:00
dingusdev 82c4a5dbcf Slight cleanup 2020-03-26 12:38:00 -07:00
dingusdev 4e41af21e8 Started config file reading 2020-03-26 12:32:24 -07:00
Maxim Poliakovski 35d6a2e011 Reduce logging when playing back audio. 2020-03-26 03:02:33 +01:00
Maxim Poliakovski 0d2301c006 Implement DMA pull method for sound output. 2020-03-26 02:07:43 +01:00
dingusdev 60ffa5bfac Initial attempt at fixing SDL2 building for Windows 2020-03-22 20:15:12 -07:00
Maxim Poliakovski 945e63bdb2 Implement DMA push method for sound. 2020-03-19 15:09:24 +01:00
Maxim Poliakovski 8e34c1657c Mock up DBDMA channel execution for sound. 2020-03-19 02:00:18 +01:00
Maxim Poliakovski 787ebfaff1 Implement DBDMA channel registers. 2020-03-18 17:34:03 +01:00
Maxim Poliakovski 751efb4cd6 Initial AWACS sound device emulation. 2020-03-15 20:08:53 +01:00
Maxim Poliakovski 9be3250142 Fix MMU region bounds check. 2020-03-15 20:08:53 +01:00
dingusdev 86d6ddf001 Fixed a ROM ID 2020-03-15 09:20:16 -07:00
Maxim Poliakovski 0044610038 Add SPD SDRAM emulation. 2020-03-15 14:44:33 +01:00
Maxim Poliakovski 9c8548c238 Finish I2C bus emulation.
This commit also cleans up and improve I2C commands
in Cuda. Also removes some related hacks.
2020-03-15 13:28:42 +01:00
Maxim Poliakovski 753e445b4b Initial I2C bus implementation. 2020-03-14 21:38:18 +01:00
Maxim Poliakovski 75f0e09f5a viacuda: cleanup print messages. 2020-03-14 19:30:05 +01:00
Maxim Poliakovski 14156dd32b Introduce subdevices interface. 2020-03-14 15:39:34 +01:00
Maxim Poliakovski d53400ebae Introduce base class HWComponent. 2020-03-14 14:26:30 +01:00
Maxim Poliakovski 822f6cafd2 Create machine factory.
It manages various hardware configurations referred to as machines.
2020-03-13 23:09:36 +01:00
dingusdev 4adcd811e3 Documenation Update 3/7/2020 2020-03-07 15:40:46 -07:00
dingusdev 831adfbda0 Documentation Update 2020-03-05 21:38:14 -07:00
dingusdev 4ceed27ccf Simplified prog_counter back to pc 2020-03-05 07:48:10 -07:00
Maxim Poliakovski 78fc5c408b CONTRIBUTING: Use code blocks for code examples. 2020-03-05 11:53:28 +01:00
dingusdev e31f7873f5 Fixed redunant variable names for PPC emulation. 2020-03-04 21:29:04 -07:00
dingusdev 392119480e Further work on fleshing out documentation 2020-03-04 19:32:15 -07:00
Maxim Poliakovski 94cf232b5e viacuda: add receiving of ADB packets. 2020-03-05 01:12:41 +01:00
Maxim Poliakovski 71d6966a03 viacuda: remove cuda prefix from method names. 2020-03-05 01:12:41 +01:00
dingusdev 85ee6e9a86 Preparing for further doc fixes 2020-03-03 20:54:09 -07:00
dingusdev e09be8126f Fixed a codename mixup 2020-03-03 19:56:30 -07:00
dingusdev 9f5e3fa47a Started expanding documentation 2020-03-03 18:21:14 -07:00
Maxim Poliakovski cea840fc09 debugger: add command to control log level. 2020-03-02 23:48:02 +01:00
Maxim Poliakovski 0eb557751b ppcopcodes: fix timebase read & write. 2020-03-02 00:01:18 +01:00
dingusdev f5e8c9cbb8 Three tiny typos fixed
All related to 4*cr1+lt
2020-03-01 14:11:26 -07:00
dingusdev 31147aada3 Fixed most condition register issues with disassembler 2020-03-01 14:09:08 -07:00
dingusdev 81cabc5730 Fixed various bugs in the disassembler 2020-03-01 11:18:29 -07:00
dingusdev 07badbb1b3 Documentation started for hardware 2020-03-01 10:58:09 -07:00
Maxim Poliakovski cbb46e8f30 More tests to reaveal wrong disassembly. 2020-03-01 18:21:57 +01:00
Maxim Poliakovski 7978d9d59f Fix SRR0 setting in exception handler. 2020-03-01 17:24:50 +01:00
dingusdev 1e06f724af Quick correction to the readme 2020-02-28 09:21:21 -07:00
dingusdev 055445e04a Merge branch 'master' of https://github.com/dingusdev/dingusppc 2020-02-28 09:04:30 -07:00
dingusdev 354409812e Updating files with proper licensing header 2020-02-28 09:04:28 -07:00
Maxim Poliakovski e08bf39af3 debugger: more checks for user input. 2020-02-28 08:58:14 +01:00
dingusdev 160566b8f8 Slight formatting fix 2020-02-27 21:05:03 -07:00
dingusdev 5991ef1dca Merge branch 'ppc-fixes' 2020-02-27 21:03:40 -07:00
dingusdev c8611dc293 Code cleanup + procedures for cleanup 2020-02-27 21:03:01 -07:00
dingusdev 51739520b5 Small formatting + logging fixes 2020-02-27 18:41:02 -07:00
Maxim Poliakovski 90779bd9c6 Remove log messages from cache/TLB instructions. 2020-02-27 16:31:22 +01:00
dingusdev d7c0a731f4 Found a message I missed. 2020-02-26 21:43:19 -07:00
dingusdev eef82649f7 Modest logging system revamp
Logging messages now go to dingusppc.log (if in realtime) or the console (if in debug)
2020-02-26 19:51:07 -07:00
dingusdev a3f55d35b4 Fixed most compiler warnings 2020-02-25 07:15:42 -07:00
dingusdev e3a1c3501a Another small fix 2020-02-24 19:56:02 -07:00
dingusdev 8bf902d945 Small fix 2020-02-24 19:55:33 -07:00
dingusdev 6c1dc8aaf0 Further logging work 2020-02-24 19:50:52 -07:00
dingusdev baef838f7c Further integration with loguru 2020-02-24 07:54:29 -07:00
dingusdev d91950e582 Further logging code. 2020-02-23 22:36:31 -07:00
dingusdev e9a616ffeb Started working on incorporating loguru 2020-02-23 20:59:10 -07:00
Maxim Poliakovski 3ffa680f6d debugger: fix address printing under Windows. 2020-02-23 18:52:09 +01:00
Maxim Poliakovski f29a63acd4 debugger: fix disasm command. 2020-02-23 18:42:42 +01:00
Maxim Poliakovski b6768d7168 debugger: add dump command for dumping memory. 2020-02-23 17:52:30 +01:00
Maxim Poliakovski 461d859e73 ppcmmu: add debug memory reading function.
This function saves and restores the MMU state
so no invalid user input can break CPU execution.
2020-02-23 16:41:58 +01:00
Maxim Poliakovski 403c19ca39 Improve the command line debugger.
Add next command. Make the debugger somewhat foolproof.
2020-02-23 15:24:55 +01:00
dingusdev 02a75f78da regsfpsab fixed 2020-02-20 22:21:58 -07:00
dingusdev d20122b3a9 Proper flag updates for fm arithmetic operations 2020-02-20 20:00:20 -07:00
260 changed files with 84401 additions and 5655 deletions

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: false
#AlignConsecutiveMacros: false
AlignEscapedNewlines: Right
AlignOperands: false
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
#AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeComma
#BreakInheritanceList: BeforeComma
BreakStringLiterals: true
ColumnLimit: 100
CompactNamespaces: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
FixNamespaceComments: true
IncludeBlocks: Preserve
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
IndentWrappedFunctionNames: true
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
PenaltyBreakAssignment: 50
PenaltyBreakBeforeFirstCallParameter: 0
PenaltyBreakComment: 100
PenaltyBreakFirstLessLess: 200
PenaltyBreakString: 100
#PenaltyBreakTemplateDeclaration: 0
PenaltyExcessCharacter: 10
PenaltyReturnTypeOnItsOwnLine: 1000
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
#SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCpp11BracedList: true
#SpaceBeforeCtorInitializerColon: false
#SpaceBeforeInheritanceColon: false
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: false
#SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 4
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
#Standard: c++17
TabWidth: 4
UseTab: Never
+8
View File
@@ -7,6 +7,9 @@ out/
*.o
*.d
# Ignore Visual Studio configuration files
CMakeSettings.json
# Ignore generated executables
dingusppc
dingusppc.exe
@@ -14,3 +17,8 @@ dingusppc.exe
# Ignore system files
.DS_Store
Thumb.db
# IDE ignores
build
build-*
*.user
+7
View File
@@ -0,0 +1,7 @@
[submodule "thirdparty/cubeb"]
path = thirdparty/cubeb
url = https://github.com/DingusDevOrg/cubeb.git
[submodule "thirdparty/capstone"]
path = thirdparty/capstone
url = https://github.com/maximumspatium/capstone.git
branch = next
+147 -12
View File
@@ -4,29 +4,164 @@ project(dingusppc)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
#set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
if (NOT WIN32)
find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
if (UNIX AND NOT APPLE)
find_package (Threads)
endif()
endif()
option(DPPC_BUILD_PPC_TESTS "Build PowerPC tests" OFF)
option(DPPC_BUILD_BENCHMARKS "Build benchmarking programs" OFF)
option(ENABLE_68K_DEBUGGER "Enable 68k debugging" OFF)
if (ENABLE_68K_DEBUGGER)
# Build capstone as static library.
set(CAPSTONE_BUILD_STATIC ON CACHE BOOL "")
# Turn off anything unnecessary.
set(CAPSTONE_BUILD_SHARED OFF CACHE BOOL "")
set(CAPSTONE_BUILD_TESTS OFF CACHE BOOL "")
set(CAPSTONE_BUILD_CSTOOL OFF CACHE BOOL "")
set(CAPSTONE_BUILD_DIET OFF CACHE BOOL "")
set(CAPSTONE_OSXKERNEL_SUPPORT OFF CACHE BOOL "")
# Disable unused Capstone architectures.
set(CAPSTONE_ARM_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_ARM64_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_MIPS_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_PPC_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_SPARC_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_SYSZ_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_XCORE_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_X86_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_TMS320C64X_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_M680X_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_EVM_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_MOS65XX_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_WASM_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_BPF_SUPPORT OFF CACHE BOOL "")
set(CAPSTONE_RISCV_SUPPORT OFF CACHE BOOL "")
ADD_DEFINITIONS(-DENABLE_68K_DEBUGGER)
add_subdirectory(thirdparty/capstone EXCLUDE_FROM_ALL)
endif()
add_subdirectory("${PROJECT_SOURCE_DIR}/cpu/ppc/")
add_subdirectory("${PROJECT_SOURCE_DIR}/debugger/")
add_subdirectory("${PROJECT_SOURCE_DIR}/devices/")
add_subdirectory("${PROJECT_SOURCE_DIR}/execution")
add_subdirectory("${PROJECT_SOURCE_DIR}/machines/")
add_subdirectory("${PROJECT_SOURCE_DIR}/thirdparty/loguru/")
#set(BUILD_EXAMPLE_PROGRAMS OFF CACHE BOOL "Build libsoundio example programs")
#set(BUILD_TESTS OFF CACHE BOOL "Build libsoundio tests")
#set(BUILD_DYNAMIC_LIBS ON CACHE BOOL "Build libsoundio dynamic libs")
#set(BUILD_STATIC_LIBS ON CACHE BOOL "Build libsoundio static libs")
#add_subdirectory("${PROJECT_SOURCE_DIR}/thirdparty/libsoundio")
set(BUILD_TESTS OFF CACHE BOOL "Build Cubeb tests")
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries")
set(BUILD_TOOLS OFF CACHE BOOL "Build Cubeb tools")
add_subdirectory(thirdparty/cubeb EXCLUDE_FROM_ALL)
set(CLI11_ROOT ${PROJECT_SOURCE_DIR}/thirdparty/CLI11)
include_directories("${PROJECT_SOURCE_DIR}" "${PROJECT_SOURCE_DIR}/devices"
"${PROJECT_SOURCE_DIR}/cpu/ppc"
"${PROJECT_SOURCE_DIR}/debugger")
"${PROJECT_SOURCE_DIR}/debugger"
"${PROJECT_SOURCE_DIR}/thirdparty/loguru/"
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/")
# "${PROJECT_SOURCE_DIR}/thirdparty/cubeb/include")
# ${LIBSOUNDIO_HEADERS})
file(GLOB SOURCES "${PROJECT_SOURCE_DIR}/*.cpp"
"${PROJECT_SOURCE_DIR}/debugger/*.cpp")
"${PROJECT_SOURCE_DIR}/*.c"
"${PROJECT_SOURCE_DIR}/*.hpp"
"${PROJECT_SOURCE_DIR}/*.h")
#get_directory_property(LIBSOUNDIO_LIBS DIRECTORY thirdparty/libsoundio DEFINITION LIBSOUNDIO_LIBS)
file(GLOB TEST_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/test/*.cpp")
add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:cpu_ppc> $<TARGET_OBJECTS:devices>)
add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:execution>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:loguru>)
add_executable(testppc ${TEST_SOURCES} $<TARGET_OBJECTS:cpu_ppc> $<TARGET_OBJECTS:devices>)
if (WIN32)
target_link_libraries(dingusppc "${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2.lib"
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2main.lib"
cubeb)
else()
#target_link_libraries(dingusppc libsoundio_static ${LIBSOUNDIO_LIBS} ${SDL2_LIBRARIES})
target_link_libraries(dingusppc cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
target_include_directories(dingusppc PRIVATE ${CLI11_ROOT})
endif()
add_custom_command(
TARGET testppc POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcinttests.csv"
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcdisasmtest.csv"
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
if (ENABLE_68K_DEBUGGER)
target_link_libraries(dingusppc capstone-static)
endif()
install (TARGETS dingusppc DESTINATION ${EXECUTABLE_OUTPUT_PATH})
if (DPPC_BUILD_PPC_TESTS)
add_executable(testppc ${TEST_SOURCES} $<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:execution>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:loguru>)
if (WIN32)
target_link_libraries(testppc
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2.lib"
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2main.lib"
cubeb)
else()
#target_link_libraries(testppc libsoundio_static ${LIBSOUNDIO_LIBS} ${SDL2_LIBRARIES})
target_link_libraries(testppc cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
endif()
if (ENABLE_68K_DEBUGGER)
target_link_libraries(testppc capstone-static)
endif()
endif()
if (DPPC_BUILD_BENCHMARKS)
file(GLOB BENCH_SOURCES "${PROJECT_SOURCE_DIR}/benchmark/*.cpp")
add_executable(bench1 ${BENCH_SOURCES} $<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:execution>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:loguru>)
target_link_libraries(bench1 cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (ENABLE_68K_DEBUGGER)
target_link_libraries(bench1 capstone-static)
endif()
endif()
if (DPPC_BUILD_PPC_TESTS)
add_custom_command(
TARGET testppc POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcinttests.csv"
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcdisasmtest.csv"
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
endif()
install (TARGETS dingusppc DESTINATION ${PROJECT_SOURCE_DIR}/build)
+1 -1
View File
@@ -21,7 +21,7 @@
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x64_x64" ],
"inheritEnvironments": [ "clang_cl_x64" ],
"variables": []
}
]
+12 -1
View File
@@ -10,7 +10,18 @@ Code
* Make sure the code can compile for all target systems - Windows, Linux, and macOS/Mac OS X.
* All code must be compatible with at least C++11.
* Minimize the amount of redundant code
* Minimize the amount of redundant code.
* Avoid using absolute paths for the headers.
* Code should maintain vertical alignment for better readability, for example:
```C
one_hundred = 100;
one_thousand = 1000;
two_thousand = 2000;
```
* CamelCase for class names, lowercase for variables, UPPERCASE for enumerations
* Avoid redundancy in namespaces (i.e. use ViaCuda::read() instead of ViaCuda::cuda_read())
Issues
=======
+47 -14
View File
@@ -1,35 +1,65 @@
# DingusPPC by divingkatae
# DingusPPC
Written by divingkatae and maximumspatium
Be warned the program is highly unfinished and could use a lot of testing. Any feedback is welcome.
## PHILOSOPHY OF USE
## Philosophy of Use
Sheepshaver, while technically impressive, is becoming harder to compile and run. While many other PowerPC emus exist, none of them currently attempt emulation of PPC Macs (except for QEMU).
While many other PowerPC emus exist (PearPC, Sheepshaver), none of them currently attempt emulation of PPC Macs accurately (except for QEMU).
This program aims to not only improve upon what Sheepshaver has done, but also to provide a better debugging environment. This currently is designed to work best with PowerPC Old World ROMs,
including those of the PowerMac G3 Beige.
This program aims to not only improve upon what Sheepshaver, PearPC, and other PowerPC mac emulators have done, but also to provide a better debugging environment. This currently is designed to work best with PowerPC Old World ROMs, including those of the PowerMac G3 Beige.
## HOW TO USE
## Implemented Features
This emulator has a debugging environment, complete with a disassembler. We also have implemented enough to allow OpenFirmware to boot, going so far as to allow audio playback of the boot-up jingles.
## How to Use
This program currently uses the command prompt to work.
There are a few command line arguments one must enter when starting the program.
-realtime
```
-r, --realtime
```
Run the emulator in runtime.
-debugger
```
-d, --debugger
```
Enter the interactive debugger.
## HOW TO COMPILE
```
-b, --bootrom TEXT:FILE
```
You'll need to install development tools first.
Specifies the Boot ROM path (optional; looks for bootrom.bin by default)
At least, a C++ compiler and [CMake](https://cmake.org) are required.
```
-m, --machine TEXT
```
For example, to build the project in a Unix-like environment, you'll need to run
Specify machine ID (optional; will attempt to determine machine ID from the boot rom otherwise)
As of now, only the Power Macintosh G3 Beige is implemented.
## How to Compile
You need to install development tools first.
At least, a C++11 compliant compiler and [CMake](https://cmake.org) are required.
You will also have to recursive clone or run
```
git submodule update --init --recursive
```
This is because the CubeB module is not included by default. All other components are already included in the thirdparty folder and compiled along with the rest of DingusPPC.
For example, to build the project in a Unix-like environment, you will need to run
the following commands in the OS terminal:
```
mkdir build
@@ -39,9 +69,12 @@ make dingusppc
```
You may specify another build type using the variable CMAKE_BUILD_TYPE.
Due to the incomplete status of the program at this time, no additional libraries are required.
Future versions may drop SDL 2 as a requirement.
Future versions will include SDL 2 as a requirement.
For Raspbian, you may also need the following command:
```
sudo apt install doxygen graphviz
```
## Testing
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-minimal
+91
View File
@@ -0,0 +1,91 @@
#include <stdlib.h>
#include <chrono>
#include "cpu/ppc/ppcemu.h"
#include "cpu/ppc/ppcmmu.h"
#include "devices/mpc106.h"
#include <thirdparty/loguru/loguru.hpp>
uint32_t cs_code[] = {
0x3863FFFC, 0x7C861671, 0x41820090, 0x70600002, 0x41E2001C, 0xA0030004,
0x3884FFFE, 0x38630002, 0x5486F0BF, 0x7CA50114, 0x41820070, 0x70C60003,
0x41820014, 0x7CC903A6, 0x84030004, 0x7CA50114, 0x4200FFF8, 0x5486E13F,
0x41820050, 0x80030004, 0x7CC903A6, 0x80C30008, 0x7CA50114, 0x80E3000C,
0x7CA53114, 0x85030010, 0x7CA53914, 0x42400028, 0x80030004, 0x7CA54114,
0x80C30008, 0x7CA50114, 0x80E3000C, 0x7CA53114, 0x85030010, 0x7CA53914,
0x4200FFE0, 0x7CA54114, 0x70800002, 0x41E20010, 0xA0030004, 0x38630002,
0x7CA50114, 0x70800001, 0x41E20010, 0x88030004, 0x5400402E, 0x7CA50114,
0x7C650194, 0x4E800020
};
int main(int argc, char** argv) {
int i;
/* initialize logging */
loguru::g_preamble_date = false;
loguru::g_preamble_time = false;
loguru::g_preamble_thread = false;
loguru::g_stderr_verbosity = 0;
loguru::init(argc, argv);
MPC106* grackle_obj = new MPC106;
/* we need some RAM */
if (!grackle_obj->add_ram_region(0, 0x9000)) {
LOG_F(ERROR, "Could not create RAM region");
delete(grackle_obj);
return -1;
}
ppc_cpu_init(grackle_obj, PPC_VER::MPC750);
/* load executable code into RAM at address 0 */
for (i = 0; i < sizeof(cs_code); i++) {
mem_write_dword(i*4, cs_code[i]);
}
srand(0xCAFEBABE);
for (i = 0; i < 32768; i++) {
mem_write_byte(0x1000+i, rand() % 256);
}
/* prepare benchmark code execution */
ppc_state.pc = 0;
ppc_state.gpr[3] = 0x1000; // buf
ppc_state.gpr[4] = 0x8000; // len
ppc_state.gpr[5] = 0; // sum
ppc_exec_until(0xC4);
LOG_F(INFO, "Checksum: 0x%08X", ppc_state.gpr[3]);
// run the clock once for cache fill etc.
auto start_time = std::chrono::steady_clock::now();
auto end_time = std::chrono::steady_clock::now();
auto time_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time);
LOG_F(INFO, "Time elapsed (dry run): %lld ns", time_elapsed.count());
for (i = 0; i < 5; i++) {
ppc_state.pc = 0;
ppc_state.gpr[3] = 0x1000; // buf
ppc_state.gpr[4] = 0x8000; // len
ppc_state.gpr[5] = 0; // sum
auto start_time = std::chrono::steady_clock::now();
ppc_exec_until(0xC4);
auto end_time = std::chrono::steady_clock::now();
LOG_F(INFO, "Checksum: 0x%08X", ppc_state.gpr[3]);
auto time_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time);
LOG_F(INFO, "Time elapsed (run #%d): %lld ns", i, time_elapsed.count());
}
delete(grackle_obj);
return 0;
}
+218 -515
View File
@@ -1,76 +1,65 @@
//DingusPPC - Prototype 5bf2
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// The Power-specific opcodes for the processor - ppcopcodes.cpp
// Any shared opcodes are in ppcopcodes.cpp
#include <iostream>
#include <array>
#include <stdio.h>
#include <stdexcept>
#include "ppcemu.h"
#include "ppcmmu.h"
#include <array>
#include <cmath>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <stdio.h>
#include <thirdparty/loguru/loguru.hpp>
void power_abs() {
// Affects the XER register's SO and OV Bits
inline void power_setsoov(uint32_t a, uint32_t b, uint32_t d) {
if ((a ^ b) & (a ^ d) & 0x80000000UL) {
ppc_state.spr[SPR::XER] |= 0xC0000000UL;
} else {
ppc_state.spr[SPR::XER] &= 0xBFFFFFFFUL;
}
}
void dppc_interpreter::power_abs() {
ppc_grab_regsda();
if (ppc_result_a == 0x80000000) {
ppc_result_d = ppc_result_a;
if (oe_flag)
ppc_state.spr[SPR::XER] |= 0x40000000;
}
else {
} else {
ppc_result_d = ppc_result_a & 0x7FFFFFFF;
}
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_absdot() {
ppc_grab_regsda();
if (ppc_result_a == 0x80000000) {
ppc_result_d = ppc_result_a;
}
else {
ppc_result_d = ppc_result_a & 0x7FFFFFFF;
}
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_abso() {
ppc_grab_regsda();
if (ppc_result_a == 0x80000000) {
ppc_result_d = ppc_result_a;
ppc_state.ppc_spr[SPR::XER] |= 0x40000000;
}
else {
ppc_result_d = ppc_result_a & 0x7FFFFFFF;
}
ppc_store_result_regd();
}
void power_absodot() {
ppc_grab_regsda();
if (ppc_result_a == 0x80000000) {
ppc_result_d = ppc_result_a;
ppc_state.ppc_spr[SPR::XER] |= 0x40000000;
}
else {
ppc_result_d = ppc_result_a & 0x7FFFFFFF;
}
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_clcs() {
void dppc_interpreter::power_clcs() {
ppc_grab_regsda();
switch (reg_a) {
case 12:
@@ -82,133 +71,77 @@ void power_clcs() {
default:
ppc_result_d = 0;
}
ppc_store_result_regd();
}
void power_clcsdot() {
switch (reg_a) {
case 12:
case 13:
case 14:
case 15:
ppc_result_d = 65535;
break;
default:
ppc_result_d = 0;
if (rc_flag) {
ppc_changecrf0(ppc_result_d);
printf("Does RC do anything here? (TODO) \n");
}
ppc_changecrf0(ppc_result_d);
printf("Does RC do anything here? (TODO) \n");
ppc_store_result_regd();
}
void power_div() {
void dppc_interpreter::power_div() {
ppc_grab_regsdab();
ppc_result_d = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) % ppc_result_b;
ppc_result_d = (ppc_result_a | ppc_state.spr[SPR::MQ]) / ppc_result_b;
ppc_state.spr[SPR::MQ] = (ppc_result_a | ppc_state.spr[SPR::MQ]) % ppc_result_b;
if (oe_flag)
power_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_divdot() {
ppc_result_d = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) % ppc_result_b;
}
void power_divo() {
ppc_result_d = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) % ppc_result_b;
}
void power_divodot() {
ppc_result_d = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a | ppc_state.ppc_spr[SPR::MQ]) % ppc_result_b;
}
void power_divs() {
void dppc_interpreter::power_divs() {
ppc_grab_regsdab();
ppc_result_d = ppc_result_a / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a % ppc_result_b);
ppc_result_d = ppc_result_a / ppc_result_b;
ppc_state.spr[SPR::MQ] = (ppc_result_a % ppc_result_b);
if (oe_flag)
power_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_divsdot() {
ppc_result_d = ppc_result_a / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a % ppc_result_b);
}
void power_divso() {
ppc_result_d = ppc_result_a / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a % ppc_result_b);
}
void power_divsodot() {
ppc_result_d = ppc_result_a / ppc_result_b;
ppc_state.ppc_spr[SPR::MQ] = (ppc_result_a % ppc_result_b);
}
void power_doz() {
void dppc_interpreter::power_doz() {
ppc_grab_regsdab();
if (((int32_t)ppc_result_a) > ((int32_t)ppc_result_b)) {
ppc_result_d = 0;
}
else {
} else {
ppc_result_d = ~ppc_result_a + ppc_result_b + 1;
}
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_rega();
}
void power_dozdot() {
ppc_grab_regsdab();
if (((int32_t)ppc_result_a) > ((int32_t)ppc_result_b)) {
ppc_result_d = 0;
}
else {
ppc_result_d = ~ppc_result_a + ppc_result_b + 1;
}
ppc_changecrf0(ppc_result_d);
ppc_store_result_rega();
}
void power_dozo() {
if (((int32_t)ppc_result_a) > ((int32_t)ppc_result_b)) {
ppc_result_d = 0;
}
else {
ppc_result_d = ~ppc_result_a + ppc_result_b + 1;
}
}
void power_dozodot() {
if (((int32_t)ppc_result_a) > ((int32_t)ppc_result_b)) {
ppc_result_d = 0;
}
else {
ppc_result_d = ~ppc_result_a + ppc_result_b + 1;
}
}
void power_dozi() {
void dppc_interpreter::power_dozi() {
ppc_grab_regsdab();
if (((int32_t)ppc_result_a) > simm) {
ppc_result_d = 0;
}
else {
} else {
ppc_result_d = ~ppc_result_a + simm + 1;
}
ppc_store_result_rega();
}
void power_lscbx() {
void dppc_interpreter::power_lscbx() {
ppc_grab_regsdab();
uint32_t bytes_copied = 0;
bool match_found = false;
bool match_found = false;
uint32_t shift_amount = 0;
uint8_t return_value;
uint8_t byte_compared = (uint8_t)((ppc_state.ppc_spr[SPR::XER] & 0xFF00) >> 8);
if ((ppc_state.ppc_spr[SPR::XER] & 0x7f) == 0) {
uint8_t byte_compared = (uint8_t)((ppc_state.spr[SPR::XER] & 0xFF00) >> 8);
if ((ppc_state.spr[SPR::XER] & 0x7f) == 0) {
return;
}
uint32_t bytes_to_load = (ppc_state.ppc_spr[SPR::XER] & 0x7f) + 1;
ppc_effective_address = (reg_a == 0) ? ppc_result_b : ppc_result_a + ppc_result_b;
uint32_t bytes_to_load = (ppc_state.spr[SPR::XER] & 0x7f) + 1;
ppc_effective_address = (reg_a == 0) ? ppc_result_b : ppc_result_a + ppc_result_b;
do {
ppc_effective_address++;
bytes_to_load--;
@@ -244,35 +177,33 @@ void power_lscbx() {
if (shift_amount == 3) {
shift_amount = 0;
reg_d = (reg_d + 1) & 0x1F;
}
else {
reg_d = (reg_d + 1) & 0x1F;
} else {
shift_amount++;
}
} while (bytes_to_load > 0);
ppc_state.ppc_spr[SPR::XER] = (ppc_state.ppc_spr[SPR::XER] & 0xFFFFFF80) | bytes_copied;
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & 0xFFFFFF80) | bytes_copied;
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_lscbxdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_maskg() {
void dppc_interpreter::power_maskg() {
ppc_grab_regssab();
uint32_t mask_start = ppc_result_d & 31;
uint32_t mask_end = ppc_result_b & 31;
uint32_t mask_start = ppc_result_d & 31;
uint32_t mask_end = ppc_result_b & 31;
uint32_t insert_mask = 0;
if (mask_start < (mask_end + 1)) {
for (uint32_t i = mask_start; i < mask_end; i++) {
insert_mask |= (0x80000000 >> i);
}
}
else if (mask_start == (mask_end + 1)) {
} else if (mask_start == (mask_end + 1)) {
insert_mask = 0xFFFFFFFF;
}
else {
} else {
insert_mask = 0xFFFFFFFF;
for (uint32_t i = (mask_end + 1); i < (mask_start - 1); i++) {
insert_mask &= (~(0x80000000 >> i));
@@ -280,38 +211,17 @@ void power_maskg() {
}
ppc_result_a = insert_mask;
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_rega();
}
void power_maskgdot() {
ppc_grab_regssab();
uint32_t mask_start = ppc_result_d & 31;
uint32_t mask_end = ppc_result_b & 31;
uint32_t insert_mask = 0;
if (mask_start < (mask_end + 1)) {
for (uint32_t i = mask_start; i < mask_end; i++) {
insert_mask |= (0x80000000 >> i);
}
}
else if (mask_start == (mask_end + 1)) {
insert_mask = 0xFFFFFFFF;
}
else {
insert_mask = 0xFFFFFFFF;
for (uint32_t i = (mask_end + 1); i < (mask_start - 1); i++) {
insert_mask &= (~(0x80000000 >> i));
}
}
ppc_result_a = insert_mask;
ppc_store_result_rega();
}
void power_maskir() {
void dppc_interpreter::power_maskir() {
ppc_grab_regssab();
uint32_t mask_insert = ppc_result_a;
uint32_t insert_rot = 0x80000000;
uint32_t insert_rot = 0x80000000;
do {
if (ppc_result_b & insert_rot) {
mask_insert &= ~insert_rot;
@@ -321,101 +231,51 @@ void power_maskir() {
} while (insert_rot > 0);
ppc_result_a = (ppc_result_d & ppc_result_b);
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_maskirdot() {
ppc_grab_regssab();
uint32_t mask_insert = ppc_result_a;
uint32_t insert_rot = 0x80000000;
do {
if (ppc_result_b & insert_rot) {
mask_insert &= ~insert_rot;
mask_insert |= (ppc_result_d & insert_rot);
}
insert_rot = insert_rot >> 1;
} while (insert_rot > 0);
ppc_result_a = (ppc_result_d & ppc_result_b);
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_mul() {
void dppc_interpreter::power_mul() {
ppc_grab_regsdab();
uint64_t product;
product = ((uint64_t)ppc_result_a) * ((uint64_t)ppc_result_b);
ppc_result_d = ((uint32_t)(product >> 32));
ppc_state.ppc_spr[SPR::MQ] = ((uint32_t)(product));
product = ((uint64_t)ppc_result_a) * ((uint64_t)ppc_result_b);
ppc_result_d = ((uint32_t)(product >> 32));
ppc_state.spr[SPR::MQ] = ((uint32_t)(product));
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_muldot() {
ppc_grab_regsdab();
uint64_t product;
product = ((uint64_t)ppc_result_a) * ((uint64_t)ppc_result_b);
ppc_result_d = ((uint32_t)(product >> 32));
ppc_state.ppc_spr[SPR::MQ] = ((uint32_t)(product));
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_mulo() {
uint64_t product;
product = ((uint64_t)ppc_result_a) * ((uint64_t)ppc_result_b);
ppc_result_d = ((uint32_t)(product >> 32));
ppc_state.ppc_spr[SPR::MQ] = ((uint32_t)(product));
}
void power_mulodot() {
uint64_t product;
product = ((uint64_t)ppc_result_a) * ((uint64_t)ppc_result_b);
ppc_result_d = ((uint32_t)(product >> 32));
ppc_state.ppc_spr[SPR::MQ] = ((uint32_t)(product));
}
void power_nabs() {
void dppc_interpreter::power_nabs() {
ppc_grab_regsda();
ppc_result_d = (0x80000000 | ppc_result_a);
if (rc_flag)
ppc_changecrf0(ppc_result_d);
ppc_store_result_regd();
}
void power_nabsdot() {
ppc_result_d = (0x80000000 | ppc_result_a);
}
void power_nabso() {
ppc_result_d = (0x80000000 | ppc_result_a);
}
void power_nabsodot() {
ppc_result_d = (0x80000000 | ppc_result_a);
}
void power_rlmi() {
void dppc_interpreter::power_rlmi() {
ppc_grab_regssab();
unsigned rot_mb = (ppc_cur_instruction >> 6) & 31;
unsigned rot_me = (ppc_cur_instruction >> 1) & 31;
uint32_t rot_amt = ppc_result_b & 31;
unsigned rot_mb = (ppc_cur_instruction >> 6) & 31;
unsigned rot_me = (ppc_cur_instruction >> 1) & 31;
uint32_t rot_amt = ppc_result_b & 31;
uint32_t insert_mask = 0;
if (rot_mb < (rot_me + 1)) {
for (uint32_t i = rot_mb; i < rot_me; i++) {
insert_mask |= (0x80000000 >> i);
}
}
else if (rot_mb == (rot_me + 1)) {
} else if (rot_mb == (rot_me + 1)) {
insert_mask = 0xFFFFFFFF;
}
else {
} else {
insert_mask = 0xFFFFFFFF;
for (uint32_t i = (rot_me + 1); i < (rot_mb - 1); i++) {
insert_mask &= (~(0x80000000 >> i));
@@ -423,69 +283,51 @@ void power_rlmi() {
}
uint32_t step2 = (ppc_result_d << rot_amt) | (ppc_result_d >> rot_amt);
ppc_result_a = step2 & insert_mask;
ppc_result_a = step2 & insert_mask;
ppc_store_result_rega();
}
void power_rrib() {
void dppc_interpreter::power_rrib() {
ppc_grab_regssab();
if (ppc_result_d & 0x80000000) {
ppc_result_a |= (0x80000000 >> ppc_result_b);
}
else {
} else {
ppc_result_a &= ~(0x80000000 >> ppc_result_b);
}
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_rribdot() {
ppc_grab_regssab();
if (ppc_result_d & 0x80000000) {
ppc_result_a |= (0x80000000 >> ppc_result_b);
}
else {
ppc_result_a &= ~(0x80000000 >> ppc_result_b);
}
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sle() {
void dppc_interpreter::power_sle() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_final = ((ppc_result_d << rot_amt) | (ppc_result_d >> (32 - rot_amt)));
ppc_state.ppc_spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final & insert_mask;
uint32_t insert_final = ((ppc_result_d << rot_amt) | (ppc_result_d >> (32 - rot_amt)));
ppc_state.spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final & insert_mask;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sledot() {
void dppc_interpreter::power_sleq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_final = ((ppc_result_d << rot_amt) | (ppc_result_d >> (32 - rot_amt)));
ppc_state.ppc_spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final & insert_mask;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sleq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_amt) | (ppc_result_d >> (rot_amt - 31)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
uint32_t insert_end = ppc_state.spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
@@ -494,43 +336,24 @@ void power_sleq() {
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_result_a = insert_end;
ppc_state.spr[SPR::MQ] = insert_start;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sleqdot() {
void dppc_interpreter::power_sliq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_amt) | (ppc_result_d >> (rot_amt - 31)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
insert_end &= ~(1 << i);
insert_end |= (insert_start & (1 << i));
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sliq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_sh) | (ppc_result_d >> (rot_sh - 31)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
uint32_t insert_end = ppc_state.spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
@@ -539,43 +362,24 @@ void power_sliq() {
}
}
ppc_result_a = insert_end & insert_mask;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_result_a = insert_end & insert_mask;
ppc_state.spr[SPR::MQ] = insert_start;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sliqdot() {
void dppc_interpreter::power_slliq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_sh) | (ppc_result_d >> (rot_sh - 31)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
insert_end &= ~(1 << i);
insert_end |= (insert_start & (1 << i));
}
}
ppc_result_a = insert_end & insert_mask;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_slliq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
uint32_t insert_end = ppc_state.spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
@@ -584,110 +388,59 @@ void power_slliq() {
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_result_a = insert_end;
ppc_state.spr[SPR::MQ] = insert_start;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_slliqdot() {
void dppc_interpreter::power_sllq() {
LOG_F(WARNING, "OOPS! Placeholder for sllq!!! \n");
}
void dppc_interpreter::power_slq() {
LOG_F(WARNING, "OOPS! Placeholder for slq!!! \n");
}
void dppc_interpreter::power_sraiq() {
LOG_F(WARNING, "OOPS! Placeholder for sraiq!!! \n");
}
void dppc_interpreter::power_sraq() {
LOG_F(WARNING, "OOPS! Placeholder for sraq!!! \n");
}
void dppc_interpreter::power_sre() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
insert_end &= ~(1 << i);
insert_end |= (insert_start & (1 << i));
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sllq() {
printf("OOPS! Placeholder!!! \n");
}
void power_sllqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_slq() {
printf("OOPS! Placeholder!!! \n");
}
void power_slqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_sraiq() {
printf("OOPS! Placeholder!!! \n");
}
void power_sraiqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_sraq() {
printf("OOPS! Placeholder!!! \n");
}
void power_sraqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_sre() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_final = ((ppc_result_d >> rot_amt) | (ppc_result_d << (32 - rot_amt)));
ppc_state.ppc_spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final;
uint32_t insert_final = ((ppc_result_d >> rot_amt) | (ppc_result_d << (32 - rot_amt)));
ppc_state.spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sredot() {
void dppc_interpreter::power_srea() {
LOG_F(WARNING, "OOPS! Placeholder for srea!!! \n");
}
void dppc_interpreter::power_sreq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
uint32_t rot_amt = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_amt; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_final = ((ppc_result_d >> rot_amt) | (ppc_result_d << (32 - rot_amt)));
ppc_state.ppc_spr[SPR::MQ] = insert_final & insert_mask;
ppc_result_a = insert_final;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_srea() {
printf("OOPS! Placeholder!!! \n");
}
void power_sreadot() {
printf("OOPS! Placeholder!!! \n");
}
void power_sreq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = ppc_result_b & 31;
unsigned rot_sh = ppc_result_b & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
uint32_t insert_end = ppc_state.spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
@@ -696,20 +449,24 @@ void power_sreq() {
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_result_a = insert_end;
ppc_state.spr[SPR::MQ] = insert_start;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sreqdot() {
void dppc_interpreter::power_sriq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = ppc_result_b & 31;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
uint32_t insert_end = ppc_state.spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
@@ -718,77 +475,23 @@ void power_sreqdot() {
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_changecrf0(ppc_result_a);
ppc_result_a = insert_end;
ppc_state.spr[SPR::MQ] = insert_start;
if (rc_flag)
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
}
void power_sriq() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
insert_end &= ~(1 << i);
insert_end |= (insert_start & (1 << i));
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_store_result_rega();
void dppc_interpreter::power_srliq() {
LOG_F(WARNING, "OOPS! Placeholder for slriq!!! \n");
}
void power_sriqdot() {
ppc_grab_regssa();
uint32_t insert_mask = 0;
unsigned rot_sh = (ppc_cur_instruction >> 11) & 31;
for (uint32_t i = 31; i > rot_sh; i--) {
insert_mask |= (1 << i);
}
uint32_t insert_start = ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh)));
uint32_t insert_end = ppc_state.ppc_spr[SPR::MQ];
for (int i = 0; i < 32; i++) {
if (insert_mask & (1 << i)) {
insert_end &= ~(1 << i);
insert_end |= (insert_start & (1 << i));
}
}
ppc_result_a = insert_end;
ppc_state.ppc_spr[SPR::MQ] = insert_start;
ppc_changecrf0(ppc_result_a);
ppc_store_result_rega();
void dppc_interpreter::power_srlq() {
LOG_F(WARNING, "OOPS! Placeholder for slrq!!! \n");
}
void power_srliq() {
printf("OOPS! Placeholder!!! \n");
}
void power_srliqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_srlq() {
printf("OOPS! Placeholder!!! \n");
}
void power_srlqdot() {
printf("OOPS! Placeholder!!! \n");
}
void power_srq() {
printf("OOPS! Placeholder!!! \n");
}
void power_srqdot() {
printf("OOPS! Placeholder!!! \n");
}
void dppc_interpreter::power_srq() {
LOG_F(WARNING, "OOPS! Placeholder for srq!!! \n");
}
+507 -420
View File
File diff suppressed because it is too large. Load diff
+26 -5
View File
@@ -1,3 +1,24 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPCDISASM_H
#define PPCDISASM_H
@@ -5,17 +26,17 @@
#include <string>
typedef struct PPCDisasmContext {
uint32_t instr_addr;
uint32_t instr_code;
uint32_t instr_addr;
uint32_t instr_code;
std::string instr_str;
bool simplified; /* true if we should output simplified mnemonics */
bool simplified; /* true if we should output simplified mnemonics */
} PPCDisasmContext;
std::string disassemble_single(PPCDisasmContext *ctx);
std::string disassemble_single(PPCDisasmContext* ctx);
int test_ppc_disasm(void);
/** sign-extend an integer. */
#define SIGNEXT(x, sb) ((x) | (((x) & (1 << (sb))) ? ~((1 << (sb))-1) : 0))
#define SIGNEXT(x, sb) ((x) | (((x) & (1 << (sb))) ? ~((1 << (sb)) - 1) : 0))
#endif /* PPCDISASM_H */
+105 -214
View File
@@ -1,28 +1,43 @@
//DingusPPC - Prototype 5bf2
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPCEMU_H
#define PPCEMU_H
#include "devices/memctrlbase.h"
#include "endianswap.h"
#include <cinttypes>
#include <setjmp.h>
#include "endianswap.h"
#include "devices/memctrlbase.h"
#include <string>
//Uncomment this to help debug the emulator further
// Uncomment this to help debug the emulator further
//#define EXHAUSTIVE_DEBUG 1
//Uncomment this to have a more graceful approach to illegal opcodes
// Uncomment this to have a more graceful approach to illegal opcodes
//#define ILLEGAL_OP_SAFE 1
//Uncomment this to use GCC built-in functions.
//#define USE_GCC_BUILTINS 1
// Uncomment this to use GCC built-in functions.
#define USE_GCC_BUILTINS 1
//Uncomment this to use Visual Studio built-in functions.
// Uncomment this to use Visual Studio built-in functions.
//#define USE_VS_BUILTINS 1
enum endian_switch { big_end = 0, little_end = 1 };
@@ -30,8 +45,8 @@ enum endian_switch { big_end = 0, little_end = 1 };
typedef void (*PPCOpcode)(void);
union FPR_storage {
double dbl64_r; // double floating-point representation
uint64_t int64_r; // double integer representation
double dbl64_r; // double floating-point representation
uint64_t int64_r; // double integer representation
};
/**
@@ -49,16 +64,16 @@ fpscr = FP Status and Condition Register
**/
typedef struct struct_ppc_state {
FPR_storage ppc_fpr[32];
uint32_t ppc_pc; //Referred as the CIA in the PPC manual
uint32_t ppc_gpr[32];
uint32_t ppc_cr;
uint32_t ppc_fpscr;
uint32_t ppc_tbr[2];
uint32_t ppc_spr[1024];
uint32_t ppc_msr;
uint32_t ppc_sr[16];
bool ppc_reserve; //reserve bit used for lwarx and stcwx
FPR_storage fpr[32];
uint32_t pc; // Referred as the CIA in the PPC manual
uint32_t gpr[32];
uint32_t cr;
uint32_t fpscr;
uint32_t tbr[2];
uint32_t spr[1024];
uint32_t msr;
uint32_t sr[16];
bool reserve; // reserve bit used for lwarx and stcwx
} SetPRS;
extern SetPRS ppc_state;
@@ -79,10 +94,7 @@ enum SPR : int {
};
/** symbolic names for frequently used SPRs */
enum TBR : int {
TBL = 0,
TBU = 1
};
enum TBR : int { TBL = 0, TBU = 1 };
/** symbolic names for common PPC processors */
enum PPC_VER : uint32_t {
@@ -95,16 +107,16 @@ enum PPC_VER : uint32_t {
/**
typedef struct struct_ppc64_state {
FPR_storage ppc_fpr [32];
uint64_t ppc_pc; //Referred as the CIA in the PPC manual
uint64_t ppc_gpr [32];
uint32_t ppc_cr;
uint32_t ppc_fpscr;
uint32_t ppc_tbr [2];
uint64_t ppc_spr [1024];
uint32_t ppc_msr;
uint32_t ppc_sr [16];
bool ppc_reserve; //reserve bit used for lwarx and stcwx
FPR_storage fpr [32];
uint64_t pc; //Referred as the CIA in the PPC manual
uint64_t gpr [32];
uint32_t cr;
uint32_t fpscr;
uint32_t tbr [2];
uint64_t spr [1024];
uint32_t msr;
uint32_t sr [16];
bool reserve; //reserve bit used for lwarx and stcwx
} SetPRS64;
extern SetPRS64 ppc_state64;
@@ -132,18 +144,15 @@ SUPERVISOR MODEL
536 - 543 are the Data BAT registers
**/
extern uint32_t opcode_value; //used for interpreting opcodes
extern uint64_t timebase_counter; //used for storing time base value
extern uint32_t opcode_value; // used for interpreting opcodes
extern uint64_t timebase_counter; // used for storing time base value
//Additional steps to prevent overflow?
// Additional steps to prevent overflow?
extern int32_t add_result;
extern int32_t simult_result;
extern uint32_t uiadd_result;
extern uint32_t uimult_result;
extern int32_t word_copy_location;
extern uint32_t strwrd_replace_value;
extern uint32_t crf_d;
extern uint32_t crf_s;
extern uint32_t reg_s;
@@ -161,19 +170,19 @@ extern uint32_t rot_mb;
extern uint32_t rot_me;
extern uint32_t uimm;
extern uint32_t grab_sr;
extern uint32_t grab_inb; //This is for grabbing the number of immediate bytes for loading and storing
extern uint32_t grab_inb; // This is for grabbing the number of immediate bytes for loading and storing
extern uint32_t ppc_to;
extern int32_t simm;
extern int32_t adr_li;
extern int32_t br_bd;
//Used for GP calcs
// Used for GP calcs
extern uint32_t ppc_result_a;
extern uint32_t ppc_result_b;
extern uint32_t ppc_result_c;
extern uint32_t ppc_result_d;
//Used for FP calcs
// Used for FP calcs
extern uint64_t ppc_result64_a;
extern uint64_t ppc_result64_b;
extern uint64_t ppc_result64_c;
@@ -182,7 +191,7 @@ extern uint64_t ppc_result64_d;
/* The precise end of a basic block. */
enum class BB_end_kind {
BB_NONE = 0, /* no basic block end is reached */
BB_NONE = 0, /* no basic block end is reached */
BB_BRANCH = 1, /* a branch instruction is encountered */
BB_EXCEPTION, /* an exception is occured */
BB_RFI /* the rfi instruction is encountered */
@@ -200,40 +209,52 @@ enum class Except_Type {
EXC_NO_FPU,
EXC_DECR,
EXC_SYSCALL = 12,
EXC_TRACE = 13
EXC_TRACE = 13
};
//extern bool bb_end;
/** Programm Exception subclasses. */
enum Exc_Cause : uint32_t {
FPU_OFF = 1 << (31 - 11),
ILLEGAL_OP = 1 << (31 - 12),
NOT_ALLOWED = 1 << (31 - 13),
TRAP = 1 << (31 - 14),
};
// extern bool bb_end;
extern BB_end_kind bb_kind;
extern jmp_buf exc_env;
extern bool grab_branch;
extern bool grab_exception;
extern bool grab_return;
extern bool power_on;
extern bool is_601; //For PowerPC 601 Emulation
extern bool is_gekko; //For GameCube Emulation
extern bool is_altivec; //For Altivec Emulation
extern bool is_64bit; //For PowerPC G5 Emulation
extern bool is_601; // For PowerPC 601 Emulation
extern bool is_altivec; // For Altivec Emulation
extern bool is_64bit; // For PowerPC G5 Emulation
//Important Addressing Integers
extern bool rc_flag; // Record flag
extern bool oe_flag; // Overflow flag
// Important Addressing Integers
extern uint32_t ppc_cur_instruction;
extern uint32_t ppc_effective_address;
extern uint32_t ppc_next_instruction_address;
//Profiling Stats
// Profiling Stats
extern uint32_t mmu_translations_num;
extern uint32_t exceptions_performed;
extern uint32_t supervisor_inst_num;
//Function prototypes
extern void ppc_cpu_init(uint32_t proc_version);
// Function prototypes
extern void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t proc_version);
extern void ppc_mmu_init();
void ppc_illegalop();
void ppc_opcode4();
[[noreturn]] void ppc_illegalop();
[[noreturn]] void ppc_fpu_off();
//void ppc_opcode4();
void ppc_opcode16();
void ppc_opcode18();
void ppc_opcode19();
@@ -241,6 +262,8 @@ void ppc_opcode31();
void ppc_opcode59();
void ppc_opcode63();
void initialize_ppc_opcode_tables();
extern bool ppc_confirm_inf_nan(uint64_t input_a, uint64_t input_b, bool is_single, uint32_t op);
extern double fp_return_double(uint32_t reg);
extern uint64_t fp_return_uint64(uint32_t reg);
@@ -259,29 +282,21 @@ extern void ppc_grab_regsdauimm();
extern void ppc_grab_regsasimm();
extern void ppc_grab_regssauimm();
extern void ppc_grab_regsfpdb(bool int_rep);
extern void ppc_grab_regsfpdab(bool int_rep);
extern void ppc_grab_regsfpdia(bool int_rep);
extern void ppc_grab_regsfpdiab(bool int_rep);
extern void ppc_grab_regsfpsia(bool int_rep);
extern void ppc_grab_regsfpsiab(bool int_rep);
extern void ppc_store_result_regd();
extern void ppc_store_result_rega();
extern void ppc_store_sfpresult(bool int_rep);
extern void ppc_store_dfpresult(bool int_rep);
void ppc_changecrf0(uint32_t set_result);
void ppc_fp_changecrf1();
void ppc_tbr_update();
[[noreturn]] void ppc_exception_handler(Except_Type exception_type,
uint32_t srr1_bits);
/* Exception handlers. */
[[noreturn]] void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits);
[[noreturn]] void dbg_exception_handler(Except_Type exception_type, uint32_t srr1_bits);
//MEMORY DECLARATIONS
// MEMORY DECLARATIONS
extern MemCtrlBase* mem_ctrl_instance;
//The functions used by the PowerPC processor
// The functions used by the PowerPC processor
namespace dppc_interpreter {
extern void ppc_bcctr();
extern void ppc_bcctrl();
extern void ppc_bclr();
@@ -297,33 +312,15 @@ extern void ppc_crxor();
extern void ppc_isync();
extern void ppc_add();
extern void ppc_adddot();
extern void ppc_addo();
extern void ppc_addodot();
extern void ppc_addc();
extern void ppc_addcdot();
extern void ppc_addco();
extern void ppc_addcodot();
extern void ppc_adde();
extern void ppc_addedot();
extern void ppc_addeo();
extern void ppc_addeodot();
extern void ppc_addme();
extern void ppc_addmedot();
extern void ppc_addmeo();
extern void ppc_addmeodot();
extern void ppc_addze();
extern void ppc_addzedot();
extern void ppc_addzeo();
extern void ppc_addzeodot();
extern void ppc_and();
extern void ppc_anddot();
extern void ppc_andc();
extern void ppc_andcdot();
extern void ppc_cmp();
extern void ppc_cmpl();
extern void ppc_cntlzw();
extern void ppc_cntlzwdot();
extern void ppc_dcbf();
extern void ppc_dcbi();
extern void ppc_dcbst();
@@ -331,20 +328,11 @@ extern void ppc_dcbt();
extern void ppc_dcbtst();
extern void ppc_dcbz();
extern void ppc_divw();
extern void ppc_divwdot();
extern void ppc_divwo();
extern void ppc_divwodot();
extern void ppc_divwu();
extern void ppc_divwudot();
extern void ppc_divwuo();
extern void ppc_divwuodot();
extern void ppc_eieio();
extern void ppc_eqv();
extern void ppc_eqvdot();
extern void ppc_extsb();
extern void ppc_extsbdot();
extern void ppc_extsh();
extern void ppc_extshdot();
extern void ppc_icbi();
extern void ppc_mftb();
extern void ppc_lhzux();
@@ -361,33 +349,17 @@ extern void ppc_lwzx();
extern void ppc_mcrxr();
extern void ppc_mfcr();
extern void ppc_mulhwu();
extern void ppc_mulhwudot();
extern void ppc_mulhw();
extern void ppc_mulhwdot();
extern void ppc_mullw();
extern void ppc_mullwdot();
extern void ppc_mullwo();
extern void ppc_mullwodot();
extern void ppc_nand();
extern void ppc_nanddot();
extern void ppc_neg();
extern void ppc_negdot();
extern void ppc_nego();
extern void ppc_negodot();
extern void ppc_nor();
extern void ppc_nordot();
extern void ppc_or();
extern void ppc_ordot();
extern void ppc_orc();
extern void ppc_orcdot();
extern void ppc_slw();
extern void ppc_slwdot();
extern void ppc_srw();
extern void ppc_srwdot();
extern void ppc_sraw();
extern void ppc_srawdot();
extern void ppc_srawi();
extern void ppc_srawidot();
extern void ppc_stbx();
extern void ppc_stbux();
extern void ppc_stfiwx();
@@ -399,25 +371,10 @@ extern void ppc_stwcx();
extern void ppc_stwux();
extern void ppc_stwbrx();
extern void ppc_subf();
extern void ppc_subfdot();
extern void ppc_subfo();
extern void ppc_subfodot();
extern void ppc_subfc();
extern void ppc_subfcdot();
extern void ppc_subfco();
extern void ppc_subfcodot();
extern void ppc_subfe();
extern void ppc_subfedot();
extern void ppc_subfeo();
extern void ppc_subfeodot();
extern void ppc_subfme();
extern void ppc_subfmedot();
extern void ppc_subfmeo();
extern void ppc_subfmeodot();
extern void ppc_subfze();
extern void ppc_subfzedot();
extern void ppc_subfzeo();
extern void ppc_subfzeodot();
extern void ppc_sync();
extern void ppc_tlbia();
extern void ppc_tlbie();
@@ -426,7 +383,6 @@ extern void ppc_tlbld();
extern void ppc_tlbsync();
extern void ppc_tw();
extern void ppc_xor();
extern void ppc_xordot();
extern void ppc_lswi();
extern void ppc_lswx();
@@ -438,6 +394,7 @@ extern void ppc_mfsrin();
extern void ppc_mtsr();
extern void ppc_mtsrin();
extern void ppc_mcrf();
extern void ppc_mtcrf();
extern void ppc_mfmsr();
extern void ppc_mfspr();
@@ -521,11 +478,11 @@ extern void ppc_stfdux();
extern void ppc_fadd();
extern void ppc_fsub();
extern void ppc_fmult();
extern void ppc_fmul();
extern void ppc_fdiv();
extern void ppc_fadds();
extern void ppc_fsubs();
extern void ppc_fmults();
extern void ppc_fmuls();
extern void ppc_fdivs();
extern void ppc_fmadd();
extern void ppc_fmsub();
@@ -547,121 +504,55 @@ extern void ppc_frsp();
extern void ppc_fctiw();
extern void ppc_fctiwz();
extern void ppc_fadddot();
extern void ppc_fsubdot();
extern void ppc_fmultdot();
extern void ppc_fdivdot();
extern void ppc_fmadddot();
extern void ppc_fmsubdot();
extern void ppc_fnmadddot();
extern void ppc_fnmsubdot();
extern void ppc_fabsdot();
extern void ppc_fnabsdot();
extern void ppc_fnegdot();
extern void ppc_fseldot();
extern void ppc_fsqrtdot();
extern void ppc_frsqrtedot();
extern void ppc_frspdot();
extern void ppc_fctiwdot();
extern void ppc_fctiwzdot();
extern void ppc_fresdot();
extern void ppc_faddsdot();
extern void ppc_fsubsdot();
extern void ppc_fmultsdot();
extern void ppc_fdivsdot();
extern void ppc_fmaddsdot();
extern void ppc_fmsubsdot();
extern void ppc_fnmaddsdot();
extern void ppc_fnmsubsdot();
extern void ppc_fsqrtsdot();
extern void ppc_fcmpo();
extern void ppc_fcmpu();
//Power-specific instructions
// Power-specific instructions
extern void power_abs();
extern void power_absdot();
extern void power_abso();
extern void power_absodot();
extern void power_clcs();
extern void power_clcsdot();
extern void power_div();
extern void power_divdot();
extern void power_divo();
extern void power_divodot();
extern void power_divs();
extern void power_divsdot();
extern void power_divso();
extern void power_divsodot();
extern void power_doz();
extern void power_dozdot();
extern void power_dozo();
extern void power_dozodot();
extern void power_dozi();
extern void power_lscbx();
extern void power_lscbxdot();
extern void power_maskg();
extern void power_maskgdot();
extern void power_maskir();
extern void power_maskirdot();
extern void power_mul();
extern void power_muldot();
extern void power_mulo();
extern void power_mulodot();
extern void power_nabs();
extern void power_nabsdot();
extern void power_nabso();
extern void power_nabsodot();
extern void power_rlmi();
extern void power_rrib();
extern void power_rribdot();
extern void power_sle();
extern void power_sledot();
extern void power_sleq();
extern void power_sleqdot();
extern void power_sliq();
extern void power_sliqdot();
extern void power_slliq();
extern void power_slliqdot();
extern void power_sllq();
extern void power_sllqdot();
extern void power_slq();
extern void power_slqdot();
extern void power_sraiq();
extern void power_sraiqdot();
extern void power_sraq();
extern void power_sraqdot();
extern void power_sre();
extern void power_sredot();
extern void power_srea();
extern void power_sreadot();
extern void power_sreq();
extern void power_sreqdot();
extern void power_sriq();
extern void power_sriqdot();
extern void power_srliq();
extern void power_srliqdot();
extern void power_srlq();
extern void power_srlqdot();
extern void power_srq();
extern void power_srqdot();
} // namespace dppc_interpreter
//Gekko instructions
extern void ppc_psq_l();
extern void ppc_psq_lu();
extern void ppc_psq_st();
extern void ppc_psq_stu();
// AltiVec instructions
//AltiVec instructions
// 64-bit instructions
//64-bit instructions
//G5+ instructions
// G5+ instructions
extern void ppc_main_opcode(void);
extern void ppc_exec(void);
extern void ppc_exec_single(void);
extern void ppc_exec_until(uint32_t goal_addr);
extern void ppc_exec_dbg(uint32_t start_addr, uint32_t size);
/* debugging support API */
void print_fprs(void); /* print content of the floating-point registers */
uint64_t get_reg(std::string& reg_name); /* get content of the register reg_name */
void set_reg(std::string& reg_name, uint64_t val); /* set reg_name to val */
#endif /* PPCEMU_H */
+142 -63
View File
@@ -1,93 +1,172 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Handling of low-level PPC exceptions. */
#include <setjmp.h>
#include "ppcemu.h"
#include <setjmp.h>
#include <stdexcept>
#include <string>
jmp_buf exc_env; /* Global exception environment. */
[[noreturn]] void ppc_exception_handler(Except_Type exception_type,
uint32_t srr1_bits)
{
[[noreturn]] void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
grab_exception = true;
#ifdef PROFILER
#ifdef PROFILER
exceptions_performed++;
#endif
#endif
bb_kind = BB_end_kind::BB_EXCEPTION;
switch(exception_type) {
case Except_Type::EXC_SYSTEM_RESET:
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0100;
break;
switch (exception_type) {
case Except_Type::EXC_SYSTEM_RESET:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0100;
break;
case Except_Type::EXC_MACHINE_CHECK:
if (!(ppc_state.ppc_msr & 0x1000)) {
/* TODO: handle internal checkstop */
}
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0200;
break;
case Except_Type::EXC_MACHINE_CHECK:
if (!(ppc_state.msr & 0x1000)) {
/* TODO: handle internal checkstop */
}
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0200;
break;
case Except_Type::EXC_DSI:
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0300;
break;
case Except_Type::EXC_DSI:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0300;
break;
case Except_Type::EXC_ISI:
ppc_state.ppc_spr[SPR::SRR0] = ppc_next_instruction_address;
ppc_next_instruction_address = 0x0400;
break;
case Except_Type::EXC_ISI:
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
ppc_next_instruction_address = 0x0400;
break;
case Except_Type::EXC_EXT_INT:
ppc_state.ppc_spr[SPR::SRR0] = ppc_next_instruction_address;
ppc_next_instruction_address = 0x0500;
break;
case Except_Type::EXC_EXT_INT:
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
ppc_next_instruction_address = 0x0500;
break;
case Except_Type::EXC_ALIGNMENT:
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0600;
break;
case Except_Type::EXC_ALIGNMENT:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0600;
break;
case Except_Type::EXC_PROGRAM:
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0700;
break;
case Except_Type::EXC_PROGRAM:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0700;
break;
case Except_Type::EXC_NO_FPU:
ppc_state.ppc_spr[SPR::SRR0] = ppc_cur_instruction & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0800;
break;
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0800;
break;
case Except_Type::EXC_DECR:
ppc_state.ppc_spr[SPR::SRR0] = (ppc_cur_instruction & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0900;
break;
case Except_Type::EXC_DECR:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0900;
break;
case Except_Type::EXC_SYSCALL:
ppc_state.ppc_spr[SPR::SRR0] = (ppc_cur_instruction & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0C00;
break;
case Except_Type::EXC_SYSCALL:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0C00;
break;
case Except_Type::EXC_TRACE:
ppc_state.ppc_spr[SPR::SRR0] = (ppc_cur_instruction & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0D00;
break;
case Except_Type::EXC_TRACE:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0D00;
break;
default:
//printf("Unknown exception occured: %X\n", exception_type);
//exit(-1);
break;
default:
// printf("Unknown exception occured: %X\n", exception_type);
// exit(-1);
break;
}
ppc_state.ppc_spr[SPR::SRR1] = (ppc_state.ppc_msr & 0x0000FF73) | srr1_bits;
ppc_state.ppc_msr &= 0xFFFB1041;
ppc_state.spr[SPR::SRR1] = (ppc_state.msr & 0x0000FF73) | srr1_bits;
ppc_state.msr &= 0xFFFB1041;
/* copy MSR[ILE] to MSR[LE] */
ppc_state.ppc_msr = (ppc_state.ppc_msr & 0xFFFFFFFE) |
((ppc_state.ppc_msr >> 16) & 1);
ppc_state.msr = (ppc_state.msr & 0xFFFFFFFE) | ((ppc_state.msr >> 16) & 1);
if (ppc_state.ppc_msr & 0x40) {
if (ppc_state.msr & 0x40) {
ppc_next_instruction_address |= 0xFFF00000;
}
longjmp(exc_env, 2); /* return to the main execution loop. */
}
[[noreturn]] void dbg_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
std::string exc_descriptor;
switch (exception_type) {
case Except_Type::EXC_SYSTEM_RESET:
exc_descriptor = "System reset exception occured";
break;
case Except_Type::EXC_MACHINE_CHECK:
exc_descriptor = "Machine check exception occured";
break;
case Except_Type::EXC_DSI:
case Except_Type::EXC_ISI:
if (ppc_state.spr[SPR::DSISR] & 0x40000000)
exc_descriptor = "DSI/ISI exception: unmapped memory access";
else if (ppc_state.spr[SPR::DSISR] & 0x08000000)
exc_descriptor = "DSI/ISI exception: access protection violation";
else {
if (exception_type == Except_Type::EXC_DSI)
exc_descriptor = "DSI exception";
else
exc_descriptor = "ISI exception";
}
break;
case Except_Type::EXC_EXT_INT:
exc_descriptor = "External interrupt exception occured";
break;
case Except_Type::EXC_ALIGNMENT:
exc_descriptor = "Alignment exception occured";
break;
case Except_Type::EXC_PROGRAM:
exc_descriptor = "Program exception occured";
break;
case Except_Type::EXC_NO_FPU:
exc_descriptor = "Floating-Point unavailable exception occured";
break;
case Except_Type::EXC_DECR:
exc_descriptor = "Decrementer exception occured";
break;
case Except_Type::EXC_SYSCALL:
exc_descriptor = "Syscall exception occured";
break;
case Except_Type::EXC_TRACE:
exc_descriptor = "Trace exception occured";
break;
}
throw std::invalid_argument(exc_descriptor);
}
+652 -594
View File
File diff suppressed because it is too large. Load diff
+861 -1072
View File
File diff suppressed because it is too large. Load diff
-32
View File
@@ -1,32 +0,0 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
// The uniquely Gekko opcodes for the processor - ppcgekkoopcodes.cpp
#include <iostream>
#include <stdio.h>
#include "ppcemu.h"
void ppc_psq_l(){
printf("Hello. There's no GameCube emulation...yet. Goodbye.");
exit(0);
}
void ppc_psq_lu(){
printf("Hello. There's no GameCube emulation...yet. Goodbye.");
exit(0);
}
void ppc_psq_st(){
printf("Hello. There's no GameCube emulation...yet. Goodbye.");
exit(0);
}
void ppc_psq_stu(){
printf("Hello. There's no GameCube emulation...yet. Goodbye.");
exit(0);
}
+288 -200
View File
@@ -1,9 +1,23 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file PowerPC Memory management unit emulation. */
@@ -14,165 +28,175 @@
- clarify what to do in the case of unaligned memory accesses
*/
#include <iostream>
#include <cstdint>
#include <cinttypes>
#include <string>
#include <array>
#include "memreadwrite.h"
#include "ppcemu.h"
#include "ppcmmu.h"
#include "devices/memctrlbase.h"
#include "memaccess.h"
#include "ppcemu.h"
#include <array>
#include <cinttypes>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <thirdparty/loguru/loguru.hpp>
/* pointer to exception handler to be called when a MMU exception is occured. */
void (*mmu_exception_handler)(Except_Type exception_type, uint32_t srr1_bits);
/** PowerPC-style MMU BAT arrays (NULL initialization isn't prescribed). */
PPC_BAT_entry ibat_array[4] = { {0} };
PPC_BAT_entry dbat_array[4] = { {0} };
PPC_BAT_entry ibat_array[4] = {{0}};
PPC_BAT_entry dbat_array[4] = {{0}};
/** remember recently used physical memory regions for quicker translation. */
AddressMapEntry last_read_area = { 0 };
AddressMapEntry last_write_area = { 0 };
AddressMapEntry last_exec_area = { 0 };
AddressMapEntry last_ptab_area = { 0 };
AddressMapEntry last_read_area = {0xFFFFFFFF, 0xFFFFFFFF};
AddressMapEntry last_write_area = {0xFFFFFFFF, 0xFFFFFFFF};
AddressMapEntry last_exec_area = {0xFFFFFFFF, 0xFFFFFFFF};
AddressMapEntry last_ptab_area = {0xFFFFFFFF, 0xFFFFFFFF};
AddressMapEntry last_dma_area = {0xFFFFFFFF, 0xFFFFFFFF};
#define WRITE_BYTE(addr, val) (*(addr) = val)
/* macro for generating code reading from physical memory */
#define READ_PHYS_MEM(ENTRY, ADDR, OP, SIZE, UNVAL) \
{ \
if ((ADDR) >= (ENTRY).start && (ADDR) <= (ENTRY).end) { \
ret = OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start)); \
} else { \
AddressMapEntry* entry = mem_ctrl_instance->find_range((ADDR)); \
if (entry) { \
if (entry->type & (RT_ROM | RT_RAM)) { \
(ENTRY).start = entry->start; \
(ENTRY).end = entry->end; \
(ENTRY).mem_ptr = entry->mem_ptr; \
ret = OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start)); \
} \
else if (entry->type & RT_MMIO) { \
ret = entry->devobj->read((ADDR) - entry->start, (SIZE)); \
} \
else { \
printf("Please check your address map!\n"); \
ret = (UNVAL); \
} \
} \
else { \
printf("WARNING: read from unmapped memory at 0x%08X!\n", (ADDR)); \
ret = (UNVAL); \
} \
} \
}
#define READ_PHYS_MEM(ENTRY, ADDR, OP, SIZE, UNVAL) \
{ \
if ((ADDR) >= (ENTRY).start && ((ADDR) + (SIZE)) <= (ENTRY).end) { \
ret = OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start)); \
} else { \
AddressMapEntry* entry = mem_ctrl_instance->find_range((ADDR)); \
if (entry) { \
if (entry->type & (RT_ROM | RT_RAM)) { \
(ENTRY).start = entry->start; \
(ENTRY).end = entry->end; \
(ENTRY).mem_ptr = entry->mem_ptr; \
ret = OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start)); \
} else if (entry->type & RT_MMIO) { \
ret = entry->devobj->read(entry->start, (ADDR)-entry->start, (SIZE)); \
} else { \
LOG_F(ERROR, "Please check your address map! \n"); \
ret = (UNVAL); \
} \
} else { \
LOG_F(WARNING, "Read from unmapped memory at 0x%08X!\n", (ADDR)); \
ret = (UNVAL); \
} \
} \
}
/* macro for generating code writing to physical memory */
#define WRITE_PHYS_MEM(ENTRY, ADDR, OP, VAL, SIZE) \
{ \
if ((ADDR) >= (ENTRY).start && (ADDR) <= (ENTRY).end) { \
OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start), (VAL)); \
} else { \
AddressMapEntry* entry = mem_ctrl_instance->find_range((ADDR)); \
if (entry) { \
if (entry->type & RT_RAM) { \
(ENTRY).start = entry->start; \
(ENTRY).end = entry->end; \
(ENTRY).mem_ptr = entry->mem_ptr; \
OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start), (VAL)); \
} \
else if (entry->type & RT_MMIO) { \
entry->devobj->write((ADDR) - entry->start, (VAL), (SIZE)); \
} \
else { \
printf("Please check your address map!\n"); \
} \
} \
else { \
printf("WARNING: write to unmapped memory at 0x%08X!\n", (ADDR)); \
} \
} \
#define WRITE_PHYS_MEM(ENTRY, ADDR, OP, VAL, SIZE) \
{ \
if ((ADDR) >= (ENTRY).start && ((ADDR) + (SIZE)) <= (ENTRY).end) { \
OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start), (VAL)); \
} else { \
AddressMapEntry* entry = mem_ctrl_instance->find_range((ADDR)); \
if (entry) { \
if (entry->type & RT_RAM) { \
(ENTRY).start = entry->start; \
(ENTRY).end = entry->end; \
(ENTRY).mem_ptr = entry->mem_ptr; \
OP((ENTRY).mem_ptr + ((ADDR) - (ENTRY).start), (VAL)); \
} else if (entry->type & RT_MMIO) { \
entry->devobj->write(entry->start, (ADDR)-entry->start, (VAL), (SIZE)); \
} else { \
LOG_F(ERROR, "Please check your address map!\n"); \
} \
} else { \
LOG_F(WARNING, "Write to unmapped memory at 0x%08X!\n", (ADDR)); \
} \
} \
}
uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size) {
if (addr >= last_dma_area.start && (addr + size) <= last_dma_area.end) {
return last_dma_area.mem_ptr + (addr - last_dma_area.start);
} else {
AddressMapEntry* entry = mem_ctrl_instance->find_range(addr);
if (entry && entry->type & (RT_ROM | RT_RAM)) {
last_dma_area.start = entry->start;
last_dma_area.end = entry->end;
last_dma_area.mem_ptr = entry->mem_ptr;
return last_dma_area.mem_ptr + (addr - last_dma_area.start);
} else {
LOG_F(ERROR, "SOS: DMA access to unmapped memory %08X!\n", addr);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
}
}
}
void ppc_set_cur_instruction(const uint8_t* ptr)
{
void ppc_set_cur_instruction(const uint8_t* ptr) {
ppc_cur_instruction = READ_DWORD_BE_A(ptr);
}
void ibat_update(uint32_t bat_reg)
{
void ibat_update(uint32_t bat_reg) {
int upper_reg_num;
uint32_t bl, lo_mask;
PPC_BAT_entry* bat_entry;
upper_reg_num = bat_reg & 0xFFFFFFFE;
if (ppc_state.ppc_spr[upper_reg_num] & 3) { // is that BAT pair valid?
if (ppc_state.spr[upper_reg_num] & 3) { // is that BAT pair valid?
bat_entry = &ibat_array[(bat_reg - 528) >> 1];
bl = (ppc_state.ppc_spr[upper_reg_num] >> 2) & 0x7FF;
lo_mask = (bl << 17) | 0x1FFFF;
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
lo_mask = (bl << 17) | 0x1FFFF;
bat_entry->access = ppc_state.ppc_spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.ppc_spr[upper_reg_num + 1] & 3;
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->lo_mask = lo_mask;
bat_entry->phys_hi = ppc_state.ppc_spr[upper_reg_num + 1] & ~lo_mask;
bat_entry->bepi = ppc_state.ppc_spr[upper_reg_num] & ~lo_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & ~lo_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & ~lo_mask;
}
}
void dbat_update(uint32_t bat_reg)
{
void dbat_update(uint32_t bat_reg) {
int upper_reg_num;
uint32_t bl, lo_mask;
PPC_BAT_entry* bat_entry;
upper_reg_num = bat_reg & 0xFFFFFFFE;
if (ppc_state.ppc_spr[upper_reg_num] & 3) { // is that BAT pair valid?
if (ppc_state.spr[upper_reg_num] & 3) { // is that BAT pair valid?
bat_entry = &dbat_array[(bat_reg - 536) >> 1];
bl = (ppc_state.ppc_spr[upper_reg_num] >> 2) & 0x7FF;
lo_mask = (bl << 17) | 0x1FFFF;
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
lo_mask = (bl << 17) | 0x1FFFF;
bat_entry->access = ppc_state.ppc_spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.ppc_spr[upper_reg_num + 1] & 3;
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->lo_mask = lo_mask;
bat_entry->phys_hi = ppc_state.ppc_spr[upper_reg_num + 1] & ~lo_mask;
bat_entry->bepi = ppc_state.ppc_spr[upper_reg_num] & ~lo_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & ~lo_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & ~lo_mask;
}
}
static inline uint8_t* calc_pteg_addr(uint32_t hash)
{
static inline uint8_t* calc_pteg_addr(uint32_t hash) {
uint32_t sdr1_val, pteg_addr;
sdr1_val = ppc_state.ppc_spr[SPR::SDR1];
sdr1_val = ppc_state.spr[SPR::SDR1];
pteg_addr = sdr1_val & 0xFE000000;
pteg_addr |= (sdr1_val & 0x01FF0000) |
(((sdr1_val & 0x1FF) << 16) & ((hash & 0x7FC00) << 6));
pteg_addr |= (sdr1_val & 0x01FF0000) | (((sdr1_val & 0x1FF) << 16) & ((hash & 0x7FC00) << 6));
pteg_addr |= (hash & 0x3FF) << 6;
if (pteg_addr >= last_ptab_area.start && pteg_addr <= last_ptab_area.end) {
return last_ptab_area.mem_ptr + (pteg_addr - last_ptab_area.start);
}
else {
} else {
AddressMapEntry* entry = mem_ctrl_instance->find_range(pteg_addr);
if (entry && entry->type & (RT_ROM | RT_RAM)) {
last_ptab_area.start = entry->start;
last_ptab_area.end = entry->end;
last_ptab_area.mem_ptr = entry->mem_ptr;
return last_ptab_area.mem_ptr + (pteg_addr - last_ptab_area.start);
}
else {
printf("SOS: no page table region was found at %08X!\n", pteg_addr);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
} else {
LOG_F(ERROR, "SOS: no page table region was found at %08X!\n", pteg_addr);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
}
}
}
static bool search_pteg(uint8_t* pteg_addr, uint8_t** ret_pte_addr,
uint32_t vsid, uint16_t page_index, uint8_t pteg_num)
{
static bool search_pteg(
uint8_t* pteg_addr, uint8_t** ret_pte_addr, uint32_t vsid, uint16_t page_index, uint8_t pteg_num) {
/* construct PTE matching word */
uint32_t pte_check = 0x80000000 | (vsid << 7) | (pteg_num << 6) |
(page_index >> 10);
uint32_t pte_check = 0x80000000 | (vsid << 7) | (pteg_num << 6) | (page_index >> 10);
#ifdef MMU_INTEGRITY_CHECKS
/* PTEG integrity check that ensures that all matching PTEs have
@@ -184,14 +208,13 @@ static bool search_pteg(uint8_t* pteg_addr, uint8_t** ret_pte_addr,
if (pte_check == READ_DWORD_BE_A(pteg_addr)) {
if (match_found) {
if ((READ_DWORD_BE_A(pteg_addr) & 0xFFFFF07B) != pte_word2_check) {
printf("Multiple PTEs with different RPN/WIMG/PP found!\n");
LOG_F(ERROR, "Multiple PTEs with different RPN/WIMG/PP found!\n");
exit(-1);
}
}
else {
} else {
/* isolate RPN, WIMG and PP fields */
pte_word2_check = READ_DWORD_BE_A(pteg_addr) & 0xFFFFF07B;
*ret_pte_addr = pteg_addr;
*ret_pte_addr = pteg_addr;
}
}
}
@@ -207,44 +230,41 @@ static bool search_pteg(uint8_t* pteg_addr, uint8_t** ret_pte_addr,
return false;
}
static uint32_t page_address_translate(uint32_t la, bool is_instr_fetch,
unsigned msr_pr, int is_write)
{
static uint32_t page_address_translate(uint32_t la, bool is_instr_fetch, unsigned msr_pr, int is_write) {
uint32_t sr_val, page_index, pteg_hash1, vsid, pte_word2;
unsigned key, pp;
uint8_t* pte_addr;
sr_val = ppc_state.ppc_sr[(la >> 28) & 0x0F];
sr_val = ppc_state.sr[(la >> 28) & 0x0F];
if (sr_val & 0x80000000) {
printf("Direct-store segments not supported, LA=%0xX\n", la);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
LOG_F(ERROR, "Direct-store segments not supported, LA=%0xX\n", la);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
}
/* instruction fetch from a no-execute segment will cause ISI exception */
if ((sr_val & 0x10000000) && is_instr_fetch) {
ppc_exception_handler(Except_Type::EXC_ISI, 0x10000000);
mmu_exception_handler(Except_Type::EXC_ISI, 0x10000000);
}
page_index = (la >> 12) & 0xFFFF;
pteg_hash1 = (sr_val & 0x7FFFF) ^ page_index;
vsid = sr_val & 0x0FFFFFF;
vsid = sr_val & 0x0FFFFFF;
if (!search_pteg(calc_pteg_addr(pteg_hash1), &pte_addr, vsid, page_index, 0)) {
if (!search_pteg(calc_pteg_addr(~pteg_hash1), &pte_addr, vsid, page_index, 1)) {
if (is_instr_fetch) {
ppc_exception_handler(Except_Type::EXC_ISI, 0x40000000);
}
else {
ppc_state.ppc_spr[SPR::DSISR] = 0x40000000 | (is_write << 25);
ppc_state.ppc_spr[SPR::DAR] = la;
ppc_exception_handler(Except_Type::EXC_DSI, 0);
mmu_exception_handler(Except_Type::EXC_ISI, 0x40000000);
} else {
ppc_state.spr[SPR::DSISR] = 0x40000000 | (is_write << 25);
ppc_state.spr[SPR::DAR] = la;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
}
}
pte_word2 = READ_DWORD_BE_A(pte_addr + 4);
key = (((sr_val >> 29) & 1)& msr_pr) | (((sr_val >> 30) & 1)& (msr_pr ^ 1));
key = (((sr_val >> 29) & 1) & msr_pr) | (((sr_val >> 30) & 1) & (msr_pr ^ 1));
/* check page access */
pp = pte_word2 & 3;
@@ -255,12 +275,11 @@ static uint32_t page_address_translate(uint32_t la, bool is_instr_fetch,
// write access with PP = %11
if ((key && (!pp || (pp == 1 && is_write))) || (pp == 3 && is_write)) {
if (is_instr_fetch) {
ppc_exception_handler(Except_Type::EXC_ISI, 0x08000000);
}
else {
ppc_state.ppc_spr[SPR::DSISR] = 0x08000000 | (is_write << 25);
ppc_state.ppc_spr[SPR::DAR] = la;
ppc_exception_handler(Except_Type::EXC_DSI, 0);
mmu_exception_handler(Except_Type::EXC_ISI, 0x08000000);
} else {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (is_write << 25);
ppc_state.spr[SPR::DAR] = la;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
}
@@ -276,12 +295,11 @@ static uint32_t page_address_translate(uint32_t la, bool is_instr_fetch,
}
/** PowerPC-style MMU instruction address translation. */
static uint32_t ppc_mmu_instr_translate(uint32_t la)
{
static uint32_t ppc_mmu_instr_translate(uint32_t la) {
uint32_t pa; /* translated physical address */
bool bat_hit = false;
unsigned msr_pr = !!(ppc_state.ppc_msr & 0x4000);
bool bat_hit = false;
unsigned msr_pr = !!(ppc_state.msr & 0x4000);
// Format: %XY
// X - supervisor access bit, Y - problem/user access bit
@@ -291,12 +309,11 @@ static uint32_t ppc_mmu_instr_translate(uint32_t la)
for (int bat_index = 0; bat_index < 4; bat_index++) {
PPC_BAT_entry* bat_entry = &ibat_array[bat_index];
if ((bat_entry->access & access_bits) &&
((la & ~bat_entry->lo_mask) == bat_entry->bepi)) {
if ((bat_entry->access & access_bits) && ((la & ~bat_entry->lo_mask) == bat_entry->bepi)) {
bat_hit = true;
if (!bat_entry->prot) {
ppc_exception_handler(Except_Type::EXC_ISI, 0x08000000);
mmu_exception_handler(Except_Type::EXC_ISI, 0x08000000);
}
// logical to physical translation
@@ -314,16 +331,15 @@ static uint32_t ppc_mmu_instr_translate(uint32_t la)
}
/** PowerPC-style MMU data address translation. */
static uint32_t ppc_mmu_addr_translate(uint32_t la, int is_write)
{
static uint32_t ppc_mmu_addr_translate(uint32_t la, int is_write) {
#ifdef PROFILER
mmu_translations_num++;
#endif
uint32_t pa; /* translated physical address */
bool bat_hit = false;
unsigned msr_pr = !!(ppc_state.ppc_msr & 0x4000);
bool bat_hit = false;
unsigned msr_pr = !!(ppc_state.msr & 0x4000);
// Format: %XY
// X - supervisor access bit, Y - problem/user access bit
@@ -333,14 +349,13 @@ static uint32_t ppc_mmu_addr_translate(uint32_t la, int is_write)
for (int bat_index = 0; bat_index < 4; bat_index++) {
PPC_BAT_entry* bat_entry = &dbat_array[bat_index];
if ((bat_entry->access & access_bits) &&
((la & ~bat_entry->lo_mask) == bat_entry->bepi)) {
if ((bat_entry->access & access_bits) && ((la & ~bat_entry->lo_mask) == bat_entry->bepi)) {
bat_hit = true;
if (!bat_entry->prot || ((bat_entry->prot & 1) && is_write)) {
ppc_state.ppc_spr[SPR::DSISR] = 0x08000000 | (is_write << 25);
ppc_state.ppc_spr[SPR::DAR] = la;
ppc_exception_handler(Except_Type::EXC_DSI, 0);
ppc_state.spr[SPR::DSISR] = 0x08000000 | (is_write << 25);
ppc_state.spr[SPR::DAR] = la;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
// logical to physical translation
@@ -357,16 +372,34 @@ static uint32_t ppc_mmu_addr_translate(uint32_t la, int is_write)
return pa;
}
static void mem_write_unaligned(uint32_t addr, uint32_t value, uint32_t size)
{
printf("WARNING! Attempt to write unaligned %d bytes to 0x%08X\n", size, addr);
static void mem_write_unaligned(uint32_t addr, uint32_t value, uint32_t size) {
#ifdef MMU_DEBUG
LOG_F(WARNING, "Attempt to write unaligned %d bytes to 0x%08X\n", size, addr);
#endif
if (((addr & 0xFFF) + size) > 0x1000) {
printf("SOS! Cross-page unaligned write, addr=%08X, size=%d\n", addr, size);
exit(-1); //FIXME!
// Special case: unaligned cross-page writes
LOG_F(WARNING, "Cross-page unaligned write, addr=%08X, size=%d\n",
addr, size);
uint32_t phys_addr;
uint32_t shift = (size - 1) * 8;
// Break misaligned memory accesses into multiple, smaller accesses
// and retranslate on page boundary.
// Because such accesses suffer a performance penalty, they will be
// presumably very rare so don't care much about performance.
for (int i = 0; i < size; shift -= 8, addr++, phys_addr++, i++) {
if ((ppc_state.msr & 0x10) && (!i || !(addr & 0xFFF))) {
phys_addr = ppc_mmu_addr_translate(addr, 0);
}
WRITE_PHYS_MEM(last_write_area, phys_addr, WRITE_BYTE,
(value >> shift) & 0xFF, 1);
}
} else {
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
// data address translation if enabled
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -378,73 +411,87 @@ static void mem_write_unaligned(uint32_t addr, uint32_t value, uint32_t size)
}
}
void mem_write_byte(uint32_t addr, uint8_t value)
{
void mem_write_byte(uint32_t addr, uint8_t value) {
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 1);
}
#define WRITE_BYTE(addr, val) (*(addr) = val)
WRITE_PHYS_MEM(last_write_area, addr, WRITE_BYTE, value, 1);
}
void mem_write_word(uint32_t addr, uint16_t value)
{
void mem_write_word(uint32_t addr, uint16_t value) {
if (addr & 1) {
mem_write_unaligned(addr, value, 2);
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 1);
}
WRITE_PHYS_MEM(last_write_area, addr, WRITE_WORD_BE_A, value, 2);
}
void mem_write_dword(uint32_t addr, uint32_t value)
{
void mem_write_dword(uint32_t addr, uint32_t value) {
if (addr & 3) {
mem_write_unaligned(addr, value, 4);
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 1);
}
WRITE_PHYS_MEM(last_write_area, addr, WRITE_DWORD_BE_A, value, 4);
}
void mem_write_qword(uint32_t addr, uint64_t value)
{
void mem_write_qword(uint32_t addr, uint64_t value) {
if (addr & 7) {
printf("SOS! Attempt to write unaligned QWORD to 0x%08X\n", addr);
exit(-1); //FIXME!
LOG_F(ERROR, "SOS! Attempt to write unaligned QWORD to 0x%08X\n", addr);
exit(-1); // FIXME!
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 1);
}
WRITE_PHYS_MEM(last_write_area, addr, WRITE_QWORD_BE_A, value, 8);
}
static uint32_t mem_grab_unaligned(uint32_t addr, uint32_t size)
{
static uint32_t mem_grab_unaligned(uint32_t addr, uint32_t size) {
uint32_t ret = 0;
printf("WARNING! Attempt to read unaligned %d bytes from 0x%08X\n", size, addr);
#ifdef MMU_DEBUG
LOG_F(WARNING, "Attempt to read unaligned %d bytes from 0x%08X\n", size, addr);
#endif
if (((addr & 0xFFF) + size) > 0x1000) {
printf("SOS! Cross-page unaligned read, addr=%08X, size=%d\n", addr, size);
exit(-1); //FIXME!
// Special case: misaligned cross-page reads
LOG_F(WARNING, "Cross-page unaligned read, addr=%08X, size=%d\n",
addr, size);
uint32_t phys_addr;
uint32_t res = 0;
// Break misaligned memory accesses into multiple, smaller accesses
// and retranslate on page boundary.
// Because such accesses suffer a performance penalty, they will be
// presumably very rare so don't care much about performance.
for (int i = 0; i < size; addr++, phys_addr++, i++) {
if ((ppc_state.msr & 0x10) && (!i || !(addr & 0xFFF))) {
phys_addr = ppc_mmu_addr_translate(addr, 0);
}
READ_PHYS_MEM(last_read_area, phys_addr, *, 1, 0xFFU);
res = (res << 8) | ret;
}
return res;
} else {
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -459,12 +506,11 @@ static uint32_t mem_grab_unaligned(uint32_t addr, uint32_t size)
}
/** Grab a value from memory into a register */
uint8_t mem_grab_byte(uint32_t addr)
{
uint8_t mem_grab_byte(uint32_t addr) {
uint8_t ret;
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -472,8 +518,7 @@ uint8_t mem_grab_byte(uint32_t addr)
return ret;
}
uint16_t mem_grab_word(uint32_t addr)
{
uint16_t mem_grab_word(uint32_t addr) {
uint16_t ret;
if (addr & 1) {
@@ -481,7 +526,7 @@ uint16_t mem_grab_word(uint32_t addr)
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -489,8 +534,7 @@ uint16_t mem_grab_word(uint32_t addr)
return ret;
}
uint32_t mem_grab_dword(uint32_t addr)
{
uint32_t mem_grab_dword(uint32_t addr) {
uint32_t ret;
if (addr & 3) {
@@ -498,7 +542,7 @@ uint32_t mem_grab_dword(uint32_t addr)
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -506,17 +550,16 @@ uint32_t mem_grab_dword(uint32_t addr)
return ret;
}
uint64_t mem_grab_qword(uint32_t addr)
{
uint64_t mem_grab_qword(uint32_t addr) {
uint64_t ret;
if (addr & 7) {
printf("SOS! Attempt to read unaligned QWORD at 0x%08X\n", addr);
exit(-1); //FIXME!
LOG_F(ERROR, "SOS! Attempt to read unaligned QWORD at 0x%08X\n", addr);
exit(-1); // FIXME!
}
/* data address translation if enabled */
if (ppc_state.ppc_msr & 0x10) {
if (ppc_state.msr & 0x10) {
addr = ppc_mmu_addr_translate(addr, 0);
}
@@ -524,33 +567,78 @@ uint64_t mem_grab_qword(uint32_t addr)
return ret;
}
uint8_t* quickinstruction_translate(uint32_t addr)
{
uint8_t* quickinstruction_translate(uint32_t addr) {
uint8_t* real_addr;
/* perform instruction address translation if enabled */
if (ppc_state.ppc_msr & 0x20) {
if (ppc_state.msr & 0x20) {
addr = ppc_mmu_instr_translate(addr);
}
if (addr >= last_exec_area.start && addr <= last_exec_area.end) {
real_addr = last_exec_area.mem_ptr + (addr - last_exec_area.start);
ppc_set_cur_instruction(real_addr);
}
else {
} else {
AddressMapEntry* entry = mem_ctrl_instance->find_range(addr);
if (entry && entry->type & (RT_ROM | RT_RAM)) {
last_exec_area.start = entry->start;
last_exec_area.end = entry->end;
last_exec_area.mem_ptr = entry->mem_ptr;
real_addr = last_exec_area.mem_ptr + (addr - last_exec_area.start);
real_addr = last_exec_area.mem_ptr + (addr - last_exec_area.start);
ppc_set_cur_instruction(real_addr);
}
else {
printf("WARNING: attempt to execute code at %08X!\n", addr);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
} else {
LOG_F(WARNING, "attempt to execute code at %08X!\n", addr);
exit(-1); // FIXME: ugly error handling, must be the proper exception!
}
}
return real_addr;
}
uint64_t mem_read_dbg(uint32_t virt_addr, uint32_t size) {
uint32_t save_dsisr, save_dar;
uint64_t ret_val;
/* save MMU-related CPU state */
save_dsisr = ppc_state.spr[SPR::DSISR];
save_dar = ppc_state.spr[SPR::DAR];
mmu_exception_handler = dbg_exception_handler;
try {
switch (size) {
case 1:
ret_val = mem_grab_byte(virt_addr);
break;
case 2:
ret_val = mem_grab_word(virt_addr);
break;
case 4:
ret_val = mem_grab_dword(virt_addr);
break;
case 8:
ret_val = mem_grab_qword(virt_addr);
break;
default:
ret_val = mem_grab_byte(virt_addr);
}
} catch (std::invalid_argument& exc) {
/* restore MMU-related CPU state */
mmu_exception_handler = ppc_exception_handler;
ppc_state.spr[SPR::DSISR] = save_dsisr;
ppc_state.spr[SPR::DAR] = save_dar;
/* rethrow MMU exception */
throw exc;
}
/* restore MMU-related CPU state */
mmu_exception_handler = ppc_exception_handler;
ppc_state.spr[SPR::DSISR] = save_dsisr;
ppc_state.spr[SPR::DAR] = save_dar;
return ret_val;
}
void ppc_mmu_init() {
mmu_exception_handler = ppc_exception_handler;
}
+31 -14
View File
@@ -1,44 +1,61 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// The opcodes for the processor - ppcopcodes.cpp
#ifndef PPCMEMORY_H
#define PPCMEMORY_H
#include <array>
#include <cinttypes>
#include <vector>
#include <array>
/* Uncomment this to exhaustive MMU integrity checks. */
//#define MMU_INTEGRITY_CHECKS
/** generic PowerPC BAT descriptor (MMU internal state) */
typedef struct PPC_BAT_entry {
uint8_t access; /* copy of Vs | Vp bits */
uint8_t prot; /* copy of PP bits */
uint32_t phys_hi; /* high-order bits for physical address generation */
uint32_t lo_mask; /* mask for low-order logical address bits */
uint32_t bepi; /* copy of Block effective page index */
uint8_t access; /* copy of Vs | Vp bits */
uint8_t prot; /* copy of PP bits */
uint32_t phys_hi; /* high-order bits for physical address generation */
uint32_t lo_mask; /* mask for low-order logical address bits */
uint32_t bepi; /* copy of Block effective page index */
} PPC_BAT_entry;
extern void ibat_update(uint32_t bat_reg);
extern void dbat_update(uint32_t bat_reg);
extern uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size);
extern void ppc_set_cur_instruction(const uint8_t* ptr);
extern void mem_write_byte(uint32_t addr, uint8_t value);
extern void mem_write_word(uint32_t addr, uint16_t value);
extern void mem_write_dword(uint32_t addr, uint32_t value);
extern void mem_write_qword(uint32_t addr, uint64_t value);
extern uint8_t mem_grab_byte(uint32_t addr);
extern uint8_t mem_grab_byte(uint32_t addr);
extern uint16_t mem_grab_word(uint32_t addr);
extern uint32_t mem_grab_dword(uint32_t addr);
extern uint64_t mem_grab_qword(uint32_t addr);
extern uint64_t mem_read_dbg(uint32_t virt_addr, uint32_t size);
extern uint8_t* quickinstruction_translate(uint32_t address_grab);
#endif // PPCMEMORY_H
#endif // PPCMEMORY_H
+979 -1497
View File
File diff suppressed because it is too large. Load diff
+31 -3
View File
@@ -64,6 +64,8 @@
# indexed load/store instructions, primary opcode 0x1F
0xFFF00100,0x7D49F02E,lwzx,r10,r9,r30
0xFFF00100,0x7C00002E,lwzx,r0,0,r0
0xFFF00100,0x7C20082E,lwzx,r1,0,r1
0xFFF00100,0x7FAB806E,lwzux,r29,r11,r16
0xFFF00100,0x7C0820AE,lbzx,r0,r8,r4
0xFFF00100,0x7F47E8EE,lbzux,r26,r7,r29
@@ -184,6 +186,16 @@
0xFFF00100,0x7D838120,mtcrf,0x38,r12
0xFFF00100,0x7D080120,mtcrf,0x80,r8
0xFFF00100,0x7E007120,mtcrf,0x07,r16
0xFFF00100,0x7C2FF120,mtcr,r1
# logical operations with the condition register
0xFFF00100,0x4C422A02,crand,eq,eq,4*cr1+gt
0xFFF00100,0x4FCAF902,crandc,4*cr7+eq,4*cr2+eq,4*cr7+so
0xFFF00100,0x4E756242,creqv,4*cr4+so,4*cr5+gt,4*cr3+lt
0xFFF00100,0x4F58C9C2,crnand,4*cr6+eq,4*cr6+lt,4*cr6+gt
0xFFF00100,0x4C411382,cror,eq,gt,eq
0xFFF00100,0x4C402342,crorc,eq,lt,4*cr1+lt
0xFFF00100,0x4C003982,crxor,lt,lt,4*cr1+so
# rotation instructions and their simplified mnemonics
#0xFFF00100,0x5084442E,rlwimi,r4,r4,8,16,23
@@ -319,9 +331,9 @@
0xFFF00100,0xCC1F0008,lfdu,f0,0x8(r31)
0xFFF00100,0xC1628398,lfs,f11,-0x7C68(r2)
0xFFF00100,0xC5BE0004,lfsu,f13,0x4(r30)
0xFFF00100,0xDBC1FFF0,sftd,f30,-0x10(r1)
0xFFF00100,0xD8010860,sftd,f0,0x860(r1)
0xFFF00100,0xDC180008,sftdu,f0,0x8(r24)
0xFFF00100,0xDBC1FFF0,stfd,f30,-0x10(r1)
0xFFF00100,0xD8010860,stfd,f0,0x860(r1)
0xFFF00100,0xDC180008,stfdu,f0,0x8(r24)
0xFFF00100,0xD01E0110,stfs,f0,0x110(r30)
0xFFF00100,0xD58B0004,stfsu,f12,0x4(r11)
0xFFF00100,0x7C1C5CAE,lfdx,f0,r28,r11
@@ -350,13 +362,26 @@
0xFFF00100,0xEDA66279,fmsubs.,f13,f6,f9,f12
0xFFF00100,0xEC00637C,fnmsubs,f0,f0,f13,f12
0xFFF00100,0xFE0820AF,fsel.,f16,f8,f2,f4
0xFFF00100,0xFDA06050,fneg,f13,f12
0xFFF00100,0xFD80EA10,fabs,f12,f29
0xFFF00100,0xFD600110,fnabs,f11,f0
0xFFF00100,0xFD002034,frsqrte,f8,f4
0xFFF00100,0x7FF957AE,stfiwx,f31,r25,r10
0xFFF00100,0xFC40F818,frsp,f2,f31
0xFFF00100,0xFC201019,frsp.,f1,f2
0xFFF00100,0xFDA0F81E,fctiwz,f13,f31
0xFFF00100,0xFCA0501D,fctiw.,f5,f10
0xFFF00100,0xFD9C0080,mcrfs,cr3,cr7
0xFFF00100,0xFDFE058E,mtfsf,255,f0
0xFFF00100,0xFF80F10C,mtfsfi,cr7,15
0xFFF00100,0xFF80F10D,mtfsfi.,cr7,15
0xFFF00100,0xFC406890,fmr,f2,f13
0xFFF00100,0xFC20E891,fmr.,f1,f29
# compare instructions
0xFFF00100,0x7C15A000,cmpw,r21,r20
0xFFF00100,0x7FBFB800,cmp,cr7,r31,r23
0xFFF00100,0x7C053040,cmplw,r5,r6
0xFFF00100,0x7F804840,cmplw,cr7,r0,r9
0xFFF00100,0x2F800000,cmpwi,cr7,r0,0x0
0xFFF00100,0x298E0022,cmplwi,cr3,r14,0x22
@@ -371,8 +396,11 @@
0xFFF00100,0x7CBC04AA,lswi,r5,r28,0x20
0xFFF00100,0x7FEF2C2A,lswx,r31,r15,r5
0xFFF00100,0x7E000400,mcrxr,cr4
0xFFF00100,0xFDC0008C,mtfsb0,14
0xFFF00100,0xFFE0004C,mtfsb1,31
0xFFF00100,0xFFE0048F,mffs.,f31
0xFFF00100,0x7C2000A6,mfmsr,r1
0xFFF00100,0x7C000124,mtmsr,r0
0xFFF00100,0x7FEF01A4,mtsr,15,r31
0xFFF00100,0x7C6021E4,mtsrin,r3,r4
0xFFF00100,0x7CA305AA,stswi,r5,r3,0x20
1 # Test data for PowerPC disassembler supplied as comma-separated values
64 0xFFF00100,0x7F47E8EE,lbzux,r26,r7,r29 0xFFF00100,0x7FAB806E,lwzux,r29,r11,r16
65 0xFFF00100,0x7C01612E,stwx,r0,r1,r12 0xFFF00100,0x7C0820AE,lbzx,r0,r8,r4
66 0xFFF00100,0x7FC3996E,stwux,r30,r3,r19 0xFFF00100,0x7F47E8EE,lbzux,r26,r7,r29
67 0xFFF00100,0x7C01612E,stwx,r0,r1,r12
68 0xFFF00100,0x7FC3996E,stwux,r30,r3,r19
69 0xFFF00100,0x7D2C09AE,stbx,r9,r12,r1
70 0xFFF00100,0x7C8531EE,stbux,r4,r5,r6
71 0xFFF00100,0x7C94DA2E,lhzx,r4,r20,r27
186 0xFFF00100,0x5485007E,clrlwi,r5,r4,1 0xFFF00100,0x4C402342,crorc,eq,lt,4*cr1+lt
187 0xFFF00100,0x572007FF,clrlwi.,r0,r25,31 0xFFF00100,0x4C003982,crxor,lt,lt,4*cr1+so
188 0xFFF00100,0x5404003C,clrrwi,r4,r0,1 # rotation instructions and their simplified mnemonics
189 #0xFFF00100,0x5084442E,rlwimi,r4,r4,8,16,23
190 0xFFF00100,0x54DF0FBC,clrlslwi,r31,r6,31,1
191 0xFFF00100,0x54DFF042,clrlslwi,r31,r6,31,30
192 0xFFF00100,0x54DF087C,clrlslwi,r31,r6,2,1
193 0xFFF00100,0x54A30FBC,clrlslwi,r3,r5,31,1
194 0xFFF00100,0x547AE884,clrlslwi,r26,r3,31,29
195 0xFFF00100,0x5485007E,clrlwi,r5,r4,1
196 0xFFF00100,0x572007FF,clrlwi.,r0,r25,31
197 0xFFF00100,0x5404003C,clrrwi,r4,r0,1
198 0xFFF00100,0x54000001,clrrwi.,r0,r0,31
199 0xFFF00100,0x54000001,clrrwi.,r0,r0,31 0xFFF00100,0x558C083A,extlwi,r12,r12,30,1
200 0xFFF00100,0x558C083A,extlwi,r12,r12,30,1 0xFFF00100,0x55CEF839,extlwi.,r14,r14,29,31
201 0xFFF00100,0x55CEF839,extlwi.,r14,r14,29,31 0xFFF00100,0x558CF83A,extlwi,r12,r12,30,31
331 0xFFF00100,0x7C4325AE,stfdx,f2,r3,r4 0xFFF00100,0x7C4325EE,stfdux,f2,r3,r4
332 0xFFF00100,0x7C4325EE,stfdux,f2,r3,r4 # floating point operations
333 # floating point operations 0xFFF00100,0xFC03282A,fadd,f0,f3,f5
334 0xFFF00100,0xFC03282A,fadd,f0,f3,f5 0xFFF00100,0xFDAD682B,fadd.,f13,f13,f13
335 0xFFF00100,0xFDAD682B,fadd.,f13,f13,f13 0xFFF00100,0xFC0D6028,fsub,f0,f13,f12
336 0xFFF00100,0xFC0D6028,fsub,f0,f13,f12 0xFFF00100,0xFC2107F2,fmul,f1,f1,f31
337 0xFFF00100,0xFC2107F2,fmul,f1,f1,f31 0xFFF00100,0xFF2C07F3,fmul.,f25,f12,f31
338 0xFFF00100,0xFF2C07F3,fmul.,f25,f12,f31 0xFFF00100,0xFC0D0024,fdiv,f0,f13,f0
339 0xFFF00100,0xFC0D0024,fdiv,f0,f13,f0 0xFFF00100,0xFC2B0025,fdiv.,f1,f11,f0
362 0xFFF00100,0x7CBC04AA,lswi,r5,r28,0x20 0xFFF00100,0x7FBFB800,cmp,cr7,r31,r23
363 0xFFF00100,0x7FEF2C2A,lswx,r31,r15,r5 0xFFF00100,0x7C053040,cmplw,r5,r6
364 0xFFF00100,0x7E000400,mcrxr,cr4 0xFFF00100,0x7F804840,cmplw,cr7,r0,r9
365 0xFFF00100,0x2F800000,cmpwi,cr7,r0,0x0
366 0xFFF00100,0x298E0022,cmplwi,cr3,r14,0x22
367 0xFFF00100,0xFFE0004C,mtfsb1,31 0xFFF00100,0xFE17C840,fcmpo,cr4,f23,f25
368 0xFFF00100,0xFFE0048F,mffs.,f31 0xFFF00100,0xFF0C6800,fcmpu,cr6,f12,f13
369 0xFFF00100,0x7FEF01A4,mtsr,15,r31 # misc instructions
370 0xFFF00100,0x7D290034,cntlzw,r9,r9
371 0xFFF00100,0x7FFF0035,cntlzw.,r31,r31
372 0xFFF00100,0x7C00D7AC,icbi,0,r26
373 0xFFF00100,0x7D604828,lwarx,r11,0,r9
374 0xFFF00100,0x7CBC04AA,lswi,r5,r28,0x20
375 0xFFF00100,0x7FEF2C2A,lswx,r31,r15,r5
376 0xFFF00100,0x7E000400,mcrxr,cr4
377 0xFFF00100,0xFDC0008C,mtfsb0,14
378 0xFFF00100,0xFFE0004C,mtfsb1,31
379 0xFFF00100,0xFFE0048F,mffs.,f31
380 0xFFF00100,0x7C6021E4,mtsrin,r3,r4 0xFFF00100,0x7C2000A6,mfmsr,r1
381 0xFFF00100,0x7CA305AA,stswi,r5,r3,0x20 0xFFF00100,0x7C000124,mtmsr,r0
382 0xFFF00100,0x7D453D2A,stswx,r10,r5,r7 0xFFF00100,0x7FEF01A4,mtsr,15,r31
383 0xFFF00100,0x7C0002E4,tlbia 0xFFF00100,0x7C6021E4,mtsrin,r3,r4
384 0xFFF00100,0x7CA305AA,stswi,r5,r3,0x20
385 0xFFF00100,0x7C004A64,tlbie,r9 0xFFF00100,0x7D453D2A,stswx,r10,r5,r7
386 # various simplified (extended) mnemonics 0xFFF00100,0x7C0002E4,tlbia
387 0xFFF00100,0x60000000,nop 0xFFF00100,0x7C004A64,tlbie,r9
396 0xFFF00100,0x7C6B0CD0,dc.l,0x7C6B0CD0 0xFFF00100,0x7D49F02F,dc.l,0x7D49F02F
397 0xFFF00100,0x7C642D90,dc.l,0x7C642D90 0xFFF00100,0x7F800009,dc.l,0x7F800009
398 # POWER/PPC601 specific instructions 0xFFF00100,0x7C6B0CD0,dc.l,0x7C6B0CD0
399 0xFFF00100,0x7C642D90,dc.l,0x7C642D90
400 0xFFF00100,0x7C440426,clcs,r2,r4 # POWER/PPC601 specific instructions
401 0xFFF00100,0x24000800,dozi,r0,r0,0x800 0xFFF00100,0x7C440426,clcs,r2,r4
402 0xFFF00100,0x24000800,dozi,r0,r0,0x800
403 0xFFF00100,0x7C00003A,maskg,r0,r0,r0
404 0xFFF00100,0x7C00003A,maskg,r0,r0,r0 0xFFF00100,0x7E3EE43A,maskir,r30,r17,r28
405 0xFFF00100,0x7E3EE43A,maskir,r30,r17,r28 0xFFF00100,0x58411800,rlmi,r1,r2,r3,0,0
406 0xFFF00100,0x58411800,rlmi,r1,r2,r3,0,0 0xFFF00100,0x58411801,rlmi.,r1,r2,r3,0,0
+66 -73
View File
@@ -1,72 +1,68 @@
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include "../ppcemu.h"
#include "../ppcdisasm.h"
#include "../ppcemu.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int ntested; /* number of tested instructions */
int nfailed; /* number of failed instructions */
void xer_ov_test(string mnem, uint32_t opcode)
{
ppc_state.ppc_gpr[3] = 2;
ppc_state.ppc_gpr[4] = 2;
ppc_state.ppc_spr[SPR::XER] = 0xFFFFFFFF;
ppc_cur_instruction = opcode;
void xer_ov_test(string mnem, uint32_t opcode) {
ppc_state.gpr[3] = 2;
ppc_state.gpr[4] = 2;
ppc_state.spr[SPR::XER] = 0xFFFFFFFF;
ppc_cur_instruction = opcode;
ppc_main_opcode();
if (ppc_state.ppc_spr[SPR::XER] & 0x40000000UL) {
cout << "Invalid " << mnem << " emulation! XER[OV] should not be set."
<< endl;
if (ppc_state.spr[SPR::XER] & 0x40000000UL) {
cout << "Invalid " << mnem << " emulation! XER[OV] should not be set." << endl;
nfailed++;
}
ntested++;
}
void xer_update_test()
{
xer_ov_test("ADDCO", 0x7C632414);
xer_ov_test("ADDCO.", 0x7C632415);
xer_ov_test("ADDO", 0x7C632614);
xer_ov_test("ADDO.", 0x7C632615);
xer_ov_test("ADDEO", 0x7C632514);
xer_ov_test("ADDEO.", 0x7C632515);
xer_ov_test("ADDMEO", 0x7C6305D4);
xer_ov_test("ADDMEO.", 0x7C6305D5);
xer_ov_test("ADDZEO", 0x7C630594);
xer_ov_test("ADDZEO.", 0x7C630595);
xer_ov_test("DIVWO", 0x7C6327D6);
xer_ov_test("DIVWO.", 0x7C6327D7);
xer_ov_test("DIVWUO", 0x7C632796);
xer_ov_test("DIVWUO.", 0x7C632797);
xer_ov_test("MULLWO", 0x7C6325D6);
xer_ov_test("MULLWO.", 0x7C6325D7);
xer_ov_test("NEGO", 0x7C6304D0);
xer_ov_test("NEGO.", 0x7C6304D1);
xer_ov_test("SUBFO", 0x7C632450);
xer_ov_test("SUBFO.", 0x7C632451);
xer_ov_test("SUBFCO", 0x7C632410);
xer_ov_test("SUBFCO.", 0x7C632411);
xer_ov_test("SUBFEO", 0x7C632510);
xer_ov_test("SUBFEO.", 0x7C632511);
xer_ov_test("SUBFMEO", 0x7C6305D0);
void xer_update_test() {
xer_ov_test("ADDCO", 0x7C632414);
xer_ov_test("ADDCO.", 0x7C632415);
xer_ov_test("ADDO", 0x7C632614);
xer_ov_test("ADDO.", 0x7C632615);
xer_ov_test("ADDEO", 0x7C632514);
xer_ov_test("ADDEO.", 0x7C632515);
xer_ov_test("ADDMEO", 0x7C6305D4);
xer_ov_test("ADDMEO.", 0x7C6305D5);
xer_ov_test("ADDZEO", 0x7C630594);
xer_ov_test("ADDZEO.", 0x7C630595);
xer_ov_test("DIVWO", 0x7C6327D6);
xer_ov_test("DIVWO.", 0x7C6327D7);
xer_ov_test("DIVWUO", 0x7C632796);
xer_ov_test("DIVWUO.", 0x7C632797);
xer_ov_test("MULLWO", 0x7C6325D6);
xer_ov_test("MULLWO.", 0x7C6325D7);
xer_ov_test("NEGO", 0x7C6304D0);
xer_ov_test("NEGO.", 0x7C6304D1);
xer_ov_test("SUBFO", 0x7C632450);
xer_ov_test("SUBFO.", 0x7C632451);
xer_ov_test("SUBFCO", 0x7C632410);
xer_ov_test("SUBFCO.", 0x7C632411);
xer_ov_test("SUBFEO", 0x7C632510);
xer_ov_test("SUBFEO.", 0x7C632511);
xer_ov_test("SUBFMEO", 0x7C6305D0);
xer_ov_test("SUBFMEO.", 0x7C6305D1);
xer_ov_test("SUBFZEO", 0x7C630590);
xer_ov_test("SUBFZEO", 0x7C630590);
xer_ov_test("SUBFZEO.", 0x7C630591);
}
/** testing vehicle */
static void read_test_data()
{
string line, token;
int i, lineno;
static void read_test_data() {
string line, token;
int i, lineno;
uint32_t opcode, dest, src1, src2, check_xer, check_cr;
ifstream tfstream("ppcinttests.csv");
ifstream tfstream("ppcinttests.csv");
if (!tfstream.is_open()) {
cout << "Could not open tests CSV file. Exiting..." << endl;
return;
@@ -74,7 +70,7 @@ static void read_test_data()
lineno = 0;
while(getline(tfstream, line)) {
while (getline(tfstream, line)) {
lineno++;
if (line.empty() || !line.rfind("#", 0))
@@ -84,7 +80,7 @@ static void read_test_data()
vector<string> tokens;
while(getline(lnstream, token, ',' )) {
while (getline(lnstream, token, ',')) {
tokens.push_back(token);
}
@@ -95,9 +91,9 @@ static void read_test_data()
opcode = stoul(tokens[1], NULL, 16);
dest = 0;
src1 = 0;
src2 = 0;
dest = 0;
src1 = 0;
src2 = 0;
check_xer = 0;
check_cr = 0;
@@ -113,16 +109,16 @@ static void read_test_data()
} else if (tokens[i].rfind("CR=", 0) == 0) {
check_cr = stoul(tokens[i].substr(3), NULL, 16);
} else {
cout << "Unknown parameter " << tokens[i] << " in line " << lineno <<
". Exiting..." << endl;
cout << "Unknown parameter " << tokens[i] << " in line " << lineno << ". Exiting..."
<< endl;
exit(0);
}
}
ppc_state.ppc_gpr[3] = src1;
ppc_state.ppc_gpr[4] = src2;
ppc_state.ppc_spr[SPR::XER] = 0;
ppc_state.ppc_cr = 0;
ppc_state.gpr[3] = src1;
ppc_state.gpr[4] = src2;
ppc_state.spr[SPR::XER] = 0;
ppc_state.cr = 0;
ppc_cur_instruction = opcode;
@@ -130,16 +126,14 @@ static void read_test_data()
ntested++;
if ((tokens[0].rfind("CMP") && (ppc_state.ppc_gpr[3] != dest)) ||
(ppc_state.ppc_spr[SPR::XER] != check_xer) ||
(ppc_state.ppc_cr != check_cr)) {
cout << "Mismatch: instr=" << tokens[0] << ", src1=0x" << hex << src1
<< ", src2=0x" << hex << src2 << endl;
cout << "expected: dest=0x" << hex << dest << ", XER=0x" << hex
<< check_xer << ", CR=0x" << hex << check_cr << endl;
cout << "got: dest=0x" << hex << ppc_state.ppc_gpr[3] << ", XER=0x"
<< hex << ppc_state.ppc_spr[SPR::XER] << ", CR=0x" << hex
<< ppc_state.ppc_cr << endl;
if ((tokens[0].rfind("CMP") && (ppc_state.gpr[3] != dest)) ||
(ppc_state.spr[SPR::XER] != check_xer) || (ppc_state.cr != check_cr)) {
cout << "Mismatch: instr=" << tokens[0] << ", src1=0x" << hex << src1 << ", src2=0x"
<< hex << src2 << endl;
cout << "expected: dest=0x" << hex << dest << ", XER=0x" << hex << check_xer
<< ", CR=0x" << hex << check_cr << endl;
cout << "got: dest=0x" << hex << ppc_state.gpr[3] << ", XER=0x" << hex
<< ppc_state.spr[SPR::XER] << ", CR=0x" << hex << ppc_state.cr << endl;
cout << "Test file line #: " << dec << lineno << endl << endl;
nfailed++;
@@ -147,9 +141,8 @@ static void read_test_data()
}
}
int main()
{
int i;
int main() {
initialize_ppc_opcode_tables(); //kludge
cout << "Running DingusPPC emulator tests..." << endl << endl;
+21 -24
View File
@@ -1,22 +1,21 @@
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include "../ppcdisasm.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
/** testing vehicle */
static vector<PPCDisasmContext> read_test_data()
{
string line, token;
int i, lineno;
static vector<PPCDisasmContext> read_test_data() {
string line, token;
int i, lineno;
PPCDisasmContext ctx;
vector<PPCDisasmContext> tstvec;
ifstream tfstream("ppcdisasmtest.csv");
ifstream tfstream("ppcdisasmtest.csv");
if (!tfstream.is_open()) {
cout << "Could not open tests CSV file. Exiting..." << endl;
return tstvec;
@@ -24,18 +23,18 @@ static vector<PPCDisasmContext> read_test_data()
lineno = 0;
while(getline(tfstream, line)) {
while (getline(tfstream, line)) {
lineno++;
if (line.empty() || !line.rfind("#", 0))
continue; // skip empty/comment lines
continue; // skip empty/comment lines
istringstream lnstream(line);
vector<string> tokens;
while(getline(lnstream, token, ',' )) {
//cout << "Token: " << token << endl;
while (getline(lnstream, token, ',')) {
// cout << "Token: " << token << endl;
tokens.push_back(token);
}
@@ -44,7 +43,7 @@ static vector<PPCDisasmContext> read_test_data()
continue;
}
ctx = {0};
ctx = {0};
ctx.instr_addr = stoul(tokens[0], NULL, 16);
ctx.instr_code = stoul(tokens[1], NULL, 16);
@@ -64,7 +63,7 @@ static vector<PPCDisasmContext> read_test_data()
ctx.instr_str = idisasm.str();
//cout << idisasm.str() << endl;
// cout << idisasm.str() << endl;
tstvec.push_back(ctx);
}
@@ -72,8 +71,7 @@ static vector<PPCDisasmContext> read_test_data()
return tstvec;
}
int test_ppc_disasm()
{
int test_ppc_disasm() {
int i, nfailed;
PPCDisasmContext ctx;
@@ -84,7 +82,7 @@ int test_ppc_disasm()
nfailed = 0;
for (i = 0; i < testdata.size(); i++) {
ctx = {0};
ctx = {0};
ctx.instr_addr = testdata[i].instr_addr;
ctx.instr_code = testdata[i].instr_code;
ctx.simplified = true;
@@ -92,14 +90,13 @@ int test_ppc_disasm()
std::string disas = disassemble_single(&ctx);
if (disas != testdata[i].instr_str) {
cout << "Mismatch found, expected={" << testdata[i].instr_str <<
"}, got={" << disas << "}" << endl;
cout << "Mismatch found, expected={" << testdata[i].instr_str << "}, got={" << disas
<< "}" << endl;
nfailed++;
}
}
cout << "Tested " << testdata.size() << " instructions. Failed: " <<
nfailed << "." << endl;
cout << "Tested " << testdata.size() << " instructions. Failed: " << nfailed << "." << endl;
return 0;
}
+6
View File
@@ -0,0 +1,6 @@
include_directories("${PROJECT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/thirdparty/capstone/include")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
add_library(debugger OBJECT ${SOURCES})
+493 -69
View File
@@ -1,75 +1,383 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <array>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <map>
#include "ppcemu.h"
#include "../cpu/ppc/ppcmmu.h"
#include <thirdparty/loguru/loguru.hpp>
#include "../cpu/ppc/ppcdisasm.h"
#include "../cpu/ppc/ppcemu.h"
#include "../cpu/ppc/ppcmmu.h"
#ifdef ENABLE_68K_DEBUGGER // optionally defined in CMakeLists.txt
#include <capstone/capstone.h>
#endif
using namespace std;
void show_help()
{
static uint32_t str2addr(string& addr_str) {
try {
return stoul(addr_str, NULL, 0);
} catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + addr_str);
}
}
static uint32_t str2num(string& num_str) {
try {
return stol(num_str, NULL, 0);
} catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + num_str);
}
}
static void show_help() {
cout << "Debugger commands:" << endl;
cout << " step -- execute single instruction" << endl;
cout << " step [N] -- execute single instruction" << endl;
cout << " N is an optional step count" << endl;
cout << " si [N] -- shortcut for step" << endl;
cout << " next -- same as step but treats subroutine calls" << endl;
cout << " as single instructions." << endl;
cout << " ni -- shortcut for next" << endl;
cout << " until X -- execute until address X is reached" << endl;
cout << " regs -- dump content of the GRPs" << endl;
cout << " set R=X -- assign value X to register R" << endl;
cout << " memdump -- dump content of the system memory to memdump.bin" << endl;
cout << " if R=loglevel, set the internal" << endl;
cout << " log level to X whose range is -2...9" << endl;
cout << " dump NT,X -- dump N memory cells of size T at address X" << endl;
cout << " T can be b(byte), w(word), d(double)," << endl;
cout << " q(quad) or c(character)." << endl;
#ifdef PROFILER
cout << " profiler -- show stats related to the processor" << endl;
#endif
cout << " disas N,X -- disassemble N instructions starting at address X" << endl;
cout << " X can be any number or a known register name" << endl;
cout << " disas with no arguments defaults to disas 1,pc" << endl;
cout << " da N,X -- shortcut for disas" << endl;
#ifdef ENABLE_68K_DEBUGGER
cout << " context X -- switch to the debugging context X." << endl;
cout << " X can be either 'ppc' (default) or '68k'" << endl;
cout << " Use 68k for debugging emulated 68k code only." << endl;
#endif
cout << " quit -- quit the debugger" << endl << endl;
cout << "Pressing ENTER will repeat last command." << endl;
}
void dump_regs()
{
for (uint32_t i = 0; i < 32; i++)
cout << "GPR " << dec << i << " : " << hex << ppc_state.ppc_gpr[i] << endl;
#ifdef ENABLE_68K_DEBUGGER
cout << "PC: " << hex << ppc_state.ppc_pc << endl;
cout << "LR: " << hex << ppc_state.ppc_spr[8] << endl;
cout << "CR: " << hex << ppc_state.ppc_cr << endl;
cout << "CTR: " << hex << ppc_state.ppc_spr[9] << endl;
cout << "XER: " << hex << ppc_state.ppc_spr[1] << endl;
cout << "MSR: " << hex << ppc_state.ppc_msr << endl;
static void disasm_68k(uint32_t count, uint32_t address) {
csh cs_handle;
uint8_t code[10];
size_t code_size;
uint64_t dis_addr;
if (cs_open(CS_ARCH_M68K, CS_MODE_M68K_040, &cs_handle) != CS_ERR_OK) {
cout << "Capstone initialization error" << endl;
return;
}
cs_insn* insn = cs_malloc(cs_handle);
for (; count > 0; count--) {
/* prefetch opcode bytes (a 68k instruction can occupy 2...10 bytes) */
for (int i = 0; i < sizeof(code); i++) {
code[i] = mem_read_dbg(address + i, 1);
}
const uint8_t *code_ptr = code;
code_size = sizeof(code);
dis_addr = address;
if (cs_disasm_iter(cs_handle, &code_ptr, &code_size, &dis_addr, insn)) {
cout << uppercase << hex << insn->address << " ";
cout << setfill(' ');
cout << setw(10) << left << insn->mnemonic << insn->op_str << endl;
address = dis_addr;
} else {
cout << "DS.W " << hex << ((code[0] << 8) | code[1]) << endl;
address += 2;
}
}
cs_free(insn, 1);
cs_close(&cs_handle);
}
void disasm(uint32_t inst_num = 1UL, uint32_t address = ppc_state.ppc_pc)
/* emulator opcode table size --> 512 KB */
#define EMU_68K_TABLE_SIZE 0x80000
/** Execute one emulated 68k instruction. */
void exec_single_68k()
{
string reg;
uint32_t emu_table_virt, cur_68k_pc, cur_instr_tab_entry, ppc_pc;
/* PPC r24 contains 68k PC advanced by two bytes
as part of instruction prefetching */
reg = "R24";
cur_68k_pc = get_reg(reg) - 2;
/* PPC r29 contains base address of the emulator opcode table */
reg = "R29";
emu_table_virt = get_reg(reg) & 0xFFF80000;
/* calculate address of the current opcode table entry as follows:
get_word(68k_PC) * entry_size + table_base */
cur_instr_tab_entry = mem_grab_word(cur_68k_pc) * 8 + emu_table_virt;
/* grab the PPC PC too */
reg = "PC";
ppc_pc = get_reg(reg);
//printf("cur_instr_tab_entry = %X\n", cur_instr_tab_entry);
/* because the first two PPC instructions for each emulated 68k once
are resided in the emulator opcode table, we need to execute them
one by one until the execution goes outside the opcode table. */
while (ppc_pc >= cur_instr_tab_entry && ppc_pc < cur_instr_tab_entry + 8) {
ppc_exec_single();
reg = "PC";
ppc_pc = get_reg(reg);
LOG_F(9, "Tracing within emulator table, PC = %X\n", ppc_pc);
}
/* Getting here means we're outside the emualtor opcode table.
Execute PPC code until we hit the opcode table again. */
LOG_F(9, "Tracing outside the emulator table, PC = %X\n", ppc_pc);
ppc_exec_dbg(emu_table_virt, EMU_68K_TABLE_SIZE - 1);
}
/** Execute emulated 68k code until target_addr is reached. */
void exec_until_68k(uint32_t target_addr)
{
string reg;
uint32_t emu_table_virt, ppc_pc;
reg = "R29";
emu_table_virt = get_reg(reg) & 0xFFF80000;
reg = "R24";
while (target_addr != (get_reg(reg) - 2)) {
reg = "PC";
ppc_pc = get_reg(reg);
if (ppc_pc >= emu_table_virt && ppc_pc < (emu_table_virt + EMU_68K_TABLE_SIZE - 1)) {
LOG_F(9, "Tracing within emulator table, PC = %X\n", ppc_pc);
ppc_exec_single();
} else {
LOG_F(9, "Tracing outside the emulator table, PC = %X\n", ppc_pc);
ppc_exec_dbg(emu_table_virt, EMU_68K_TABLE_SIZE - 1);
}
reg = "R24";
}
}
void print_68k_regs()
{
int i;
string reg;
for (i = 0; i < 8; i++) {
reg = "R" + to_string(i + 8);
cout << "D" << dec << i << " : " << uppercase << hex << get_reg(reg) << endl;
}
for (i = 0; i < 7; i++) {
reg = "R" + to_string(i + 16);
cout << "A" << dec << i << " : " << uppercase << hex << get_reg(reg) << endl;
}
reg = "R1";
cout << "A7 : " << uppercase << hex << get_reg(reg) << endl;
reg = "R24";
cout << "PC: " << uppercase << hex << get_reg(reg) - 2 << endl;
reg = "R25";
cout << "SR: " << uppercase << hex << ((get_reg(reg) & 0xFF) << 8) << endl;
reg = "R26";
cout << "CCR: " << uppercase << hex << get_reg(reg) << endl;
}
#endif // ENABLE_68K_DEBUGGER
static void dump_mem(string& params) {
int cell_size, chars_per_line;
bool is_char;
uint32_t count, addr;
uint64_t val;
string num_type_str, addr_str;
size_t separator_pos;
separator_pos = params.find_first_of(",");
if (separator_pos == std::string::npos) {
cout << "dump: not enough arguments specified." << endl;
return;
}
num_type_str = params.substr(0, params.find_first_of(","));
addr_str = params.substr(params.find_first_of(",") + 1);
is_char = false;
switch (num_type_str.back()) {
case 'b':
case 'B':
cell_size = 1;
break;
case 'w':
case 'W':
cell_size = 2;
break;
case 'd':
case 'D':
cell_size = 4;
break;
case 'q':
case 'Q':
cell_size = 8;
break;
case 'c':
case 'C':
cell_size = 1;
is_char = true;
break;
default:
cout << "Invalid data type " << num_type_str << endl;
return;
}
try {
num_type_str = num_type_str.substr(0, num_type_str.length() - 1);
count = str2addr(num_type_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return;
}
try {
addr = str2addr(addr_str);
} catch (invalid_argument& exc) {
try {
/* number conversion failed, trying reg name */
addr = get_reg(addr_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return;
}
}
cout << "Dumping memory at address " << hex << addr << ":" << endl;
chars_per_line = 0;
try {
for (int i = 0; i < count; addr += cell_size, i++) {
if (chars_per_line + cell_size * 2 > 80) {
cout << endl;
chars_per_line = 0;
}
val = mem_read_dbg(addr, cell_size);
if (is_char) {
cout << (char)val;
chars_per_line += cell_size;
} else {
cout << setw(cell_size * 2) << setfill('0') << right;
cout << uppercase << hex << val << " ";
chars_per_line += cell_size * 2 + 2;
}
}
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return;
}
cout << endl << endl;
}
static void disasm(uint32_t count, uint32_t address) {
PPCDisasmContext ctx;
quickinstruction_translate(ppc_state.ppc_pc);
ctx.instr_addr = ppc_state.ppc_pc;
ctx.instr_code = ppc_cur_instruction;
ctx.instr_addr = address;
ctx.simplified = true;
cout << hex << ppc_state.ppc_pc << " " << disassemble_single(&ctx) << endl;
for (int i = 0; i < count; i++) {
ctx.instr_code = mem_read_dbg(ctx.instr_addr, 4);
cout << uppercase << hex << ctx.instr_addr;
cout << " " << disassemble_single(&ctx) << endl;
}
}
void enter_debugger()
{
static void print_gprs() {
string reg_name;
int i;
for (i = 0; i < 32; i++) {
reg_name = "R" + to_string(i);
cout << right << std::setw(3) << setfill(' ') << reg_name << " : " <<
setw(8) << setfill('0') << right << uppercase << hex << get_reg(reg_name);
if (i & 1) {
cout << endl;
} else {
cout << "\t\t";
}
}
array<string,6> sprs = {"PC", "LR", "CR", "CTR", "XER", "MSR"};
for (auto &spr : sprs) {
cout << right << std::setw(3) << setfill(' ') << spr << " : " <<
setw(8) << setfill('0') << uppercase << hex << get_reg(spr);
if (i & 1) {
cout << endl;
} else {
cout << "\t\t";
}
i++;
}
}
void enter_debugger() {
string inp, cmd, addr_str, expr_str, reg_expr, last_cmd, reg_value_str, inst_string, inst_num_str;
uint32_t addr, inst_grab;
std::stringstream ss;
int log_level, context;
size_t separator_pos;
cout << "Welcome to the PowerPC debugger." << endl;
context = 1; /* start with the PowerPC context */
cout << "Welcome to the DingusPPC command line debugger." << endl;
cout << "Please enter a command or 'help'." << endl << endl;
while (1) {
cout << "ppcdbg> ";
cout << "dingusdbg> ";
/* reset string stream */
ss.str("");
@@ -86,8 +394,7 @@ void enter_debugger()
}
if (cmd == "help") {
show_help();
}
else if (cmd == "quit") {
} else if (cmd == "quit") {
break;
}
#ifdef PROFILER
@@ -98,47 +405,164 @@ void enter_debugger()
}
#endif
else if (cmd == "regs") {
dump_regs();
}
else if (cmd == "set") {
if (context == 2) {
#ifdef ENABLE_68K_DEBUGGER
print_68k_regs();
#endif
} else {
print_gprs();
}
} else if (cmd == "set") {
ss >> expr_str;
reg_expr = expr_str.substr(0, expr_str.find("="));
if (reg_expr == "pc") {
addr_str = expr_str.substr(expr_str.find("=") + 1);
addr = stol(addr_str, NULL, 0);
ppc_state.ppc_pc = addr;
separator_pos = expr_str.find_first_of("=");
if (separator_pos == std::string::npos) {
cout << "set: not enough arguments specified." << endl;
continue;
}
else {
cout << "Unknown register " << reg_expr << endl;
try {
reg_expr = expr_str.substr(0, expr_str.find_first_of("="));
addr_str = expr_str.substr(expr_str.find_first_of("=") + 1);
if (reg_expr == "loglevel") {
log_level = str2num(addr_str);
if (log_level < -2 || log_level > 9) {
cout << "Log level must be in the range -2...9!" << endl;
continue;
}
loguru::g_stderr_verbosity = log_level;
} else {
addr = str2addr(addr_str);
set_reg(reg_expr, addr);
}
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
}
}
else if (cmd == "step") {
ppc_exec_single();
}
else if (cmd == "until") {
ss >> addr_str;
addr = stol(addr_str, NULL, 16);
ppc_exec_until(addr);
}
else if (cmd == "disas") {
} else if (cmd == "step" || cmd == "si") {
int count;
expr_str = "";
ss >> expr_str;
if (expr_str.length() > 0) {
cout << "Parsing disas params." << endl;
inst_num_str = expr_str.substr(expr_str.find(" ") + 1, expr_str.find(","));
inst_grab = stoul(inst_num_str, NULL, 0);
addr_str = expr_str.substr(expr_str.find(",") + 1, expr_str.length() - 1);
addr = stoul(addr_str, NULL, 16);
disasm(inst_grab, addr);
try {
count = str2num(expr_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
count = 1;
}
} else {
count = 1;
}
else {
disasm();
if (context == 2) {
#ifdef ENABLE_68K_DEBUGGER
for (; --count >= 0;) {
exec_single_68k();
}
#endif
} else {
for (; --count >= 0;) {
ppc_exec_single();
}
}
}
else {
} else if (cmd == "next" || cmd == "ni") {
addr_str = "PC";
addr = get_reg(addr_str) + 4;
ppc_exec_until(addr);
} else if (cmd == "until") {
ss >> addr_str;
try {
addr = str2addr(addr_str);
if (context == 2) {
#ifdef ENABLE_68K_DEBUGGER
exec_until_68k(addr);
#endif
} else {
ppc_exec_until(addr);
}
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
}
} else if (cmd == "disas" || cmd == "da") {
expr_str = "";
ss >> expr_str;
if (expr_str.length() > 0) {
separator_pos = expr_str.find_first_of(",");
if (separator_pos == std::string::npos) {
cout << "disas: not enough arguments specified." << endl;
continue;
}
inst_num_str = expr_str.substr(0, expr_str.find_first_of(","));
try {
inst_grab = str2num(inst_num_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
continue;
}
addr_str = expr_str.substr(expr_str.find_first_of(",") + 1);
try {
addr = str2addr(addr_str);
} catch (invalid_argument& exc) {
try {
/* number conversion failed, trying reg name */
if (context == 2 && (addr_str == "pc" || addr_str == "PC")) {
addr_str = "R24";
addr = get_reg(addr_str) - 2;
} else {
addr = get_reg(addr_str);
}
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
continue;
}
}
try {
if (context == 2) {
#ifdef ENABLE_68K_DEBUGGER
disasm_68k(inst_grab, addr);
#endif
} else {
disasm(inst_grab, addr);
}
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
}
} else {
/* disas without arguments defaults to disas 1,pc */
if (context == 2) {
#ifdef ENABLE_68K_DEBUGGER
addr_str = "R24";
addr = get_reg(addr_str);
disasm_68k(1, addr - 2);
#endif
} else {
addr_str = "PC";
addr = get_reg(addr_str);
disasm(1, addr);
}
}
} else if (cmd == "dump") {
expr_str = "";
ss >> expr_str;
dump_mem(expr_str);
#ifdef ENABLE_68K_DEBUGGER
} else if (cmd == "context") {
expr_str = "";
ss >> expr_str;
if (expr_str == "ppc" || expr_str == "PPC") {
context = 1;
} else if (expr_str == "68k" || expr_str == "68K") {
context = 2;
} else {
cout << "Unknown debugging context: " << expr_str << endl;
}
#endif
} else {
cout << "Unknown command: " << cmd << endl;
continue;
}
last_cmd = cmd;
}
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
void enter_debugger(void);
#endif // DEBUGGER_H_
#endif // DEBUGGER_H_
+1
View File
@@ -3,3 +3,4 @@ include_directories("${PROJECT_SOURCE_DIR}")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
add_library(devices OBJECT ${SOURCES})
target_link_libraries(devices PRIVATE cubeb)
+474
View File
@@ -0,0 +1,474 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** ADB bus definitions
Simulates Apple Desktop Bus (ADB) bus
*/
#include "devices/adb.h"
#include <cinttypes>
#include <cstring>
#if 0
#include <thirdparty/SDL2/include/SDL.h>
#include <thirdparty/SDL2/include/SDL_events.h>
#include <thirdparty/SDL2/include/SDL_keycode.h>
#include <thirdparty/SDL2/include/SDL_mouse.h>
#include <thirdparty/SDL2/include/SDL_stdinc.h>
#endif
#include <thirdparty/loguru/loguru.hpp>
using namespace std;
ADB_Bus::ADB_Bus() {
// set data streams as clear
this->adb_mouse_register0 = 0x8080;
input_stream_len = 0;
output_stream_len = 2;
adb_keybd_register3 = 0x6201;
adb_mouse_register3 = 0x6302;
keyboard_access_no = adb_encoded;
mouse_access_no = adb_relative;
}
ADB_Bus::~ADB_Bus() {}
bool ADB_Bus::listen(int device, int reg) {
if (device == keyboard_access_no) {
if (adb_keybd_listen(reg)) {
return true;
} else {
return false;
}
} else if (device == mouse_access_no) {
if (adb_mouse_listen(reg)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
bool ADB_Bus::talk(int device, int reg, uint16_t value) {
// temp code
return false;
}
bool ADB_Bus::bus_reset() {
// temp code
return true;
}
bool ADB_Bus::set_addr(int dev_addr, int new_addr) {
// temp code
return false;
}
bool ADB_Bus::flush(int dev_addr) {
// temp code
return false;
}
bool ADB_Bus::adb_keybd_listen(int reg) {
if (reg == 3) {
output_data_stream[0] = (adb_keybd_register3 >> 8);
output_data_stream[1] = (adb_keybd_register3 & 0xff);
return true;
}
#if 0
while (SDL_PollEvent(&adb_keybd_evt)) {
// Poll our SDL key event for any keystrokes.
switch (adb_keybd_evt.type) {
case SDL_KEYDOWN:
switch (adb_keybd_evt.key.keysym.sym) {
case SDLK_a:
ask_key_pressed = 0x00;
break;
case SDLK_s:
ask_key_pressed = 0x01;
break;
case SDLK_d:
ask_key_pressed = 0x02;
break;
case SDLK_f:
ask_key_pressed = 0x03;
break;
case SDLK_h:
ask_key_pressed = 0x04;
break;
case SDLK_g:
ask_key_pressed = 0x05;
break;
case SDLK_z:
ask_key_pressed = 0x06;
break;
case SDLK_x:
ask_key_pressed = 0x07;
break;
case SDLK_c:
ask_key_pressed = 0x08;
break;
case SDLK_v:
ask_key_pressed = 0x09;
break;
case SDLK_b:
ask_key_pressed = 0x0B;
break;
case SDLK_q:
ask_key_pressed = 0x0C;
break;
case SDLK_w:
ask_key_pressed = 0x0D;
break;
case SDLK_e:
ask_key_pressed = 0x0E;
break;
case SDLK_r:
ask_key_pressed = 0x0F;
break;
case SDLK_y:
ask_key_pressed = 0x10;
break;
case SDLK_t:
ask_key_pressed = 0x11;
break;
case SDLK_1:
ask_key_pressed = 0x12;
break;
case SDLK_2:
ask_key_pressed = 0x13;
break;
case SDLK_3:
ask_key_pressed = 0x14;
break;
case SDLK_4:
ask_key_pressed = 0x15;
break;
case SDLK_6:
ask_key_pressed = 0x16;
break;
case SDLK_5:
ask_key_pressed = 0x17;
break;
case SDLK_EQUALS:
ask_key_pressed = 0x18;
break;
case SDLK_9:
ask_key_pressed = 0x19;
break;
case SDLK_7:
ask_key_pressed = 0x1A;
break;
case SDLK_MINUS:
ask_key_pressed = 0x1B;
break;
case SDLK_8:
ask_key_pressed = 0x1C;
break;
case SDLK_0:
ask_key_pressed = 0x1D;
break;
case SDLK_RIGHTBRACKET:
ask_key_pressed = 0x1E;
break;
case SDLK_o:
ask_key_pressed = 0x1F;
break;
case SDLK_u:
ask_key_pressed = 0x20;
break;
case SDLK_LEFTBRACKET:
ask_key_pressed = 0x21;
break;
case SDLK_i:
ask_key_pressed = 0x22;
break;
case SDLK_p:
ask_key_pressed = 0x23;
break;
case SDLK_RETURN:
ask_key_pressed = 0x24;
break;
case SDLK_l:
ask_key_pressed = 0x25;
break;
case SDLK_j:
ask_key_pressed = 0x26;
break;
case SDLK_QUOTE:
ask_key_pressed = 0x27;
break;
case SDLK_k:
ask_key_pressed = 0x28;
break;
case SDLK_SEMICOLON:
ask_key_pressed = 0x29;
break;
case SDLK_BACKSLASH:
ask_key_pressed = 0x2A;
break;
case SDLK_COMMA:
ask_key_pressed = 0x2B;
break;
case SDLK_SLASH:
ask_key_pressed = 0x2C;
break;
case SDLK_n:
ask_key_pressed = 0x2D;
break;
case SDLK_m:
ask_key_pressed = 0x2E;
break;
case SDLK_PERIOD:
ask_key_pressed = 0x2F;
break;
case SDLK_BACKQUOTE:
ask_key_pressed = 0x32;
break;
case SDLK_ESCAPE:
ask_key_pressed = 0x35;
break;
case SDLK_LEFT:
ask_key_pressed = 0x3B;
break;
case SDLK_RIGHT:
ask_key_pressed = 0x3C;
break;
case SDLK_DOWN:
ask_key_pressed = 0x3D;
break;
case SDLK_UP:
ask_key_pressed = 0x3E;
break;
case SDLK_KP_PERIOD:
ask_key_pressed = 0x41;
break;
case SDLK_KP_MULTIPLY:
ask_key_pressed = 0x43;
break;
case SDLK_KP_PLUS:
ask_key_pressed = 0x45;
break;
case SDLK_DELETE:
ask_key_pressed = 0x47;
break;
case SDLK_KP_DIVIDE:
ask_key_pressed = 0x4B;
break;
case SDLK_KP_ENTER:
ask_key_pressed = 0x4C;
break;
case SDLK_KP_MINUS:
ask_key_pressed = 0x4E;
break;
case SDLK_KP_0:
ask_key_pressed = 0x52;
break;
case SDLK_KP_1:
ask_key_pressed = 0x53;
break;
case SDLK_KP_2:
ask_key_pressed = 0x54;
break;
case SDLK_KP_3:
ask_key_pressed = 0x55;
break;
case SDLK_KP_4:
ask_key_pressed = 0x56;
break;
case SDLK_KP_5:
ask_key_pressed = 0x57;
break;
case SDLK_KP_6:
ask_key_pressed = 0x58;
break;
case SDLK_KP_7:
ask_key_pressed = 0x59;
break;
case SDLK_KP_8:
ask_key_pressed = 0x5B;
break;
case SDLK_KP_9:
ask_key_pressed = 0x5C;
break;
case SDLK_BACKSPACE:
// ask_key_pressed = 0x33;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x40;
break;
case SDLK_CAPSLOCK:
// ask_key_pressed = 0x39;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x20;
break;
case SDLK_RALT:
case SDLK_RCTRL: // Temp key for Control key
// ask_key_pressed = 0x36;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x8;
break;
case SDLK_LSHIFT:
case SDLK_RSHIFT:
// ask_key_pressed = 0x38;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x4;
break;
case SDLK_LALT:
// ask_key_pressed = 0x3A;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x2;
break;
case SDLK_LCTRL: // Temp key for the Command/Apple key
// ask_key_pressed = 0x37;
confirm_ask_reg_2 = true;
mod_key_pressed = 0x1;
break;
default:
break;
}
if (adb_keybd_register0 & 0x8000) {
adb_keybd_register0 &= 0x7FFF;
adb_keybd_register0 &= (ask_key_pressed << 8);
output_data_stream[0] = (adb_keybd_register0 >> 8);
output_data_stream[1] = (adb_keybd_register0 & 0xff);
} else if (adb_keybd_register0 & 0x80) {
adb_keybd_register0 &= 0xFF7F;
adb_keybd_register0 &= (ask_key_pressed);
output_data_stream[0] = (adb_keybd_register0 >> 8);
output_data_stream[1] = (adb_keybd_register0 & 0xff);
}
// check if mod keys are being pressed
if (confirm_ask_reg_2) {
adb_keybd_register0 |= (mod_key_pressed << 8);
output_data_stream[0] = (adb_keybd_register2 >> 8);
output_data_stream[1] = (adb_keybd_register2 & 0xff);
}
break;
case SDL_KEYUP:
if (!(adb_keybd_register0 & 0x8000)) {
adb_keybd_register0 |= 0x8000;
output_data_stream[0] = (adb_keybd_register0 >> 8);
output_data_stream[1] = (adb_keybd_register0 & 0xff);
} else if (adb_keybd_register0 & 0x80)
adb_keybd_register0 |= 0x0080;
output_data_stream[0] = (adb_keybd_register0 >> 8);
output_data_stream[1] = (adb_keybd_register0 & 0xff);
if (confirm_ask_reg_2) {
adb_keybd_register2 &= (mod_key_pressed << 8);
output_data_stream[0] = (adb_keybd_register2 >> 8);
output_data_stream[1] = (adb_keybd_register2 & 0xff);
confirm_ask_reg_2 = false;
}
}
}
#endif
if ((reg != 1)) {
return true;
} else {
return false;
}
}
bool ADB_Bus::adb_mouse_listen(int reg) {
if ((reg != 0) | (reg != 3)) {
return false;
}
#if 0
while (SDL_PollEvent(&adb_mouse_evt)) {
if (adb_mouse_evt.motion.x) {
this->adb_mouse_register0 &= 0x7F;
if (adb_mouse_evt.motion.xrel < 0) {
if (adb_mouse_evt.motion.xrel <= -64) {
this->adb_mouse_register0 |= 0x7F;
} else if (adb_mouse_evt.motion.xrel >= 63) {
this->adb_mouse_register0 |= 0x3F;
} else {
this->adb_mouse_register0 |= adb_mouse_evt.motion.xrel;
}
}
}
if (adb_mouse_evt.motion.y) {
this->adb_mouse_register0 &= 0x7F00;
if (adb_mouse_evt.motion.yrel < 0) {
if (adb_mouse_evt.motion.yrel <= -64) {
this->adb_mouse_register0 |= 0x7F00;
} else if (adb_mouse_evt.motion.yrel >= 63) {
this->adb_mouse_register0 |= 0x3F00;
} else {
this->adb_mouse_register0 |= (adb_mouse_evt.motion.yrel << 8);
}
}
}
switch (adb_mouse_evt.type) {
case SDL_MOUSEBUTTONDOWN:
this->adb_mouse_register0 &= 0x7FFF;
case SDL_MOUSEBUTTONUP:
this->adb_mouse_register0 |= 0x8000;
}
}
#endif
if (reg == 0) {
output_data_stream[0] = (adb_mouse_register0 >> 8);
output_data_stream[1] = (adb_mouse_register0 & 0xff);
} else if (reg == 3) {
output_data_stream[0] = (adb_mouse_register3 >> 8);
output_data_stream[1] = (adb_mouse_register3 & 0xff);
}
return true;
}
uint8_t ADB_Bus::get_input_byte(int offset) {
return input_data_stream[offset];
}
uint8_t ADB_Bus::get_output_byte(int offset) {
return output_data_stream[offset];
}
int ADB_Bus::get_input_len() {
return input_stream_len;
}
int ADB_Bus::get_output_len() {
return output_stream_len;
}
+100
View File
@@ -0,0 +1,100 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef ADB_H
#define ADB_H
#include <cinttypes>
#if 0
#include <thirdparty/SDL2/include/SDL.h>
#include <thirdparty/SDL2/include/SDL_events.h>
#endif
enum adb_default_values {
adb_reserved0,
adb_reserved1,
adb_encoded,
adb_relative,
adb_absolute,
adb_reserved5,
adb_reserved6,
adb_reserved7,
adb_other8,
adb_other9,
adb_other10,
adb_other11,
adb_other12,
adb_other13,
adb_other14,
adb_other15
};
class ADB_Bus {
public:
ADB_Bus();
~ADB_Bus();
bool listen(int device, int reg);
bool talk(int device, int reg, uint16_t value);
bool bus_reset();
bool set_addr(int dev_addr, int new_addr);
bool flush(int dev_addr);
bool adb_keybd_listen(int reg);
bool adb_mouse_listen(int reg);
uint8_t get_input_byte(int offset);
uint8_t get_output_byte(int offset);
int get_input_len();
int get_output_len();
private:
int keyboard_access_no;
int mouse_access_no;
// Keyboard Variables
uint16_t adb_keybd_register0;
uint16_t adb_keybd_register2;
uint16_t adb_keybd_register3;
//SDL_Event adb_keybd_evt;
uint8_t ask_key_pressed;
uint8_t mod_key_pressed;
bool confirm_ask_reg_2;
// Mouse Variables
//SDL_Event adb_mouse_evt;
uint16_t adb_mouse_register0;
uint16_t adb_mouse_register3;
uint8_t input_data_stream[16]; // temp buffer
int input_stream_len;
uint8_t output_data_stream[16]; // temp buffer
int output_stream_len;
};
#endif /* ADB_H */
+499
View File
@@ -0,0 +1,499 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "displayid.h"
#include "endianswap.h"
#include "memaccess.h"
#include "pcidevice.h"
#include <atirage.h>
#include <cstdint>
#include <map>
#include <thirdparty/loguru/loguru.hpp>
/* Mach64 post dividers. */
static const int mach64_post_div[8] = {
1, 2, 4, 8, // standard post dividers
3, 5, 6, 12 // alternate post dividers
};
/* Human readable Mach64 HW register names for easier debugging. */
static const std::map<uint16_t, std::string> mach64_reg_names = {
{0x0000, "CRTC_H_TOTAL_DISP"},
{0x0004, "CRTC_H_SYNC_STRT_WID"},
{0x0008, "CRTC_V_TOTAL_DISP"},
{0x000C, "CRTC_V_SYNC_STRT_WID"},
{0x0010, "CRTC_VLINE_CRNT_VLINE"},
{0x0014, "CRTC_OFF_PITCH"},
{0x0018, "CRTC_INT_CNTL"},
{0x001C, "CRTC_GEN_CNTL"},
{0x0020, "DSP_CONFIG"},
{0x0024, "DSP_ON_OFF"},
{0x002C, "MEM_BUF_CNTL"},
{0x0034, "MEM_ADDR_CFG"},
{0x0040, "OVR_CLR"},
{0x0044, "OVR_WID_LEFT_RIGHT"},
{0x0048, "OVR_WID_TOP_BOTTOM"},
{0x0060, "CUR_CLR0"},
{0x0064, "CUR_CLR1"},
{0x0068, "CUR_OFFSET"},
{0x006C, "CUR_HORZ_VERT_POSN"},
{0x0078, "GP_IO"},
{0x007C, "HW_DEBUG"},
{0x0080, "SCRATCH_REG0"},
{0x0084, "SCRATCH_REG1"},
{0x0088, "SCRATCH_REG2"},
{0x008C, "SCRATCH_REG3"},
{0x0090, "CLOCK_CNTL"},
{0x00A0, "BUS_CNTL"},
{0x00AC, "EXT_MEM_CNTL"},
{0x00B0, "MEM_CNTL"},
{0x00C0, "DAC_REGS"},
{0x00C4, "DAC_CNTL"},
{0x00D0, "GEN_TEST_CNTL"},
{0x00D4, "CUSTOM_MACRO_CNTL"},
{0x00E0, "CONFIG_CHIP_ID"},
{0x00E4, "CONFIG_STAT0"},
{0x01B4, "SRC_CNTL"},
{0x01FC, "SCALE_3D_CNTL"},
{0x0310, "FIFO_STAT"},
{0x0338, "GUI_STAT"},
};
ATIRage::ATIRage(uint16_t dev_id, uint32_t mem_amount) : PCIDevice("ati-rage") {
uint8_t asic_id;
this->vram_size = mem_amount << 20;
/* allocate video RAM */
this->vram_ptr = new uint8_t[this->vram_size];
/* ATI Rage driver needs to know ASIC ID (manufacturer's internal chip code)
to operate properly */
switch (dev_id) {
case ATI_RAGE_PRO_DEV_ID:
asic_id = 0x5C; // R3B/D/P-A4 fabricated by UMC
break;
default:
asic_id = 0xDD;
LOG_F(WARNING, "ATI Rage: bogus ASIC ID assigned!");
}
/* set up PCI configuration space header */
WRITE_DWORD_LE_A(&this->pci_cfg[0], (dev_id << 16) | ATI_PCI_VENDOR_ID);
WRITE_DWORD_LE_A(&this->pci_cfg[8], (0x030000 << 8) | asic_id);
WRITE_DWORD_LE_A(&this->pci_cfg[0x3C], 0x00080100);
/* stuff default values into chip registers */
WRITE_DWORD_LE_A(&this->block_io_regs[ATI_CONFIG_CHIP_ID],
(asic_id << 24) | dev_id);
/* initialize display identification */
this->disp_id = new DisplayID();
}
ATIRage::~ATIRage()
{
if (this->vram_ptr) {
delete this->vram_ptr;
}
delete (this->disp_id);
}
const char* ATIRage::get_reg_name(uint32_t reg_offset) {
auto iter = mach64_reg_names.find(reg_offset & ~3);
if (iter != mach64_reg_names.end()) {
return iter->second.c_str();
} else {
return "unknown Mach64 register";
}
}
uint32_t ATIRage::read_reg(uint32_t offset, uint32_t size) {
uint32_t res;
switch (offset & ~3) {
case ATI_GP_IO:
break;
case ATI_CLOCK_CNTL:
/* reading from internal PLL registers */
if (offset == ATI_CLOCK_CNTL+2 && size == 1 &&
!(this->block_io_regs[ATI_CLOCK_CNTL+1] & 0x2)) {
return this->plls[this->block_io_regs[ATI_CLOCK_CNTL+1] >> 2];
}
break;
case ATI_DAC_REGS:
if (offset == ATI_DAC_DATA) {
this->block_io_regs[ATI_DAC_DATA] =
this->palette[this->block_io_regs[ATI_DAC_R_INDEX]][this->comp_index];
this->comp_index++; /* move to next color component */
if (this->comp_index >= 3) {
/* autoincrement reading index - move to next palette entry */
(this->block_io_regs[ATI_DAC_R_INDEX])++;
this->comp_index = 0;
}
}
break;
default:
LOG_F(
INFO,
"ATI Rage: read I/O reg %s at 0x%X, size=%d, val=0x%X",
get_reg_name(offset),
offset,
size,
read_mem(&this->block_io_regs[offset], size));
}
if (offset > sizeof(this->block_io_regs)) {
LOG_F(WARNING, "ATI Rage: register offset 0x%04X out of bounds!", offset);
return 0;
}
res = read_mem(&this->block_io_regs[offset], size);
return res;
}
void ATIRage::write_reg(uint32_t offset, uint32_t value, uint32_t size) {
uint32_t gpio_val;
uint16_t gpio_dir;
if (offset > sizeof(this->block_io_regs)) {
LOG_F(WARNING, "ATI Rage: register offset 0x%04X out of bounds!", offset);
return;
}
/* size-dependent endian conversion */
write_mem(&this->block_io_regs[offset], value, size);
switch (offset & ~3) {
case ATI_CRTC_GEN_CNTL:
if (this->block_io_regs[ATI_CRTC_GEN_CNTL+3] & 2) {
this->crtc_enable();
} else {
this->crtc_on = false;
}
break;
case ATI_GP_IO:
if (offset < (ATI_GP_IO + 2)) {
gpio_val = READ_DWORD_LE_A(&this->block_io_regs[ATI_GP_IO]);
gpio_dir = (gpio_val >> 16) & 0x3FFF;
WRITE_WORD_LE_A(
&this->block_io_regs[ATI_GP_IO],
this->disp_id->read_monitor_sense(gpio_val, gpio_dir));
}
break;
case ATI_CLOCK_CNTL:
/* writing to internal PLL registers */
if (offset == ATI_CLOCK_CNTL+2 && size == 1 &&
(this->block_io_regs[ATI_CLOCK_CNTL+1] & 0x2)) {
int pll_addr = this->block_io_regs[ATI_CLOCK_CNTL+1] >> 2;
uint8_t pll_data = this->block_io_regs[ATI_CLOCK_CNTL+2];
this->plls[pll_addr] = pll_data;
LOG_F(INFO, "ATI Rage: PLL #%d set to 0x%02X", pll_addr, pll_data);
} else if (offset == ATI_CLOCK_CNTL && size == 1) {
LOG_F(INFO, "ATI Rage: CLOCK_SEL = 0x%02X",
this->block_io_regs[ATI_CLOCK_CNTL] & 3);
}
break;
case ATI_DAC_REGS:
switch (offset) {
/* writing to read/write index registers resets color component index */
case ATI_DAC_W_INDEX:
case ATI_DAC_R_INDEX:
this->comp_index = 0;
break;
case ATI_DAC_DATA:
this->palette[this->block_io_regs[ATI_DAC_W_INDEX]][this->comp_index] = value & 0xFF;
this->comp_index++; /* move to next color component */
if (this->comp_index >= 3) {
LOG_F(
INFO,
"ATI DAC palette entry #%d set to R=%X, G=%X, B=%X",
this->block_io_regs[ATI_DAC_W_INDEX],
this->palette[this->block_io_regs[ATI_DAC_W_INDEX]][0],
this->palette[this->block_io_regs[ATI_DAC_W_INDEX]][1],
this->palette[this->block_io_regs[ATI_DAC_W_INDEX]][2]);
/* autoincrement writing index - move to next palette entry */
(this->block_io_regs[ATI_DAC_W_INDEX])++;
this->comp_index = 0;
}
}
break;
default:
LOG_F(
INFO,
"ATI Rage: %s register at 0x%X set to 0x%X",
get_reg_name(offset),
offset & ~3,
READ_DWORD_LE_A(&this->block_io_regs[offset & ~3]));
}
}
uint32_t ATIRage::pci_cfg_read(uint32_t reg_offs, uint32_t size) {
uint32_t res = 0;
LOG_F(INFO, "Reading ATI Rage config space, offset = 0x%X, size=%d", reg_offs, size);
res = read_mem(&this->pci_cfg[reg_offs], size);
LOG_F(INFO, "Return value: 0x%X", res);
return res;
}
void ATIRage::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) {
LOG_F(
INFO,
"Writing into ATI Rage PCI config space, offset = 0x%X, val=0x%X size=%d",
reg_offs,
BYTESWAP_32(value),
size);
switch (reg_offs) {
case 0x10: /* BAR 0 */
if (value == 0xFFFFFFFFUL) {
WRITE_DWORD_LE_A(&this->pci_cfg[CFG_REG_BAR0], 0xFF000000UL);
}
else {
this->aperture_base = BYTESWAP_32(value);
LOG_F(INFO, "ATI Rage aperture address set to 0x%08X", this->aperture_base);
WRITE_DWORD_BE_A(&this->pci_cfg[CFG_REG_BAR0], value);
this->host_instance->pci_register_mmio_region(this->aperture_base,
APERTURE_SIZE, this);
}
break;
case 0x14: /* BAR 1: I/O space base, 256 bytes wide */
if (value == 0xFFFFFFFFUL) {
WRITE_DWORD_BE_A(&this->pci_cfg[CFG_REG_BAR1], 0xFFFFFF01UL);
}
else {
WRITE_DWORD_BE_A(&this->pci_cfg[CFG_REG_BAR1], value);
}
break;
case 0x18: /* BAR 2 */
if (value == 0xFFFFFFFFUL) {
WRITE_DWORD_BE_A(&this->pci_cfg[CFG_REG_BAR2], 0xFFFFF000UL);
}
else {
WRITE_DWORD_BE_A(&this->pci_cfg[CFG_REG_BAR2], value);
}
break;
case CFG_REG_BAR3: /* unimplemented */
case CFG_REG_BAR4: /* unimplemented */
case CFG_REG_BAR5: /* unimplemented */
WRITE_DWORD_BE_A(&this->pci_cfg[reg_offs], 0);
break;
case CFG_EXP_BASE: /* no expansion ROM */
if (value == 0x00F8FFFFUL) {
// return 0 (not implemented) when attempting to size the expansion ROM
WRITE_DWORD_BE_A(&this->pci_cfg[reg_offs], 0);
} else {
WRITE_DWORD_BE_A(&this->pci_cfg[reg_offs], value);
}
break;
default:
write_mem(&this->pci_cfg[reg_offs], value, size);
}
}
bool ATIRage::io_access_allowed(uint32_t offset, uint32_t* p_io_base) {
if (!(this->pci_cfg[CFG_REG_CMD] & 1)) {
LOG_F(WARNING, "ATI I/O space disabled in the command reg");
return false;
}
uint32_t io_base = READ_DWORD_LE_A(&this->pci_cfg[CFG_REG_BAR1]) & ~3;
if (offset < io_base || offset > (io_base + 0x100)) {
LOG_F(WARNING, "Rage: I/O out of range, base=0x%X, offset=0x%X", io_base, offset);
return false;
}
*p_io_base = io_base;
return true;
}
bool ATIRage::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res) {
uint32_t io_base;
if (!this->io_access_allowed(offset, &io_base)) {
return false;
}
*res = this->read_reg(offset - io_base, size);
return true;
}
bool ATIRage::pci_io_write(uint32_t offset, uint32_t value, uint32_t size) {
uint32_t io_base;
if (!this->io_access_allowed(offset, &io_base)) {
return false;
}
this->write_reg(offset - io_base, value, size);
return true;
}
uint32_t ATIRage::read(uint32_t reg_start, uint32_t offset, int size)
{
LOG_F(8, "Reading ATI Rage PCI memory: region=%X, offset=%X, size %d", reg_start, offset, size);
if (reg_start < this->aperture_base || offset > APERTURE_SIZE) {
LOG_F(WARNING, "ATI Rage: attempt to read outside the aperture!");
return 0;
}
if (offset < this->vram_size) {
/* read from little-endian VRAM region */
return read_mem(this->vram_ptr + offset, size);
}
else if (offset >= MEMMAP_OFFSET) {
/* read from memory-mapped registers */
return this->read_reg(offset - MEMMAP_OFFSET, size);
}
else {
LOG_F(WARNING, "ATI Rage: read attempt from unmapped aperture region at 0x%08X", offset);
}
return 0;
}
void ATIRage::write(uint32_t reg_start, uint32_t offset, uint32_t value, int size)
{
LOG_F(8, "Writing reg=%X, offset=%X, value=%X, size %d", reg_start, offset, value, size);
if (reg_start < this->aperture_base || offset > APERTURE_SIZE) {
LOG_F(WARNING, "ATI Rage: attempt to write outside the aperture!");
return;
}
if (offset < this->vram_size) {
/* write to little-endian VRAM region */
write_mem(this->vram_ptr + offset, value, size);
} else if (offset >= MEMMAP_OFFSET) {
/* write to memory-mapped registers */
this->write_reg(offset - MEMMAP_OFFSET, value, size);
}
else {
LOG_F(WARNING, "ATI Rage: write attempt to unmapped aperture region at 0x%08X", offset);
}
}
float ATIRage::calc_pll_freq(int scale, int fb_div) {
return (ATI_XTAL * scale * fb_div) / this->plls[PLL_REF_DIV];
}
void ATIRage::verbose_pixel_format(int crtc_index) {
if (crtc_index) {
LOG_F(ERROR, "CRTC2 not supported yet");
return;
}
const char* what = "Pixel format:";
switch (this->block_io_regs[ATI_CRTC_GEN_CNTL+1] & 7) {
case 1:
LOG_F(INFO, "%s 4 bpp with DAC palette", what);
break;
case 2:
// check the undocumented DAC_DIRECT bit
if (this->block_io_regs[ATI_DAC_CNTL+1] & 4) {
LOG_F(INFO, "%s 8 bpp direct color (RGB322)", what);
} else {
LOG_F(INFO, "%s 8 bpp with DAC palette", what);
}
break;
case 3:
LOG_F(INFO, "%s 15 bpp direct color (RGB555)", what);
break;
case 4:
LOG_F(INFO, "%s 16 bpp direct color (RGB565)", what);
break;
case 5:
LOG_F(INFO, "%s 24 bpp direct color (RGB888)", what);
break;
case 6:
LOG_F(INFO, "%s 32 bpp direct color (ARGB8888)", what);
break;
default:
LOG_F(ERROR, "ATI Rage: CRTC pixel format %d not supported",
this->block_io_regs[ATI_CRTC_GEN_CNTL+2] & 7);
}
}
void ATIRage::crtc_enable() {
/* active (visible) width is specified in characters (8 px) - 1 */
this->active_width = (this->block_io_regs[ATI_CRTC_H_TOTAL_DISP+2] + 1) * 8;
/* active (visible) height is specified in lines - 1 */
this->active_height =
(READ_WORD_LE_A(&this->block_io_regs[ATI_CRTC_V_TOTAL_DISP+2]) & 0x7FFUL) + 1;
if ((this->plls[PLL_VCLK_CNTL] & 3) == 3) {
/* look up which VPLL ouput is requested */
int clock_sel = this->block_io_regs[ATI_CLOCK_CNTL] & 3;
/* calculate VPLL output frequency */
float vpll_freq = calc_pll_freq(2, this->plls[VCLK0_FB_DIV + clock_sel]);
/* calculate post divider's index */
/* NOTE: post divider's index has been extended by an additional
bit in Rage Pro. This bit is resided in PLL_EXT_CNTL register.
*/
int post_div_idx = ((this->plls[PLL_EXT_CNTL] >> (clock_sel + 2)) & 4) |
((this->plls[VCLK_POST_DIV] >> (clock_sel * 2)) & 3);
/* pixel clock = source_freq / post_div */
this->pixel_clock = vpll_freq / mach64_post_div[post_div_idx];
/* calculate display refresh rate */
int hori_total =
((READ_WORD_LE_A(&this->block_io_regs[ATI_CRTC_H_TOTAL_DISP])
& 0x1FFUL) + 1) * 8;
int vert_total =
(READ_WORD_LE_A(&this->block_io_regs[ATI_CRTC_V_TOTAL_DISP]) & 0x7FFUL) + 1;
this->refresh_rate = pixel_clock / hori_total / vert_total;
LOG_F(INFO, "ATI Rage: primary CRT controller enabled:");
LOG_F(INFO, "Video mode: %s",
(this->block_io_regs[ATI_CRTC_GEN_CNTL+3] & 1) ? "extended" : "VGA");
LOG_F(INFO, "Video width: %d px", this->active_width);
LOG_F(INFO, "Video height: %d px", this->active_height);
verbose_pixel_format(0);
LOG_F(INFO, "VPLL frequency: %f MHz", vpll_freq * 1e-6);
LOG_F(INFO, "Pixel (dot) clock: %f MHz", this->pixel_clock * 1e-6);
LOG_F(INFO, "Refresh rate: %f Hz", this->refresh_rate);
} else {
LOG_F(WARNING, "ATI Rage: VLCK source != VPLL!");
}
this->crtc_on = true;
}
+250
View File
@@ -0,0 +1,250 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef ATI_RAGE_H
#define ATI_RAGE_H
#include "displayid.h"
#include "pcidevice.h"
#include <cinttypes>
/* PCI related definitions. */
enum {
ATI_PCI_VENDOR_ID = 0x1002,
ATI_RAGE_PRO_DEV_ID = 0x4750,
ATI_RAGE_GT_DEV_ID = 0x4754,
};
/** Mach registers offsets. */
enum {
ATI_CRTC_H_TOTAL_DISP = 0x0000,
ATI_CRTC_H_SYNC_STRT_WID = 0x0004,
ATI_CRTC_V_TOTAL_DISP = 0x0008,
ATI_CRTC_V_SYNC_STRT_WID = 0x000C,
ATI_CRTC_VLINE_CRNT_VLINE = 0x0010,
ATI_CRTC_OFF_PITCH = 0x0014,
ATI_CRTC_INT_CNTL = 0x0018,
ATI_CRTC_GEN_CNTL = 0x001C,
ATI_DSP_CONFIG = 0x0020,
ATI_DSP_ON_OFF = 0x0024,
ATI_TIMER_CFG = 0x0028,
ATI_MEM_BUF_CNTL = 0x002C,
ATI_MEM_ADDR_CFG = 0x0034,
ATI_CRT_TRAP = 0x0038,
ATI_I2C_CNTL_0 = 0x003C,
ATI_OVR_CLR = 0x0040,
ATI_OVR_WID_LEFT_RIGHT = 0x0044,
ATI_OVR_WID_TOP_BOTTOM = 0x0048,
ATI_VGA_DSP_CFG = 0x004C,
ATI_VGA_DSP_TGL = 0x0050,
ATI_DSP2_CONFIG = 0x0054,
ATI_DSP2_TOGGLE = 0x0058,
ATI_CRTC2_OFF_PITCH = 0x005C,
ATI_CUR_CLR0 = 0x0060,
ATI_CUR_CLR1 = 0x0064,
ATI_CUR_OFFSET = 0x0068,
ATI_CUR_HORZ_VERT_POSN = 0x006C,
ATI_CUR_HORZ_VERT_OFF = 0x0070,
ATI_GP_IO = 0x0078,
ATI_HW_DEBUG = 0x007C,
ATI_SCRATCH_REG0 = 0x0080,
ATI_SCRATCH_REG1 = 0x0084,
ATI_SCRATCH_REG2 = 0x0088,
ATI_SCRATCH_REG3 = 0x008C,
ATI_CLOCK_CNTL = 0x0090,
ATI_CONFIG_STAT1 = 0x0094,
ATI_CONFIG_STAT2 = 0x0098,
ATI_BUS_CNTL = 0x00A0,
ATI_EXT_MEM_CNTL = 0x00AC,
ATI_MEM_CNTL = 0x00B0,
ATI_MEM_VGA_WP_SEL = 0x00B4,
ATI_MEM_VGA_RP_SEL = 0x00B8,
ATI_I2C_CNTL_1 = 0x00BC,
ATI_DAC_REGS = 0x00C0,
ATI_DAC_W_INDEX = 0x00C0,
ATI_DAC_DATA = 0x00C1,
ATI_DAC_MASK = 0x00C2,
ATI_DAC_R_INDEX = 0x00C3,
ATI_DAC_CNTL = 0x00C4,
ATI_GEN_TEST_CNTL = 0x00D0,
ATI_CUSTOM_MACRO_CNTL = 0x00D4,
ATI_CONFIG_CNTL = 0x00DC,
ATI_CONFIG_CHIP_ID = 0x00E0,
ATI_CONFIG_STAT0 = 0x00E4,
ATI_CRC_SIG = 0x00E8,
ATI_DST_Y_X_ALIAS1 = 0x00F4,
ATI_DST_OFF_PITCH = 0x0100,
ATI_DST_X = 0x0104,
ATI_DST_Y = 0x0108,
ATI_DST_Y_X = 0x010C,
ATI_DST_WIDTH = 0x0110,
ATI_DST_HEIGHT = 0x0114,
ATI_DST_HEIGHT_WIDTH = 0x0118,
ATI_DST_X_WIDTH = 0x011C,
ATI_DST_BRES_LNTH = 0x0120,
ATI_DST_BRES_ERR = 0x0124,
ATI_DST_BRES_INC = 0x0128,
ATI_DST_BRES_DEC = 0x012C,
ATI_DST_CNTL = 0x0130,
ATI_DST_Y_X_ALIAS2 = 0x0134,
ATI_TRAIL_BRES_ERR = 0x0138,
ATI_TRAIL_BRES_INC = 0x013C,
ATI_TRAIL_BRES_DEC = 0x0140,
ATI_DST_BRES_LNTH_ALIAS1 = 0x0144,
ATI_Z_OFF_PITCH = 0x0148,
ATI_Z_CNTL = 0x014C,
ATI_ALPHA_TST_CNTL = 0x0150,
ATI_SRC_OFF_PITCH = 0x0180,
ATI_SRC_X = 0x0184,
ATI_SRC_Y = 0x0188,
ATI_SRC_Y_X = 0x018C,
ATI_SRC_WIDTH1 = 0x0190,
ATI_SRC_HEIGHT1 = 0x0194,
ATI_SRC_HEIGHT1_WIDTH1 = 0x0198,
ATI_SRC_X_START = 0x019C,
ATI_SRC_Y_START = 0x01A0,
ATI_SRC_Y_X_START = 0x01A4,
ATI_SRC_WIDTH2 = 0x01A8,
ATI_SRC_HEIGHT2 = 0x01AC,
ATI_SRC_HEIGHT2_WIDTH2 = 0x01B0,
ATI_SRC_CNTL = 0x01B4,
ATI_SCALE_OFF = 0x01C0,
ATI_SCALE_WIDTH = 0x01DC,
ATI_SCALE_HEIGHT = 0x01E0,
ATI_SCALE_PITCH = 0x01EC,
ATI_SCALE_X_INC = 0x01F0,
ATI_SCALE_Y_INC = 0x01F4,
ATI_SCALE_VACC = 0x01F8,
ATI_SCALE_3D_CNTL = 0x01FC,
ATI_HOST_CNTL = 0x0240,
ATI_PAT_REG0 = 0x0280,
ATI_PAT_REG1 = 0x0284,
ATI_PAT_CNTL = 0x0288,
ATI_SC_LEFT = 0x02A0,
ATI_SC_RIGHT = 0x02A4,
ATI_SC_LEFT_RIGHT = 0x02A8,
ATI_SC_TOP = 0x02AC,
ATI_SC_BOTTOM = 0x02B0,
ATI_SC_TOP_BOTTOM = 0x02B4,
ATI_DP_BKGD_CLR = 0x02C0,
ATI_DP_FOG_CLR = 0x02C0,
ATI_DP_WRITE_MSK = 0x02C8,
ATI_DP_PIX_WIDTH = 0x02D0,
ATI_DP_MIX = 0x02D4,
ATI_DP_SRC = 0x02D8,
ATI_FRGD_CLR_MIX = 0x02DC,
ATI_FRGD_BKGD_CLR = 0x02E0,
ATI_DST_X_Y = 0x02E8,
ATI_DST_WIDTH_HEIGHT = 0x02EC,
ATI_USR_DST_PITCH = 0x02F0,
ATI_DP_SET_GUI_ENGINE2 = 0x02F4,
ATI_DP_SET_GUI_ENGINE = 0x02F8,
ATI_CLR_CMP_CLR = 0x0300,
ATI_CLR_CMP_MSK = 0x0304,
ATI_CLR_CMP_CNTL = 0x0308,
ATI_FIFO_STAT = 0x0310,
ATI_CONTEXT_MASK = 0x0320,
ATI_GUI_TRAJ_CNTL = 0x0330,
ATI_GUI_STAT = 0x0338,
ATI_MPP_CONFIG = 0x04C0,
ATI_MPP_STROBE_SEQ = 0x04C4,
ATI_MPP_ADDR = 0x04C8,
ATI_MPP_DATA = 0x04CC,
ATI_TVO_CNTL = 0x0500,
};
/* Mach64 PLL register indices. */
enum {
PLL_REF_DIV = 2, // reference divider, same for all Mach64 clocks
PLL_VCLK_CNTL = 5,
VCLK_POST_DIV = 6,
VCLK0_FB_DIV = 7, // feedback divider for VCLK0
VCLK1_FB_DIV = 8, // feedback divider for VCLK1
VCLK2_FB_DIV = 9, // feedback divider for VCLK2
VCLK3_FB_DIV = 10, // feedback divider for VCLK3
PLL_EXT_CNTL = 11,
};
constexpr auto APERTURE_SIZE = 0x01000000UL; /* Mach64 aperture size */
constexpr auto MEMMAP_OFFSET = 0x007FFC00UL; /* offset to memory mapped registers */
constexpr auto ATI_XTAL = 14318180.0f; // external crystal oscillator frequency
class ATIRage : public PCIDevice {
public:
ATIRage(uint16_t dev_id, uint32_t mem_amount);
~ATIRage();
/* MMIODevice methods */
uint32_t read(uint32_t reg_start, uint32_t offset, int size);
void write(uint32_t reg_start, uint32_t offset, uint32_t value, int size);
bool supports_type(HWCompType type) {
return type == HWCompType::MMIO_DEV;
};
/* PCI device methods */
bool supports_io_space(void) {
return true;
};
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
/* I/O space access methods */
bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res);
bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size);
protected:
const char* get_reg_name(uint32_t reg_offset);
bool io_access_allowed(uint32_t offset, uint32_t* p_io_base);
uint32_t read_reg(uint32_t offset, uint32_t size);
void write_reg(uint32_t offset, uint32_t value, uint32_t size);
float calc_pll_freq(int scale, int fb_div);
void verbose_pixel_format(int crtc_index);
void crtc_enable();
private:
uint8_t block_io_regs[512] = {0};
uint8_t pci_cfg[256] = {0}; /* PCI configuration space */
uint8_t plls[64] = {0}; // internal PLL registers
/* CRT controller parameters */
bool crtc_on = false;
int active_width; // width of the visible display area
int active_height; // height of the visible display area
float pixel_clock;
float refresh_rate;
/* Video RAM variables */
uint32_t vram_size;
uint8_t* vram_ptr;
uint32_t aperture_base;
DisplayID* disp_id;
uint8_t palette[256][4]; /* internal DAC palette in RGBA format */
int comp_index; /* color component index for DAC palette access */
};
#endif /* ATI_RAGE_H */
+289
View File
@@ -0,0 +1,289 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** AWAC sound device emulation.
Author: Max Poliakovski 2019-20
*/
#include "awacs.h"
#include "dbdma.h"
#include "endianswap.h"
#include "machines/machinebase.h"
#include "soundserver.h"
#include <algorithm>
#include <thirdparty/loguru/loguru.hpp>
static int awac_freqs[8] = {44100, 29400, 22050, 17640, 14700, 11025, 8820, 7350};
AWACDevice::AWACDevice()
{
this->audio_proc = new AudioProcessor();
/* register audio processor chip with the I2C bus */
I2CBus* i2c_bus = dynamic_cast<I2CBus*>(gMachineObj->get_comp_by_type(HWCompType::I2C_HOST));
i2c_bus->register_device(0x45, this->audio_proc);
this->snd_server = dynamic_cast<SoundServer *>
(gMachineObj->get_comp_by_name("SoundServer"));
this->out_stream_ready = false;
}
AWACDevice::~AWACDevice()
{
if (this->out_stream_ready) {
snd_server->close_out_stream();
}
delete this->audio_proc;
}
void AWACDevice::set_dma_out(DMAChannel* dma_out_ch) {
this->dma_out_ch = dma_out_ch;
}
uint32_t AWACDevice::snd_ctrl_read(uint32_t offset, int size) {
switch (offset) {
case AWAC_SOUND_CTRL_REG:
return this->snd_ctrl_reg;
case AWAC_CODEC_CTRL_REG:
return this->is_busy;
case AWAC_CODEC_STATUS_REG:
return (AWAC_AVAILABLE << 8) | (AWAC_MAKER_CRYSTAL << 16) | (AWAC_REV_SCREAMER << 20);
break;
default:
LOG_F(ERROR, "AWAC: unsupported register at offset 0x%X", offset);
}
return 0;
}
void AWACDevice::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
int subframe, reg_num;
uint16_t data;
switch (offset) {
case AWAC_SOUND_CTRL_REG:
this->snd_ctrl_reg = BYTESWAP_32(value);
LOG_F(INFO, "New sound control value = 0x%X", this->snd_ctrl_reg);
break;
case AWAC_CODEC_CTRL_REG:
subframe = (value >> 14) & 3;
reg_num = (value >> 20) & 7;
data = ((value >> 8) & 0xF00) | ((value >> 24) & 0xFF);
LOG_F(INFO, "AWAC subframe = %d, reg = %d, data = %08X\n", subframe, reg_num, data);
if (!subframe)
this->control_regs[reg_num] = data;
break;
default:
LOG_F(ERROR, "AWAC: unsupported register at offset 0x%X", offset);
}
}
#if 0
static void convert_data(const uint8_t *in, SoundIoChannelArea *out_buf, uint32_t frame_count)
{
uint16_t *p_in = (uint16_t *)in;
for (int i = 0; i < frame_count; i += 2, p_in += 4) {
*(uint16_t *)(out_buf[0].ptr) = BYTESWAP_16(p_in[0]);
out_buf[0].ptr += out_buf[0].step;
*(uint16_t *)(out_buf[0].ptr) = BYTESWAP_16(p_in[1]);
out_buf[0].ptr += out_buf[0].step;
*(uint16_t *)(out_buf[1].ptr) = BYTESWAP_16(p_in[2]);
out_buf[1].ptr += out_buf[1].step;
*(uint16_t *)(out_buf[1].ptr) = BYTESWAP_16(p_in[3]);
out_buf[1].ptr += out_buf[1].step;
}
}
static void insert_silence(SoundIoChannelArea *out_buf, uint32_t frame_count)
{
for (int i = 0; i < frame_count; i += 2) {
*(uint16_t *)(out_buf[0].ptr) = 0;
out_buf[0].ptr += out_buf[0].step;
*(uint16_t *)(out_buf[0].ptr) = 0;
out_buf[0].ptr += out_buf[0].step;
*(uint16_t *)(out_buf[1].ptr) = 0;
out_buf[1].ptr += out_buf[1].step;
*(uint16_t *)(out_buf[1].ptr) = 0;
out_buf[1].ptr += out_buf[1].step;
}
}
#endif
#if 0
static void sound_out_callback(struct SoundIoOutStream *outstream,
int frame_count_min, int frame_count_max)
{
int err, frame_count;
uint8_t *p_in;
uint32_t buf_len, rem_len, got_len;
struct SoundIoChannelArea *areas;
DMAChannel *dma_ch = (DMAChannel *)outstream->userdata; /* C API baby! */
int n_channels = outstream->layout.channel_count;
bool stop = false;
//if (!dma_ch->is_active()) {
// soundio_outstream_clear_buffer(outstream);
// soundio_outstream_pause(outstream, true);
// return;
//}
if (frame_count_max > 512) {
frame_count = 512;
}
else {
frame_count = frame_count_max;
}
buf_len = (frame_count * n_channels) << 1;
//frame_count = frame_count_max;
//LOG_F(INFO, "frame_count_min=%d", frame_count_min);
//LOG_F(INFO, "frame_count_max=%d", frame_count_max);
//LOG_F(INFO, "channel count: %d", n_channels);
//LOG_F(INFO, "buf_len: %d", buf_len);
if ((err = soundio_outstream_begin_write(outstream, &areas, &frame_count))) {
LOG_F(ERROR, "unrecoverable stream error: %s\n", soundio_strerror(err));
return;
}
for (rem_len = buf_len; rem_len > 0; rem_len -= got_len) {
if (!dma_ch->get_data(rem_len, &got_len, &p_in)) {
//LOG_F(INFO, "SndCallback: got_len = %d", got_len);
convert_data(p_in, areas, got_len >> 2);
//LOG_F(9, "Converted sound data, len = %d", got_len);
} else { /* no more data */
//memset(buf, 0, rem_len); /* fill the buffer with silence */
//LOG_F(9, "Inserted silence, len = %d", rem_len);
/* fill the buffer with silence */
//LOG_F(ERROR, "rem_len=%d", rem_len);
insert_silence(areas, rem_len >> 2);
stop = true;
break;
}
}
if ((err = soundio_outstream_end_write(outstream))) {
LOG_F(ERROR, "unrecoverable stream error: %s\n", soundio_strerror(err));
return;
}
if (stop) {
LOG_F(INFO, "pausing result: %s",
soundio_strerror(soundio_outstream_pause(outstream, true)));
}
}
#endif
long AWACDevice::sound_out_callback(cubeb_stream *stream, void *user_data,
void const *input_buffer, void *output_buffer,
long req_frames)
{
uint8_t *p_in;
int16_t* in_buf, * out_buf;
uint32_t got_len;
long frames, out_frames;
AWACDevice *this_ptr = static_cast<AWACDevice*>(user_data); /* C API baby! */
if (!this_ptr->dma_out_ch->is_active()) {
return 0;
}
out_buf = (int16_t*)output_buffer;
out_frames = 0;
while (req_frames > 0) {
if (!this_ptr->dma_out_ch->get_data(req_frames << 2, &got_len, &p_in)) {
frames = got_len >> 2;
in_buf = (int16_t*)p_in;
for (int i = frames; i > 0; i--) {
out_buf[0] = BYTESWAP_16(in_buf[0]);
out_buf[1] = BYTESWAP_16(in_buf[1]);
in_buf += 2;
out_buf += 2;
}
req_frames -= frames;
out_frames += frames;
}
else {
break;
}
}
return out_frames;
}
void status_callback(cubeb_stream *stream, void *user_data, cubeb_state state)
{
LOG_F(9, "Cubeb status callback fired, status = %d", state);
}
void AWACDevice::open_stream(int sample_rate)
{
int err;
if ((err = this->snd_server->open_out_stream(sample_rate, sound_out_callback,
status_callback, (void *)this))) {
LOG_F(ERROR, "AWAC: unable to open sound output stream: %d", err);
this->out_stream_ready = false;
} else {
this->out_sample_rate = sample_rate;
this->out_stream_ready = true;
}
}
void AWACDevice::dma_start()
{
int err;
if (!this->out_stream_ready) {
this->open_stream(awac_freqs[(this->snd_ctrl_reg >> 8) & 7]);
} else if (this->out_sample_rate != awac_freqs[(this->snd_ctrl_reg >> 8) & 7]) {
snd_server->close_out_stream();
this->open_stream(awac_freqs[(this->snd_ctrl_reg >> 8) & 7]);
} else {
LOG_F(ERROR, "AWAC: unpausing attempted!");
return;
}
if (!this->out_stream_ready) {
return;
}
if ((err = snd_server->start_out_stream())) {
LOG_F(ERROR, "Could not start sound output stream");
}
}
void AWACDevice::dma_end()
{
}
+141
View File
@@ -0,0 +1,141 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** AWAC sound devices family definitions.
Audio Waveform Aplifier and Converter (AWAC) is a family of custom audio
chips used in Power Macintosh.
*/
#ifndef AWAC_H
#define AWAC_H
#include "dbdma.h"
#include "i2c.h"
#include "soundserver.h"
#include <cinttypes>
#include <thirdparty/SDL2/include/SDL.h>
/** AWAC registers offsets. */
enum {
AWAC_SOUND_CTRL_REG = 0x00,
AWAC_CODEC_CTRL_REG = 0x10,
AWAC_CODEC_STATUS_REG = 0x20,
};
/** AWAC manufacturer and revision. */
#define AWAC_MAKER_CRYSTAL 1
#define AWAC_REV_SCREAMER 3
/** Apple source calls this kValidData but doesn't explain
what it actually means. It seems like it's used to check
if the sound codec is available.
*/
#define AWAC_AVAILABLE 0x40
/** Audio processor chip (TDA7433) emulation. */
class AudioProcessor : public I2CDevice {
public:
AudioProcessor() = default;
~AudioProcessor() = default;
void start_transaction() {
this->pos = 0;
};
bool send_subaddress(uint8_t sub_addr) {
if ((sub_addr & 0xF) > 6)
return false; /* invalid subaddress -> no acknowledge */
this->sub_addr = sub_addr & 0xF;
this->auto_inc = !!(sub_addr & 0x10);
LOG_F(INFO, "TDA7433 subaddress = 0x%X, auto increment = %d", this->sub_addr, this->auto_inc);
this->pos++;
return true;
};
bool send_byte(uint8_t data) {
if (!this->pos) {
return send_subaddress(data);
} else if (this->sub_addr <= 6) {
LOG_F(INFO, "TDA7433 byte 0x%X received", data);
this->regs[this->sub_addr] = data;
if (this->auto_inc) {
this->sub_addr++;
}
return true;
} else {
return false; /* invalid sub_addr -> no acknowledge */
}
};
bool receive_byte(uint8_t* p_data) {
*p_data = this->regs[this->sub_addr];
LOG_F(INFO, "TDA7433 byte 0x%X sent", *p_data);
return true;
};
private:
uint8_t regs[7]; /* control registers, see TDA7433 datasheet */
uint8_t sub_addr;
int pos;
int auto_inc;
};
class AWACDevice : public DMACallback {
public:
AWACDevice();
~AWACDevice();
void set_dma_out(DMAChannel* dma_out_ch);
uint32_t snd_ctrl_read(uint32_t offset, int size);
void snd_ctrl_write(uint32_t offset, uint32_t value, int size);
/* DMACallback methods */
void dma_start();
void dma_end();
protected:
void open_stream(int sample_rate);
private:
static long sound_out_callback(cubeb_stream* stream, void* user_data,
void const* input_buffer, void* output_buffer,
long req_frames);
uint32_t snd_ctrl_reg = {0};
uint16_t control_regs[8] = {0}; /* control registers, each 12-bits wide */
uint8_t is_busy = 0;
AudioProcessor* audio_proc;
SoundServer *snd_server;
bool out_stream_ready;
int out_sample_rate;
DMAChannel *dma_out_ch;
};
#endif /* AWAC_H */
+261
View File
@@ -0,0 +1,261 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Descriptor-based direct memory access emulation. */
#include "dbdma.h"
#include "cpu/ppc/ppcmmu.h"
#include "endianswap.h"
#include <cinttypes>
#include <cstring>
#include <thirdparty/loguru/loguru.hpp>
void DMAChannel::get_next_cmd(uint32_t cmd_addr, DMACmd* p_cmd) {
/* load DMACmd from physical memory */
memcpy((uint8_t*)p_cmd, mmu_get_dma_mem(cmd_addr, 16), 16);
}
uint8_t DMAChannel::interpret_cmd() {
DMACmd cmd_struct;
get_next_cmd(this->cmd_ptr, &cmd_struct);
this->ch_stat &= ~CH_STAT_WAKE; /* clear wake bit (DMA spec, 5.5.3.4) */
switch (cmd_struct.cmd_key >> 4) {
case 0:
LOG_F(9, "Executing DMA Command OUTPUT_MORE");
if (cmd_struct.cmd_key & 7) {
LOG_F(ERROR, "Key > 0 not implemented");
break;
}
if (cmd_struct.cmd_bits & 0x3F) {
LOG_F(ERROR, "non-zero i/b/w not implemented");
break;
}
// this->dma_cb->dma_push(
// mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count),
// cmd_struct.req_count);
this->queue_data = mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count);
this->queue_len = cmd_struct.req_count;
this->cmd_ptr += 16;
break;
case 1:
LOG_F(9, "Executing DMA Command OUTPUT_LAST");
if (cmd_struct.cmd_key & 7) {
LOG_F(ERROR, "Key > 0 not implemented");
break;
}
if (cmd_struct.cmd_bits & 0x3F) {
LOG_F(ERROR, "non-zero i/b/w not implemented");
break;
}
// this->dma_cb->dma_push(
// mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count),
// cmd_struct.req_count);
this->queue_data = mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count);
this->queue_len = cmd_struct.req_count;
this->cmd_ptr += 16;
break;
case 2:
LOG_F(ERROR, "Unsupported DMA Command INPUT_MORE");
break;
case 3:
LOG_F(ERROR, "Unsupported DMA Command INPUT_LAST");
break;
case 4:
LOG_F(ERROR, "Unsupported DMA Command STORE_QUAD");
break;
case 5:
LOG_F(ERROR, "Unsupported DMA Command LOAD_QUAD");
break;
case 6:
LOG_F(INFO, "Unsupported DMA Command NOP");
break;
case 7:
LOG_F(INFO, "DMA Command: 7 (STOP)");
this->ch_stat &= ~CH_STAT_ACTIVE;
break;
default:
LOG_F(ERROR, "Unsupported DMA command 0x%X", cmd_struct.cmd_key >> 4);
this->ch_stat |= CH_STAT_DEAD;
this->ch_stat &= ~CH_STAT_ACTIVE;
}
return (cmd_struct.cmd_key >> 4);
}
uint32_t DMAChannel::reg_read(uint32_t offset, int size) {
uint32_t res = 0;
if (size != 4) {
LOG_F(WARNING, "Unsupported non-DWORD read from DMA channel");
return 0;
}
switch (offset) {
case DMAReg::CH_CTRL:
res = 0; /* ChannelControl reads as 0 (DBDMA spec 5.5.1, table 74) */
break;
case DMAReg::CH_STAT:
res = BYTESWAP_32(this->ch_stat);
break;
default:
LOG_F(WARNING, "Unsupported DMA channel register 0x%X", offset);
}
return res;
}
void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
uint16_t mask, old_stat, new_stat;
if (size != 4) {
LOG_F(WARNING, "Unsupported non-DWORD write to DMA channel");
return;
}
value = BYTESWAP_32(value);
old_stat = this->ch_stat;
switch (offset) {
case DMAReg::CH_CTRL:
mask = value >> 16;
new_stat = (value & mask & 0xF0FFU) | (old_stat & ~mask);
LOG_F(INFO, "New ChannelStatus value = 0x%X", new_stat);
if ((new_stat & CH_STAT_RUN) != (old_stat & CH_STAT_RUN)) {
if (new_stat & CH_STAT_RUN) {
new_stat |= CH_STAT_ACTIVE;
this->ch_stat = new_stat;
this->start();
} else {
new_stat &= ~CH_STAT_ACTIVE;
new_stat &= ~CH_STAT_DEAD;
this->ch_stat = new_stat;
this->abort();
}
} else if ((new_stat & CH_STAT_WAKE) != (old_stat & CH_STAT_WAKE)) {
new_stat |= CH_STAT_ACTIVE;
this->ch_stat = new_stat;
this->resume();
} else if ((new_stat & CH_STAT_PAUSE) != (old_stat & CH_STAT_PAUSE)) {
if (new_stat & CH_STAT_PAUSE) {
new_stat &= ~CH_STAT_ACTIVE;
this->ch_stat = new_stat;
this->pause();
}
}
if (new_stat & CH_STAT_FLUSH) {
LOG_F(WARNING, "DMA flush not implemented!");
new_stat &= ~CH_STAT_FLUSH;
this->ch_stat = new_stat;
}
break;
case DMAReg::CH_STAT:
break; /* ingore writes to ChannelStatus */
case DMAReg::CMD_PTR_LO:
if (!(this->ch_stat & CH_STAT_RUN) && !(this->ch_stat & CH_STAT_ACTIVE)) {
this->cmd_ptr = value;
LOG_F(INFO, "CommandPtrLo set to 0x%X", this->cmd_ptr);
}
break;
default:
LOG_F(WARNING, "Unsupported DMA channel register 0x%X", offset);
}
}
int DMAChannel::get_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data)
{
*avail_len = 0;
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
LOG_F(WARNING, "Dead/idle channel -> no more data");
return -1; /* dead or idle channel? -> no more data */
}
/* interpret DBDMA program until we get data or become idle */
while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
/* dequeue data if any */
if (this->queue_len) {
if (this->queue_len >= req_len) {
LOG_F(9, "Return req_len = %d data", req_len);
*p_data = this->queue_data;
*avail_len = req_len;
this->queue_len -= req_len;
this->queue_data += req_len;
} else { /* return less data than req_len */
LOG_F(9, "Return queue_len = %d data", this->queue_len);
*p_data = this->queue_data;
*avail_len = this->queue_len;
this->queue_len = 0;
}
return 0; /* tell the caller there is more data */
}
return -1; /* tell the caller there is no more data */
}
bool DMAChannel::is_active()
{
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false;
}
else {
return true;
}
}
void DMAChannel::start()
{
if (this->ch_stat & CH_STAT_PAUSE) {
LOG_F(WARNING, "Cannot start DMA channel, PAUSE bit is set");
return;
}
LOG_F(INFO, "Starting DMA channel, stat = 0x%X", this->ch_stat);
this->queue_len = 0;
this->dma_cb->dma_start();
}
void DMAChannel::resume() {
if (this->ch_stat & CH_STAT_PAUSE) {
LOG_F(WARNING, "Cannot resume DMA channel, PAUSE bit is set");
return;
}
LOG_F(INFO, "Resuming DMA channel");
}
void DMAChannel::abort() {
LOG_F(INFO, "Aborting DMA channel");
}
void DMAChannel::pause() {
LOG_F(INFO, "Pausing DMA channel");
this->dma_cb->dma_end();
}
+101
View File
@@ -0,0 +1,101 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Descriptor-based direct memory access emulation.
Official documentation can be found in the fifth chapter of the book
"Macintosh Technology in the Common Hardware Reference Platform"
by Apple Computer, Inc.
*/
#ifndef DB_DMA_H
#define DB_DMA_H
#include <cinttypes>
/** DBDMA Channel registers offsets */
enum DMAReg : uint32_t {
CH_CTRL = 0,
CH_STAT = 4,
CMD_PTR_LO = 12,
};
/** Channel Status bits (DBDMA spec, 5.5.3) */
enum {
CH_STAT_ACTIVE = 0x400,
CH_STAT_DEAD = 0x800,
CH_STAT_WAKE = 0x1000,
CH_STAT_FLUSH = 0x2000,
CH_STAT_PAUSE = 0x4000,
CH_STAT_RUN = 0x8000
};
/** DBDMA command (DBDMA spec, 5.6.1) - all fields are little-endian! */
typedef struct DMACmd {
uint16_t req_count;
uint8_t cmd_bits;
uint8_t cmd_key;
uint32_t address;
uint32_t cmd_arg;
uint16_t res_count;
uint16_t xfer_stat;
} DMACmd;
class DMACallback {
public:
virtual void dma_start(void) = 0;
virtual void dma_end(void) = 0;
//virtual void dma_push(uint8_t *buf, int size) = 0;
//virtual void dma_pull(uint8_t *buf, int size) = 0;
};
class DMAChannel {
public:
DMAChannel(DMACallback* cb) {
this->dma_cb = cb;
};
~DMAChannel() = default;
uint32_t reg_read(uint32_t offset, int size);
void reg_write(uint32_t offset, uint32_t value, int size);
int get_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data);
bool is_active();
protected:
void get_next_cmd(uint32_t cmd_addr, DMACmd* p_cmd);
uint8_t interpret_cmd(void);
void start(void);
void resume(void);
void abort(void);
void pause(void);
private:
DMACallback* dma_cb = 0;
uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0;
uint32_t queue_len;
uint8_t* queue_data;
};
#endif /* DB_DMA_H */
+209
View File
@@ -0,0 +1,209 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "displayid.h"
#include <thirdparty/loguru/loguru.hpp>
DisplayID::DisplayID() {
/* Initialize Apple monitor codes */
this->std_sense_code = 6;
this->ext_sense_code = 0x2B;
/* Initialize DDC I2C bus */
this->next_state = I2CState::STOP;
this->prev_state = I2CState::STOP;
this->last_sda = 1;
this->last_scl = 1;
this->data_out = 0x3000;
this->data_ptr = 0;
/* DDC sense mode is on by default */
this->i2c_on = true;
}
uint16_t DisplayID::set_result(uint8_t sda, uint8_t scl) {
this->last_sda = sda;
this->last_scl = scl;
if (scl) {
this->data_out |= 0x1000;
} else {
this->data_out &= ~0x1000U;
}
if (sda) {
this->data_out |= 0x2000;
} else {
this->data_out &= ~0x2000U;
}
return this->data_out;
}
uint16_t DisplayID::read_monitor_sense(uint16_t data, uint16_t dirs) {
uint8_t scl, sda;
uint16_t result;
if ((dirs & 0x3100) == 0 && (data & 0x3100) == 0x3100) {
LOG_F(WARNING, "DisplayID: Hackish Monitor ID Switch activated!");
this->i2c_on = false;
}
if (this->i2c_on) {
/* if GPIO pins are in the output mode, pick up their values
In the input mode, GPIO pins will be read "high" */
scl = (dirs & 0x1000) ? !!(data & 0x1000) : 1;
sda = (dirs & 0x2000) ? !!(data & 0x2000) : 1;
return update_ddc_i2c(sda, scl);
} else { /* Apple legacy monitor codes (see Technical Note HW30) */
switch (dirs & 0x3100) {
case 0:
result = ((this->std_sense_code & 6) << 11) | ((this->std_sense_code & 1) << 8);
break;
case 0x2000: /* Sense line 2 is low */
result = ((this->ext_sense_code & 0x20) << 7) | ((this->ext_sense_code & 0x10) << 4);
break;
case 0x1000: /* Sense line 1 is low */
result = ((this->ext_sense_code & 8) << 10) | ((this->ext_sense_code & 4) << 6);
break;
case 0x100: /* Sense line 0 is low */
result = ((this->ext_sense_code & 2) << 12) | ((this->ext_sense_code & 1) << 12);
break;
default:
result = 0x3100U;
}
return result;
}
}
uint16_t DisplayID::update_ddc_i2c(uint8_t sda, uint8_t scl) //(uint16_t data, uint16_t dirs)
{
bool clk_gone_high = false;
if (scl != this->last_scl) {
this->last_scl = scl;
if (scl) {
clk_gone_high = true;
}
}
if (sda != this->last_sda) {
/* START = SDA goes high to low while SCL is high */
/* STOP = SDA goes low to high while SCL is high */
if (this->last_scl) {
if (!sda) {
LOG_F(9, "DDC-I2C: START condition detected!");
this->next_state = I2CState::DEV_ADDR;
this->bit_count = 0;
} else {
LOG_F(9, "DDC-I2C: STOP condition detected!");
this->next_state = I2CState::STOP;
}
}
return set_result(sda, scl);
}
if (!clk_gone_high) {
return set_result(sda, scl);
}
switch (this->next_state) {
case I2CState::STOP:
break;
case I2CState::ACK:
this->bit_count = 0;
this->byte = 0;
switch (this->prev_state) {
case I2CState::DEV_ADDR:
if ((dev_addr & 0xFE) == 0xA0) {
sda = 0; /* send ACK */
} else {
LOG_F(ERROR, "DDC-I2C: unknown device address 0x%X", this->dev_addr);
sda = 1; /* send NACK */
}
if (this->dev_addr & 1) {
this->next_state = I2CState::DATA;
this->data_ptr = this->edid;
this->byte = *(this->data_ptr++);
} else {
this->next_state = I2CState::REG_ADDR;
}
break;
case I2CState::REG_ADDR:
this->next_state = I2CState::DATA;
if (!this->reg_addr) {
sda = 0; /* send ACK */
} else {
LOG_F(ERROR, "DDC-I2C: unknown register address 0x%X", this->reg_addr);
sda = 1; /* send NACK */
}
break;
case I2CState::DATA:
this->next_state = I2CState::DATA;
if (dev_addr & 1) {
if (!sda) {
/* load next data byte */
this->byte = *(this->data_ptr++);
} else {
LOG_F(ERROR, "DDC-I2C: Oops! NACK received");
}
} else {
sda = 0; /* send ACK */
}
break;
}
break;
case I2CState::DEV_ADDR:
case I2CState::REG_ADDR:
this->byte = (this->byte << 1) | this->last_sda;
if (this->bit_count++ >= 7) {
this->bit_count = 0;
this->prev_state = this->next_state;
this->next_state = I2CState::ACK;
if (this->prev_state == I2CState::DEV_ADDR) {
LOG_F(9, "DDC-I2C: device address received, addr=0x%X", this->byte);
this->dev_addr = this->byte;
} else {
LOG_F(9, "DDC-I2C: register address received, addr=0x%X", this->byte);
this->reg_addr = this->byte;
}
}
break;
case I2CState::DATA:
sda = (this->byte >> (7 - this->bit_count)) & 1;
if (this->bit_count++ >= 7) {
this->bit_count = 0;
this->prev_state = this->next_state;
this->next_state = I2CState::ACK;
}
break;
}
return set_result(sda, scl);
}
+102
View File
@@ -0,0 +1,102 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file DisplayID class definitions.
DisplayID is a special purpose class for handling display
identification (aka Monitor Plug-n-Play) as required by
video cards.
DisplayID provides two methods for display identification:
- Apple monitor sense codes as described in the Technical Note HW30
- Display Data Channel (DDC) standardized by VESA
*/
#ifndef DISPLAY_ID_H
#define DISPLAY_ID_H
#include <cinttypes>
/** I2C bus states. */
enum I2CState : uint8_t {
STOP = 0, /* transaction started */
START = 1, /* transaction ended (idle) */
DEV_ADDR = 2, /* receiving device address */
REG_ADDR = 3, /* receiving register address */
DATA = 4, /* sending/receiving data */
ACK = 5, /* sending/receiving acknowledge */
NACK = 6 /* no acknowledge (error) */
};
class DisplayID {
public:
DisplayID();
~DisplayID() = default;
uint16_t read_monitor_sense(uint16_t data, uint16_t dirs);
protected:
uint16_t set_result(uint8_t sda, uint8_t scl);
uint16_t update_ddc_i2c(uint8_t sda, uint8_t scl);
private:
bool i2c_on;
uint8_t std_sense_code;
uint8_t ext_sense_code;
/* DDC I2C variables. */
uint8_t next_state;
uint8_t prev_state;
uint8_t last_sda;
uint8_t last_scl;
uint16_t data_out;
int bit_count; /* number of bits processed so far */
uint8_t byte; /* byte value being currently transferred */
uint8_t dev_addr; /* current device address */
uint8_t reg_addr; /* current register address */
uint8_t* data_ptr; /* ptr to data byte to be transferred next */
uint8_t edid[128] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x06, 0x10, 0x02, 0x9d, 0x01, 0x01, 0x01,
0x01, 0x08, 0x09, 0x01, 0x01, 0x68, 0x20, 0x18, 0x28, 0xe8, 0x04, 0x89, 0xa0, 0x57, 0x4a,
0x9b, 0x26, 0x12, 0x48, 0x4c, 0x31, 0x2b, 0x80, 0x31, 0x59, 0x45, 0x59, 0x61, 0x59, 0xa9,
0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x60, 0x16, 0x40, 0x40, 0x31, 0x70,
0x2b, 0x20, 0x20, 0x40, 0x23, 0x00, 0x38, 0xea, 0x10, 0x00, 0x00, 0x18, 0x48, 0x3f, 0x40,
0x32, 0x62, 0xb0, 0x32, 0x40, 0x40, 0xc2, 0x13, 0x00, 0x38, 0xea, 0x10, 0x00, 0x00, 0x18,
0x00, 0x00, 0x00, 0xfd, 0x00, 0x30, 0xa0, 0x1e, 0x55, 0x10, 0x00, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x53, 0x74, 0x75, 0x64, 0x69, 0x6f, 0x44,
0x73, 0x70, 0x6c, 0x79, 0x31, 0x37, 0x00, 0x19};
/* More EDID:
00ff ffff ffff ff00 5a63 5151 0341 0000
240a 0102 1f28 1eb3 e850 69a7 5148 9b24
0e48 4cff ff80 3159 4559 6159 714f 8140
8199 a940 a94f 0000 00ff 0053 5a30 3336
3136 3634 330a 2020 0000 00fd 0032 b41e
61ff 000a 2020 2020 2020 0000 00fc 0056
6965 7753 6f6e 6963 2047 3831 0000 00fc
0030 2d34 4d0a 2020 2020 2020 2020 00f7
*/
};
#endif /* DISPLAY_ID_H */
+141 -58
View File
@@ -1,14 +1,33 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
#include <cinttypes>
#include <iostream>
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "awacs.h"
#include "dbdma.h"
#include "machines/machinebase.h"
#include "macio.h"
#include "viacuda.h"
#include <cinttypes>
#include <iostream>
#include <thirdparty/loguru/loguru.hpp>
#include <cpu/ppc/ppcemu.h>
/** Heathrow Mac I/O device emulation.
@@ -17,67 +36,94 @@
using namespace std;
HeathrowIC::HeathrowIC() : PCIDevice("mac-io/heathrow")
{
HeathrowIC::HeathrowIC() : PCIDevice("mac-io/heathrow") {
this->nvram = new NVram();
this->viacuda = new ViaCuda();
this->nvram = new NVram();
gMachineObj->add_subdevice("ViaCuda", this->viacuda);
this->screamer = new AWACDevice();
this->snd_out_dma = new DMAChannel(this->screamer);
this->screamer->set_dma_out(this->snd_out_dma);
}
HeathrowIC::~HeathrowIC()
{
HeathrowIC::~HeathrowIC() {
if (this->nvram)
delete(this->nvram);
delete (this->nvram);
if (this->viacuda)
delete(this->viacuda);
delete (this->viacuda);
}
uint32_t HeathrowIC::pci_cfg_read(uint32_t reg_offs, uint32_t size)
{
uint32_t HeathrowIC::pci_cfg_read(uint32_t reg_offs, uint32_t size) {
return this->pci_cfg_hdr[reg_offs & 0xFF];
}
void HeathrowIC::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size)
{
switch(reg_offs) {
case CFG_REG_BAR0: // base address register
value = LE2BE(value);
void HeathrowIC::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) {
switch (reg_offs) {
case CFG_REG_BAR0: // base address register
value = LE2BE(value);
if (value == 0xFFFFFFFF) {
cout << this->name << " err: BAR0 block size determination not "
<< "implemented yet" << endl;
LOG_F(
ERROR,
"%s err: BAR0 block size determination not \
implemented yet \n",
this->name.c_str());
} else if (value & 1) {
cout << this->name << " err: BAR0 I/O space not supported!" << endl;
LOG_F(ERROR, "%s err: BAR0 I/O space not supported! \n", this->name.c_str());
} else if (value & 0x06) {
cout << this->name << " err: BAR0 64-bit I/O space not supported!"
<< endl;
LOG_F(ERROR, "%s err: BAR0 64-bit I/O space not supported! \n", this->name.c_str());
} else {
this->base_addr = value & 0xFFF80000;
this->host_instance->pci_register_mmio_region(this->base_addr, 0x80000, this);
cout << this->name << " base address set to " << hex << this->base_addr
<< endl;
LOG_F(INFO, "%s base address set to %x \n", this->name.c_str(), this->base_addr);
}
break;
}
}
uint32_t HeathrowIC::read(uint32_t offset, int size)
{
uint32_t HeathrowIC::dma_read(uint32_t offset, int size) {
uint32_t res = 0;
cout << this->name << ": reading from offset " << hex << offset << endl;
switch (offset >> 8) {
case 8:
res = this->snd_out_dma->reg_read(offset & 0xFF, size);
break;
default:
LOG_F(WARNING, "Unsupported DMA channel read, offset=0x%X", offset);
}
return res;
}
void HeathrowIC::dma_write(uint32_t offset, uint32_t value, int size) {
switch (offset >> 8) {
case 8:
this->snd_out_dma->reg_write(offset & 0xFF, value, size);
break;
default:
LOG_F(WARNING, "Unsupported DMA channel write, offset=0x%X, val=0x%X", offset, value);
}
}
uint32_t HeathrowIC::read(uint32_t reg_start, uint32_t offset, int size) {
uint32_t res = 0;
LOG_F(9, "%s: reading from offset %x \n", this->name.c_str(), offset);
unsigned sub_addr = (offset >> 12) & 0x7F;
switch(sub_addr) {
switch (sub_addr) {
case 0:
res = mio_ctrl_read(offset, size);
break;
case 8:
cout << "DMA channel register space" << endl;
res = dma_read(offset - 0x8000, size);
break;
case 0x14:
cout << "AWACS-Screamer register space" << endl;
res = this->screamer->snd_ctrl_read(offset - 0x14000, size);
break;
case 0x16:
case 0x17:
@@ -87,28 +133,27 @@ uint32_t HeathrowIC::read(uint32_t offset, int size)
if (sub_addr >= 0x60) {
res = this->nvram->read_byte((offset - 0x60000) >> 4);
} else {
cout << "unmapped I/O space: " << hex << offset << endl;
LOG_F(WARNING, "Attempting to read unmapped I/O space: %x \n", offset);
}
}
return res;
}
void HeathrowIC::write(uint32_t offset, uint32_t value, int size)
{
cout << this->name << ": writing to offset " << hex << offset << endl;
void HeathrowIC::write(uint32_t reg_start, uint32_t offset, uint32_t value, int size) {
LOG_F(9, "%s: writing to offset %x \n", this->name.c_str(), offset);
unsigned sub_addr = (offset >> 12) & 0x7F;
switch(sub_addr) {
switch (sub_addr) {
case 0:
mio_ctrl_write(offset, value, size);
break;
case 8:
cout << "DMA channel register space" << endl;
dma_write(offset - 0x8000, value, size);
break;
case 0x14:
cout << "AWACS-Screamer register space" << endl;
this->screamer->snd_ctrl_write(offset - 0x14000, value, size);
break;
case 0x16:
case 0x17:
@@ -118,56 +163,94 @@ void HeathrowIC::write(uint32_t offset, uint32_t value, int size)
if (sub_addr >= 0x60) {
this->nvram->write_byte((offset - 0x60000) >> 4, value);
} else {
cout << "unmapped I/O space: " << hex << offset << endl;
LOG_F(WARNING, "Attempting to write to unmapped I/O space: %x \n", offset);
}
}
}
uint32_t HeathrowIC::mio_ctrl_read(uint32_t offset, int size)
{
uint32_t HeathrowIC::mio_ctrl_read(uint32_t offset, int size) {
uint32_t res = 0;
switch(offset & 0xFF) {
switch (offset & 0xFC) {
case 0x14:
LOG_F(9, "read from MIO:Int_Mask2 register \n");
res = this->int_mask2;
break;
case 0x18:
LOG_F(9, "read from MIO:Int_Clear2 register \n");
res = this->int_clear2;
break;
case 0x1C:
LOG_F(9, "read from MIO:Int_Levels2 register \n");
res = this->int_levels2;
break;
case 0x24:
cout << "read from MIO:Int_Mask1 register" << endl;
LOG_F(9, "read from MIO:Int_Mask1 register \n");
res = this->int_mask1;
break;
case 0x28:
cout << "read from MIO:Int_Clear1 register" << endl;
LOG_F(9, "read from MIO:Int_Clear1 register \n");
res = this->int_clear1;
break;
case 0x2C:
LOG_F(9, "read from MIO:Int_Levels1 register \n");
res = this->int_levels1;
break;
case 0x34: /* heathrowIDs / HEATHROW_MBCR (Linux): media bay config reg? */
res = 0xF0700000UL;
LOG_F(9, "read from MIO:ID register at Address %x \n", ppc_state.pc);
res = this->macio_id;
break;
case 0x38:
cout << "read from MIO:Feat_Ctrl register" << endl;
LOG_F(9, "read from MIO:Feat_Ctrl register \n");
res = this->feat_ctrl;
break;
default:
cout << "unknown MIO register at " << hex << offset << endl;
LOG_F(WARNING, "read from unknown MIO register at %x \n", offset);
break;
}
return res;
}
void HeathrowIC::mio_ctrl_write(uint32_t offset, uint32_t value, int size)
{
switch(offset & 0xFF) {
void HeathrowIC::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
switch (offset & 0xFC) {
case 0x14:
LOG_F(9, "write %x to MIO:Int_Mask2 register \n", value);
this->int_mask2 = value;
break;
case 0x18:
LOG_F(9, "write %x to MIO:Int_Clear2 register \n", value);
this->int_clear2 = value;
break;
case 0x1C:
LOG_F(9, "write %x to MIO:Int_Levels2 register \n", value);
this->int_levels2 = value;
break;
case 0x24:
cout << "write " << hex << value << " to MIO:Int_Mask1 register" << endl;
LOG_F(9, "write %x to MIO:Int_Mask1 register \n", value);
this->int_mask1 = value;
break;
case 0x28:
cout << "write " << hex << value << " to MIO:Int_Clear1 register" << endl;
LOG_F(9, "write %x to MIO:Int_Clear1 register \n", value);
this->int_clear1 = value;
break;
case 0x2C:
LOG_F(9, "write %x to MIO:Int_Levels1 register \n", value);
this->int_levels1 = value;
break;
case 0x34:
LOG_F(WARNING, "Attempted to write %x to MIO:ID at %x; Address : %x \n", value, offset, ppc_state.pc);
break;
case 0x38:
cout << "write " << hex << value << " to MIO:Feat_Ctrl register" << endl;
LOG_F(9, "write %x to MIO:Feat_Ctrl register \n", value);
this->feat_ctrl = value;
break;
case 0x3C:
LOG_F(9, "write %x to MIO:Aux_Ctrl register \n", value);
this->aux_ctrl = value;
break;
default:
cout << "unknown MIO register at " << hex << offset << endl;
LOG_F(WARNING, "write %x to unknown MIO register at %x \n", value, offset);
break;
}
}
+62
View File
@@ -0,0 +1,62 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef HW_COMPONENT_H
#define HW_COMPONENT_H
#include <string>
/** types of different HW components */
enum HWCompType : int {
UNKNOWN = 0, /* unknown component type */
MEM_CTRL = 10, /* memory controller */
ROM = 20, /* read-only memory */
RAM = 30, /* random access memory */
MMIO_DEV = 40, /* memory mapped I/O device */
PCI_HOST = 50, /* PCI host */
PCI_DEV = 51, /* PCI device */
I2C_HOST = 60, /* I2C host */
I2C_DEV = 61, /* I2C device */
ADB_HOST = 70, /* ADB host */
ADB_DEV = 71, /* ADB device */
SND_SERVER = 100, /* host sound server */
};
/** Abstract base class for HW components. */
class HWComponent {
public:
virtual ~HWComponent() = default;
virtual std::string get_name(void) {
return this->name;
};
virtual void set_name(std::string name) {
this->name = name;
};
virtual bool supports_type(HWCompType type) = 0;
protected:
std::string name;
};
#endif /* HW_COMPONENT_H */
+96
View File
@@ -0,0 +1,96 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file I2C bus emulation.
Author: Max Poliakovski
*/
#ifndef I2C_H
#define I2C_H
#include <stdexcept>
#include <cstring>
#include <string>
#include <thirdparty/loguru/loguru.hpp>
/** Base class for I2C devices */
class I2CDevice {
public:
virtual void start_transaction() = 0;
virtual bool send_subaddress(uint8_t sub_addr) = 0;
virtual bool send_byte(uint8_t data) = 0;
virtual bool receive_byte(uint8_t* p_data) = 0;
};
/** Base class for I2C hosts */
class I2CBus {
public:
I2CBus() {
std::memset(this->dev_list, 0, sizeof(this->dev_list));
};
~I2CBus() {
std::memset(this->dev_list, 0, sizeof(this->dev_list));
};
virtual void register_device(uint8_t dev_addr, I2CDevice* dev_obj) {
if (this->dev_list[dev_addr]) {
throw std::invalid_argument(std::string("I2C address already taken!"));
}
this->dev_list[dev_addr] = dev_obj;
LOG_F(INFO, "New I2C device, address = 0x%X", dev_addr);
};
virtual bool start_transaction(uint8_t dev_addr) {
if (this->dev_list[dev_addr]) {
this->dev_list[dev_addr]->start_transaction();
return true;
} else {
return false;
}
};
virtual bool send_subaddress(uint8_t dev_addr, uint8_t sub_addr) {
if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */
}
return this->dev_list[dev_addr]->send_subaddress(sub_addr);
};
virtual bool send_byte(uint8_t dev_addr, uint8_t data) {
if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */
}
return this->dev_list[dev_addr]->send_byte(data);
};
virtual bool receive_byte(uint8_t dev_addr, uint8_t* p_data) {
if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */
}
return this->dev_list[dev_addr]->receive_byte(p_data);
};
protected:
I2CDevice* dev_list[128]; /* list of registered I2C devices */
};
#endif /* I2C_H */
+34 -5
View File
@@ -1,8 +1,30 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACHINE_ID_H
#define MACHINE_ID_H
#include <cinttypes>
#include "hwcomponent.h"
#include "mmiodevice.h"
#include <cinttypes>
/**
@file Contains definitions for PowerMacintosh machine ID registers.
@@ -22,13 +44,20 @@
*/
class GossamerID : public MMIODevice {
public:
GossamerID(const uint16_t id) { this->id = id, this->name = "Machine-id"; };
GossamerID(const uint16_t id) {
this->id = id, this->name = "Machine-id";
};
~GossamerID() = default;
uint32_t read(uint32_t offset, int size) {
return ((!offset && size == 2) ? this->id : 0); };
bool supports_type(HWCompType type) {
return type == HWCompType::MMIO_DEV;
};
void write(uint32_t offset, uint32_t value, int size) {}; /* not writable */
uint32_t read(uint32_t reg_start, uint32_t offset, int size) {
return ((!offset && size == 2) ? this->id : 0);
};
void write(uint32_t reg_start, uint32_t offset, uint32_t value, int size){}; /* not writable */
private:
uint16_t id;
+71 -26
View File
@@ -1,3 +1,24 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** MacIO device family emulation
Mac I/O (MIO) is a family of ASICs to bring support for Apple legacy
@@ -30,13 +51,16 @@
#ifndef MACIO_H
#define MACIO_H
#include <cinttypes>
#include "pcidevice.h"
#include "awacs.h"
#include "dbdma.h"
#include "hwcomponent.h"
#include "memctrlbase.h"
#include "mmiodevice.h"
#include "nvram.h"
#include "pcidevice.h"
#include "pcihost.h"
#include "viacuda.h"
#include "nvram.h"
#include <cinttypes>
/**
Heathrow ASIC emulation
@@ -62,50 +86,71 @@
VIA-CUDA register space: 0x00016000, size: 0x00002000
*/
class HeathrowIC : public PCIDevice
{
class HeathrowIC : public PCIDevice {
public:
using PCIDevice::name;
HeathrowIC();
~HeathrowIC();
void set_host(PCIHost *host_instance) {this->host_instance = host_instance;};
bool supports_type(HWCompType type) {
return type == HWCompType::MMIO_DEV;
};
/* PCI device methods */
bool supports_io_space(void) {
return false;
};
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
/* MMIO device methods */
uint32_t read(uint32_t offset, int size);
void write(uint32_t offset, uint32_t value, int size);
uint32_t read(uint32_t reg_start, uint32_t offset, int size);
void write(uint32_t reg_start, uint32_t offset, uint32_t value, int size);
protected:
uint32_t dma_read(uint32_t offset, int size);
void dma_write(uint32_t offset, uint32_t value, int size);
uint32_t mio_ctrl_read(uint32_t offset, int size);
void mio_ctrl_write(uint32_t offset, uint32_t value, int size);
private:
uint8_t pci_cfg_hdr[256] = {
0x6B, 0x10, // vendor ID: Apple Computer Inc.
0x10, 0x00, // device ID: Heathrow Mac I/O
0x00, 0x00, // PCI command (set to 0 at power-up?)
0x00, 0x00, // PCI status (set to 0 at power-up?)
0x01, // revision ID
0x6B,
0x10, // vendor ID: Apple Computer Inc.
0x10,
0x00, // device ID: Heathrow Mac I/O
0x00,
0x00, // PCI command (set to 0 at power-up?)
0x00,
0x00, // PCI status (set to 0 at power-up?)
0x01, // revision ID
// class code is reported in OF property "class-code" as 0xff0000
0x00, // standard programming
0x00, // subclass code
0xFF, // class code: unassigned
0x00, 0x00, // unknown defaults
0x00, 0x00 // unknown defaults
0x00, // standard programming
0x00, // subclass code
0xFF, // class code: unassigned
0x00,
0x00, // unknown defaults
0x00,
0x00 // unknown defaults
};
uint32_t int_mask1;
uint32_t int_clear1;
uint32_t feat_ctrl; // features control register
uint32_t int_mask2 = 0;
uint32_t int_clear2 = 0;
uint32_t int_levels2 = 0;
uint32_t int_mask1 = 0;
uint32_t int_clear1 = 0;
uint32_t int_levels1 = 0;
uint32_t macio_id = 0xF0700008UL;
uint32_t feat_ctrl = 0; // features control register
uint32_t aux_ctrl = 0; // aux features control register
/* device cells */
ViaCuda *viacuda; /* VIA cell with Cuda MCU attached to it */
NVram *nvram; /* NVRAM cell */
ViaCuda* viacuda; /* VIA cell with Cuda MCU attached to it */
NVram* nvram; /* NVRAM cell */
AWACDevice* screamer; /* Screamer audio codec instance */
DMAChannel* snd_out_dma;
};
#endif /* MACIO_H */
+36 -37
View File
@@ -1,38 +1,44 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
#include <string>
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <algorithm> // to shut up MSVC errors (:
#include <cstring>
#include <string>
#include <vector>
#include <algorithm> // to shut up MSVC errors (:
#include "memctrlbase.h"
MemCtrlBase::MemCtrlBase(std::string name)
{
this->name = name;
}
MemCtrlBase::~MemCtrlBase()
{
for (auto &reg : mem_regions) {
MemCtrlBase::~MemCtrlBase() {
for (auto& reg : mem_regions) {
if (reg)
delete(reg);
delete (reg);
}
this->mem_regions.clear();
this->address_map.clear();
}
AddressMapEntry *MemCtrlBase::find_range(uint32_t addr)
{
for (auto &entry : address_map) {
AddressMapEntry* MemCtrlBase::find_range(uint32_t addr) {
for (auto& entry : address_map) {
if (addr >= entry.start && addr <= entry.end)
return &entry;
}
@@ -41,16 +47,15 @@ AddressMapEntry *MemCtrlBase::find_range(uint32_t addr)
}
bool MemCtrlBase::add_mem_region(uint32_t start_addr, uint32_t size,
uint32_t dest_addr, uint32_t type, uint8_t init_val = 0)
{
bool MemCtrlBase::add_mem_region(
uint32_t start_addr, uint32_t size, uint32_t dest_addr, uint32_t type, uint8_t init_val = 0) {
AddressMapEntry entry;
/* error if a memory region for the given range already exists */
if (find_range(start_addr) || find_range(start_addr + size))
return false;
uint8_t *reg_content = new uint8_t[size];
uint8_t* reg_content = new uint8_t[size];
this->mem_regions.push_back(reg_content);
@@ -67,20 +72,17 @@ bool MemCtrlBase::add_mem_region(uint32_t start_addr, uint32_t size,
}
bool MemCtrlBase::add_rom_region(uint32_t start_addr, uint32_t size)
{
bool MemCtrlBase::add_rom_region(uint32_t start_addr, uint32_t size) {
return add_mem_region(start_addr, size, 0, RT_ROM);
}
bool MemCtrlBase::add_ram_region(uint32_t start_addr, uint32_t size)
{
bool MemCtrlBase::add_ram_region(uint32_t start_addr, uint32_t size) {
return add_mem_region(start_addr, size, 0, RT_RAM);
}
bool MemCtrlBase::add_mem_mirror(uint32_t start_addr, uint32_t dest_addr)
{
bool MemCtrlBase::add_mem_mirror(uint32_t start_addr, uint32_t dest_addr) {
AddressMapEntry entry, *ref_entry;
ref_entry = find_range(dest_addr);
@@ -100,9 +102,8 @@ bool MemCtrlBase::add_mem_mirror(uint32_t start_addr, uint32_t dest_addr)
}
bool MemCtrlBase::set_data(uint32_t reg_addr, const uint8_t *data, uint32_t size)
{
AddressMapEntry *ref_entry;
bool MemCtrlBase::set_data(uint32_t reg_addr, const uint8_t* data, uint32_t size) {
AddressMapEntry* ref_entry;
uint32_t cpy_size;
ref_entry = find_range(reg_addr);
@@ -116,9 +117,7 @@ bool MemCtrlBase::set_data(uint32_t reg_addr, const uint8_t *data, uint32_t size
}
bool MemCtrlBase::add_mmio_region(uint32_t start_addr, uint32_t size,
MMIODevice *dev_instance)
{
bool MemCtrlBase::add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance) {
AddressMapEntry entry;
/* error if another region for the given range already exists */
+41 -21
View File
@@ -1,52 +1,72 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MEMORY_CONTROLLER_BASE_H
#define MEMORY_CONTROLLER_BASE_H
#include "mmiodevice.h"
#include <cinttypes>
#include <string>
#include <vector>
#include "mmiodevice.h"
enum RangeType {
RT_ROM = 1, /* read-only memory */
RT_RAM = 2, /* random access memory */
RT_MMIO = 4, /* memory mapped I/O */
RT_MIRROR = 8 /* region mirror (content of another region is acessible
at some other address) */
RT_ROM = 1, /* read-only memory */
RT_RAM = 2, /* random access memory */
RT_MMIO = 4, /* memory mapped I/O */
RT_MIRROR = 8 /* region mirror (content of another region is acessible
at some other address) */
};
/** Defines the format for the address map entry. */
typedef struct AddressMapEntry {
uint32_t start; /* first address of the corresponding range */
uint32_t end; /* last address of the corresponding range */
uint32_t mirror; /* mirror address for RT_MIRROR */
uint32_t type; /* range type */
MMIODevice *devobj; /* pointer to device object */
unsigned char *mem_ptr; /* direct pointer to data for memory objects */
uint32_t start; /* first address of the corresponding range */
uint32_t end; /* last address of the corresponding range */
uint32_t mirror; /* mirror address for RT_MIRROR */
uint32_t type; /* range type */
MMIODevice* devobj; /* pointer to device object */
unsigned char* mem_ptr; /* direct pointer to data for memory objects */
} AddressMapEntry;
/** Base class for memory controllers. */
class MemCtrlBase {
public:
MemCtrlBase(std::string name);
MemCtrlBase() = default;
virtual ~MemCtrlBase();
virtual bool add_rom_region(uint32_t start_addr, uint32_t size);
virtual bool add_ram_region(uint32_t start_addr, uint32_t size);
virtual bool add_mem_mirror(uint32_t start_addr, uint32_t dest_addr);
virtual bool add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice *dev_instance);
virtual bool add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance);
virtual bool set_data(uint32_t reg_addr, const uint8_t *data, uint32_t size);
virtual bool set_data(uint32_t reg_addr, const uint8_t* data, uint32_t size);
AddressMapEntry *find_range(uint32_t addr);
AddressMapEntry* find_range(uint32_t addr);
protected:
bool add_mem_region(uint32_t start_addr, uint32_t size, uint32_t dest_addr, uint32_t type, uint8_t init_val);
std::string name;
bool add_mem_region(
uint32_t start_addr, uint32_t size, uint32_t dest_addr, uint32_t type, uint8_t init_val);
private:
std::vector<uint8_t *> mem_regions;
std::vector<uint8_t*> mem_regions;
std::vector<AddressMapEntry> address_map;
};
+26 -7
View File
@@ -1,18 +1,37 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MMIO_DEVICE_H
#define MMIO_DEVICE_H
#include "hwcomponent.h"
#include <cinttypes>
#include <string>
/** Abstract class representing a simple, memory-mapped I/O device */
class MMIODevice {
class MMIODevice : public HWComponent {
public:
virtual uint32_t read(uint32_t offset, int size) = 0;
virtual void write(uint32_t offset, uint32_t value, int size) = 0;
virtual ~MMIODevice() = default;
protected:
std::string name;
virtual uint32_t read(uint32_t reg_start, uint32_t offset, int size) = 0;
virtual void write(uint32_t reg_start, uint32_t offset, uint32_t value, int size) = 0;
virtual ~MMIODevice() = default;
};
#endif /* MMIO_DEVICE_H */
+125 -96
View File
@@ -1,43 +1,84 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** MPC106 (Grackle) emulation
Author: Max Poliakovski
*/
#include <iostream>
#include <cstring>
#include <cinttypes>
#include <cstring>
#include <iostream>
#include <thirdparty/loguru/loguru.hpp>
#include "memreadwrite.h"
#include "hwcomponent.h"
#include "memctrlbase.h"
#include "memaccess.h"
#include "mmiodevice.h"
#include "mpc106.h"
MPC106::MPC106() : MemCtrlBase("Grackle"), PCIDevice("Grackle PCI host bridge")
{
MPC106::MPC106() : MemCtrlBase(), PCIDevice("Grackle PCI host bridge") {
this->name = "Grackle";
/* add PCI/ISA I/O space, 64K for now */
add_mmio_region(0xFE000000, 0x10000, this);
/* add memory mapped I/O region for MPC106 registers */
add_mmio_region(0xFEC00000, 0x300000, this);
this->pci_0_bus.clear();
this->io_space_devs.clear();
}
MPC106::~MPC106()
{
MPC106::~MPC106() {
this->pci_0_bus.clear();
}
uint32_t MPC106::read(uint32_t offset, int size)
{
if (offset >= 0x200000) {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_read(size);
bool MPC106::supports_type(HWCompType type) {
if (type == HWCompType::MEM_CTRL || type == HWCompType::MMIO_DEV ||
type == HWCompType::PCI_HOST || type == HWCompType::PCI_DEV) {
return true;
} else {
return false;
}
}
uint32_t MPC106::read(uint32_t reg_start, uint32_t offset, int size) {
uint32_t result;
if (reg_start == 0xFE000000) {
/* broadcast I/O request to devices that support I/O space
until a device returns true that means "request accepted" */
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_read(offset, size, &result)) {
return result;
}
}
LOG_F(ERROR, "Attempt to read from unmapped PCI I/O space, offset=0x%X", offset);
} else {
if (offset >= 0x200000) {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_read(size);
}
}
/* FIXME: reading from CONFIG_ADDR is ignored for now */
@@ -45,24 +86,36 @@ uint32_t MPC106::read(uint32_t offset, int size)
return 0;
}
void MPC106::write(uint32_t offset, uint32_t value, int size)
{
if (offset < 0x200000) {
this->config_addr = value;
void MPC106::write(uint32_t reg_start, uint32_t offset, uint32_t value, int size) {
if (reg_start == 0xFE000000) {
/* broadcast I/O request to devices that support I/O space
until a device returns true that means "request accepted" */
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_write(offset, value, size)) {
return;
}
}
LOG_F(ERROR, "Attempt to write to unmapped PCI I/O space, offset=0x%X", offset);
} else {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_write(value, size);
if (offset < 0x200000) {
this->config_addr = value;
} else {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_write(value, size);
}
}
}
uint32_t MPC106::pci_read(uint32_t size)
{
uint32_t MPC106::pci_read(uint32_t size) {
int bus_num, dev_num, fun_num, reg_offs;
bus_num = (this->config_addr >> 8) & 0xFF;
if (bus_num) {
std::cout << this->name << " err: read attempt from non-local PCI bus, "
<< "config_addr = " << std::hex << this->config_addr << std::endl;
LOG_F(
ERROR,
"%s err: read attempt from non-local PCI bus, config_addr = %x \n",
this->name.c_str(),
this->config_addr);
return 0;
}
@@ -70,14 +123,17 @@ uint32_t MPC106::pci_read(uint32_t size)
fun_num = (this->config_addr >> 16) & 0x07;
reg_offs = (this->config_addr >> 24) & 0xFC;
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
return this->pci_cfg_read(reg_offs, size);
} else {
if (this->pci_0_bus.count(dev_num)) {
return this->pci_0_bus[dev_num]->pci_cfg_read(reg_offs, size);
} else {
std::cout << this->name << " err: read attempt from non-existing PCI device "
<< dev_num << std::endl;
LOG_F(
ERROR,
"%s err: read attempt from non-existing PCI device %d \n",
this->name.c_str(),
dev_num);
return 0;
}
}
@@ -85,14 +141,16 @@ uint32_t MPC106::pci_read(uint32_t size)
return 0;
}
void MPC106::pci_write(uint32_t value, uint32_t size)
{
void MPC106::pci_write(uint32_t value, uint32_t size) {
int bus_num, dev_num, fun_num, reg_offs;
bus_num = (this->config_addr >> 8) & 0xFF;
if (bus_num) {
std::cout << this->name << " err: write attempt to non-local PCI bus, "
<< "config_addr = " << std::hex << this->config_addr << std::endl;
LOG_F(
ERROR,
"%s err: write attempt to non-local PCI bus, config_addr = %x \n",
this->name.c_str(),
this->config_addr);
return;
}
@@ -100,125 +158,96 @@ void MPC106::pci_write(uint32_t value, uint32_t size)
fun_num = (this->config_addr >> 16) & 0x07;
reg_offs = (this->config_addr >> 24) & 0xFC;
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
this->pci_cfg_write(reg_offs, value, size);
} else {
if (this->pci_0_bus.count(dev_num)) {
this->pci_0_bus[dev_num]->pci_cfg_write(reg_offs, value, size);
} else {
std::cout << this->name << " err: write attempt to non-existing PCI device "
<< dev_num << std::endl;
LOG_F(
ERROR,
"%s err: write attempt to non-existing PCI device %d \n",
this->name.c_str(),
dev_num);
}
}
}
uint32_t MPC106::pci_cfg_read(uint32_t reg_offs, uint32_t size)
{
uint32_t MPC106::pci_cfg_read(uint32_t reg_offs, uint32_t size) {
#ifdef MPC106_DEBUG
printf("read from Grackle register %08X\n", reg_offs);
LOG_F(9, "read from Grackle register %08X\n", reg_offs);
#endif
switch(size) {
case 1:
return this->my_pci_cfg_hdr[reg_offs];
break;
case 2:
return READ_WORD_BE_A(&this->my_pci_cfg_hdr[reg_offs]);
break;
case 4:
return READ_DWORD_BE_A(&this->my_pci_cfg_hdr[reg_offs]);
break;
default:
std::cout << "MPC106 read error: invalid size parameter " << size
<< std::endl;
}
return 0;
return read_mem(&this->my_pci_cfg_hdr[reg_offs], size);
}
void MPC106::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size)
{
void MPC106::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) {
#ifdef MPC106_DEBUG
printf("write %08X to Grackle register %08X\n", value, reg_offs);
LOG_F(9, "write %08X to Grackle register %08X\n", value, reg_offs);
#endif
// FIXME: implement write-protection for read-only registers
switch(size) {
case 1:
this->my_pci_cfg_hdr[reg_offs] = value & 0xFF;
break;
case 2:
this->my_pci_cfg_hdr[reg_offs] = (value >> 8) & 0xFF;
this->my_pci_cfg_hdr[reg_offs+1] = value & 0xFF;
break;
case 4:
this->my_pci_cfg_hdr[reg_offs] = (value >> 24) & 0xFF;
this->my_pci_cfg_hdr[reg_offs+1] = (value >> 16) & 0xFF;
this->my_pci_cfg_hdr[reg_offs+2] = (value >> 8) & 0xFF;
this->my_pci_cfg_hdr[reg_offs+3] = value & 0xFF;
break;
default:
std::cout << "MPC106 read error: invalid size parameter " << size
<< std::endl;
}
write_mem(&this->my_pci_cfg_hdr[reg_offs], value, size);
if (this->my_pci_cfg_hdr[0xF2] & 8) {
#ifdef MPC106_DEBUG
std::cout << "MPC106: MCCR1[MEMGO] was set! " << std::endl;
LOG_F(9, "MPC106: MCCR1[MEMGO] was set! \n");
#endif
setup_ram();
}
}
bool MPC106::pci_register_device(int dev_num, PCIDevice *dev_instance)
{
if (this->pci_0_bus.count(dev_num)) // is dev_num already registered?
bool MPC106::pci_register_device(int dev_num, PCIDevice* dev_instance) {
if (this->pci_0_bus.count(dev_num)) // is dev_num already registered?
return false;
this->pci_0_bus[dev_num] = dev_instance;
dev_instance->set_host(this);
if (dev_instance->supports_io_space()) {
this->io_space_devs.push_back(dev_instance);
}
return true;
}
bool MPC106::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice *obj)
{
bool MPC106::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj) {
// FIXME: add sanity checks!
return this->add_mmio_region(start_addr, size, obj);
}
void MPC106::setup_ram()
{
void MPC106::setup_ram() {
uint32_t mem_start, mem_end, ext_mem_start, ext_mem_end, bank_start, bank_end;
uint32_t ram_size = 0;
uint8_t bank_en = this->my_pci_cfg_hdr[0xA0];
uint8_t bank_en = this->my_pci_cfg_hdr[0xA0];
for (int bank = 0; bank < 8; bank++) {
if (bank_en & (1 << bank)) {
if (bank < 4) {
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x80]);
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x80]);
ext_mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x88]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x90]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x98]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x90]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x98]);
} else {
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x84]);
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x84]);
ext_mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x8C]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x94]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x9C]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x94]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x9C]);
}
bank_start = (((ext_mem_start >> bank * 8) & 3) << 30) |
(((mem_start >> bank * 8) & 0xFF) << 20);
bank_end = (((ext_mem_end >> bank * 8) & 3) << 30) |
(((mem_end >> bank * 8) & 0xFF) << 20) | 0xFFFFFUL;
if (bank && bank_start != ram_size)
std::cout << "MPC106 error: RAM not contiguous!" << std::endl;
ram_size += bank_end + 1;
LOG_F(WARNING, "MPC106: RAM not contiguous! \n");
ram_size += bank_end - bank_start + 1;
}
}
if (!this->add_ram_region(0, ram_size)) {
std::cout << "MPC106 RAM allocation failed!" << std::endl;
LOG_F(ERROR, "MPC106 RAM allocation failed! \n");
}
}
+99 -94
View File
@@ -1,10 +1,23 @@
//DingusPPC - Prototype 5bf2
//Written by divingkatae
//(c)2018-20 (theweirdo)
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** MPC106 (Grackle) emulation
Author: Max Poliakovski
@@ -22,26 +35,27 @@
#ifndef MPC106_H_
#define MPC106_H_
#include <cinttypes>
#include <unordered_map>
#include "hwcomponent.h"
#include "memctrlbase.h"
#include "mmiodevice.h"
#include "pcidevice.h"
#include "pcihost.h"
#include <cinttypes>
#include <unordered_map>
class MPC106 : public MemCtrlBase, public PCIDevice, public PCIHost
{
class MPC106 : public MemCtrlBase, public PCIDevice, public PCIHost {
public:
using MemCtrlBase::name;
MPC106();
~MPC106();
uint32_t read(uint32_t offset, int size);
void write(uint32_t offset, uint32_t value, int size);
bool supports_type(HWCompType type);
uint32_t read(uint32_t reg_start, uint32_t offset, int size);
void write(uint32_t reg_start, uint32_t offset, uint32_t value, int size);
/* PCI host bridge API */
bool pci_register_device(int dev_num, PCIDevice *dev_instance);
bool pci_register_device(int dev_num, PCIDevice* dev_instance);
protected:
/* PCI access */
@@ -52,114 +66,105 @@ protected:
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
void set_host(PCIHost *host_instance) {}; // unimplemented for now
bool supports_io_space(void) {
return true;
};
/* PCI host bridge API */
//bool pci_register_device(int dev_num, PCIDevice *dev_instance);
bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice *obj);
bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj);
void setup_ram(void);
private:
uint8_t my_pci_cfg_hdr[256] = {
0x57, 0x10, // vendor ID: Motorola
0x02, 0x00, // device ID: MPC106
0x06, 0x00, // PCI command
0x80, 0x00, // PCI status
0x40, // revision ID: 4.0
0x00, // standard programming
0x00, // subclass code: host bridge
0x06, // class code: bridge device
0x08, // cache line size
0x00, // latency timer
0x00, // header type
0x00, // BIST Control
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, //Interrupt line
0x00, //Interrupt pin
0x00, //MIN GNT
0x00, //MAX LAT
0x00, //Bus number
0x00, //Subordinate bus number
0x00, //Discount counter
0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, //Performance monitor command
0x00, 0x00, //Performance monitor mode control
0x57, 0x10, // vendor ID: Motorola
0x02, 0x00, // device ID: MPC106
0x06, 0x00, // PCI command
0x80, 0x00, // PCI status
0x40, // revision ID: 4.0
0x00, // standard programming
0x00, // subclass code: host bridge
0x06, // class code: bridge device
0x08, // cache line size
0x00, // latency timer
0x00, // header type
0x00, // BIST Control
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, // Interrupt line
0x00, // Interrupt pin
0x00, // MIN GNT
0x00, // MAX LAT
0x00, // Bus number
0x00, // Subordinate bus number
0x00, // Discount counter
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, // Performance monitor command
0x00, 0x00, // Performance monitor mode control
0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, //Performance monitor counter 0
0x00, 0x00, 0x00, 0x00, //Performance monitor counter 1
0x00, 0x00, 0x00, 0x00, //Performance monitor counter 2
0x00, 0x00, 0x00, 0x00, //Performance monitor counter 3
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 0
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 1
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 2
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 3
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF,
0x00, 0x00, //Power mgt config 1
0x00, //Power mgt config 2
0xCD, //default value for ODCR
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //Extended Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //Memory Ending Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //Extended Memory Ending Address
0x00, 0x00, // Power mgt config 1
0x00, // Power mgt config 2
0xCD, // default value for ODCR
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, // Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Extended Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Memory Ending Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Extended Memory Ending Address
0x00, //Memory bank enable
0x00, // Memory bank enable
0xFF, 0xFF,
0x00, //Memory page mode
0x00, // Memory page mode
0xFF, 0xFF, 0xFF, 0xFF,
0x10, 0x00, 0x00, 0xFF, // PICR1
0x0C, 0x06, 0x0C, 0x00, // PICR2
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, //ECC single-bit error counter
0x00, //ECC single-bit error trigger
0x04, //Alternate OS visible paramaters 1
0x01, //Alternate OS visible paramaters 2
0x10, 0x00, 0x00, 0xFF, // PICR1
0x0C, 0x06, 0x0C, 0x00, // PICR2
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, // ECC single-bit error counter
0x00, // ECC single-bit error trigger
0x04, // Alternate OS visible paramaters 1
0x01, // Alternate OS visible paramaters 2
0xFF, 0xFF, 0xFF, 0xFF,
0x01, //Error enabling 1
0x00, //Error detection 1
0x01, // Error enabling 1
0x00, // Error detection 1
0xFF,
0x00, //60x bus error status
0x00, //Error enabling 2
0x00, //Error detection 2
0x00, // 60x bus error status
0x00, // Error enabling 2
0x00, // Error detection 2
0xFF,
0x00, //PCI bus error status
0x00, 0x00, 0x00, 0x00, //60x/PCI ERROR address
0x00, // PCI bus error status
0x00, 0x00, 0x00, 0x00, // 60x/PCI ERROR address
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF,
0x42, 0x00, 0xFF, 0x0F, //Emulation support config 1
0x00, 0x00, 0x00, 0x00, //Modified memory status (no clear)
0x20, 0x00, 0x00, 0x00, //Emulation support config 2
0x00, 0x00, 0x00, 0x00, //Modified memory status (clear)
0x42, 0x00, 0xFF, 0x0F, // Emulation support config 1
0x00, 0x00, 0x00, 0x00, // Modified memory status (no clear)
0x20, 0x00, 0x00, 0x00, // Emulation support config 2
0x00, 0x00, 0x00, 0x00, // Modified memory status (clear)
0x00, 0x00, 0x02, 0xFF, //Memory ctrl config 1
0x03, 0x00, 0x00, 0x00, //Memory ctrl config 2
0x00, 0x00, 0x00, 0x00, //Memory ctrl config 3
0x00, 0x00, 0x10, 0x00 //Memory ctrl config 4
0x00, 0x00, 0x02, 0xFF, // Memory ctrl config 1
0x03, 0x00, 0x00, 0x00, // Memory ctrl config 2
0x00, 0x00, 0x00, 0x00, // Memory ctrl config 3
0x00, 0x00, 0x10, 0x00 // Memory ctrl config 4
};
uint32_t config_addr;
//uint32_t config_data;
// uint32_t config_data;
std::unordered_map<int, PCIDevice*> pci_0_bus;
std::vector<PCIDevice*> io_space_devs;
};
#endif
+38 -30
View File
@@ -1,15 +1,30 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include <cinttypes>
#include "nvram.h"
#include <cinttypes>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thirdparty/loguru/loguru.hpp>
/** @file Non-volatile RAM implementation.
*/
@@ -19,8 +34,7 @@ using namespace std;
/** the signature for NVRAM backing file identification. */
static char NVRAM_FILE_ID[] = "DINGUSPPCNVRAM";
NVram::NVram(std::string file_name, uint32_t ram_size)
{
NVram::NVram(std::string file_name, uint32_t ram_size) {
this->file_name = file_name;
this->ram_size = ram_size;
@@ -29,52 +43,46 @@ NVram::NVram(std::string file_name, uint32_t ram_size)
this->init();
}
NVram::~NVram()
{
NVram::~NVram() {
this->save();
if (this->storage)
delete this->storage;
}
uint8_t NVram::read_byte(uint32_t offset)
{
uint8_t NVram::read_byte(uint32_t offset) {
return (this->storage[offset]);
}
void NVram::write_byte(uint32_t offset, uint8_t val)
{
void NVram::write_byte(uint32_t offset, uint8_t val) {
this->storage[offset] = val;
}
void NVram::init() {
char sig[sizeof(NVRAM_FILE_ID)];
char sig[sizeof(NVRAM_FILE_ID)];
uint16_t data_size;
ifstream f(this->file_name, ios::in | ios::binary);
if (f.fail() || !f.read(sig, sizeof(NVRAM_FILE_ID)) ||
!f.read((char *)&data_size, sizeof(data_size)) ||
memcmp(sig, NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID)) ||
data_size != this->ram_size ||
!f.read((char *)this->storage, this->ram_size))
{
cout << "WARN: Could not restore NVRAM content from the given file." << endl;
if (f.fail() || !f.read(sig, sizeof(NVRAM_FILE_ID)) ||
!f.read((char*)&data_size, sizeof(data_size)) ||
memcmp(sig, NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID)) || data_size != this->ram_size ||
!f.read((char*)this->storage, this->ram_size)) {
LOG_F(WARNING, "Could not restore NVRAM content from the given file. \n");
memset(this->storage, 0, sizeof(this->ram_size));
}
f.close();
}
void NVram::save()
{
void NVram::save() {
ofstream f(this->file_name, ios::out | ios::binary);
/* write file identification */
f.write(NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID));
f.write((char *)&this->ram_size, sizeof(this->ram_size));
f.write((char*)&this->ram_size, sizeof(this->ram_size));
/* write NVRAM content */
f.write((char *)this->storage, this->ram_size);
f.write((char*)this->storage, this->ram_size);
f.close();
}
+28 -8
View File
@@ -1,8 +1,29 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NVRAM_H
#define NVRAM_H
#include <string>
#include <cinttypes>
#include <string>
/** @file Non-volatile RAM emulation.
@@ -10,22 +31,21 @@
automatically saved to and restored from the dedicated file.
*/
class NVram
{
class NVram {
public:
NVram(std::string file_name = "nvram.bin", uint32_t ram_size = 8192);
~NVram();
uint8_t read_byte(uint32_t offset);
void write_byte(uint32_t offset, uint8_t value);
void write_byte(uint32_t offset, uint8_t value);
private:
std::string file_name; /* file name for the backing file. */
uint16_t ram_size; /* NVRAM size. */
uint8_t* storage;
uint16_t ram_size; /* NVRAM size. */
uint8_t* storage;
void init();
void save();
void init();
void save();
};
#endif /* NVRAM_H */
+55 -11
View File
@@ -1,34 +1,78 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PCI_DEVICE_H
#define PCI_DEVICE_H
#include <cinttypes>
#include <string>
#include "mmiodevice.h"
#include "pcihost.h"
#include <cinttypes>
#include <string>
/* convert little-endian DWORD to big-endian DWORD */
#define LE2BE(x) (x >> 24) | ((x & 0x00FF0000) >> 8) | ((x & 0x0000FF00) << 8) | (x << 24)
/** PCI configuration space registers offsets */
enum {
CFG_REG_BAR0 = 0x10 // base address register 0
CFG_REG_CMD = 0x04, // command/status register
CFG_REG_BAR0 = 0x10, // base address register 0
CFG_REG_BAR1 = 0x14, // base address register 1
CFG_REG_BAR2 = 0x18, // base address register 2
CFG_REG_BAR3 = 0x1C, // base address register 3
CFG_REG_BAR4 = 0x20, // base address register 4
CFG_REG_BAR5 = 0x24, // base address register 5
CFG_EXP_BASE = 0x30, // expansion ROM base
};
class PCIDevice : public MMIODevice {
public:
PCIDevice(std::string name) {this->name = name;};
PCIDevice(std::string name) {
this->pci_name = name;
};
virtual ~PCIDevice() = default;
/* configuration space access methods */
virtual uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size) = 0;
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) = 0;
virtual bool supports_io_space(void) = 0;
virtual void set_host(PCIHost *host_instance) = 0;
/* I/O space access methods */
virtual bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res) {
return false;
};
virtual bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size) {
return false;
};
/* configuration space access methods */
virtual uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size) = 0;
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) = 0;
virtual void set_host(PCIHost* host_instance) {
this->host_instance = host_instance;
};
protected:
std::string name; // human-readable device name
PCIHost *host_instance; // host bridge instance to call back
uint32_t base_addr; // base address register 0
std::string pci_name; // human-readable device name
PCIHost* host_instance; // host bridge instance to call back
uint32_t base_addr; // base address register 0
};
#endif /* PCI_DEVICE_H */
+3 -4
View File
@@ -3,13 +3,12 @@
#include <cinttypes>
class PCIDevice; // forward declaration to prevent errors
class PCIDevice; // forward declaration to prevent errors
class PCIHost {
public:
virtual bool pci_register_device(int dev_num, PCIDevice *dev_instance) = 0;
virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size,
PCIDevice *obj) = 0;
virtual bool pci_register_device(int dev_num, PCIDevice* dev_instance) = 0;
virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj) = 0;
};
#endif /* PCI_HOST_H */
+172
View File
@@ -0,0 +1,172 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "soundserver.h"
//#include <thirdparty/libsoundio/soundio/soundio.h>
#include <thirdparty/loguru/loguru.hpp>
#include <cubeb/cubeb.h>
#ifdef _WIN32
#include <objbase.h>
#endif
#if 0
int SoundServer::start()
{
int err;
this->status = SND_SERVER_DOWN;
this->soundio = soundio_create();
if (!this->soundio) {
LOG_F(ERROR, "Sound Server: out of memory");
return -1;
}
if ((err = soundio_connect(this->soundio))) {
LOG_F(ERROR, "Unable to connect to backend: %s", soundio_strerror(err));
return -1;
}
LOG_F(INFO, "Connected to backend: %s", soundio_backend_name(soundio->current_backend));
soundio_flush_events(this->soundio);
this->status = SND_API_READY;
this->out_dev_index = soundio_default_output_device_index(this->soundio);
if (this->out_dev_index < 0) {
LOG_F(ERROR, "Sound Server: no output device found");
return -1;
}
this->out_device = soundio_get_output_device(this->soundio, this->out_dev_index);
if (!this->out_device) {
LOG_F(ERROR, "Sound Server: out of memory");
return -1;
}
LOG_F(INFO, "Sound Server output device: %s", this->out_device->name);
this->status = SND_SERVER_UP;
return 0;
}
void SoundServer::shutdown()
{
switch (this->status) {
case SND_SERVER_UP:
soundio_device_unref(this->out_device);
/* fall through */
case SND_API_READY:
soundio_destroy(this->soundio);
}
this->status = SND_SERVER_DOWN;
LOG_F(INFO, "Sound Server shut down.");
}
#endif
int SoundServer::start()
{
int res;
#ifdef _WIN32
CoInitialize(nullptr);
#endif
this->status = SND_SERVER_DOWN;
res = cubeb_init(&this->cubeb_ctx, "Dingus sound server", NULL);
if (res != CUBEB_OK) {
LOG_F(ERROR, "Could not initialize Cubeb library");
return -1;
}
LOG_F(INFO, "Connected to backend: %s", cubeb_get_backend_id(this->cubeb_ctx));
this->status = SND_API_READY;
return 0;
}
void SoundServer::shutdown()
{
switch (this->status) {
case SND_SERVER_UP:
//soundio_device_unref(this->out_device);
/* fall through */
case SND_API_READY:
cubeb_destroy(this->cubeb_ctx);
}
this->status = SND_SERVER_DOWN;
LOG_F(INFO, "Sound Server shut down.");
}
int SoundServer::open_out_stream(uint32_t sample_rate, cubeb_data_callback data_cb,
cubeb_state_callback status_cb, void *user_data)
{
int res;
uint32_t latency_frames;
cubeb_stream_params params;
params.format = CUBEB_SAMPLE_S16NE;
params.rate = sample_rate;
params.channels = 2;
params.layout = CUBEB_LAYOUT_STEREO;
params.prefs = CUBEB_STREAM_PREF_NONE;
res = cubeb_get_min_latency(this->cubeb_ctx, &params, &latency_frames);
if (res != CUBEB_OK) {
LOG_F(ERROR, "Could not get minimum latency, error: %d", res);
return -1;
} else {
LOG_F(INFO, "Minimum sound latency: %d frames", latency_frames);
}
res = cubeb_stream_init(this->cubeb_ctx, &this->out_stream, "SndOut stream",
NULL, NULL, NULL, &params, latency_frames,
data_cb, status_cb, user_data);
if (res != CUBEB_OK) {
LOG_F(ERROR, "Could not open sound output stream, error: %d", res);
return -1;
}
LOG_F(INFO, "Sound output stream opened.");
return 0;
}
int SoundServer::start_out_stream()
{
return cubeb_stream_start(this->out_stream);
}
void SoundServer::close_out_stream()
{
cubeb_stream_stop(this->out_stream);
cubeb_stream_destroy(this->out_stream);
LOG_F(INFO, "Sound output stream closed.");
}
+83
View File
@@ -0,0 +1,83 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Sound server definitions.
This class manages host audio HW. It's directly connected
to a sound abstraction API (libsoundio in our case).
Sound server provides a way to select between various
host input and output devices independendly of emulated
sound HW.
Emulated sound HW only need to process sound streams.
*/
#ifndef SOUND_SERVER_H
#define SOUND_SERVER_H
#include "hwcomponent.h"
//#include <thirdparty/libsoundio/soundio/soundio.h>
#include <cubeb/cubeb.h>
enum {
SND_SERVER_DOWN = 0,
SND_API_READY,
SND_SERVER_UP,
};
class SoundServer : public HWComponent {
public:
SoundServer() { this->start(); };
~SoundServer() { this->shutdown(); };
int start();
void shutdown();
int open_out_stream(uint32_t sample_rate, cubeb_data_callback data_cb,
cubeb_state_callback status_cb, void *user_data);
int start_out_stream();
void close_out_stream();
bool supports_type(HWCompType type) { return type == HWCompType::SND_SERVER; };
#if 0
SoundIoDevice *get_out_device() {
if (this->status == SND_SERVER_UP) {
return this->out_device;
} else {
return NULL;
}
};
#endif
private:
int status; /* server status */
cubeb *cubeb_ctx;
cubeb_stream *out_stream;
//SoundIo *soundio;
//int out_dev_index; /* current output device index */
//SoundIoDevice *out_device; /* current output device instance */
//SoundIoOutStream *outstream;
};
#endif /* SOUND_SERVER_H */
+142
View File
@@ -0,0 +1,142 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Serial presence detect (SPD) RAM module emulation.
Author: Max Poliakovski
@description
Serial presence detect (SPD) is a standard that prescribes an automatic way
to supply various information about a memory module.
A SPD-compatible memory module contains a small EEPROM that stores useful
information like memory size, configuration, speed, manufacturer etc.
The content depends on the module type.
This EEPROM is accessible via the I2C bus. The EEPROM I2C address will be
configured depending on the physical RAM slot the module is inserted to.
A 168-Pin SDRAM slot includes three specialized pins SA0-SA2 for setting
an unique I2C address for each module EEPROM. The SA0-SA2 pins are hardwired
differently for each RAM slot. Example:
Slot SA0-SA2 I2C address
A %000 0x50 + %000 = 0x50
B %001 0x50 + %001 = 0x51
Further reading: https://en.wikipedia.org/wiki/Serial_presence_detect
*/
#ifndef SPD_EEPROM_H
#define SPD_EEPROM_H
#include "hwcomponent.h"
#include "i2c.h"
#include <cinttypes>
#include <stdexcept>
#include <string>
#include <thirdparty/loguru/loguru.hpp>
enum RAMType : int { SDRAM = 4 };
class SpdSdram168 : public HWComponent, public I2CDevice {
public:
SpdSdram168(uint8_t addr) {
this->dev_addr = addr;
this->pos = 0;
};
~SpdSdram168() = default;
bool supports_type(HWCompType type) {
return type == HWCompType::RAM;
};
void set_capacity(int capacity_megs) {
switch (capacity_megs) {
case 32:
this->eeprom_data[3] = 0xC; /* 12 rows */
this->eeprom_data[4] = 0x8; /* 8 columns */
this->eeprom_data[5] = 0x1; /* one bank */
break;
case 64:
this->eeprom_data[3] = 0xC; /* 12 rows */
this->eeprom_data[4] = 0x9; /* 9 columns */
this->eeprom_data[5] = 0x1; /* one bank */
break;
case 128:
this->eeprom_data[3] = 0xC; /* 12 rows */
this->eeprom_data[4] = 0xA; /* 10 columns */
this->eeprom_data[5] = 0x1; /* one bank */
break;
case 256:
this->eeprom_data[3] = 0xC; /* 12 rows */
this->eeprom_data[4] = 0xA; /* 10 columns */
this->eeprom_data[5] = 0x2; /* two banks */
break;
default:
throw std::invalid_argument(std::string("Unsupported capacity!"));
}
LOG_F(INFO, "SDRAM capacity set to %dMB, I2C addr = 0x%X", capacity_megs, this->dev_addr);
};
void start_transaction() {
this->pos = 0;
};
bool send_subaddress(uint8_t sub_addr) {
this->pos = sub_addr;
LOG_F(9, "SDRAM subaddress set to 0x%X", sub_addr);
return true;
};
bool send_byte(uint8_t data) {
LOG_F(9, "SDRAM byte 0x%X received", data);
return true;
};
bool receive_byte(uint8_t* p_data) {
if (this->pos >= this->eeprom_data[0]) {
this->pos = 0; /* attempt to read past SPD data should wrap around */
}
LOG_F(9, "SDRAM sending EEPROM byte 0x%X", this->eeprom_data[this->pos]);
*p_data = this->eeprom_data[this->pos++];
return true;
};
private:
uint8_t dev_addr; /* I2C address */
int pos; /* actual read position */
/* EEPROM content */
uint8_t eeprom_data[256] = {
128, /* number of bytes present */
8, /* log2(EEPROM size) */
RAMType::SDRAM, /* memory type */
/* the following fields will be set up in set_capacity() */
0, /* number of row addresses */
0, /* number of column addresses */
0 /* number of banks */
};
};
#endif /* SPD_EEPROM_H */
+312 -168
View File
@@ -1,25 +1,39 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** VIA-CUDA combo device emulation.
Author: Max Poliakovski 2019
*/
#include <iostream>
#include <fstream>
#include <cinttypes>
#include <vector>
#include "viacuda.h"
#include "adb.h"
#include <cinttypes>
#include <thirdparty/loguru/loguru.hpp>
using namespace std;
ViaCuda::ViaCuda()
{
ViaCuda::ViaCuda() {
this->name = "ViaCuda";
/* FIXME: is this the correct
VIA initialization? */
this->via_regs[VIA_A] = 0x80;
@@ -29,44 +43,43 @@ ViaCuda::ViaCuda()
this->via_regs[VIA_T1LH] = 0xFF;
this->via_regs[VIA_IER] = 0x7F;
//PRAM Pre-Initialization
// PRAM Pre-Initialization
this->pram_obj = new NVram("pram.bin", 256);
this->cuda_init();
this->adb_obj = new ADB_Bus();
this->init();
}
ViaCuda::~ViaCuda()
{
ViaCuda::~ViaCuda() {
if (this->pram_obj)
delete (this->pram_obj);
}
void ViaCuda::cuda_init()
{
this->old_tip = 0;
void ViaCuda::init() {
this->old_tip = 0;
this->old_byteack = 0;
this->treq = 1;
this->in_count = 0;
this->out_count = 0;
this->treq = 1;
this->in_count = 0;
this->out_count = 0;
this->poll_rate = 11;
}
uint8_t ViaCuda::read(int reg)
{
uint8_t ViaCuda::read(int reg) {
uint8_t res;
cout << "Read VIA reg " << hex << (uint32_t)reg << endl;
LOG_F(9, "Read VIA reg %x \n", (uint32_t)reg);
res = this->via_regs[reg & 0xF];
/* reading from some VIA registers triggers special actions */
switch(reg & 0xF) {
switch (reg & 0xF) {
case VIA_B:
res = this->via_regs[VIA_B];
break;
case VIA_A:
case VIA_ANH:
cout << "WARNING: read attempt from VIA Port A!" << endl;
LOG_F(WARNING, "Attempted read from VIA Port A! \n");
break;
case VIA_IER:
res |= 0x80; /* bit 7 always reads as "1" */
@@ -75,38 +88,35 @@ uint8_t ViaCuda::read(int reg)
return res;
}
void ViaCuda::write(int reg, uint8_t value)
{
switch(reg & 0xF) {
void ViaCuda::write(int reg, uint8_t value) {
switch (reg & 0xF) {
case VIA_B:
this->via_regs[VIA_B] = value;
cuda_write(value);
write(value);
break;
case VIA_A:
case VIA_ANH:
cout << "WARNING: write attempt to VIA Port A!" << endl;
LOG_F(WARNING, "Attempted read from VIA Port A! \n");
break;
case VIA_DIRB:
cout << "VIA_DIRB = " << hex << (uint32_t)value << endl;
LOG_F(9, "VIA_DIRB = %x \n", (uint32_t)value);
this->via_regs[VIA_DIRB] = value;
break;
case VIA_DIRA:
cout << "VIA_DIRA = " << hex << (uint32_t)value << endl;
LOG_F(9, "VIA_DIRA = %x \n", (uint32_t)value);
this->via_regs[VIA_DIRA] = value;
break;
case VIA_PCR:
cout << "VIA_PCR = " << hex << (uint32_t)value << endl;
LOG_F(9, "VIA_PCR = %x \n", (uint32_t)value);
this->via_regs[VIA_PCR] = value;
break;
case VIA_ACR:
cout << "VIA_ACR = " << hex << (uint32_t)value << endl;
LOG_F(9, "VIA_ACR = %x \n", (uint32_t)value);
this->via_regs[VIA_ACR] = value;
break;
case VIA_IER:
this->via_regs[VIA_IER] = (value & 0x80) ? value & 0x7F
: this->via_regs[VIA_IER] & ~value;
cout << "VIA_IER updated to " << hex << (uint32_t)this->via_regs[VIA_IER]
<< endl;
this->via_regs[VIA_IER] = (value & 0x80) ? value & 0x7F : this->via_regs[VIA_IER] & ~value;
LOG_F(INFO, "VIA_IER updated to %d \n", (uint32_t)this->via_regs[VIA_IER]);
print_enabled_ints();
break;
default:
@@ -114,43 +124,39 @@ void ViaCuda::write(int reg, uint8_t value)
}
}
void ViaCuda::print_enabled_ints()
{
vector<string> via_int_src = {"CA2", "CA1", "SR", "CB2", "CB1", "T2", "T1"};
void ViaCuda::print_enabled_ints() {
const char* via_int_src[] = {"CA2", "CA1", "SR", "CB2", "CB1", "T2", "T1"};
for (int i = 0; i < 7; i++) {
if (this->via_regs[VIA_IER] & (1 << i))
cout << "VIA " << via_int_src[i] << " interrupt enabled." << endl;
LOG_F(INFO, "VIA %s interrupt enabled \n", via_int_src[i]);
}
}
inline bool ViaCuda::cuda_ready()
{
inline bool ViaCuda::ready() {
return ((this->via_regs[VIA_DIRB] & 0x38) == 0x30);
}
inline void ViaCuda::assert_sr_int()
{
inline void ViaCuda::assert_sr_int() {
this->via_regs[VIA_IFR] |= 0x84;
}
void ViaCuda::cuda_write(uint8_t new_state)
{
if (!cuda_ready()) {
cout << "Cuda not ready!" << endl;
void ViaCuda::write(uint8_t new_state) {
if (!ready()) {
LOG_F(WARNING, "Cuda not ready! \n");
return;
}
int new_tip = !!(new_state & CUDA_TIP);
int new_tip = !!(new_state & CUDA_TIP);
int new_byteack = !!(new_state & CUDA_BYTEACK);
/* return if there is no state change */
if (new_tip == this->old_tip && new_byteack == this->old_byteack)
return;
cout << "Cuda state changed!" << endl;
LOG_F(9, "Cuda state changed! \n");
this->old_tip = new_tip;
this->old_tip = new_tip;
this->old_byteack = new_byteack;
if (new_tip) {
@@ -159,7 +165,7 @@ void ViaCuda::cuda_write(uint8_t new_state)
this->treq = 1;
if (this->in_count) {
cuda_process_packet();
process_packet();
/* start response transaction */
this->via_regs[VIA_B] &= ~CUDA_TREQ; /* assert TREQ */
@@ -168,10 +174,10 @@ void ViaCuda::cuda_write(uint8_t new_state)
this->in_count = 0;
} else {
cout << "Cuda: enter sync state" << endl;
LOG_F(9, "Cuda: enter sync state \n");
this->via_regs[VIA_B] &= ~CUDA_TREQ; /* assert TREQ */
this->treq = 0;
this->in_count = 0;
this->treq = 0;
this->in_count = 0;
this->out_count = 0;
}
@@ -182,163 +188,301 @@ void ViaCuda::cuda_write(uint8_t new_state)
this->in_buf[this->in_count++] = this->via_regs[VIA_SR];
assert_sr_int(); /* tell the system we've read the data */
} else {
cout << "Cuda input buffer exhausted!" << endl;
LOG_F(WARNING, "Cuda input buffer exhausted! \n");
}
} else { /* data transfer: Cuda --> Host */
if (this->out_count) {
this->via_regs[VIA_SR] = this->out_buf[this->out_pos++];
if (this->out_pos >= this->out_count) {
cout << "Cuda: sending last byte" << endl;
this->out_count = 0;
this->via_regs[VIA_B] |= CUDA_TREQ; /* negate TREQ */
this->treq = 1;
}
assert_sr_int(); /* tell the system we've written the data */
}
(this->*out_handler)();
assert_sr_int(); /* tell the system we've written the data */
}
}
}
void ViaCuda::cuda_response_header(uint32_t pkt_type, uint32_t pkt_flag)
{
this->out_buf[0] = pkt_type;
this->out_buf[1] = pkt_flag;
this->out_buf[2] = this->in_buf[1]; /* copy original cmd */
this->out_count = 3;
this->out_pos = 0;
/* sends zeros to host at infinitum */
void ViaCuda::null_out_handler() {
this->via_regs[VIA_SR] = 0;
}
void ViaCuda::cuda_error_response(uint32_t error)
{
this->out_buf[0] = CUDA_PKT_ERROR;
this->out_buf[1] = error;
this->out_buf[2] = this->in_buf[0];
this->out_buf[3] = this->in_buf[1]; /* copy original cmd */
this->out_count = 4;
this->out_pos = 0;
/* sends data from out_buf until exhausted, then switches to next_out_handler */
void ViaCuda::out_buf_handler() {
if (this->out_pos < this->out_count) {
LOG_F(9, "OutBufHandler: sending next byte 0x%X", this->out_buf[this->out_pos]);
this->via_regs[VIA_SR] = this->out_buf[this->out_pos++];
} else if (this->is_open_ended) {
LOG_F(9, "OutBufHandler: switching to next handler");
this->out_handler = this->next_out_handler;
this->next_out_handler = &ViaCuda::null_out_handler;
(this->*out_handler)();
} else {
LOG_F(9, "Sending last byte");
this->out_count = 0;
this->via_regs[VIA_B] |= CUDA_TREQ; /* negate TREQ */
this->treq = 1;
}
}
void ViaCuda::cuda_process_packet()
{
void ViaCuda::response_header(uint32_t pkt_type, uint32_t pkt_flag) {
this->out_buf[0] = pkt_type;
this->out_buf[1] = pkt_flag;
this->out_buf[2] = this->in_buf[1]; /* copy original cmd */
this->out_count = 3;
this->out_pos = 0;
this->out_handler = &ViaCuda::out_buf_handler;
this->next_out_handler = &ViaCuda::null_out_handler;
this->is_open_ended = false;
}
void ViaCuda::error_response(uint32_t error) {
this->out_buf[0] = CUDA_PKT_ERROR;
this->out_buf[1] = error;
this->out_buf[2] = this->in_buf[0];
this->out_buf[3] = this->in_buf[1]; /* copy original cmd */
this->out_count = 4;
this->out_pos = 0;
this->out_handler = &ViaCuda::out_buf_handler;
this->next_out_handler = &ViaCuda::null_out_handler;
this->is_open_ended = false;
}
void ViaCuda::process_packet() {
if (this->in_count < 2) {
cout << "Cuda: invalid packet (too few data)!" << endl;
LOG_F(ERROR, "Cuda: invalid packet (too few data)!\n");
error_response(CUDA_ERR_BAD_SIZE);
return;
}
switch(this->in_buf[0]) {
switch (this->in_buf[0]) {
case CUDA_PKT_ADB:
cout << "Cuda: ADB packet received" << endl;
LOG_F(9, "Cuda: ADB packet received \n");
process_adb_command(this->in_buf[1], this->in_count - 2);
break;
case CUDA_PKT_PSEUDO:
cout << "Cuda: pseudo command packet received" << endl;
cout << "Command: " << hex << (uint32_t)(this->in_buf[1]) << endl;
cout << "Data count: " << dec << this->in_count << endl;
LOG_F(9, "Cuda: pseudo command packet received \n");
LOG_F(9, "Command: %x \n", (uint32_t)(this->in_buf[1]));
LOG_F(9, "Data count: %d \n ", this->in_count);
for (int i = 0; i < this->in_count; i++) {
cout << hex << (uint32_t)(this->in_buf[i]) << ", ";
LOG_F(9, "%x ,", (uint32_t)(this->in_buf[i]));
}
cout << endl;
cuda_pseudo_command(this->in_buf[1], this->in_count - 2);
pseudo_command(this->in_buf[1], this->in_count - 2);
break;
default:
cout << "Cuda: unsupported packet type = " << dec << (uint32_t)(this->in_buf[0]) << endl;
LOG_F(ERROR, "Cuda: unsupported packet type = %d \n", (uint32_t)(this->in_buf[0]));
error_response(CUDA_ERR_BAD_PKT);
}
}
void ViaCuda::cuda_pseudo_command(int cmd, int data_count)
{
switch(cmd) {
void ViaCuda::process_adb_command(uint8_t cmd_byte, int data_count) {
int adb_dev = cmd_byte >> 4; // 2 for keyboard, 3 for mouse
int cmd = cmd_byte & 0xF;
if (!cmd) {
LOG_F(9, "Cuda: ADB SendReset command requested\n");
response_header(CUDA_PKT_ADB, 0);
} else if (cmd == 1) {
LOG_F(9, "Cuda: ADB Flush command requested\n");
response_header(CUDA_PKT_ADB, 0);
} else if ((cmd & 0xC) == 8) {
LOG_F(9, "Cuda: ADB Listen command requested\n");
int adb_reg = cmd_byte & 0x3;
if (adb_obj->listen(adb_dev, adb_reg)) {
response_header(CUDA_PKT_ADB, 0);
for (int data_ptr = 0; data_ptr < adb_obj->get_output_len(); data_ptr++) {
this->in_buf[(2 + data_ptr)] = adb_obj->get_output_byte(data_ptr);
}
} else {
response_header(CUDA_PKT_ADB, 2);
}
} else if ((cmd & 0xC) == 0xC) {
LOG_F(9, "Cuda: ADB Talk command requested\n");
response_header(CUDA_PKT_ADB, 0);
int adb_reg = cmd_byte & 0x3;
if (adb_obj->talk(adb_dev, adb_reg, this->in_buf[2])) {
response_header(CUDA_PKT_ADB, 0);
} else {
response_header(CUDA_PKT_ADB, 2);
}
} else {
LOG_F(ERROR, "Cuda: unsupported ADB command 0x%x \n", cmd);
error_response(CUDA_ERR_BAD_CMD);
}
}
void ViaCuda::pseudo_command(int cmd, int data_count) {
switch (cmd) {
case CUDA_START_STOP_AUTOPOLL:
if (this->in_buf[2]) {
LOG_F(INFO, "Cuda: autopoll started, rate: %dms", this->poll_rate);
} else {
LOG_F(INFO, "Cuda: autopoll stopped");
}
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_GET_6805_ADDRESS:
response_header(CUDA_PKT_PSEUDO, 0);
this->out_buf[2] = (uint8_t)((this->m6805_address >> 8) & 0xFF);
this->out_buf[3] = (uint8_t)((this->m6805_address) & 0xFF);
break;
case CUDA_GET_REAL_TIME:
response_header(CUDA_PKT_PSEUDO, 0);
this->out_buf[2] = (uint8_t)((this->real_time >> 24) & 0xFF);
this->out_buf[3] = (uint8_t)((this->real_time >> 16) & 0xFF);
this->out_buf[4] = (uint8_t)((this->real_time >> 8) & 0xFF);
this->out_buf[5] = (uint8_t)((this->real_time) & 0xFF);
break;
case CUDA_READ_PRAM:
cuda_response_header(CUDA_PKT_PSEUDO, 0);
response_header(CUDA_PKT_PSEUDO, 0);
this->pram_obj->read_byte(this->in_buf[2]);
break;
case CUDA_SET_6805_ADDRESS:
response_header(CUDA_PKT_PSEUDO, 0);
this->m6805_address = ((uint16_t)in_buf[2]) >> 8;
this->m6805_address += ((uint16_t)in_buf[3]);
LOG_F(INFO, "6805 address set to: %x", this->m6805_address);
break;
case CUDA_SET_REAL_TIME:
response_header(CUDA_PKT_PSEUDO, 0);
this->real_time = ((uint32_t)in_buf[2]) >> 24;
this->real_time += ((uint32_t)in_buf[3]) >> 16;
this->real_time += ((uint32_t)in_buf[4]) >> 8;
this->real_time += ((uint32_t)in_buf[5]);
break;
case CUDA_WRITE_PRAM:
cuda_response_header(CUDA_PKT_PSEUDO, 0);
response_header(CUDA_PKT_PSEUDO, 0);
this->pram_obj->write_byte(this->in_buf[2], this->in_buf[3]);
break;
case CUDA_FILE_SERVER_FLAG:
response_header(CUDA_PKT_PSEUDO, 0);
if (this->in_buf[2]) {
LOG_F(INFO, "Cuda: File server flag on");
this->file_server = true;
}
else {
LOG_F(INFO, "Cuda: File server flag off");
this->file_server = false;
}
break;
case CUDA_SET_AUTOPOLL_RATE:
this->poll_rate = this->in_buf[2];
LOG_F(INFO, "Cuda: autopoll rate set to: %d", this->poll_rate);
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_GET_AUTOPOLL_RATE:
response_header(CUDA_PKT_PSEUDO, 0);
this->out_buf[3] = this->poll_rate;
this->out_count++;
break;
case CUDA_SET_DEVICE_LIST:
response_header(CUDA_PKT_PSEUDO, 0);
this->device_mask = ((uint16_t)in_buf[2]) >> 8;
this->device_mask += ((uint16_t)in_buf[3]);
break;
case CUDA_GET_DEVICE_LIST:
response_header(CUDA_PKT_PSEUDO, 0);
this->out_buf[2] = (uint8_t)((this->device_mask >> 8) & 0xFF);
this->out_buf[3] = (uint8_t)((this->device_mask) & 0xFF);
break;
case CUDA_READ_WRITE_I2C:
cuda_response_header(CUDA_PKT_PSEUDO, 0);
/* bit 0 of the I2C address byte indicates operation kind:
0 - write to device, 1 - read from device
In the case of reading, Cuda will append one-byte result
to the response packet header */
response_header(CUDA_PKT_PSEUDO, 0);
i2c_simple_transaction(this->in_buf[2], &this->in_buf[3], this->in_count - 3);
break;
case CUDA_COMB_FMT_I2C:
/* HACK:
This command performs the so-called open-ended transaction, i.e.
Cuda will continue to send data as long as handshaking is completed
for each byte. To support that, we'd need another emulation approach.
Fortunately, HWInit is known to read/write max. 4 bytes at once
so we're going to use a prefilled buffer to make it work.
*/
cuda_response_header(CUDA_PKT_PSEUDO, 0);
response_header(CUDA_PKT_PSEUDO, 0);
if (this->in_count >= 5) {
i2c_comb_transaction(this->in_buf[2], this->in_buf[3], this->in_buf[4],
&this->in_buf[5], this->in_count - 5);
i2c_comb_transaction(
this->in_buf[2], this->in_buf[3], this->in_buf[4], &this->in_buf[5], this->in_count - 5);
}
break;
case CUDA_OUT_PB0: /* undocumented call! */
cout << "Cuda: send " << dec << (int)(this->in_buf[2]) << " to PB0" << endl;
cuda_response_header(CUDA_PKT_PSEUDO, 0);
LOG_F(INFO, "Cuda: send %d to PB0 \n", (int)(this->in_buf[2]));
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_WARM_START:
case CUDA_POWER_DOWN:
case CUDA_MONO_STABLE_RESET:
case CUDA_RESTART_SYSTEM:
/* really kludge temp code */
LOG_F(INFO, "Cuda: Restart/Shutdown signal sent with command 0x%x! \n", cmd);
exit(0);
break;
default:
cout << "Cuda: unsupported pseudo command 0x" << hex << cmd << endl;
cuda_error_response(CUDA_ERR_BAD_CMD);
LOG_F(ERROR, "Cuda: unsupported pseudo command 0x%x \n", cmd);
error_response(CUDA_ERR_BAD_CMD);
}
}
void ViaCuda::i2c_simple_transaction(uint8_t dev_addr, const uint8_t *in_buf,
int in_bytes)
{
int tr_type = dev_addr & 1;
switch(dev_addr & 0xFE) {
case 0x50: /* unknown device on the Gossamer board */
if (tr_type) { /* read */
/* send dummy byte for now */
this->out_buf[this->out_count++] = 0xDD;
} else {
/* ignore writes */
}
break;
default:
cout << "Unsupported I2C device 0x" << hex << (int)dev_addr << endl;
cuda_error_response(CUDA_ERR_I2C);
}
/* sends data from the current I2C to host ad infinitum */
void ViaCuda::i2c_handler() {
this->receive_byte(this->curr_i2c_addr, &this->via_regs[VIA_SR]);
}
void ViaCuda::i2c_comb_transaction(uint8_t dev_addr, uint8_t sub_addr,
uint8_t dev_addr1, const uint8_t *in_buf, int in_bytes)
{
int tr_type = dev_addr1 & 1;
void ViaCuda::i2c_simple_transaction(uint8_t dev_addr, const uint8_t* in_buf, int in_bytes) {
int op_type = dev_addr & 1; /* 0 - write to device, 1 - read from device */
if ((dev_addr & 0xFE) != (dev_addr1 & 0xFE)) {
cout << "I2C combined, dev_addr mismatch!" << endl;
dev_addr >>= 1; /* strip RD/WR bit */
if (!this->start_transaction(dev_addr)) {
LOG_F(WARNING, "Unsupported I2C device 0x%X \n", (int)(dev_addr));
error_response(CUDA_ERR_I2C);
return;
}
switch(dev_addr1 & 0xFE) {
case 0xAE: /* SDRAM EEPROM, no clue which one */
if (tr_type) { /* read */
if (sub_addr != 2) {
cout << "Unsupported read position 0x" << hex << (int)sub_addr
<< " in SDRAM EEPROM 0x" << hex << (int)dev_addr1;
return;
}
/* FIXME: hardcoded SPD EEPROM values! This should be a proper
I2C device with user-configurable params */
this->out_buf[this->out_count++] = 0x04; /* memory type = SDRAM */
this->out_buf[this->out_count++] = 0x0B; /* row address bits per bank */
this->out_buf[this->out_count++] = 0x09; /* col address bits per bank */
this->out_buf[this->out_count++] = 0x02; /* num of RAM banks */
} else {
/* ignore writes */
/* send data to the target I2C device until there is no more data to send
or the target device doesn't acknowledge that indicates an error */
for (int i = 0; i < in_bytes; i++) {
if (!this->send_byte(dev_addr, in_buf[i])) {
LOG_F(WARNING, "NO_ACK during sending, device 0x%X \n", (int)(dev_addr));
error_response(CUDA_ERR_I2C);
return;
}
break;
default:
cout << "Unsupported I2C device 0x" << hex << (int)dev_addr1 << endl;
cuda_error_response(CUDA_ERR_I2C);
}
if (op_type) { /* read request initiate an open ended transaction */
this->curr_i2c_addr = dev_addr;
this->out_handler = &ViaCuda::out_buf_handler;
this->next_out_handler = &ViaCuda::i2c_handler;
this->is_open_ended = true;
}
}
void ViaCuda::i2c_comb_transaction(
uint8_t dev_addr, uint8_t sub_addr, uint8_t dev_addr1, const uint8_t* in_buf, int in_bytes) {
int op_type = dev_addr1 & 1; /* 0 - write to device, 1 - read from device */
if ((dev_addr & 0xFE) != (dev_addr1 & 0xFE)) {
LOG_F(ERROR, "Combined I2C: dev_addr mismatch!\n");
error_response(CUDA_ERR_I2C);
return;
}
dev_addr >>= 1; /* strip RD/WR bit */
if (!this->start_transaction(dev_addr)) {
LOG_F(WARNING, "Unsupported I2C device 0x%X \n", (int)(dev_addr));
error_response(CUDA_ERR_I2C);
return;
}
if (!this->send_subaddress(dev_addr, sub_addr)) {
LOG_F(WARNING, "NO_ACK while sending subaddress, device 0x%X \n", (int)(dev_addr));
error_response(CUDA_ERR_I2C);
return;
}
/* send data to the target I2C device until there is no more data to send
or the target device doesn't acknowledge that indicates an error */
for (int i = 0; i < in_bytes; i++) {
if (!this->send_byte(dev_addr, in_buf[i])) {
LOG_F(WARNING, "NO_ACK during sending, device 0x%X \n", (int)(dev_addr));
error_response(CUDA_ERR_I2C);
return;
}
}
if (!op_type) { /* return dummy response for writes */
LOG_F(WARNING, "Combined I2C - write request!");
} else {
this->curr_i2c_addr = dev_addr;
this->out_handler = &ViaCuda::out_buf_handler;
this->next_out_handler = &ViaCuda::i2c_handler;
this->is_open_ended = true;
}
}
+83 -30
View File
@@ -1,9 +1,23 @@
//DingusPPC - Prototype 5bf2
//Written by divingkatae
//(c)2018-20 (theweirdo)
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** VIA-CUDA combo device emulation.
@@ -28,11 +42,14 @@
firmware using bit banging (https://en.wikipedia.org/wiki/Bit_banging).
*/
#include "nvram.h"
#ifndef VIACUDA_H
#define VIACUDA_H
#include "adb.h"
#include "hwcomponent.h"
#include "i2c.h"
#include "nvram.h"
/** VIA register offsets. */
enum {
VIA_B = 0x00, /* input/output register B */
@@ -71,26 +88,45 @@ enum {
/** Cuda pseudo commands. */
enum {
CUDA_READ_PRAM = 0x07, /* read parameter RAM*/
CUDA_WRITE_PRAM = 0x0C, /* write parameter RAM*/
CUDA_READ_WRITE_I2C = 0x22, /* read/write I2C device */
CUDA_COMB_FMT_I2C = 0x25, /* combined format I2C transaction */
CUDA_OUT_PB0 = 0x26, /* output one bit to Cuda's PB0 line */
CUDA_WARM_START = 0x00, /* warm start */
CUDA_START_STOP_AUTOPOLL = 0x01, /* start/stop device auto-polling */
CUDA_GET_6805_ADDRESS = 0x02, /* get 6805 address */
CUDA_GET_REAL_TIME = 0x03, /* get real time */
CUDA_READ_PRAM = 0x07, /* read parameter RAM */
CUDA_SET_6805_ADDRESS = 0x08, /* set 6805 address */
CUDA_SET_REAL_TIME = 0x09, /* set real time */
CUDA_POWER_DOWN = 0x0A, /* power down system */
CUDA_WRITE_PRAM = 0x0C, /* write parameter RAM */
CUDA_MONO_STABLE_RESET = 0x0D, /* mono stable reset */
CUDA_RESTART_SYSTEM = 0x11, /* restart system */
CUDA_FILE_SERVER_FLAG = 0x13, /* set file server flag */
CUDA_SET_AUTOPOLL_RATE = 0x14, /* set auto-polling rate */
CUDA_GET_AUTOPOLL_RATE = 0x16, /* get auto-polling rate */
CUDA_SET_DEVICE_LIST = 0x19, /* set device list */
CUDA_GET_DEVICE_LIST = 0x1A, /* get device list */
CUDA_READ_WRITE_I2C = 0x22, /* read/write I2C device */
CUDA_COMB_FMT_I2C = 0x25, /* combined format I2C transaction */
CUDA_OUT_PB0 = 0x26, /* output one bit to Cuda's PB0 line */
};
/** Cuda error codes. */
enum {
CUDA_ERR_BAD_CMD = 2, /* invalid pseudo command */
CUDA_ERR_I2C = 5 /* invalid I2C data or no acknowledge */
CUDA_ERR_BAD_PKT = 1, /* invalid packet type */
CUDA_ERR_BAD_CMD = 2, /* invalid pseudo command */
CUDA_ERR_BAD_SIZE = 3, /* invalid packet size */
CUDA_ERR_I2C = 5 /* invalid I2C data or no acknowledge */
};
class ViaCuda
{
class ViaCuda : public HWComponent, public I2CBus {
public:
ViaCuda();
~ViaCuda();
bool supports_type(HWCompType type) {
return (type == HWCompType::ADB_HOST || type == HWCompType::I2C_HOST);
};
uint8_t read(int reg);
void write(int reg, uint8_t value);
@@ -106,25 +142,42 @@ private:
uint8_t out_buf[16];
int32_t out_count;
int32_t out_pos;
uint8_t poll_rate;
int32_t real_time = 0;
bool file_server;
uint16_t m6805_address = 0x1100;
uint16_t device_mask = 0;
NVram *pram_obj;
bool is_open_ended;
uint8_t curr_i2c_addr;
void (ViaCuda::*out_handler)(void);
void (ViaCuda::*next_out_handler)(void);
NVram* pram_obj;
ADB_Bus* adb_obj;
void print_enabled_ints(); /* print enabled VIA interrupts and their sources */
void cuda_init();
bool cuda_ready();
void init();
bool ready();
void assert_sr_int();
void cuda_write(uint8_t new_state);
void cuda_response_header(uint32_t pkt_type, uint32_t pkt_flag);
//void cuda_response_packet();
void cuda_error_response(uint32_t error);
void cuda_process_packet();
void cuda_pseudo_command(int cmd, int data_count);
void write(uint8_t new_state);
void response_header(uint32_t pkt_type, uint32_t pkt_flag);
// void cuda_response_packet();
void error_response(uint32_t error);
void process_packet();
void process_adb_command(uint8_t cmd_byte, int data_count);
void pseudo_command(int cmd, int data_count);
void null_out_handler(void);
void out_buf_handler(void);
void i2c_handler(void);
/* I2C related methods */
void i2c_simple_transaction(uint8_t dev_addr, const uint8_t *in_buf, int in_bytes);
void i2c_comb_transaction(uint8_t dev_addr, uint8_t sub_addr, uint8_t dev_addr1,
const uint8_t *in_buf, int in_bytes);
void i2c_simple_transaction(uint8_t dev_addr, const uint8_t* in_buf, int in_bytes);
void i2c_comb_transaction(
uint8_t dev_addr, uint8_t sub_addr, uint8_t dev_addr1, const uint8_t* in_buf, int in_bytes);
};
#endif /* VIACUDA_H */
#endif /* VIACUDA_H */
+6
View File
@@ -0,0 +1,6 @@
include_directories("${PROJECT_SOURCE_DIR}")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
add_library(execution OBJECT ${SOURCES})
target_link_libraries(execution PRIVATE cubeb)
+111
View File
@@ -0,0 +1,111 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <chrono>
#include <cinttypes>
#include <ctime>
#include <iostream>
#include <interpreter_loop.h>
#include <thirdparty/loguru/loguru.hpp>
#include <cpu/ppc/ppcemu.h>
std::chrono::high_resolution_clock::time_point global; // global timer
std::chrono::high_resolution_clock::time_point cuda_timer; // updates every 11 ms
std::chrono::high_resolution_clock::time_point disp_timer; // updates every 16 ms
using namespace std;
const uint64_t cuda_update = 11000;
const uint64_t display_update = 16667;
bool cuda_priority = 0;
bool disp_priority = 0;
uint64_t elapsed_times[3] = {0}; // Elapsed time to reach a cycle (for display)
uint64_t routine_bench[3] = {0}; // Estimated time (in microseconds) to cycle through functions
uint64_t routine_runtime[3] = {0, cuda_update, display_update}; // Time to elapse before execution
enum general_routine_timepoint { OVERALL_UPDATE_TIME, CUDA_UPDATE_TIME, DISPLAY_UPDATE_TIME };
void round_robin_bench() {
// Benchmark how much time elapses during a minimal CPU block
std::chrono::high_resolution_clock::time_point dummy = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 4096; i++) {
dppc_interpreter::ppc_ori(); //execute NOPs as a basic test
}
std::chrono::high_resolution_clock::time_point dummy2 = std::chrono::high_resolution_clock::now();
routine_bench[OVERALL_UPDATE_TIME] =
std::chrono::duration_cast<std::chrono::microseconds>(dummy2 - dummy).count();
std::cout << "Initial test: " << routine_bench[OVERALL_UPDATE_TIME] << endl;
}
void interpreter_update_counters() {
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
elapsed_times[OVERALL_UPDATE_TIME] =
std::chrono::duration_cast<std::chrono::microseconds>(end - global).count();
elapsed_times[CUDA_UPDATE_TIME] =
std::chrono::duration_cast<std::chrono::microseconds>(end - cuda_timer).count();
elapsed_times[DISPLAY_UPDATE_TIME] =
std::chrono::duration_cast<std::chrono::microseconds>(end - disp_timer).count();
// Calculate if the threshold for updating a time-critical section has reached or is about to be reached
if ((elapsed_times[CUDA_UPDATE_TIME] + routine_bench[OVERALL_UPDATE_TIME]) >=
routine_runtime[CUDA_UPDATE_TIME]) {
cuda_priority = true;
elapsed_times[CUDA_UPDATE_TIME] = 0;
cuda_timer = end;
}
if ((elapsed_times[DISPLAY_UPDATE_TIME] + routine_bench[OVERALL_UPDATE_TIME]) >=
routine_runtime[DISPLAY_UPDATE_TIME]) {
disp_priority = true;
elapsed_times[DISPLAY_UPDATE_TIME] = 0;
disp_timer = end;
}
}
void interpreter_main_loop() {
// Round robin algorithm goes here
round_robin_bench();
global = std::chrono::high_resolution_clock::now();
cuda_timer = global;
disp_timer = global;
for (;;) {
if (cuda_priority) {
LOG_F(9, "Placeholder for Cuda Update function!\n");
cuda_priority = false;
}
if (disp_priority) {
LOG_F(9, "Placeholder for Display Update function! \n");
disp_priority = false;
}
ppc_exec();
interpreter_update_counters();
}
}
+23
View File
@@ -0,0 +1,23 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
void interpreter_update_counters();
void interpreter_main_loop();
+8
View File
@@ -0,0 +1,8 @@
set(CMAKE_CXX_STANDARD 11)
include_directories("${PROJECT_SOURCE_DIR}")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
add_library(machines OBJECT ${SOURCES})
target_link_libraries(machines PRIVATE cubeb)
+99
View File
@@ -0,0 +1,99 @@
#include "machinebase.h"
#include "devices/hwcomponent.h"
#include <map>
#include <memory>
#include <string>
#include <thirdparty/loguru/loguru.hpp>
std::unique_ptr<MachineBase> gMachineObj = 0;
MachineBase::MachineBase(std::string name) {
this->name = name;
/* initialize internal maps */
this->comp_map.clear();
this->subdev_map.clear();
this->aliases.clear();
}
MachineBase::~MachineBase() {
for (auto it = this->comp_map.begin(); it != this->comp_map.end(); it++) {
delete it->second;
}
this->comp_map.clear();
this->aliases.clear();
this->subdev_map.clear();
}
bool MachineBase::add_component(std::string name, HWComponent* dev_obj) {
if (this->comp_map.count(name)) {
LOG_F(ERROR, "Component %s already exists!", name.c_str());
return false;
}
this->comp_map[name] = dev_obj;
return true;
}
bool MachineBase::add_subdevice(std::string name, HWComponent* dev_obj) {
if (this->subdev_map.count(name)) {
LOG_F(ERROR, "Subdevice %s already exists!", name.c_str());
return false;
}
this->subdev_map[name] = dev_obj;
return true;
}
void MachineBase::add_alias(std::string name, std::string alias) {
this->aliases[alias] = name;
}
HWComponent* MachineBase::get_comp_by_name(std::string name) {
if (this->aliases.count(name)) {
name = this->aliases[name];
}
if (this->comp_map.count(name)) {
return this->comp_map[name];
}
if (this->subdev_map.count(name)) {
return this->subdev_map[name];
} else {
return NULL;
}
}
HWComponent* MachineBase::get_comp_by_type(HWCompType type) {
std::string comp_name;
bool found = false;
for (auto it = this->comp_map.begin(); it != this->comp_map.end(); it++) {
if (it->second->supports_type(type)) {
comp_name = it->first;
found = true;
break;
}
}
if (found) {
return this->get_comp_by_name(comp_name);
}
for (auto it = this->subdev_map.begin(); it != this->subdev_map.end(); it++) {
if (it->second->supports_type(type)) {
comp_name = it->first;
found = true;
break;
}
}
if (found) {
return this->get_comp_by_name(comp_name);
} else {
return NULL;
}
}
+55
View File
@@ -0,0 +1,55 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Base class for managing different HW components of a machine.
Author: Max Poliakovski
*/
#ifndef MACHINE_BASE_H
#define MACHINE_BASE_H
#include "devices/hwcomponent.h"
#include <map>
#include <memory>
#include <string>
class MachineBase {
public:
MachineBase(std::string name);
~MachineBase();
bool add_component(std::string name, HWComponent* dev_obj);
bool add_subdevice(std::string name, HWComponent* dev_obj);
void add_alias(std::string name, std::string alias);
HWComponent* get_comp_by_name(std::string name);
HWComponent* get_comp_by_type(HWCompType type);
private:
std::string name;
std::map<std::string, HWComponent*> comp_map;
std::map<std::string, HWComponent*> subdev_map;
std::map<std::string, std::string> aliases;
};
extern std::unique_ptr<MachineBase> gMachineObj;
#endif /* MACHINE_BASE_H */
+279
View File
@@ -0,0 +1,279 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Factory for creating different machines.
Author: Max Poliakovski
*/
#include "machinefactory.h"
#include "devices/memctrlbase.h"
#include "memaccess.h"
#include "machineproperties.h"
#include <cinttypes>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <iomanip>
#include <map>
#include <memory>
#include <vector>
#include <thirdparty/loguru/loguru.hpp>
using namespace std;
map<string, unique_ptr<BasicProperty>> gMachineSettings;
/**
Power Macintosh ROM identification map.
Maps Bootstrap string located at offset 0x30D064 (PCI Macs)
or 0x30C064 (Nubus Macs) to machine name and description.
*/
static const map<uint32_t, std::tuple<string, const char*>> rom_identity = {
{0x416C6368, {"pm6400", "Performa 6400"}}, // Alchemy
//{"Come", "PowerBook 2400"}, // Comet
{0x436F7264, {"pm5200", "Power Mac 5200/6200 series"}}, // Cordyceps
{0x47617A65, {"pm6500", "Power Mac 6500"}}, // Gazelle
{0x476F7373, {"pmg3", "Power Mac G3 Beige"}}, // Gossamer
{0x47525820, {"pbg3", "PowerBook G3 Wallstreet"}},
//{"Hoop", "PowerBook 3400"}, // Hooper
{0x50425820, {"pb-preg3", "PowerBook Pre-G3"}},
{0x50444D20, {"pm6100", "Nubus Power Mac"}}, // Piltdown Man (6100/7100/8100)
{0x50697020, {"pippin", "Bandai Pippin"}}, // Pippin
//{"Powe", "Generic Power Mac"}, // PowerMac?
{0x544E5420, {"pm7200", "Power Mac 7xxxx/8xxx series"}}, // Trinitrotoluene :-)
{0x5A616E7A, {"pm4400", "Power Mac 4400/7220"}}, // Zanzibar
};
static const PropMap GossamerSettings = {
{"rambank1_size",
new IntProperty(256, vector<uint32_t>({8, 16, 32, 64, 128, 256}))},
{"rambank2_size",
new IntProperty( 0, vector<uint32_t>({0, 8, 16, 32, 64, 128, 256}))},
{"rambank3_size",
new IntProperty( 0, vector<uint32_t>({0, 8, 16, 32, 64, 128, 256}))},
{"gfxmem_size",
new IntProperty( 2, vector<uint32_t>({2, 4, 6}))},
};
static const map<string, string> PropHelp = {
{"rambank1_size", "specifies RAM bank 1 size in MB"},
{"rambank2_size", "specifies RAM bank 2 size in MB"},
{"rambank3_size", "specifies RAM bank 3 size in MB"},
{"gfxmem_size", "specifies video memory size in MB"},
};
static const map<string, tuple<PropMap, function<int(void)>, string>> machines = {
{"pmg3", {GossamerSettings, create_gossamer, "Power Macintosh G3 (Beige)"}},
};
string machine_name_from_rom(string& rom_filepath) {
ifstream rom_file;
uint32_t file_size, config_info_offset, rom_id;
char rom_id_str[17];
string machine_name = "";
rom_file.open(rom_filepath, ios::in | ios::binary);
if (rom_file.fail()) {
LOG_F(ERROR, "Cound not open the specified ROM file.");
goto bail_out;
}
rom_file.seekg(0, rom_file.end);
file_size = rom_file.tellg();
rom_file.seekg(0, rom_file.beg);
if (file_size != 0x400000UL) {
LOG_F(ERROR, "Unxpected ROM File size. Expected size is 4 megabytes.");
goto bail_out;
}
/* read config info offset from file */
config_info_offset = 0;
rom_file.seekg(0x300080, ios::beg);
rom_file.read((char*)&config_info_offset, 4);
config_info_offset = READ_DWORD_BE_A(&config_info_offset);
/* rewind to ConfigInfo.BootstrapVersion field */
rom_file.seekg(0x300064 + config_info_offset, ios::beg);
/* read BootstrapVersion as C string */
rom_file.read(rom_id_str, 16);
rom_id_str[16] = 0;
LOG_F(INFO, "ROM BootstrapVersion: %s", rom_id_str);
if (strncmp(rom_id_str, "Boot", 4) != 0) {
LOG_F(ERROR, "Invalid BootstrapVersion string.");
goto bail_out;
}
/* convert BootstrapVersion string to ROM ID */
rom_id = (rom_id_str[5] << 24) | (rom_id_str[6] << 16) |
(rom_id_str[7] << 8) | rom_id_str[8];
LOG_F(INFO, "The machine is identified as... %s\n",
std::get<1>(rom_identity.at(rom_id)));
machine_name = std::get<0>(rom_identity.at(rom_id));
bail_out:
rom_file.close();
return machine_name;
}
int get_machine_settings(string& id, map<string, string> &settings) {
try {
auto props = get<0>(machines.at(id));
gMachineSettings.clear();
for (auto& p : props) {
settings[p.first] = p.second->get_string();
/* populate dynamic machine settings from presets */
gMachineSettings[p.first] = unique_ptr<BasicProperty>(p.second->clone());
}
}
catch(out_of_range ex) {
LOG_F(ERROR, "Unknown machine id %s", id.c_str());
return -1;
}
return 0;
}
void set_machine_settings(map<string, string> &settings) {
for (auto& s : settings) {
gMachineSettings.at(s.first)->set_string(s.second);
}
/* print machine settings summary */
cout << endl << "Machine settings summary: " << endl;
for (auto& p : gMachineSettings) {
cout << p.first << " : " << p.second->get_string() << endl;
}
}
void list_machines() {
cout << endl << "Supported machines:" << endl << endl;
for (auto& mach : machines) {
cout << setw(13) << mach.first << "\t\t" << get<2>(mach.second) << endl;
}
cout << endl;
}
void list_properties() {
cout << endl;
for (auto& mach : machines) {
cout << get<2>(mach.second) << " supported properties:" << endl << endl;
for (auto& p : get<0>(mach.second)) {
cout << setw(13) << p.first << "\t\t" << PropHelp.at(p.first)
<< endl;
if (p.second->get_type() == PROP_TYPE_INTEGER) {
cout << setw(13) << "\t\t\t" "Valid values: " <<
dynamic_cast<IntProperty*>(p.second)->get_valid_values_as_str()
<< endl;
}
cout << endl;
}
}
cout << endl;
}
/* Read ROM file content and transfer it to the dedicated ROM region */
void load_rom(std::ifstream& rom_file, uint32_t file_size) {
unsigned char* sysrom_mem = new unsigned char[file_size];
rom_file.seekg(0, ios::beg);
rom_file.read((char*)sysrom_mem, file_size);
MemCtrlBase* mem_ctrl = dynamic_cast<MemCtrlBase*>(
gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
mem_ctrl->set_data(0xFFC00000, sysrom_mem, file_size);
delete[] sysrom_mem;
}
/* Read ROM file content and transfer it to the dedicated ROM region */
int load_boot_rom(string& rom_filepath) {
ifstream rom_file;
size_t file_size;
int result;
rom_file.open(rom_filepath, ios::in | ios::binary);
if (rom_file.fail()) {
LOG_F(ERROR, "Cound not open the specified ROM file.");
rom_file.close();
return -1;
}
rom_file.seekg(0, rom_file.end);
file_size = rom_file.tellg();
rom_file.seekg(0, rom_file.beg);
if (file_size != 0x400000UL) {
LOG_F(ERROR, "Unxpected ROM File size. Expected size is 4 megabytes.");
result = -1;
} else {
unsigned char* sysrom_mem = new unsigned char[file_size];
rom_file.seekg(0, ios::beg);
rom_file.read((char*)sysrom_mem, file_size);
MemCtrlBase* mem_ctrl = dynamic_cast<MemCtrlBase*>(
gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
mem_ctrl->set_data(0xFFC00000, sysrom_mem, file_size);
delete[] sysrom_mem;
result = 0;
}
rom_file.close();
return result;
}
int create_machine_for_id(string& id, string& rom_filepath) {
try {
auto machine = machines.at(id);
/* build machine and load boot ROM */
if (get<1>(machine)() < 0 || load_boot_rom(rom_filepath) < 0) {
return -1;
}
} catch(out_of_range ex) {
LOG_F(ERROR, "Unknown machine id %s", id.c_str());
return -1;
}
return 0;
}
+47
View File
@@ -0,0 +1,47 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Factory for creating different machines.
Author: Max Poliakovski
*/
#ifndef MACHINE_FACTORY_H
#define MACHINE_FACTORY_H
#include "machinebase.h"
#include <fstream>
#include <string>
using namespace std;
std::string machine_name_from_rom(std::string& rom_filepath);
int get_machine_settings(string& id, map<string, string> &settings);
void set_machine_settings(map<string, string> &settings);
int create_machine_for_id(string& id, string& rom_filepath);
void list_machines(void);
void list_properties(void);
/* Machine-specific factory functions. */
int create_gossamer(void);
#endif /* MACHINE_FACTORY_H */
+107
View File
@@ -0,0 +1,107 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Constructs the Gossamer machine.
Author: Max Poliakovski
*/
#include "cpu/ppc/ppcemu.h"
#include "devices/atirage.h"
#include "devices/machineid.h"
#include "devices/soundserver.h"
#include "devices/macio.h"
#include "devices/mpc106.h"
#include "devices/spdram.h"
#include "devices/viacuda.h"
#include "machinebase.h"
#include "machineproperties.h"
#include <thirdparty/loguru/loguru.hpp>
static void setup_ram_slot(std::string name, int i2c_addr, int capacity_megs) {
if (!capacity_megs)
return;
gMachineObj->add_component(name, new SpdSdram168(i2c_addr));
SpdSdram168* ram_dimm = dynamic_cast<SpdSdram168*>(gMachineObj->get_comp_by_name(name));
ram_dimm->set_capacity(capacity_megs);
/* register RAM DIMM with the I2C bus */
I2CBus* i2c_bus = dynamic_cast<I2CBus*>(gMachineObj->get_comp_by_type(HWCompType::I2C_HOST));
i2c_bus->register_device(i2c_addr, ram_dimm);
}
int create_gossamer() {
if (gMachineObj) {
LOG_F(ERROR, "Global machine object not empty!");
return -1;
}
LOG_F(INFO, "Initializing the Gossamer hardware...");
/* initialize the global machine object */
gMachineObj.reset(new MachineBase("Gossamer"));
/* register MPC106 aka Grackle as memory controller and PCI host */
gMachineObj->add_component("Grackle", new MPC106);
gMachineObj->add_alias("Grackle", "PCI_Host");
/* get raw pointer to MPC106 object */
MPC106* grackle_obj = dynamic_cast<MPC106*>(gMachineObj->get_comp_by_name("Grackle"));
/* add the machine ID register */
gMachineObj->add_component("MachineID", new GossamerID(0x3d8c));
grackle_obj->add_mmio_region(
0xFF000004, 4096, dynamic_cast<MMIODevice*>(gMachineObj->get_comp_by_name("MachineID")));
gMachineObj->add_component("SoundServer", new SoundServer());
/* add the Heathrow I/O controller */
gMachineObj->add_component("Heathrow", new HeathrowIC);
grackle_obj->pci_register_device(
16, dynamic_cast<PCIDevice*>(gMachineObj->get_comp_by_name("Heathrow")));
/* allocate ROM region */
if (!grackle_obj->add_rom_region(0xFFC00000, 0x400000)) {
LOG_F(ERROR, "Could not allocate ROM region!\n");
return -1;
}
/* configure RAM slots */
setup_ram_slot("RAM_DIMM_1", 0x57, GET_INT_PROP("rambank1_size"));
setup_ram_slot("RAM_DIMM_2", 0x56, GET_INT_PROP("rambank2_size"));
setup_ram_slot("RAM_DIMM_3", 0x55, GET_INT_PROP("rambank3_size"));
/* register ATI 3D Rage Pro video card with the PCI host bridge */
gMachineObj->add_component("ATIRage",
new ATIRage(ATI_RAGE_PRO_DEV_ID, GET_INT_PROP("gfxmem_size")));
grackle_obj->pci_register_device(
18, dynamic_cast<PCIDevice*>(gMachineObj->get_comp_by_name("ATIRage")));
/* Init virtual CPU and request MPC750 CPU aka G3 */
ppc_cpu_init(grackle_obj, PPC_VER::MPC750);
LOG_F(INFO, "Initialization complete.\n");
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#include "machineproperties.h"
#include <map>
static std::map<std::string, StrProperty> PowerMac6100_Properties = {
{"machineid", StrProperty("PowerMacG3")},
{"cputype", StrProperty("PPC_MPC750")},
{"motherboard", StrProperty("Grackle")},
{"ioboard", StrProperty("Heathrow")},
{"rambank1", StrProperty("8")},
{"minram", StrProperty("32")},
{"maxram", StrProperty("256")},
{"gfxcard", StrProperty("Nubus_Video")},
{"gfxmem", StrProperty("2")}
};
static std::map<std::string, StrProperty> PowerMacG3_Properties = {
{"machineid", StrProperty("PowerMacG3")},
{"cputype", StrProperty("PPC_MPC750")},
{"motherboard", StrProperty("Grackle")},
{"ioboard", StrProperty("Heathrow")},
{"rambank1", StrProperty("64")},
{"minram", StrProperty("32")},
{"maxram", StrProperty("256")},
{"gfxcard", StrProperty("ATI_Rage_Pro")},
{"gfxmem", StrProperty("2")}
};
static std::map<std::string, uint32_t> PPC_CPUs = {
{"PPC_MPC601", 0x00010001},
{"PPC_MPC603", 0x00030001},
{"PPC_MPC604", 0x00040001},
{"PPC_MPC603E", 0x00060101},
{"PPC_MPC750", 0x00080200}
};
static std::map<std::string, uint32_t> GFX_CARDs = {
{"ATI_Rage_Pro", 0x10024750},
{"ATI_Rage_128_Pro", 0x10025052}
};
+193
View File
@@ -0,0 +1,193 @@
#include "endianswap.h"
#include <thirdparty/loguru/loguru.hpp>
#include <algorithm>
#include <cinttypes>
#include <string>
#include <map>
#include <memory>
#include <limits>
#include <sstream>
#include <utility>
#include <vector>
#ifndef MACHINE_PROPERTIES_H
#define MACHINE_PROPERTIES_H
using namespace std;
#define ILLEGAL_DEVICE_VALUE 0x168A523B
/** Property types. */
enum PropType : int {
PROP_TYPE_UNKNOWN = 0,
PROP_TYPE_STRING = 1,
PROP_TYPE_INTEGER = 2,
};
/** Check types for property values. */
enum CheckType : int {
CHECK_TYPE_NONE = 0,
CHECK_TYPE_RANGE = 1,
CHECK_TYPE_LIST = 2,
};
/** Abstract base class for properties. */
class BasicProperty {
public:
BasicProperty(PropType type, string val) {
this->type = type;
set_string(val);
}
virtual ~BasicProperty() = default;
/* Clone method for copying derived property objects. */
virtual BasicProperty* clone() const = 0;
string get_string() {
return this->val;
}
void set_string(string str) {
this->val = str;
}
PropType get_type() {
return this->type;
}
protected:
PropType type;
string val;
};
/** Property class that holds a string value. */
class StrProperty : public BasicProperty {
public:
StrProperty(string str)
: BasicProperty(PROP_TYPE_STRING, str) {}
BasicProperty* clone() const { return new StrProperty(*this); }
};
/** Property class that holds an integer value. */
class IntProperty : public BasicProperty {
public:
/* construct an integer property without value check. */
IntProperty(uint32_t val)
: BasicProperty(PROP_TYPE_INTEGER, to_string(val))
{
this->int_val = val;
this->min = std::numeric_limits<uint32_t>::min();
this->max = std::numeric_limits<uint32_t>::max();
this->check_type = CHECK_TYPE_NONE;
this->vec.clear();
}
/* construct an integer property with a predefined range. */
IntProperty(uint32_t val, uint32_t min, uint32_t max)
: BasicProperty(PROP_TYPE_INTEGER, to_string(val))
{
this->int_val = val;
this->min = min;
this->max = max;
this->check_type = CHECK_TYPE_RANGE;
this->vec.clear();
}
/* construct an integer property with a list of valid values. */
IntProperty(uint32_t val, vector<uint32_t> vec)
: BasicProperty(PROP_TYPE_INTEGER, to_string(val))
{
this->int_val = val;
this->min = std::numeric_limits<uint32_t>::min();
this->max = std::numeric_limits<uint32_t>::max();
this->check_type = CHECK_TYPE_LIST;
this->vec = vec;
}
BasicProperty* clone() const { return new IntProperty(*this); }
uint32_t get_int() {
try {
uint32_t result = strtoul(this->get_string().c_str(), 0, 0);
/* perform value check */
if (!this->check_val(result)) {
LOG_F(ERROR, "Invalid property value %d!", result);
LOG_F(ERROR, "Valid values: %s!",
this->get_valid_values_as_str().c_str());
this->set_string(to_string(this->int_val));
} else {
this->int_val = result;
}
} catch (string bad_string) {
LOG_F(ERROR, "Could not convert string %s to an integer!",
bad_string.c_str());
}
return this->int_val;
}
string get_valid_values_as_str() {
stringstream ss;
switch (this->check_type) {
case CHECK_TYPE_RANGE:
ss << "[" << this->min << "..." << this->max << "]";
return ss.str();
case CHECK_TYPE_LIST: {
bool first = true;
for (auto it = begin(this->vec); it != end(this->vec); ++it) {
if (!first)
ss << ", ";
ss << *it;
first = false;
}
return ss.str();
}
default:
return string("None");
}
}
protected:
bool check_val(uint32_t val) {
switch (this->check_type) {
case CHECK_TYPE_RANGE:
if (val < this->min || val > this->max)
return false;
else
return true;
case CHECK_TYPE_LIST:
if (find(this->vec.begin(), this->vec.end(), val) != this->vec.end())
return true;
else
return false;
default:
return true;
}
}
private:
uint32_t int_val;
CheckType check_type;
uint32_t min;
uint32_t max;
vector<uint32_t> vec;
};
/** Special map type for specifying machine presets. */
typedef map<string, BasicProperty*> PropMap;
/** Global map that holds settings for the running machine. */
extern map<string, unique_ptr<BasicProperty>> gMachineSettings;
/** Conveniency macros to hide complex casts. */
#define GET_STR_PROP(name) \
dynamic_cast<StrProperty*>(gMachineSettings.at(name).get())->get_string()
#define GET_INT_PROP(name) \
dynamic_cast<IntProperty*>(gMachineSettings.at(name).get())->get_int()
#endif /* MACHINE_PROPERTIES_H */
+151 -155
View File
@@ -1,189 +1,185 @@
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-20 divingkatae and maximum
(theweirdo) spatium
//The main runfile - main.cpp
//This is where the magic begins
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// The main runfile - main.cpp
// This is where the magic begins
#include <iostream>
#include <map>
#include <cstring>
#include <cinttypes>
#include <array>
#include <stdio.h>
#include <fstream>
#include <stdexcept>
#include "ppcemu.h"
#include "ppcmmu.h"
#include "memreadwrite.h"
#include "devices/mpc106.h"
#include "debugger/debugger.h"
#include "devices/machineid.h"
#include "devices/macio.h"
#include "devices/mpc106.h"
#include "execution/interpreter_loop.h"
#include "machines/machinefactory.h"
#include "machines/machineproperties.h"
#include "ppcemu.h"
#include <cinttypes>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <thirdparty/CLI11/CLI11.hpp>
#include <thirdparty/SDL2/include/SDL.h>
#include <thirdparty/loguru/loguru.hpp>
using namespace std;
/**
Power Macintosh ROM identification string
static string appDescription = string(
"\nDingusPPC - Prototype 5bf5 (8/23/2020) "
"\nWritten by divingkatae and maximumspatium "
"\n(c) 2018-2020 The DingusPPC Dev Team. "
"\nThis is not intended for general use. "
"\nUse at your own discretion. "
"\n"
);
is located in the ConfigInfo structure starting at 0x30D064 (PCI Macs)
or 0x30C064 (Nubus Macs). This helps a lot to determine which
hardware is to be used.
*/
static const map<string,string> PPCMac_ROMIdentity = { //Codename Abbreviation for...
{"Alch", "Performa 6400"}, //Alchemy
{"Come", "PowerBook 2400"}, //Comet
{"Cord", "Power Mac 5200/6200 series"}, //Cordyceps
{"Gaze", "Power Mac 6500"}, //Gazelle
{"Goss", "Power Mac G3 Beige"}, //Gossamer
{"GRX ", "PowerBook G3 Wallstreet"}, //(Unknown)
{"Hoop", "PowerBook 3400"}, //Hooper
{"PBX ", "PowerBook Pre-G3"}, //(Unknown)
{"PDM ", "Nubus Power Mac or WGS"}, //Piltdown Man (6100/7100/8100)
{"Pip ", "Pippin... uh... yeah..."}, //Pippin
{"Powe", "Generic Power Mac"}, //PowerMac?
{"Spar", "20th Anniversay Mac, you lucky thing."}, //Spartacus
{"Tanz", "Power Mac 4400"}, //Tanzania
{"TNT ", "Power Mac 7xxxx/8xxx series"}, //Trinitrotoluene :-)
{"Zanz", "A complete engima."}, //Zanzibar (mentioned in Sheepshaver's code, but no match to any known ROM)
{"????", "A clone, perhaps?"} //N/A (Placeholder ID)
};
int main(int argc, char** argv) {
/*
Execution Type:
0 = Realtime (Interpreter)
1 = Realtime (Debugger)
2 = Recompiler (to-do)
HeathrowIC *heathrow = 0;
GossamerID *machine_id;
The rest will be decided later
*/
uint32_t execution_mode = 0;
int main(int argc, char **argv)
{
uint32_t rom_filesize;
CLI::App app(appDescription);
app.allow_windows_style_options(); /* we want Windows-style options */
app.allow_extras();
/* Init virtual CPU and request MPC750 CPU aka G3 */
ppc_cpu_init(PPC_VER::MPC750);
bool realtime_enabled, debugger_enabled = false;
string machine_str;
string bootrom_path("bootrom.bin");
uint32_t opcode_entered = 0; //used for testing opcodes in playground
app.add_flag("-r,--realtime", realtime_enabled,
"Run the emulator in real-time");
std::cout << "DingusPPC - Prototype 5bf4 (7/14/2019) " << endl;
std::cout << "Written by divingkatae, (c) 2019. " << endl;
std::cout << "This is not intended for general use. " << endl;
std::cout << "Use at your own discretion. " << endl;
app.add_flag("-d,--debugger", debugger_enabled,
"Enter the built-in debugger");
//Open the ROM File.
ifstream romFile;
app.add_option("-b,--bootrom", bootrom_path, "Specifies BootROM path")
->check(CLI::ExistingFile);
romFile.open("rom.bin", ios::in|ios::binary);
CLI::Option* machine_opt = app.add_option("-m,--machine",
machine_str, "Specify machine ID");
if (romFile.fail()){
cerr << "rom.bin not present. Please provide an appropriate ROM file"
<< " and restart this program.\n";
auto list_cmd = app.add_subcommand("list",
"Display available machine configurations and exit");
romFile.close();
return 1;
string sub_arg;
list_cmd->add_option("machines", sub_arg, "List supported machines");
list_cmd->add_option("properties", sub_arg, "List available properties");
CLI11_PARSE(app, argc, argv);
if (*list_cmd) {
if (sub_arg == "machines") {
list_machines();
} else if (sub_arg == "properties") {
list_properties();
} else {
cout << "Unknown list subcommand " << sub_arg << endl;
}
return 0;
}
//Calculate and validate ROM file size.
romFile.seekg(0, romFile.end);
rom_filesize = (uint32_t) romFile.tellg();
printf("Rom SIZE: %d \n", rom_filesize);
romFile.seekg (0, romFile.beg);
if (rom_filesize != 0x400000){
cerr << "Unsupported ROM File size. Expected size is 4 megabytes.\n";
romFile.close();
return 1;
if (debugger_enabled) {
if (realtime_enabled)
cout << "Both realtime and debugger enabled! Using debugger" << endl;
execution_mode = 1;
}
char configGrab = 0;
uint32_t configInfoOffset = 0;
/* initialize logging */
loguru::g_preamble_date = false;
loguru::g_preamble_time = false;
loguru::g_preamble_thread = false;
romFile.seekg (0x300082, ios::beg); //This is where the place to get the offset is
romFile.get(configGrab); //just one byte to determine ConfigInfo location
configInfoOffset = (uint32_t)(configGrab & 0xff);
if (!execution_mode) {
loguru::g_stderr_verbosity = loguru::Verbosity_OFF;
loguru::init(argc, argv);
loguru::add_file("dingusppc.log", loguru::Append, 0);
} else {
loguru::g_stderr_verbosity = 0;
loguru::init(argc, argv);
}
uint32_t configInfoAddr = 0x300000 + (configInfoOffset << 8) + 0x69; //address to check the identifier string
char memPPCBlock[5]; //First four chars are enough to distinguish between codenames
romFile.seekg (configInfoAddr, ios::beg);
romFile.read(memPPCBlock, 4);
memPPCBlock[4] = 0;
uint32_t rom_id = READ_DWORD_BE_A(memPPCBlock);
if (*machine_opt) {
LOG_F(INFO, "Machine option was passed in: %s", machine_str.c_str());
} else {
machine_str = machine_name_from_rom(bootrom_path);
if (machine_str.empty()) {
LOG_F(ERROR, "Could not autodetect machine");
return 0;
}
else {
LOG_F(INFO, "Machine was autodetected as: %s", machine_str.c_str());
}
}
std::string string_test = std::string(memPPCBlock);
/* handle overriding of machine settings from command line */
map<string, string> settings;
if (get_machine_settings(machine_str, settings) < 0) {
return 0;
}
//Just auto-iterate through the list
for (auto iter = PPCMac_ROMIdentity.begin(); iter != PPCMac_ROMIdentity.end(); ){
CLI::App sa;
sa.allow_extras();
string redo_me = iter->first;
for (auto& s : settings) {
sa.add_option("--" + s.first, s.second);
}
sa.parse(app.remaining_for_passthrough()); /* TODO: handle exceptions! */
if (string_test.compare(redo_me) == 0){
cout << "The machine is identified as..." << iter->second << endl;
romFile.seekg (0x0, ios::beg);
set_machine_settings(settings);
cout << "BootROM path: " << bootrom_path << endl;
cout << "Execution mode: " << execution_mode << endl;
if (create_machine_for_id(machine_str, bootrom_path) < 0) {
goto bail;
}
#ifdef SDL
if (SDL_Init(SDL_INIT_AUDIO)){
LOG_F(ERROR, "SDL_Init error: %s", SDL_GetError());
return 0;
}
#endif
switch (execution_mode) {
case 0:
interpreter_main_loop();
break;
}
else{
iter++;
}
}
switch(rom_id) {
case 0x476F7373: {
cout << "Initialize Gossamer hardware..." << endl;
MPC106 *mpc106 = new MPC106();
mem_ctrl_instance = mpc106;
if (!mem_ctrl_instance->add_rom_region(0xFFC00000, 0x400000)) {
cout << "failure!\n" << endl;
delete(mem_ctrl_instance);
romFile.close();
return 1;
}
machine_id = new GossamerID(0x3d8c);
mpc106->add_mmio_region(0xFF000004, 4096, machine_id);
heathrow = new HeathrowIC();
mpc106->pci_register_device(16, heathrow);
cout << "done" << endl;
}
break;
default:
cout << "This machine not supported yet." << endl;
return 1;
}
/* Read ROM file content and transfer it to the dedicated ROM region */
unsigned char *sysrom_mem = new unsigned char[rom_filesize];
romFile.read ((char *)sysrom_mem, rom_filesize);
mem_ctrl_instance->set_data(0xFFC00000, sysrom_mem, rom_filesize);
romFile.close();
delete[] sysrom_mem;
if (argc > 1) {
string checker = argv[1];
cout << checker << endl;
if ((checker == "1") || (checker == "realtime") || (checker == "/realtime")
|| (checker == "-realtime")) {
ppc_exec();
} else if ((checker == "debugger") || (checker == "/debugger") ||
(checker == "-debugger")) {
case 1:
enter_debugger();
}
}
else {
std::cout << " " << endl;
std::cout << "Please enter one of the following commands when " << endl;
std::cout << "booting up DingusPPC... " << endl;
std::cout << " " << endl;
std::cout << " " << endl;
std::cout << "realtime - Run the emulator in real-time. " << endl;
std::cout << "debugger - Enter the interactive debugger. " << endl;
break;
default:
LOG_F(ERROR, "Invalid EXECUTION MODE");
return 0;
}
/* Free memory after the emulation is completed. */
delete(heathrow);
delete(machine_id);
delete(mem_ctrl_instance);
bail:
LOG_F(INFO, "Cleaning up...");
delete gMachineObj.release();
return 0;
}
+181
View File
@@ -0,0 +1,181 @@
/** @file Set of macros for accessing host memory units of various sizes
and endianness.
*/
#ifndef MEM_ACCESS_H
#define MEM_ACCESS_H
#include "endianswap.h"
#include <cinttypes>
#include <thirdparty/loguru/loguru.hpp>
/* read an aligned big-endian WORD (16bit) */
#define READ_WORD_BE_A(addr) (BYTESWAP_16(*((uint16_t*)((addr)))))
/* read an aligned big-endian DWORD (32bit) */
#define READ_DWORD_BE_A(addr) (BYTESWAP_32(*((uint32_t*)((addr)))))
/* read an aligned big-endian QWORD (64bit) */
#define READ_QWORD_BE_A(addr) (BYTESWAP_64(*((uint64_t*)((addr)))))
/* read an aligned little-endian WORD (16bit) */
#define READ_WORD_LE_A(addr) (*(uint16_t*)((addr)))
/* read an aligned little-endian DWORD (32bit) */
#define READ_DWORD_LE_A(addr) (*(uint32_t*)((addr)))
/* read an aligned little-endian QWORD (64bit) */
#define READ_QWORD_LE_A(addr) (*(uint64_t*)((addr)))
/* read an unaligned big-endian WORD (16bit) */
#define READ_WORD_BE_U(addr) (((addr)[0] << 8) | (addr)[1])
/* read an unaligned big-endian DWORD (32bit) */
#define READ_DWORD_BE_U(addr) (((addr)[0] << 24) | ((addr)[1] << 16) | ((addr)[2] << 8) | (addr)[3])
/* read an unaligned big-endian QWORD (32bit) */
#define READ_QWORD_BE_U(addr) \
(((addr)[0] << 56) | ((addr)[1] << 48) | ((addr)[2] << 40) | ((addr)[3] << 32) | \
((addr)[4] << 24) | ((addr)[5] << 16) | ((addr)[6] << 8) | (addr)[7])
/* read an unaligned little-endian WORD (16bit) */
#define READ_WORD_LE_U(addr) (((addr)[1] << 8) | (addr)[0])
/* read an unaligned little-endian DWORD (32bit) */
#define READ_DWORD_LE_U(addr) (((addr)[3] << 24) | ((addr)[2] << 16) | ((addr)[1] << 8) | (addr)[0])
/* read an unaligned little-endian DWORD (32bit) */
#define READ_QWORD_LE_U(addr) \
(((addr)[7] << 56) | ((addr)[6] << 48) | ((addr)[5] << 40) | ((addr)[4] << 32) | \
((addr)[3] << 24) | ((addr)[2] << 16) | ((addr)[1] << 8) | (addr)[0])
/* write an aligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_A(addr, val) (*((uint16_t*)((addr))) = BYTESWAP_16(val))
/* write an aligned big-endian DWORD (32bit) */
#define WRITE_DWORD_BE_A(addr, val) (*((uint32_t*)((addr))) = BYTESWAP_32(val))
/* write an aligned big-endian QWORD (64bit) */
#define WRITE_QWORD_BE_A(addr, val) (*((uint64_t*)((addr))) = BYTESWAP_64(val))
/* write an unaligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_U(addr, val) \
do { \
(addr)[0] = ((val) >> 8) & 0xFF; \
(addr)[1] = (val)&0xFF; \
} while (0)
/* write an unaligned big-endian DWORD (32bit) */
#define WRITE_DWORD_BE_U(addr, val) \
do { \
(addr)[0] = ((val) >> 24) & 0xFF; \
(addr)[1] = ((val) >> 16) & 0xFF; \
(addr)[2] = ((val) >> 8) & 0xFF; \
(addr)[3] = (val)&0xFF; \
} while (0)
/* write an aligned little-endian WORD (16bit) */
#define WRITE_WORD_LE_A(addr, val) (*((uint16_t*)((addr))) = (val))
/* write an aligned little-endian DWORD (32bit) */
#define WRITE_DWORD_LE_A(addr, val) (*((uint32_t*)((addr))) = (val))
/* write an aligned little-endian QWORD (64bit) */
#define WRITE_QWORD_LE_A(addr, val) (*((uint64_t*)((addr))) = (val))
/* write an unaligned little-endian WORD (16bit) */
#define WRITE_WORD_LE_U(addr, val) \
do { \
(addr)[0] = (val)&0xFF; \
(addr)[1] = ((val) >> 8) & 0xFF; \
} while (0)
/* write an unaligned little-endian DWORD (32bit) */
#define WRITE_DWORD_LE_U(addr, val) \
do { \
(addr)[0] = (val)&0xFF; \
(addr)[1] = ((val) >> 8) & 0xFF; \
(addr)[2] = ((val) >> 16) & 0xFF; \
(addr)[3] = ((val) >> 24) & 0xFF; \
} while (0)
/* read value of the specified size from memory starting at addr,
perform byte swapping when necessary so that the source
byte order remains unchanged. */
inline uint32_t read_mem(const uint8_t* buf, uint32_t size) {
switch (size) {
case 4:
return READ_DWORD_BE_A(buf);
break;
case 2:
return READ_WORD_BE_A(buf);
break;
case 1:
return *buf;
break;
default:
LOG_F(WARNING, "READ_MEM: invalid size %d!", size);
return 0;
}
}
/* read value of the specified size from memory starting at addr,
perform byte swapping when necessary so that the destination data
will be in the reversed byte order. */
inline uint32_t read_mem_rev(const uint8_t* buf, uint32_t size) {
switch (size) {
case 4:
return READ_DWORD_LE_A(buf);
break;
case 2:
return READ_WORD_LE_A(buf);
break;
case 1:
return *buf;
break;
default:
LOG_F(WARNING, "READ_MEM_REV: invalid size %d!", size);
return 0;
}
}
/* write the specified value of the specified size to memory pointed
to by addr, perform necessary byte swapping so that the byte order
of the destination remains unchanged. */
inline void write_mem(uint8_t* buf, uint32_t value, uint32_t size) {
switch (size) {
case 4:
WRITE_DWORD_BE_A(buf, value);
break;
case 2:
WRITE_WORD_BE_A(buf, value & 0xFFFFU);
break;
case 1:
*buf = value & 0xFF;
break;
default:
LOG_F(WARNING, "WRITE_MEM: invalid size %d!", size);
}
}
/* write the specified value of the specified size to memory pointed
to by addr, perform necessary byte swapping so that the destination
data in memory will be in the reversed byte order. */
inline void write_mem_rev(uint8_t* buf, uint32_t value, uint32_t size) {
switch (size) {
case 4:
WRITE_DWORD_LE_A(buf, value);
break;
case 2:
WRITE_WORD_LE_A(buf, value & 0xFFFFU);
break;
case 1:
*buf = value & 0xFF;
break;
default:
LOG_F(WARNING, "WRITE_MEM_REV: invalid size %d!", size);
}
}
#endif /* MEM_ACCESS_H */
-81
View File
@@ -1,81 +0,0 @@
/** @file Set of macros for accessing integers of various sizes and endianness
in host memory.
*/
#ifndef MEM_READ_WRITE_H
#define MEM_READ_WRITE_H
#include <cinttypes>
#include "endianswap.h"
/* read an aligned big-endian WORD (16bit) */
#define READ_WORD_BE_A(addr) (BYTESWAP_16(*((uint16_t *)((addr)))))
/* read an aligned big-endian DWORD (32bit) */
#define READ_DWORD_BE_A(addr) (BYTESWAP_32(*((uint32_t *)((addr)))))
/* read an aligned big-endian QWORD (64bit) */
#define READ_QWORD_BE_A(addr) (BYTESWAP_64(*((uint64_t *)((addr)))))
/* read an aligned little-endian WORD (16bit) */
#define READ_WORD_LE_A(addr) (*(uint16_t *)((addr)))
/* read an aligned little-endian DWORD (32bit) */
#define READ_DWORD_LE_A(addr) (*(uint32_t *)((addr)))
/* read an aligned little-endian QWORD (64bit) */
#define READ_QWORD_LE_A(addr) (*(uint64_t *)((addr)))
/* read an unaligned big-endian WORD (16bit) */
#define READ_WORD_BE_U(addr) (((addr)[0] << 8) | (addr)[1])
/* read an unaligned big-endian DWORD (32bit) */
#define READ_DWORD_BE_U(addr) (((addr)[0] << 24) | ((addr)[1] << 16) | \
((addr)[2] << 8) | (addr)[3])
/* read an unaligned big-endian QWORD (32bit) */
#define READ_QWORD_BE_U(addr) (((addr)[0] << 56) | ((addr)[1] << 48) | \
((addr)[2] << 40) | ((addr)[3] << 32) | \
((addr)[4] << 24) | ((addr)[5] << 16) | \
((addr)[6] << 8) | (addr)[7])
/* read an unaligned little-endian WORD (16bit) */
#define READ_WORD_LE_U(addr) (((addr)[1] << 8) | (ptr)[0])
/* read an unaligned little-endian DWORD (32bit) */
#define READ_DWORD_LE_U(addr) (((addr)[3] << 24) | ((addr)[2] << 16) | \
((addr)[1] << 8) | (addr)[0])
/* read an unaligned little-endian DWORD (32bit) */
#define READ_QWORD_LE_U(addr) (((addr)[7] << 56) | ((addr)[6] << 48) | \
((addr)[5] << 40) | ((addr)[4] << 32) | \
((addr)[3] << 24) | ((addr)[2] << 16) | \
((addr)[1] << 8) | (addr)[0])
/* write an aligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_A(addr,val) (*((uint16_t *)((addr))) = BYTESWAP_16(val))
/* write an aligned big-endian DWORD (32bit) */
#define WRITE_DWORD_BE_A(addr,val) (*((uint32_t *)((addr))) = BYTESWAP_32(val))
/* write an aligned big-endian QWORD (64bit) */
#define WRITE_QWORD_BE_A(addr,val) (*((uint64_t *)((addr))) = BYTESWAP_64(val))
/* write an unaligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_U(addr, val) \
do { \
(addr)[0] = ((val) >> 8) & 0xFF; \
(addr)[1] = (val) & 0xFF; \
} while(0)
/* write an unaligned big-endian DWORD (32bit) */
#define WRITE_DWORD_BE_U(addr, val) \
do { \
(addr)[0] = ((val) >> 24) & 0xFF; \
(addr)[1] = ((val) >> 16) & 0xFF; \
(addr)[2] = ((val) >> 8) & 0xFF; \
(addr)[3] = (val) & 0xFF; \
} while(0)
#endif /* MEM_READ_WRITE_H */
+8258
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
Bugs are now managed in the SDL bug tracker, here:
https://bugzilla.libsdl.org/
You may report bugs there, and search to see if a given issue has already
been reported, discussed, and maybe even fixed.
You may also find help at the SDL forums/mailing list:
https://discourse.libsdl.org/
Bug reports are welcome here, but we really appreciate if you use Bugzilla, as
bugs discussed on the mailing list may be forgotten or missed.
+20
View File
@@ -0,0 +1,20 @@
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
+13
View File
@@ -0,0 +1,13 @@
Please distribute this file with the SDL runtime environment:
The Simple DirectMedia Layer (SDL for short) is a cross-platform library
designed to make it easy to write multi-media software, such as games
and emulators.
The Simple DirectMedia Layer library source code is available from:
https://www.libsdl.org/
This library is distributed under the terms of the zlib license:
http://www.zlib.net/zlib_license.html
+21
View File
@@ -0,0 +1,21 @@
Simple DirectMedia Layer
(SDL)
Version 2.0
---
https://www.libsdl.org/
Simple DirectMedia Layer is a cross-platform development library designed
to provide low level access to audio, keyboard, mouse, joystick, and graphics
hardware via OpenGL and Direct3D. It is used by video playback software,
emulators, and popular games including Valve's award winning catalog
and many Humble Bundle games.
More extensive documentation is available in the docs directory, starting
with README.md
Enjoy!
Sam Lantinga ([email protected])
+529
View File
@@ -0,0 +1,529 @@
This is a list of major changes in SDL's version history.
---------------------------------------------------------------------------
2.0.12:
---------------------------------------------------------------------------
General:
* Added SDL_GetTextureScaleMode() and SDL_SetTextureScaleMode() to get and set the scaling mode used for a texture
* Added SDL_LockTextureToSurface(), similar to SDL_LockTexture() but the locked area is exposed as a SDL surface.
* Added new blend mode, SDL_BLENDMODE_MUL, which does a modulate and blend operation
* Added the hint SDL_HINT_DISPLAY_USABLE_BOUNDS to override the results of SDL_GetDisplayUsableBounds() for display index 0.
* Added the window underneath the finger to the SDL_TouchFingerEvent
* Added SDL_GameControllerTypeForIndex(), SDL_GameControllerGetType() to return the type of a game controller (Xbox 360, Xbox One, PS3, PS4, or Nintendo Switch Pro)
* Added the hint SDL_HINT_GAMECONTROLLERTYPE to override the automatic game controller type detection
* Added SDL_JoystickFromPlayerIndex() and SDL_GameControllerFromPlayerIndex() to get the device associated with a player index
* Added SDL_JoystickSetPlayerIndex() and SDL_GameControllerSetPlayerIndex() to set the player index associated with a device
* Added the hint SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS to specify whether Nintendo Switch Pro controllers should use the buttons as labeled or swapped to match positional layout. The default is to use the buttons as labeled.
* Added support for Nintendo GameCube controllers to the HIDAPI driver, and a hint SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE to control whether this is used.
* Improved support for Xbox 360 and Xbox One controllers when using the HIDAPI driver
* Added support for many game controllers, including:
* 8BitDo FC30 Pro
* 8BitDo M30 GamePad
* BDA PS4 Fightpad
* HORI Fighting Commander
* Hyperkin Duke
* Hyperkin X91
* MOGA XP5-A Plus
* NACON GC-400ES
* NVIDIA Controller v01.04
* PDP Versus Fighting Pad
* Razer Raion Fightpad for PS4
* Razer Serval
* Stadia Controller
* SteelSeries Stratus Duo
* Victrix Pro Fight Stick for PS4
* Xbox One Elite Series 2
* Fixed blocking game controller rumble calls when using the HIDAPI driver
* Added SDL_zeroa() macro to zero an array of elements
* Added SDL_HasARMSIMD() which returns true if the CPU has ARM SIMD (ARMv6+) features
Windows:
* Fixed crash when using the release SDL DLL with applications built with gcc
* Fixed performance regression in event handling introduced in 2.0.10
* Added support for SDL_SetThreadPriority() for UWP applications
Linux:
* Added the hint SDL_HINT_VIDEO_X11_WINDOW_VISUALID to specify the visual chosen for new X11 windows
* Added the hint SDL_HINT_VIDEO_X11_FORCE_EGL to specify whether X11 should use GLX or EGL by default
iOS / tvOS / macOS:
* Added SDL_Metal_CreateView() and SDL_Metal_DestroyView() to create CAMetalLayer-backed NSView/UIView and attach it to the specified window.
iOS/ tvOS:
* Added support for Bluetooth Steam Controllers as game controllers
tvOS:
* Fixed support for surround sound on Apple TV
Android:
* Added SDL_GetAndroidSDKVersion() to return the API level of the current device
* Added support for audio capture using OpenSL-ES
* Added support for Bluetooth Steam Controllers as game controllers
* Fixed rare crashes when the app goes into the background or terminates
---------------------------------------------------------------------------
2.0.10:
---------------------------------------------------------------------------
General:
* The SDL_RW* macros have been turned into functions that are available only in 2.0.10 and onward
* Added SDL_SIMDGetAlignment(), SDL_SIMDAlloc(), and SDL_SIMDFree(), to allocate memory aligned for SIMD operations for the current CPU
* Added SDL_RenderDrawPointF(), SDL_RenderDrawPointsF(), SDL_RenderDrawLineF(), SDL_RenderDrawLinesF(), SDL_RenderDrawRectF(), SDL_RenderDrawRectsF(), SDL_RenderFillRectF(), SDL_RenderFillRectsF(), SDL_RenderCopyF(), SDL_RenderCopyExF(), to allow floating point precision in the SDL rendering API.
* Added SDL_GetTouchDeviceType() to get the type of a touch device, which can be a touch screen or a trackpad in relative or absolute coordinate mode.
* The SDL rendering API now uses batched rendering by default, for improved performance
* Added SDL_RenderFlush() to force batched render commands to execute, if you're going to mix SDL rendering with native rendering
* Added the hint SDL_HINT_RENDER_BATCHING to control whether batching should be used for the rendering API. This defaults to "1" if you don't specify what rendering driver to use when creating the renderer.
* Added the hint SDL_HINT_EVENT_LOGGING to enable logging of SDL events for debugging purposes
* Added the hint SDL_HINT_GAMECONTROLLERCONFIG_FILE to specify a file that will be loaded at joystick initialization with game controller bindings
* Added the hint SDL_HINT_MOUSE_TOUCH_EVENTS to control whether SDL will synthesize touch events from mouse events
* Improved handling of malformed WAVE and BMP files, fixing potential security exploits
Linux:
* Removed the Mir video driver in favor of Wayland
iOS / tvOS:
* Added support for Xbox and PS4 wireless controllers in iOS 13 and tvOS 13
* Added support for text input using Bluetooth keyboards
Android:
* Added low latency audio using OpenSL ES
* Removed SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH (replaced by SDL_HINT_MOUSE_TOUCH_EVENTS and SDL_HINT_TOUCH_MOUSE_EVENTS)
SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH=1, should be replaced by setting both previous hints to 0.
SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH=0, should be replaced by setting both previous hints to 1.
* Added the hint SDL_HINT_ANDROID_BLOCK_ON_PAUSE to set whether the event loop will block itself when the app is paused.
---------------------------------------------------------------------------
2.0.9:
---------------------------------------------------------------------------
General:
* Added a new sensor API, initialized by passing SDL_INIT_SENSOR to SDL_Init(), and defined in SDL_sensor.h
* Added an event SDL_SENSORUPDATE which is sent when a sensor is updated
* Added SDL_GetDisplayOrientation() to return the current display orientation
* Added an event SDL_DISPLAYEVENT which is sent when the display orientation changes
* Added HIDAPI joystick drivers for more consistent support for Xbox, PS4 and Nintendo Switch Pro controller support across platforms. (Thanks to Valve for contributing the PS4 and Nintendo Switch Pro controller support)
* Added support for many other popular game controllers
* Added SDL_JoystickGetDevicePlayerIndex(), SDL_JoystickGetPlayerIndex(), and SDL_GameControllerGetPlayerIndex() to get the player index for a controller. For XInput controllers this returns the XInput index for the controller.
* Added SDL_GameControllerRumble() and SDL_JoystickRumble() which allow simple rumble without using the haptics API
* Added SDL_GameControllerMappingForDeviceIndex() to get the mapping for a controller before it's opened
* Added the hint SDL_HINT_MOUSE_DOUBLE_CLICK_TIME to control the mouse double-click time
* Added the hint SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS to control the mouse double-click radius, in pixels
* Added SDL_HasColorKey() to return whether a surface has a colorkey active
* Added SDL_HasAVX512F() to return whether the CPU has AVX-512F features
* Added SDL_IsTablet() to return whether the application is running on a tablet
* Added SDL_THREAD_PRIORITY_TIME_CRITICAL for threads that must run at the highest priority
Mac OS X:
* Fixed black screen at start on Mac OS X Mojave
Linux:
* Added SDL_LinuxSetThreadPriority() to allow adjusting the thread priority of native threads using RealtimeKit if available.
iOS:
* Fixed Asian IME input
Android:
* Updated required Android SDK to API 26, to match Google's new App Store requirements
* Added support for wired USB Xbox, PS4, and Nintendo Switch Pro controllers
* Added support for relative mouse mode on Android 7.0 and newer (except where it's broken, on Chromebooks and when in DeX mode with Samsung Experience 9.0)
* Added support for custom mouse cursors on Android 7.0 and newer
* Added the hint SDL_HINT_ANDROID_TRAP_BACK_BUTTON to control whether the back button will back out of the app (the default) or be passed to the application as SDL_SCANCODE_AC_BACK
* Added SDL_AndroidBackButton() to trigger the Android system back button behavior when handling the back button in the application
* Added SDL_IsChromebook() to return whether the app is running in the Chromebook Android runtime
* Added SDL_IsDeXMode() to return whether the app is running while docked in the Samsung DeX
---------------------------------------------------------------------------
2.0.8:
---------------------------------------------------------------------------
General:
* Added SDL_fmod() and SDL_log10()
* Each of the SDL math functions now has the corresponding float version
* Added SDL_SetYUVConversionMode() and SDL_GetYUVConversionMode() to control the formula used when converting to and from YUV colorspace. The options are JPEG, BT.601, and BT.709
Windows:
* Implemented WASAPI support on Windows UWP and removed the deprecated XAudio2 implementation
* Added resampling support on WASAPI on Windows 7 and above
Windows UWP:
* Added SDL_WinRTGetDeviceFamily() to find out what type of device your application is running on
Mac OS X:
* Added support for the Vulkan SDK for Mac:
https://www.lunarg.com/lunarg-releases-vulkan-sdk-1-0-69-0-for-mac/
* Added support for OpenGL ES using ANGLE when it's available
Mac OS X / iOS / tvOS:
* Added a Metal 2D render implementation
* Added SDL_RenderGetMetalLayer() and SDL_RenderGetMetalCommandEncoder() to insert your own drawing into SDL rendering when using the Metal implementation
iOS:
* Added the hint SDL_HINT_IOS_HIDE_HOME_INDICATOR to control whether the home indicator bar on iPhone X should be hidden. This defaults to dimming the indicator for fullscreen applications and showing the indicator for windowed applications.
iOS / Android:
* Added the hint SDL_HINT_RETURN_KEY_HIDES_IME to control whether the return key on the software keyboard should hide the keyboard or send a key event (the default)
Android:
* SDL now supports building with Android Studio and Gradle by default, and the old Ant project is available in android-project-ant
* SDL now requires the API 19 SDK to build, but can still target devices down to API 14 (Android 4.0.1)
* Added SDL_IsAndroidTV() to tell whether the application is running on Android TV
Android / tvOS:
* Added the hint SDL_HINT_TV_REMOTE_AS_JOYSTICK to control whether TV remotes should be listed as joystick devices (the default) or send keyboard events.
Linux:
* Added the hint SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR to control whether the X server should skip the compositor for the SDL application. This defaults to "1"
* Added the hint SDL_HINT_VIDEO_DOUBLE_BUFFER to control whether the Raspberry Pi and KMSDRM video drivers should use double or triple buffering (the default)
---------------------------------------------------------------------------
2.0.7:
---------------------------------------------------------------------------
General:
* Added audio stream conversion functions:
SDL_NewAudioStream
SDL_AudioStreamPut
SDL_AudioStreamGet
SDL_AudioStreamAvailable
SDL_AudioStreamFlush
SDL_AudioStreamClear
SDL_FreeAudioStream
* Added functions to query and set the SDL memory allocation functions:
SDL_GetMemoryFunctions()
SDL_SetMemoryFunctions()
SDL_GetNumAllocations()
* Added locking functions for multi-threaded access to the joystick and game controller APIs:
SDL_LockJoysticks()
SDL_UnlockJoysticks()
* The following functions are now thread-safe:
SDL_SetEventFilter()
SDL_GetEventFilter()
SDL_AddEventWatch()
SDL_DelEventWatch()
General:
---------------------------------------------------------------------------
2.0.6:
---------------------------------------------------------------------------
General:
* Added cross-platform Vulkan graphics support in SDL_vulkan.h
SDL_Vulkan_LoadLibrary()
SDL_Vulkan_GetVkGetInstanceProcAddr()
SDL_Vulkan_GetInstanceExtensions()
SDL_Vulkan_CreateSurface()
SDL_Vulkan_GetDrawableSize()
SDL_Vulkan_UnloadLibrary()
This is all the platform-specific code you need to bring up Vulkan on all SDL platforms. You can look at an example in test/testvulkan.c
* Added SDL_ComposeCustomBlendMode() to create custom blend modes for 2D rendering
* Added SDL_HasNEON() which returns whether the CPU has NEON instruction support
* Added support for many game controllers, including the Nintendo Switch Pro Controller
* Added support for inverted axes and separate axis directions in game controller mappings
* Added functions to return information about a joystick before it's opened:
SDL_JoystickGetDeviceVendor()
SDL_JoystickGetDeviceProduct()
SDL_JoystickGetDeviceProductVersion()
SDL_JoystickGetDeviceType()
SDL_JoystickGetDeviceInstanceID()
* Added functions to return information about an open joystick:
SDL_JoystickGetVendor()
SDL_JoystickGetProduct()
SDL_JoystickGetProductVersion()
SDL_JoystickGetType()
SDL_JoystickGetAxisInitialState()
* Added functions to return information about an open game controller:
SDL_GameControllerGetVendor()
SDL_GameControllerGetProduct()
SDL_GameControllerGetProductVersion()
* Added SDL_GameControllerNumMappings() and SDL_GameControllerMappingForIndex() to be able to enumerate the built-in game controller mappings
* Added SDL_LoadFile() and SDL_LoadFile_RW() to load a file into memory
* Added SDL_DuplicateSurface() to make a copy of a surface
* Added an experimental JACK audio driver
* Implemented non-power-of-two audio resampling, optionally using libsamplerate to perform the resampling
* Added the hint SDL_HINT_AUDIO_RESAMPLING_MODE to control the quality of resampling
* Added the hint SDL_HINT_RENDER_LOGICAL_SIZE_MODE to control the scaling policy for SDL_RenderSetLogicalSize():
"0" or "letterbox" - Uses letterbox/sidebars to fit the entire rendering on screen (the default)
"1" or "overscan" - Will zoom the rendering so it fills the entire screen, allowing edges to be drawn offscreen
* Added the hints SDL_HINT_MOUSE_NORMAL_SPEED_SCALE and SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE to scale the mouse speed when being read from raw mouse input
* Added the hint SDL_HINT_TOUCH_MOUSE_EVENTS to control whether SDL will synthesize mouse events from touch events
Windows:
* The new default audio driver on Windows is WASAPI and supports hot-plugging devices and changing the default audio device
* The old XAudio2 audio driver is deprecated and will be removed in the next release
* Added hints SDL_HINT_WINDOWS_INTRESOURCE_ICON and SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL to specify a custom icon resource ID for SDL windows
* The hint SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING is now on by default for compatibility with .NET languages and various Windows debuggers
* Updated the GUID format for game controller mappings, older mappings will be automatically converted on load
* Implemented the SDL_WINDOW_ALWAYS_ON_TOP flag on Windows
Linux:
* Added an experimental KMS/DRM video driver for embedded development
iOS:
* Added a hint SDL_HINT_AUDIO_CATEGORY to control the audio category, determining whether the phone mute switch affects the audio
---------------------------------------------------------------------------
2.0.5:
---------------------------------------------------------------------------
General:
* Implemented audio capture support for some platforms
* Added SDL_DequeueAudio() to retrieve audio when buffer queuing is turned on for audio capture
* Added events for dragging and dropping text
* Added events for dragging and dropping multiple items
* By default the click raising a window will not be delivered to the SDL application. You can set the hint SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH to "1" to allow that click through to the window.
* Saving a surface with an alpha channel as a BMP will use a newer BMP format that supports alpha information. You can set the hint SDL_HINT_BMP_SAVE_LEGACY_FORMAT to "1" to use the old format.
* Added SDL_GetHintBoolean() to get the boolean value of a hint
* Added SDL_RenderSetIntegerScale() to set whether to smoothly scale or use integral multiples of the viewport size when scaling the rendering output
* Added SDL_CreateRGBSurfaceWithFormat() and SDL_CreateRGBSurfaceWithFormatFrom() to create an SDL surface with a specific pixel format
* Added SDL_GetDisplayUsableBounds() which returns the area usable for windows. For example, on Mac OS X, this subtracts the area occupied by the menu bar and dock.
* Added SDL_GetWindowBordersSize() which returns the size of the window's borders around the client area
* Added a window event SDL_WINDOWEVENT_HIT_TEST when a window had a hit test that wasn't SDL_HITTEST_NORMAL (e.g. in the title bar or window frame)
* Added SDL_SetWindowResizable() to change whether a window is resizable
* Added SDL_SetWindowOpacity() and SDL_GetWindowOpacity() to affect the window transparency
* Added SDL_SetWindowModalFor() to set a window as modal for another window
* Added support for AUDIO_U16LSB and AUDIO_U16MSB to SDL_MixAudioFormat()
* Fixed flipped images when reading back from target textures when using the OpenGL renderer
* Fixed texture color modulation with SDL_BLENDMODE_NONE when using the OpenGL renderer
* Fixed bug where the alpha value of colorkeys was ignored when blitting in some cases
Windows:
* Added a hint SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING to prevent SDL from raising a debugger exception to name threads. This exception can cause problems with .NET applications when running under a debugger.
* The hint SDL_HINT_THREAD_STACK_SIZE is now supported on Windows
* Fixed XBox controller triggers automatically being pulled at startup
* The first icon from the executable is used as the default window icon at runtime
* Fixed SDL log messages being printed twice if SDL was built with C library support
* Reset dead keys when the SDL window loses focus, so dead keys pressed in SDL applications don't affect text input into other applications.
Mac OS X:
* Fixed selecting the dummy video driver
* The caps lock key now generates a pressed event when pressed and a released event when released, instead of a press/release event pair when pressed.
* Fixed mouse wheel events on Mac OS X 10.12
* The audio driver has been updated to use AVFoundation for better compatibility with newer versions of Mac OS X
Linux:
* Added support for the Fcitx IME
* Added a window event SDL_WINDOWEVENT_TAKE_FOCUS when a window manager asks the SDL window whether it wants to take focus.
* Refresh rates are now rounded instead of truncated, e.g. 59.94 Hz is rounded up to 60 Hz instead of 59.
* Added initial support for touchscreens on Raspberry Pi
OpenBSD:
* SDL_GetBasePath() is now implemented on OpenBSD
iOS:
* Added support for dynamically loaded objects on iOS 8 and newer
tvOS:
* Added support for Apple TV
* Added a hint SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION to control whether he Apple TV remote's joystick axes will automatically match the rotation of the remote.
Android:
* Fixed SDL not resizing window when Android screen resolution changes
* Corrected the joystick Z axis reporting for the accelerometer
Emscripten (running in a web browser):
* Many bug fixes and improvements
---------------------------------------------------------------------------
2.0.4:
---------------------------------------------------------------------------
General:
* Added support for web applications using Emscripten, see docs/README-emscripten.md for more information
* Added support for web applications using Native Client (NaCl), see docs/README-nacl.md for more information
* Added an API to queue audio instead of using the audio callback:
SDL_QueueAudio(), SDL_GetQueuedAudioSize(), SDL_ClearQueuedAudio()
* Added events for audio device hot plug support:
SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED
* Added SDL_PointInRect()
* Added SDL_HasAVX2() to detect CPUs with AVX2 support
* Added SDL_SetWindowHitTest() to let apps treat parts of their SDL window like traditional window decorations (drag areas, resize areas)
* Added SDL_GetGrabbedWindow() to get the window that currently has input grab, if any
* Added SDL_RenderIsClipEnabled() to tell whether clipping is currently enabled in a renderer
* Added SDL_CaptureMouse() to capture the mouse to get events while the mouse is not in your window
* Added SDL_WarpMouseGlobal() to warp the mouse cursor in global screen space
* Added SDL_GetGlobalMouseState() to get the current mouse state outside of an SDL window
* Added a direction field to mouse wheel events to tell whether they are flipped (natural) or not
* Added GL_CONTEXT_RELEASE_BEHAVIOR GL attribute (maps to [WGL|GLX]_ARB_context_flush_control extension)
* Added EGL_KHR_create_context support to allow OpenGL ES version selection on some platforms
* Added NV12 and NV21 YUV texture support for OpenGL and OpenGL ES 2.0 renderers
* Added a Vivante video driver that is used on various SoC platforms
* Added an event SDL_RENDER_DEVICE_RESET that is sent from the D3D renderers when the D3D device is lost, and from Android's event loop when the GLES context had to be recreated
* Added a hint SDL_HINT_NO_SIGNAL_HANDLERS to disable SDL's built in signal handling
* Added a hint SDL_HINT_THREAD_STACK_SIZE to set the stack size of SDL's threads
* Added SDL_sqrtf(), SDL_tan(), and SDL_tanf() to the stdlib routines
* Improved support for WAV and BMP files with unusual chunks in them
* Renamed SDL_assert_data to SDL_AssertData and SDL_assert_state to SDL_AssertState
* Added a hint SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN to prevent window interaction while cursor is hidden
* Added SDL_GetDisplayDPI() to get the DPI information for a display
* Added SDL_JoystickCurrentPowerLevel() to get the battery level of a joystick
* Added SDL_JoystickFromInstanceID(), as a helper function, to get the SDL_Joystick* that an event is referring to.
* Added SDL_GameControllerFromInstanceID(), as a helper function, to get the SDL_GameController* that an event is referring to.
Windows:
* Added support for Windows Phone 8.1 and Windows 10/UWP (Universal Windows Platform)
* Timer resolution is now 1 ms by default, adjustable with the SDL_HINT_TIMER_RESOLUTION hint
* SDLmain no longer depends on the C runtime, so you can use the same .lib in both Debug and Release builds
* Added SDL_SetWindowsMessageHook() to set a function to be called for every windows message before TranslateMessage()
* Added a hint SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP to control whether SDL_PumpEvents() processes the Windows message loop
* You can distinguish between real mouse and touch events by looking for SDL_TOUCH_MOUSEID in the mouse event "which" field
* SDL_SysWMinfo now contains the window HDC
* Added support for Unicode command line options
* Prevent beeping when Alt-key combos are pressed
* SDL_SetTextInputRect() re-positions the OS-rendered IME
* Added a hint SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 to prevent generating SDL_WINDOWEVENT_CLOSE events when Alt-F4 is pressed
* Added a hint SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING to use the old axis and button mapping for XInput devices (deprecated)
Mac OS X:
* Implemented drag-and-drop support
* Improved joystick hot-plug detection
* The SDL_WINDOWEVENT_EXPOSED window event is triggered in the appropriate situations
* Fixed relative mouse mode when the application loses/regains focus
* Fixed bugs related to transitioning to and from Spaces-aware fullscreen-desktop mode
* Fixed the refresh rate of display modes
* SDL_SysWMInfo is now ARC-compatible
* Added a hint SDL_HINT_MAC_BACKGROUND_APP to prevent forcing the application to become a foreground process
Linux:
* Enabled building with Mir and Wayland support by default.
* Added IBus IME support
* Added a hint SDL_HINT_IME_INTERNAL_EDITING to control whether IBus should handle text editing internally instead of sending SDL_TEXTEDITING events
* Added a hint SDL_HINT_VIDEO_X11_NET_WM_PING to allow disabling _NET_WM_PING protocol handling in SDL_CreateWindow()
* Added support for multiple audio devices when using Pulseaudio
* Fixed duplicate mouse events when using relative mouse motion
iOS:
* Added support for iOS 8
* The SDL_WINDOW_ALLOW_HIGHDPI window flag now enables high-dpi support, and SDL_GL_GetDrawableSize() or SDL_GetRendererOutputSize() gets the window resolution in pixels
* SDL_GetWindowSize() and display mode sizes are in the "DPI-independent points" / "screen coordinates" coordinate space rather than pixels (matches OS X behavior)
* Added native resolution support for the iPhone 6 Plus
* Added support for MFi game controllers
* Added support for the hint SDL_HINT_ACCELEROMETER_AS_JOYSTICK
* Added sRGB OpenGL ES context support on iOS 7+
* Added support for SDL_DisableScreenSaver(), SDL_EnableScreenSaver() and the hint SDL_HINT_VIDEO_ALLOW_SCREENSAVER
* SDL_SysWMinfo now contains the OpenGL ES framebuffer and color renderbuffer objects used by the window's active GLES view
* Fixed various rotation and orientation issues
* Fixed memory leaks
Android:
* Added a hint SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH to prevent mouse events from being registered as touch events
* Added hints SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION and SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION
* Added support for SDL_DisableScreenSaver(), SDL_EnableScreenSaver() and the hint SDL_HINT_VIDEO_ALLOW_SCREENSAVER
* Added support for SDL_ShowMessageBox() and SDL_ShowSimpleMessageBox()
Raspberry Pi:
* Added support for the Raspberry Pi 2
---------------------------------------------------------------------------
2.0.3:
---------------------------------------------------------------------------
Mac OS X:
* Fixed creating an OpenGL context by default on Mac OS X 10.6
---------------------------------------------------------------------------
2.0.2:
---------------------------------------------------------------------------
General:
* Added SDL_GL_ResetAttributes() to reset OpenGL attributes to default values
* Added an API to load a database of game controller mappings from a file:
SDL_GameControllerAddMappingsFromFile(), SDL_GameControllerAddMappingsFromRW()
* Added game controller mappings for the PS4 and OUYA controllers
* Added SDL_GetDefaultAssertionHandler() and SDL_GetAssertionHandler()
* Added SDL_DetachThread()
* Added SDL_HasAVX() to determine if the CPU has AVX features
* Added SDL_vsscanf(), SDL_acos(), and SDL_asin() to the stdlib routines
* EGL can now create/manage OpenGL and OpenGL ES 1.x/2.x contexts, and share
them using SDL_GL_SHARE_WITH_CURRENT_CONTEXT
* Added a field "clicks" to the mouse button event which records whether the event is a single click, double click, etc.
* The screensaver is now disabled by default, and there is a hint SDL_HINT_VIDEO_ALLOW_SCREENSAVER that can change that behavior.
* Added a hint SDL_HINT_MOUSE_RELATIVE_MODE_WARP to specify whether mouse relative mode should be emulated using mouse warping.
* testgl2 does not need to link with libGL anymore
* Added testgles2 test program to demonstrate working with OpenGL ES 2.0
* Added controllermap test program to visually map a game controller
Windows:
* Support for OpenGL ES 2.x contexts using either WGL or EGL (natively via
the driver or emulated through ANGLE)
* Added a hint SDL_HINT_VIDEO_WIN_D3DCOMPILER to specify which D3D shader compiler to use for OpenGL ES 2 support through ANGLE
* Added a hint SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT that is useful when creating multiple windows that should share the same OpenGL context.
* Added an event SDL_RENDER_TARGETS_RESET that is sent when D3D9 render targets are reset after the device has been restored.
Mac OS X:
* Added a hint SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK to control whether Ctrl+click should be treated as a right click on Mac OS X. This is off by default.
Linux:
* Fixed fullscreen and focused behavior when receiving NotifyGrab events
* Added experimental Wayland and Mir support, disabled by default
Android:
* Joystick support (minimum SDK version required to build SDL is now 12,
the required runtime version remains at 10, but on such devices joystick
support won't be available).
* Hotplugging support for joysticks
* Added a hint SDL_HINT_ACCELEROMETER_AS_JOYSTICK to control whether the accelerometer should be listed as a 3 axis joystick, which it will by default.
---------------------------------------------------------------------------
2.0.1:
---------------------------------------------------------------------------
General:
* Added an API to get common filesystem paths in SDL_filesystem.h:
SDL_GetBasePath(), SDL_GetPrefPath()
* Added an API to do optimized YV12 and IYUV texture updates:
SDL_UpdateYUVTexture()
* Added an API to get the amount of RAM on the system:
SDL_GetSystemRAM()
* Added a macro to perform timestamp comparisons with SDL_GetTicks():
SDL_TICKS_PASSED()
* Dramatically improved OpenGL ES 2.0 rendering performance
* Added OpenGL attribute SDL_GL_FRAMEBUFFER_SRGB_CAPABLE
Windows:
* Created a static library configuration for the Visual Studio 2010 project
* Added a hint to create the Direct3D device with support for multi-threading:
SDL_HINT_RENDER_DIRECT3D_THREADSAFE
* Added a function to get the D3D9 adapter index for a display:
SDL_Direct3D9GetAdapterIndex()
* Added a function to get the D3D9 device for a D3D9 renderer:
SDL_RenderGetD3D9Device()
* Fixed building SDL with the mingw32 toolchain (mingw-w64 is preferred)
* Fixed crash when using two XInput controllers at the same time
* Fixed detecting a mixture of XInput and DirectInput controllers
* Fixed clearing a D3D render target larger than the window
* Improved support for format specifiers in SDL_snprintf()
Mac OS X:
* Added support for retina displays:
Create your window with the SDL_WINDOW_ALLOW_HIGHDPI flag, and then use SDL_GL_GetDrawableSize() to find the actual drawable size. You are responsible for scaling mouse and drawing coordinates appropriately.
* Fixed mouse warping in fullscreen mode
* Right mouse click is emulated by holding the Ctrl key while left clicking
Linux:
* Fixed float audio support with the PulseAudio driver
* Fixed missing line endpoints in the OpenGL renderer on some drivers
* X11 symbols are no longer defined to avoid collisions when linking statically
iOS:
* Fixed status bar visibility on iOS 7
* Flipped the accelerometer Y axis to match expected values
Android:
IMPORTANT: You MUST get the updated SDLActivity.java to match C code
* Moved EGL initialization to native code
* Fixed the accelerometer axis rotation relative to the device rotation
* Fixed race conditions when handling the EGL context on pause/resume
* Touch devices are available for enumeration immediately after init
Raspberry Pi:
* Added support for the Raspberry Pi, see README-raspberrypi.txt for details
+454
View File
@@ -0,0 +1,454 @@
Android
================================================================================
Matt Styles wrote a tutorial on building SDL for Android with Visual Studio:
http://trederia.blogspot.de/2017/03/building-sdl2-for-android-with-visual.html
The rest of this README covers the Android gradle style build process.
If you are using the older ant build process, it is no longer officially
supported, but you can use the "android-project-ant" directory as a template.
================================================================================
Requirements
================================================================================
Android SDK (version 26 or later)
https://developer.android.com/sdk/index.html
Android NDK r15c or later
https://developer.android.com/tools/sdk/ndk/index.html
Minimum API level supported by SDL: 16 (Android 4.1)
================================================================================
How the port works
================================================================================
- Android applications are Java-based, optionally with parts written in C
- As SDL apps are C-based, we use a small Java shim that uses JNI to talk to
the SDL library
- This means that your application C code must be placed inside an Android
Java project, along with some C support code that communicates with Java
- This eventually produces a standard Android .apk package
The Android Java code implements an "Activity" and can be found in:
android-project/app/src/main/java/org/libsdl/app/SDLActivity.java
The Java code loads your game code, the SDL shared library, and
dispatches to native functions implemented in the SDL library:
src/core/android/SDL_android.c
================================================================================
Building an app
================================================================================
For simple projects you can use the script located at build-scripts/androidbuild.sh
There's two ways of using it:
androidbuild.sh com.yourcompany.yourapp < sources.list
androidbuild.sh com.yourcompany.yourapp source1.c source2.c ...sourceN.c
sources.list should be a text file with a source file name in each line
Filenames should be specified relative to the current directory, for example if
you are in the build-scripts directory and want to create the testgles.c test, you'll
run:
./androidbuild.sh org.libsdl.testgles ../test/testgles.c
One limitation of this script is that all sources provided will be aggregated into
a single directory, thus all your source files should have a unique name.
Once the project is complete the script will tell you where the debug APK is located.
If you want to create a signed release APK, you can use the project created by this
utility to generate it.
Finally, a word of caution: re running androidbuild.sh wipes any changes you may have
done in the build directory for the app!
For more complex projects, follow these instructions:
1. Copy the android-project directory wherever you want to keep your projects
and rename it to the name of your project.
2. Move or symlink this SDL directory into the "<project>/app/jni" directory
3. Edit "<project>/app/jni/src/Android.mk" to include your source files
4a. If you want to use Android Studio, simply open your <project> directory and start building.
4b. If you want to build manually, run './gradlew installDebug' in the project directory. This compiles the .java, creates an .apk with the native code embedded, and installs it on any connected Android device
If you already have a project that uses CMake, the instructions change somewhat:
1. Do points 1 and 2 from the instruction above.
2. Edit "<project>/app/build.gradle" to comment out or remove sections containing ndk-build
and uncomment the cmake sections. Add arguments to the CMake invocation as needed.
3. Edit "<project>/app/jni/CMakeLists.txt" to include your project (it defaults to
adding the "src" subdirectory). Note that you'll have SDL2, SDL2main and SDL2-static
as targets in your project, so you should have "target_link_libraries(yourgame SDL2 SDL2main)"
in your CMakeLists.txt file. Also be aware that you should use add_library() instead of
add_executable() for the target containing your "main" function.
If you wish to use Android Studio, you can skip the last step.
4. Run './gradlew installDebug' or './gradlew installRelease' in the project directory. It will build and install your .apk on any
connected Android device
Here's an explanation of the files in the Android project, so you can customize them:
android-project/app
build.gradle - build info including the application version and SDK
src/main/AndroidManifest.xml - package manifest. Among others, it contains the class name of the main Activity and the package name of the application.
jni/ - directory holding native code
jni/Application.mk - Application JNI settings, including target platform and STL library
jni/Android.mk - Android makefile that can call recursively the Android.mk files in all subdirectories
jni/CMakeLists.txt - Top-level CMake project that adds SDL as a subproject
jni/SDL/ - (symlink to) directory holding the SDL library files
jni/SDL/Android.mk - Android makefile for creating the SDL shared library
jni/src/ - directory holding your C/C++ source
jni/src/Android.mk - Android makefile that you should customize to include your source code and any library references
jni/src/CMakeLists.txt - CMake file that you may customize to include your source code and any library references
src/main/assets/ - directory holding asset files for your application
src/main/res/ - directory holding resources for your application
src/main/res/mipmap-* - directories holding icons for different phone hardware
src/main/res/values/strings.xml - strings used in your application, including the application name
src/main/java/org/libsdl/app/SDLActivity.java - the Java class handling the initialization and binding to SDL. Be very careful changing this, as the SDL library relies on this implementation. You should instead subclass this for your application.
================================================================================
Customizing your application name
================================================================================
To customize your application name, edit AndroidManifest.xml and replace
"org.libsdl.app" with an identifier for your product package.
Then create a Java class extending SDLActivity and place it in a directory
under src matching your package, e.g.
src/com/gamemaker/game/MyGame.java
Here's an example of a minimal class file:
--- MyGame.java --------------------------
package com.gamemaker.game;
import org.libsdl.app.SDLActivity;
/**
* A sample wrapper class that just calls SDLActivity
*/
public class MyGame extends SDLActivity { }
------------------------------------------
Then replace "SDLActivity" in AndroidManifest.xml with the name of your
class, .e.g. "MyGame"
================================================================================
Customizing your application icon
================================================================================
Conceptually changing your icon is just replacing the "ic_launcher.png" files in
the drawable directories under the res directory. There are several directories
for different screen sizes.
================================================================================
Loading assets
================================================================================
Any files you put in the "app/src/main/assets" directory of your project
directory will get bundled into the application package and you can load
them using the standard functions in SDL_rwops.h.
There are also a few Android specific functions that allow you to get other
useful paths for saving and loading data:
* SDL_AndroidGetInternalStoragePath()
* SDL_AndroidGetExternalStorageState()
* SDL_AndroidGetExternalStoragePath()
See SDL_system.h for more details on these functions.
The asset packaging system will, by default, compress certain file extensions.
SDL includes two asset file access mechanisms, the preferred one is the so
called "File Descriptor" method, which is faster and doesn't involve the Dalvik
GC, but given this method does not work on compressed assets, there is also the
"Input Stream" method, which is automatically used as a fall back by SDL. You
may want to keep this fact in mind when building your APK, specially when large
files are involved.
For more information on which extensions get compressed by default and how to
disable this behaviour, see for example:
http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/
================================================================================
Pause / Resume behaviour
================================================================================
If SDL_HINT_ANDROID_BLOCK_ON_PAUSE hint is set (the default),
the event loop will block itself when the app is paused (ie, when the user
returns to the main Android dashboard). Blocking is better in terms of battery
use, and it allows your app to spring back to life instantaneously after resume
(versus polling for a resume message).
Upon resume, SDL will attempt to restore the GL context automatically.
In modern devices (Android 3.0 and up) this will most likely succeed and your
app can continue to operate as it was.
However, there's a chance (on older hardware, or on systems under heavy load),
where the GL context can not be restored. In that case you have to listen for
a specific message, (which is not yet implemented!) and restore your textures
manually or quit the app (which is actually the kind of behaviour you'll see
under iOS, if the OS can not restore your GL context it will just kill your app)
================================================================================
Threads and the Java VM
================================================================================
For a quick tour on how Linux native threads interoperate with the Java VM, take
a look here: https://developer.android.com/guide/practices/jni.html
If you want to use threads in your SDL app, it's strongly recommended that you
do so by creating them using SDL functions. This way, the required attach/detach
handling is managed by SDL automagically. If you have threads created by other
means and they make calls to SDL functions, make sure that you call
Android_JNI_SetupThread() before doing anything else otherwise SDL will attach
your thread automatically anyway (when you make an SDL call), but it'll never
detach it.
================================================================================
Using STL
================================================================================
You can use STL in your project by creating an Application.mk file in the jni
folder and adding the following line:
APP_STL := c++_shared
For more information go here:
https://developer.android.com/ndk/guides/cpp-support
================================================================================
Using the emulator
================================================================================
There are some good tips and tricks for getting the most out of the
emulator here: https://developer.android.com/tools/devices/emulator.html
Especially useful is the info on setting up OpenGL ES 2.0 emulation.
Notice that this software emulator is incredibly slow and needs a lot of disk space.
Using a real device works better.
================================================================================
Troubleshooting
================================================================================
You can see if adb can see any devices with the following command:
adb devices
You can see the output of log messages on the default device with:
adb logcat
You can push files to the device with:
adb push local_file remote_path_and_file
You can push files to the SD Card at /sdcard, for example:
adb push moose.dat /sdcard/moose.dat
You can see the files on the SD card with a shell command:
adb shell ls /sdcard/
You can start a command shell on the default device with:
adb shell
You can remove the library files of your project (and not the SDL lib files) with:
ndk-build clean
You can do a build with the following command:
ndk-build
You can see the complete command line that ndk-build is using by passing V=1 on the command line:
ndk-build V=1
If your application crashes in native code, you can use ndk-stack to get a symbolic stack trace:
https://developer.android.com/ndk/guides/ndk-stack
If you want to go through the process manually, you can use addr2line to convert the
addresses in the stack trace to lines in your code.
For example, if your crash looks like this:
I/DEBUG ( 31): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 400085d0
I/DEBUG ( 31): r0 00000000 r1 00001000 r2 00000003 r3 400085d4
I/DEBUG ( 31): r4 400085d0 r5 40008000 r6 afd41504 r7 436c6a7c
I/DEBUG ( 31): r8 436c6b30 r9 435c6fb0 10 435c6f9c fp 4168d82c
I/DEBUG ( 31): ip 8346aff0 sp 436c6a60 lr afd1c8ff pc afd1c902 cpsr 60000030
I/DEBUG ( 31): #00 pc 0001c902 /system/lib/libc.so
I/DEBUG ( 31): #01 pc 0001ccf6 /system/lib/libc.so
I/DEBUG ( 31): #02 pc 000014bc /data/data/org.libsdl.app/lib/libmain.so
I/DEBUG ( 31): #03 pc 00001506 /data/data/org.libsdl.app/lib/libmain.so
You can see that there's a crash in the C library being called from the main code.
I run addr2line with the debug version of my code:
arm-eabi-addr2line -C -f -e obj/local/armeabi/libmain.so
and then paste in the number after "pc" in the call stack, from the line that I care about:
000014bc
I get output from addr2line showing that it's in the quit function, in testspriteminimal.c, on line 23.
You can add logging to your code to help show what's happening:
#include <android/log.h>
__android_log_print(ANDROID_LOG_INFO, "foo", "Something happened! x = %d", x);
If you need to build without optimization turned on, you can create a file called
"Application.mk" in the jni directory, with the following line in it:
APP_OPTIM := debug
================================================================================
Memory debugging
================================================================================
The best (and slowest) way to debug memory issues on Android is valgrind.
Valgrind has support for Android out of the box, just grab code using:
svn co svn://svn.valgrind.org/valgrind/trunk valgrind
... and follow the instructions in the file README.android to build it.
One thing I needed to do on Mac OS X was change the path to the toolchain,
and add ranlib to the environment variables:
export RANLIB=$NDKROOT/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-ranlib
Once valgrind is built, you can create a wrapper script to launch your
application with it, changing org.libsdl.app to your package identifier:
--- start_valgrind_app -------------------
#!/system/bin/sh
export TMPDIR=/data/data/org.libsdl.app
exec /data/local/Inst/bin/valgrind --log-file=/sdcard/valgrind.log --error-limit=no $*
------------------------------------------
Then push it to the device:
adb push start_valgrind_app /data/local
and make it executable:
adb shell chmod 755 /data/local/start_valgrind_app
and tell Android to use the script to launch your application:
adb shell setprop wrap.org.libsdl.app "logwrapper /data/local/start_valgrind_app"
If the setprop command says "could not set property", it's likely that
your package name is too long and you should make it shorter by changing
AndroidManifest.xml and the path to your class file in android-project/src
You can then launch your application normally and waaaaaaaiiittt for it.
You can monitor the startup process with the logcat command above, and
when it's done (or even while it's running) you can grab the valgrind
output file:
adb pull /sdcard/valgrind.log
When you're done instrumenting with valgrind, you can disable the wrapper:
adb shell setprop wrap.org.libsdl.app ""
================================================================================
Graphics debugging
================================================================================
If you are developing on a compatible Tegra-based tablet, NVidia provides
Tegra Graphics Debugger at their website. Because SDL2 dynamically loads EGL
and GLES libraries, you must follow their instructions for installing the
interposer library on a rooted device. The non-rooted instructions are not
compatible with applications that use SDL2 for video.
The Tegra Graphics Debugger is available from NVidia here:
https://developer.nvidia.com/tegra-graphics-debugger
================================================================================
Why is API level 16 the minimum required?
================================================================================
The latest NDK toolchain doesn't support targeting earlier than API level 16.
As of this writing, according to https://developer.android.com/about/dashboards/index.html
about 99% of the Android devices accessing Google Play support API level 16 or
higher (January 2018).
================================================================================
A note regarding the use of the "dirty rectangles" rendering technique
================================================================================
If your app uses a variation of the "dirty rectangles" rendering technique,
where you only update a portion of the screen on each frame, you may notice a
variety of visual glitches on Android, that are not present on other platforms.
This is caused by SDL's use of EGL as the support system to handle OpenGL ES/ES2
contexts, in particular the use of the eglSwapBuffers function. As stated in the
documentation for the function "The contents of ancillary buffers are always
undefined after calling eglSwapBuffers".
Setting the EGL_SWAP_BEHAVIOR attribute of the surface to EGL_BUFFER_PRESERVED
is not possible for SDL as it requires EGL 1.4, available only on the API level
17+, so the only workaround available on this platform is to redraw the entire
screen each frame.
Reference: http://www.khronos.org/registry/egl/specs/EGLTechNote0001.html
================================================================================
Ending your application
================================================================================
Two legitimate ways:
- return from your main() function. Java side will automatically terminate the
Activity by calling Activity.finish().
- Android OS can decide to terminate your application by calling onDestroy()
(see Activity life cycle). Your application will receive a SDL_QUIT event you
can handle to save things and quit.
Don't call exit() as it stops the activity badly.
NB: "Back button" can be handled as a SDL_KEYDOWN/UP events, with Keycode
SDLK_AC_BACK, for any purpose.
================================================================================
Known issues
================================================================================
- The number of buttons reported for each joystick is hardcoded to be 36, which
is the current maximum number of buttons Android can report.
+84
View File
@@ -0,0 +1,84 @@
CMake
================================================================================
(www.cmake.org)
SDL's build system was traditionally based on autotools. Over time, this
approach has suffered from several issues across the different supported
platforms.
To solve these problems, a new build system based on CMake is under development.
It works in parallel to the legacy system, so users can experiment with it
without complication.
While still experimental, the build system should be usable on the following
platforms:
* FreeBSD
* Linux
* VS.NET 2010
* MinGW and Msys
* macOS, iOS, and tvOS, with support for XCode
================================================================================
Usage
================================================================================
Assuming the source for SDL is located at ~/sdl
cd ~
mkdir build
cd build
cmake ../sdl
This will build the static and dynamic versions of SDL in the ~/build directory.
================================================================================
Usage, iOS/tvOS
================================================================================
CMake 3.14+ natively includes support for iOS and tvOS. SDL binaries may be built
using Xcode or Make, possibly among other build-systems.
When using a recent version of CMake (3.14+), it should be possible to:
- build SDL for iOS, both static and dynamic
- build SDL test apps (as iOS/tvOS .app bundles)
- generate a working SDL_config.h for iOS (using SDL_config.h.cmake as a basis)
To use, set the following CMake variables when running CMake's configuration stage:
- `CMAKE_SYSTEM_NAME=<OS>` (either `iOS` or `tvOS`)
- `CMAKE_OSX_SYSROOT=<SDK>` (examples: `iphoneos`, `iphonesimulator`, `iphoneos12.4`, `/full/path/to/iPhoneOS.sdk`,
`appletvos`, `appletvsimulator`, `appletvos12.4`, `/full/path/to/AppleTVOS.sdk`, etc.)
- `CMAKE_OSX_ARCHITECTURES=<semicolon-separated list of CPU architectures>` (example: "arm64;armv7s;x86_64")
### Examples (for iOS/tvOS):
- for iOS-Simulator, using the latest, installed SDK:
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64`
- for iOS-Device, using the latest, installed SDK, 64-bit only
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES=arm64`
- for iOS-Device, using the latest, installed SDK, mixed 32/64 bit
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES="arm64;armv7s"`
- for iOS-Device, using a specific SDK revision (iOS 12.4, in this example):
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos12.4 -DCMAKE_OSX_ARCHITECTURES=arm64`
- for iOS-Simulator, using the latest, installed SDK, and building SDL test apps (as .app bundles):
`cmake ~/sdl -DSDL_TEST=1 -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64`
- for tvOS-Simulator, using the latest, installed SDK:
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvsimulator -DCMAKE_OSX_ARCHITECTURES=x86_64`
- for tvOS-Device, using the latest, installed SDK:
`cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvos -DCMAKE_OSX_ARCHITECTURES=arm64`
+107
View File
@@ -0,0 +1,107 @@
DirectFB
========
Supports:
- Hardware YUV overlays
- OpenGL - software only
- 2D/3D accelerations (depends on directfb driver)
- multiple displays
- windows
What you need:
* DirectFB 1.0.1, 1.2.x, 1.3.0
* Kernel-Framebuffer support: required: vesafb, radeonfb ....
* Mesa 7.0.x - optional for OpenGL
/etc/directfbrc
This file should contain the following lines to make
your joystick work and avoid crashes:
------------------------
disable-module=joystick
disable-module=cle266
disable-module=cyber5k
no-linux-input-grab
------------------------
To disable to use x11 backend when DISPLAY variable is found use
export SDL_DIRECTFB_X11_CHECK=0
To disable the use of linux input devices, i.e. multimice/multikeyboard support,
use
export SDL_DIRECTFB_LINUX_INPUT=0
To use hardware accelerated YUV-overlays for YUV-textures, use:
export SDL_DIRECTFB_YUV_DIRECT=1
This is disabled by default. It will only support one
YUV texture, namely the first. Every other YUV texture will be
rendered in software.
In addition, you may use (directfb-1.2.x)
export SDL_DIRECTFB_YUV_UNDERLAY=1
to make the YUV texture an underlay. This will make the cursor to
be shown.
Simple Window Manager
=====================
The driver has support for a very, very basic window manager you may
want to use when running with "wm=default". Use
export SDL_DIRECTFB_WM=1
to enable basic window borders. In order to have the window title rendered,
you need to have the following font installed:
/usr/share/fonts/truetype/freefont/FreeSans.ttf
OpenGL Support
==============
The following instructions will give you *software* OpenGL. However this
works at least on all directfb supported platforms.
As of this writing 20100802 you need to pull Mesa from git and do the following:
------------------------
git clone git://anongit.freedesktop.org/git/mesa/mesa
cd mesa
git checkout 2c9fdaf7292423c157fc79b5ce43f0f199dd753a
------------------------
Edit configs/linux-directfb so that the Directories-section looks like
------------------------
# Directories
SRC_DIRS = mesa glu
GLU_DIRS = sgi
DRIVER_DIRS = directfb
PROGRAM_DIRS =
------------------------
make linux-directfb
make
echo Installing - please enter sudo pw.
sudo make install INSTALL_DIR=/usr/local/dfb_GL
cd src/mesa/drivers/directfb
make
sudo make install INSTALL_DIR=/usr/local/dfb_GL
------------------------
To run the SDL - testprograms:
export SDL_VIDEODRIVER=directfb
export LD_LIBRARY_PATH=/usr/local/dfb_GL/lib
export LD_PRELOAD=/usr/local/dfb_GL/libGL.so.7
./testgl
+130
View File
@@ -0,0 +1,130 @@
Dynamic API
================================================================================
Originally posted by Ryan at:
https://plus.google.com/103391075724026391227/posts/TB8UfnDYu4U
Background:
- The Steam Runtime has (at least in theory) a really kick-ass build of SDL2,
but developers are shipping their own SDL2 with individual Steam games.
These games might stop getting updates, but a newer SDL2 might be needed later.
Certainly we'll always be fixing bugs in SDL, even if a new video target isn't
ever needed, and these fixes won't make it to a game shipping its own SDL.
- Even if we replace the SDL2 in those games with a compatible one, that is to
say, edit a developer's Steam depot (yuck!), there are developers that are
statically linking SDL2 that we can't do this for. We can't even force the
dynamic loader to ignore their SDL2 in this case, of course.
- If you don't ship an SDL2 with the game in some form, people that disabled the
Steam Runtime, or just tried to run the game from the command line instead of
Steam might find themselves unable to run the game, due to a missing dependency.
- If you want to ship on non-Steam platforms like GOG or Humble Bundle, or target
generic Linux boxes that may or may not have SDL2 installed, you have to ship
the library or risk a total failure to launch. So now, you might have to have
a non-Steam build plus a Steam build (that is, one with and one without SDL2
included), which is inconvenient if you could have had one universal build
that works everywhere.
- We like the zlib license, but the biggest complaint from the open source
community about the license change is the static linking. The LGPL forced this
as a legal, not technical issue, but zlib doesn't care. Even those that aren't
concerned about the GNU freedoms found themselves solving the same problems:
swapping in a newer SDL to an older game often times can save the day.
Static linking stops this dead.
So here's what we did:
SDL now has, internally, a table of function pointers. So, this is what SDL_Init
now looks like:
UInt32 SDL_Init(Uint32 flags)
{
return jump_table.SDL_Init(flags);
}
Except that is all done with a bunch of macro magic so we don't have to maintain
every one of these.
What is jump_table.SDL_init()? Eventually, that's a function pointer of the real
SDL_Init() that you've been calling all this time. But at startup, it looks more
like this:
Uint32 SDL_Init_DEFAULT(Uint32 flags)
{
SDL_InitDynamicAPI();
return jump_table.SDL_Init(flags);
}
SDL_InitDynamicAPI() fills in jump_table with all the actual SDL function
pointers, which means that this _DEFAULT function never gets called again.
First call to any SDL function sets the whole thing up.
So you might be asking, what was the value in that? Isn't this what the operating
system's dynamic loader was supposed to do for us? Yes, but now we've got this
level of indirection, we can do things like this:
export SDL_DYNAMIC_API=/my/actual/libSDL-2.0.so.0
./MyGameThatIsStaticallyLinkedToSDL2
And now, this game that is statically linked to SDL, can still be overridden
with a newer, or better, SDL. The statically linked one will only be used as
far as calling into the jump table in this case. But in cases where no override
is desired, the statically linked version will provide its own jump table,
and everyone is happy.
So now:
- Developers can statically link SDL, and users can still replace it.
(We'd still rather you ship a shared library, though!)
- Developers can ship an SDL with their game, Valve can override it for, say,
new features on SteamOS, or distros can override it for their own needs,
but it'll also just work in the default case.
- Developers can ship the same package to everyone (Humble Bundle, GOG, etc),
and it'll do the right thing.
- End users (and Valve) can update a game's SDL in almost any case,
to keep abandoned games running on newer platforms.
- Everyone develops with SDL exactly as they have been doing all along.
Same headers, same ABI. Just get the latest version to enable this magic.
A little more about SDL_InitDynamicAPI():
Internally, InitAPI does some locking to make sure everything waits until a
single thread initializes everything (although even SDL_CreateThread() goes
through here before spinning a thread, too), and then decides if it should use
an external SDL library. If not, it sets up the jump table using the current
SDL's function pointers (which might be statically linked into a program, or in
a shared library of its own). If so, it loads that library and looks for and
calls a single function:
SInt32 SDL_DYNAPI_entry(Uint32 version, void *table, Uint32 tablesize);
That function takes a version number (more on that in a moment), the address of
the jump table, and the size, in bytes, of the table.
Now, we've got policy here: this table's layout never changes; new stuff gets
added to the end. Therefore SDL_DYNAPI_entry() knows that it can provide all
the needed functions if tablesize <= sizeof its own jump table. If tablesize is
bigger (say, SDL 2.0.4 is trying to load SDL 2.0.3), then we know to abort, but
if it's smaller, we know we can provide the entire API that the caller needs.
The version variable is a failsafe switch.
Right now it's always 1. This number changes when there are major API changes
(so we know if the tablesize might be smaller, or entries in it have changed).
Right now SDL_DYNAPI_entry gives up if the version doesn't match, but it's not
inconceivable to have a small dispatch library that only supplies this one
function and loads different, otherwise-incompatible SDL libraries and has the
right one initialize the jump table based on the version. For something that
must generically catch lots of different versions of SDL over time, like the
Steam Client, this isn't a bad option.
Finally, I'm sure some people are reading this and thinking,
"I don't want that overhead in my project!"
To which I would point out that the extra function call through the jump table
probably wouldn't even show up in a profile, but lucky you: this can all be
disabled. You can build SDL without this if you absolutely must, but we would
encourage you not to do that. However, on heavily locked down platforms like
iOS, or maybe when debugging, it makes sense to disable it. The way this is
designed in SDL, you just have to change one #define, and the entire system
vaporizes out, and SDL functions exactly like it always did. Most of it is
macro magic, so the system is contained to one C file and a few headers.
However, this is on by default and you have to edit a header file to turn it
off. Our hopes is that if we make it easy to disable, but not too easy,
everyone will ultimately be able to get what they want, but we've gently
nudged everyone towards what we think is the best solution.
+35
View File
@@ -0,0 +1,35 @@
Emscripten
================================================================================
Build:
$ mkdir build
$ cd build
$ emconfigure ../configure --host=asmjs-unknown-emscripten --disable-assembly --disable-threads --disable-cpuinfo CFLAGS="-O2"
$ emmake make
Or with cmake:
$ mkdir build
$ cd build
$ emcmake cmake ..
$ emmake make
To build one of the tests:
$ cd test/
$ emcc -O2 --js-opts 0 -g4 testdraw2.c -I../include ../build/.libs/libSDL2.a ../build/libSDL2_test.a -o a.html
Uses GLES2 renderer or software
Some other SDL2 libraries can be easily built (assuming SDL2 is installed somewhere):
SDL_mixer (http://www.libsdl.org/projects/SDL_mixer/):
$ EMCONFIGURE_JS=1 emconfigure ../configure
build as usual...
SDL_gfx (http://cms.ferzkopp.net/index.php/software/13-sdl-gfx):
$ EMCONFIGURE_JS=1 emconfigure ../configure --disable-mmx
build as usual...
+71
View File
@@ -0,0 +1,71 @@
Dollar Gestures
===========================================================================
SDL provides an implementation of the $1 gesture recognition system. This allows for recording, saving, loading, and performing single stroke gestures.
Gestures can be performed with any number of fingers (the centroid of the fingers must follow the path of the gesture), but the number of fingers must be constant (a finger cannot go down in the middle of a gesture). The path of a gesture is considered the path from the time when the final finger went down, to the first time any finger comes up.
Dollar gestures are assigned an Id based on a hash function. This is guaranteed to remain constant for a given gesture. There is a (small) chance that two different gestures will be assigned the same ID. In this case, simply re-recording one of the gestures should result in a different ID.
Recording:
----------
To begin recording on a touch device call:
SDL_RecordGesture(SDL_TouchID touchId), where touchId is the id of the touch device you wish to record on, or -1 to record on all connected devices.
Recording terminates as soon as a finger comes up. Recording is acknowledged by an SDL_DOLLARRECORD event.
A SDL_DOLLARRECORD event is a dgesture with the following fields:
* event.dgesture.touchId - the Id of the touch used to record the gesture.
* event.dgesture.gestureId - the unique id of the recorded gesture.
Performing:
-----------
As long as there is a dollar gesture assigned to a touch, every finger-up event will also cause an SDL_DOLLARGESTURE event with the following fields:
* event.dgesture.touchId - the Id of the touch which performed the gesture.
* event.dgesture.gestureId - the unique id of the closest gesture to the performed stroke.
* event.dgesture.error - the difference between the gesture template and the actual performed gesture. Lower error is a better match.
* event.dgesture.numFingers - the number of fingers used to draw the stroke.
Most programs will want to define an appropriate error threshold and check to be sure that the error of a gesture is not abnormally high (an indicator that no gesture was performed).
Saving:
-------
To save a template, call SDL_SaveDollarTemplate(gestureId, dst) where gestureId is the id of the gesture you want to save, and dst is an SDL_RWops pointer to the file where the gesture will be stored.
To save all currently loaded templates, call SDL_SaveAllDollarTemplates(dst) where dst is an SDL_RWops pointer to the file where the gesture will be stored.
Both functions return the number of gestures successfully saved.
Loading:
--------
To load templates from a file, call SDL_LoadDollarTemplates(touchId,src) where touchId is the id of the touch to load to (or -1 to load to all touch devices), and src is an SDL_RWops pointer to a gesture save file.
SDL_LoadDollarTemplates returns the number of templates successfully loaded.
===========================================================================
Multi Gestures
===========================================================================
SDL provides simple support for pinch/rotate/swipe gestures.
Every time a finger is moved an SDL_MULTIGESTURE event is sent with the following fields:
* event.mgesture.touchId - the Id of the touch on which the gesture was performed.
* event.mgesture.x - the normalized x coordinate of the gesture. (0..1)
* event.mgesture.y - the normalized y coordinate of the gesture. (0..1)
* event.mgesture.dTheta - the amount that the fingers rotated during this motion.
* event.mgesture.dDist - the amount that the fingers pinched during this motion.
* event.mgesture.numFingers - the number of fingers used in the gesture.
===========================================================================
Notes
===========================================================================
For a complete example see test/testgesture.c
Please direct questions/comments to:
jim.tla+sdl_touch@gmail.com
+22
View File
@@ -0,0 +1,22 @@
Mercurial
=========
The latest development version of SDL is available via Mercurial.
Mercurial allows you to get up-to-the-minute fixes and enhancements;
as a developer works on a source tree, you can use "hg" to mirror that
source tree instead of waiting for an official release. Please look
at the Mercurial website ( https://www.mercurial-scm.org/ ) for more
information on using hg, where you can also download software for
Mac OS X, Windows, and Unix systems.
hg clone http://hg.libsdl.org/SDL
If you are building SDL via configure, you will need to run autogen.sh
before running configure.
There is a web interface to the subversion repository at:
http://hg.libsdl.org/SDL/
There is an RSS feed available at that URL, for those that want to
track commits in real time.
+284
View File
@@ -0,0 +1,284 @@
iOS
======
==============================================================================
Building the Simple DirectMedia Layer for iOS 5.1+
==============================================================================
Requirements: Mac OS X 10.8 or later and the iOS 7+ SDK.
Instructions:
1. Open SDL.xcodeproj (located in Xcode-iOS/SDL) in Xcode.
2. Select your desired target, and hit build.
There are three build targets:
- libSDL.a:
Build SDL as a statically linked library
- testsdl:
Build a test program (there are known test failures which are fine)
- Template:
Package a project template together with the SDL for iPhone static libraries and copies of the SDL headers. The template includes proper references to the SDL library and headers, skeleton code for a basic SDL program, and placeholder graphics for the application icon and startup screen.
==============================================================================
Build SDL for iOS from the command line
==============================================================================
1. cd (PATH WHERE THE SDL CODE IS)/build-scripts
2. ./iosbuild.sh
If everything goes fine, you should see a build/ios directory, inside there's
two directories "lib" and "include".
"include" contains a copy of the SDL headers that you'll need for your project,
make sure to configure XCode to look for headers there.
"lib" contains find two files, libSDL2.a and libSDL2main.a, you have to add both
to your XCode project. These libraries contain three architectures in them,
armv6 for legacy devices, armv7, and i386 (for the simulator).
By default, iosbuild.sh will autodetect the SDK version you have installed using
xcodebuild -showsdks, and build for iOS >= 3.0, you can override this behaviour
by setting the MIN_OS_VERSION variable, ie:
MIN_OS_VERSION=4.2 ./iosbuild.sh
==============================================================================
Using the Simple DirectMedia Layer for iOS
==============================================================================
FIXME: This needs to be updated for the latest methods
Here is the easiest method:
1. Build the SDL library (libSDL2.a) and the iPhone SDL Application template.
2. Install the iPhone SDL Application template by copying it to one of Xcode's template directories. I recommend creating a directory called "SDL" in "/Developer/Platforms/iOS.platform/Developer/Library/Xcode/Project Templates/" and placing it there.
3. Start a new project using the template. The project should be immediately ready for use with SDL.
Here is a more manual method:
1. Create a new iOS view based application.
2. Build the SDL static library (libSDL2.a) for iOS and include them in your project. Xcode will ignore the library that is not currently of the correct architecture, hence your app will work both on iOS and in the iOS Simulator.
3. Include the SDL header files in your project.
4. Remove the ApplicationDelegate.h and ApplicationDelegate.m files -- SDL for iOS provides its own UIApplicationDelegate. Remove MainWindow.xib -- SDL for iOS produces its user interface programmatically.
5. Delete the contents of main.m and program your app as a regular SDL program instead. You may replace main.m with your own main.c, but you must tell Xcode not to use the project prefix file, as it includes Objective-C code.
==============================================================================
Notes -- Retina / High-DPI and window sizes
==============================================================================
Window and display mode sizes in SDL are in "screen coordinates" (or "points",
in Apple's terminology) rather than in pixels. On iOS this means that a window
created on an iPhone 6 will have a size in screen coordinates of 375 x 667,
rather than a size in pixels of 750 x 1334. All iOS apps are expected to
size their content based on screen coordinates / points rather than pixels,
as this allows different iOS devices to have different pixel densities
(Retina versus non-Retina screens, etc.) without apps caring too much.
By default SDL will not use the full pixel density of the screen on
Retina/high-dpi capable devices. Use the SDL_WINDOW_ALLOW_HIGHDPI flag when
creating your window to enable high-dpi support.
When high-dpi support is enabled, SDL_GetWindowSize() and display mode sizes
will still be in "screen coordinates" rather than pixels, but the window will
have a much greater pixel density when the device supports it, and the
SDL_GL_GetDrawableSize() or SDL_GetRendererOutputSize() functions (depending on
whether raw OpenGL or the SDL_Render API is used) can be queried to determine
the size in pixels of the drawable screen framebuffer.
Some OpenGL ES functions such as glViewport expect sizes in pixels rather than
sizes in screen coordinates. When doing 2D rendering with OpenGL ES, an
orthographic projection matrix using the size in screen coordinates
(SDL_GetWindowSize()) can be used in order to display content at the same scale
no matter whether a Retina device is used or not.
==============================================================================
Notes -- Application events
==============================================================================
On iOS the application goes through a fixed life cycle and you will get
notifications of state changes via application events. When these events
are delivered you must handle them in an event callback because the OS may
not give you any processing time after the events are delivered.
e.g.
int HandleAppEvents(void *userdata, SDL_Event *event)
{
switch (event->type)
{
case SDL_APP_TERMINATING:
/* Terminate the app.
Shut everything down before returning from this function.
*/
return 0;
case SDL_APP_LOWMEMORY:
/* You will get this when your app is paused and iOS wants more memory.
Release as much memory as possible.
*/
return 0;
case SDL_APP_WILLENTERBACKGROUND:
/* Prepare your app to go into the background. Stop loops, etc.
This gets called when the user hits the home button, or gets a call.
*/
return 0;
case SDL_APP_DIDENTERBACKGROUND:
/* This will get called if the user accepted whatever sent your app to the background.
If the user got a phone call and canceled it, you'll instead get an SDL_APP_DIDENTERFOREGROUND event and restart your loops.
When you get this, you have 5 seconds to save all your state or the app will be terminated.
Your app is NOT active at this point.
*/
return 0;
case SDL_APP_WILLENTERFOREGROUND:
/* This call happens when your app is coming back to the foreground.
Restore all your state here.
*/
return 0;
case SDL_APP_DIDENTERFOREGROUND:
/* Restart your loops here.
Your app is interactive and getting CPU again.
*/
return 0;
default:
/* No special processing, add it to the event queue */
return 1;
}
}
int main(int argc, char *argv[])
{
SDL_SetEventFilter(HandleAppEvents, NULL);
... run your main loop
return 0;
}
==============================================================================
Notes -- Accelerometer as Joystick
==============================================================================
SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory.
The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_JoystickGetAxis() reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_JoystickGetAxis() reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
==============================================================================
Notes -- OpenGL ES
==============================================================================
Your SDL application for iOS uses OpenGL ES for video by default.
OpenGL ES for iOS supports several display pixel formats, such as RGBA8 and RGB565, which provide a 32 bit and 16 bit color buffer respectively. By default, the implementation uses RGB565, but you may use RGBA8 by setting each color component to 8 bits in SDL_GL_SetAttribute().
If your application doesn't use OpenGL's depth buffer, you may find significant performance improvement by setting SDL_GL_DEPTH_SIZE to 0.
Finally, if your application completely redraws the screen each frame, you may find significant performance improvement by setting the attribute SDL_GL_RETAINED_BACKING to 0.
OpenGL ES on iOS doesn't use the traditional system-framebuffer setup provided in other operating systems. Special care must be taken because of this:
- The drawable Renderbuffer must be bound to the GL_RENDERBUFFER binding point when SDL_GL_SwapWindow() is called.
- The drawable Framebuffer Object must be bound while rendering to the screen and when SDL_GL_SwapWindow() is called.
- If multisample antialiasing (MSAA) is used and glReadPixels is used on the screen, the drawable framebuffer must be resolved to the MSAA resolve framebuffer (via glBlitFramebuffer or glResolveMultisampleFramebufferAPPLE), and the MSAA resolve framebuffer must be bound to the GL_READ_FRAMEBUFFER binding point, before glReadPixels is called.
The above objects can be obtained via SDL_GetWindowWMInfo() (in SDL_syswm.h).
==============================================================================
Notes -- Keyboard
==============================================================================
The SDL keyboard API has been extended to support on-screen keyboards:
void SDL_StartTextInput()
-- enables text events and reveals the onscreen keyboard.
void SDL_StopTextInput()
-- disables text events and hides the onscreen keyboard.
SDL_bool SDL_IsTextInputActive()
-- returns whether or not text events are enabled (and the onscreen keyboard is visible)
==============================================================================
Notes -- Reading and Writing files
==============================================================================
Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory.
Once your application is installed its directory tree looks like:
MySDLApp Home/
MySDLApp.app
Documents/
Library/
Preferences/
tmp/
When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences".
More information on this subject is available here:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html
==============================================================================
Notes -- iPhone SDL limitations
==============================================================================
Windows:
Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow() the flag SDL_WINDOW_BORDERLESS).
Textures:
The optimal texture formats on iOS are SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_BGR888, and SDL_PIXELFORMAT_RGB24 pixel formats.
Loading Shared Objects:
This is disabled by default since it seems to break the terms of the iOS SDK agreement for iOS versions prior to iOS 8. It can be re-enabled in SDL_config_iphoneos.h.
==============================================================================
Game Center
==============================================================================
Game Center integration might require that you break up your main loop in order to yield control back to the system. In other words, instead of running an endless main loop, you run each frame in a callback function, using:
int SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
This will set up the given function to be called back on the animation callback, and then you have to return from main() to let the Cocoa event loop run.
e.g.
extern "C"
void ShowFrame(void*)
{
... do event handling, frame logic and rendering ...
}
int main(int argc, char *argv[])
{
... initialize game ...
#if __IPHONEOS__
// Initialize the Game Center for scoring and matchmaking
InitGameCenter();
// Set up the game to run in the window animation callback on iOS
// so that Game Center and so forth works correctly.
SDL_iPhoneSetAnimationCallback(window, 1, ShowFrame, NULL);
#else
while ( running ) {
ShowFrame(0);
DelayFrame();
}
#endif
return 0;
}
==============================================================================
Deploying to older versions of iOS
==============================================================================
SDL supports deploying to older versions of iOS than are supported by the latest version of Xcode, all the way back to iOS 6.1
In order to do that you need to download an older version of Xcode:
https://developer.apple.com/download/more/?name=Xcode
Open the package contents of the older Xcode and your newer version of Xcode and copy over the folders in Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Then open the file Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/SDKSettings.plist and add the versions of iOS you want to deploy to the key Root/DefaultProperties/DEPLOYMENT_TARGET_SUGGESTED_VALUES
Open your project and set your deployment target to the desired version of iOS
Finally, remove GameController from the list of frameworks linked by your application and edit the build settings for "Other Linker Flags" and add -weak_framework GameController
+87
View File
@@ -0,0 +1,87 @@
Linux
================================================================================
By default SDL will only link against glibc, the rest of the features will be
enabled dynamically at runtime depending on the available features on the target
system. So, for example if you built SDL with Xinerama support and the target
system does not have the Xinerama libraries installed, it will be disabled
at runtime, and you won't get a missing library error, at least with the
default configuration parameters.
================================================================================
Build Dependencies
================================================================================
Ubuntu 13.04, all available features enabled:
sudo apt-get install build-essential mercurial make cmake autoconf automake \
libtool libasound2-dev libpulse-dev libaudio-dev libx11-dev libxext-dev \
libxrandr-dev libxcursor-dev libxi-dev libxinerama-dev libxxf86vm-dev \
libxss-dev libgl1-mesa-dev libesd0-dev libdbus-1-dev libudev-dev \
libgles1-mesa-dev libgles2-mesa-dev libegl1-mesa-dev libibus-1.0-dev \
fcitx-libs-dev libsamplerate0-dev libsndio-dev
Ubuntu 16.04+ can also add "libwayland-dev libxkbcommon-dev wayland-protocols"
to that command line for Wayland support.
NOTES:
- This includes all the audio targets except arts, because Ubuntu pulled the
artsc0-dev package, but in theory SDL still supports it.
- libsamplerate0-dev lets SDL optionally link to libresamplerate at runtime
for higher-quality audio resampling. SDL will work without it if the library
is missing, so it's safe to build in support even if the end user doesn't
have this library installed.
- DirectFB isn't included because the configure script (currently) fails to find
it at all. You can do "sudo apt-get install libdirectfb-dev" and fix the
configure script to include DirectFB support. Send patches. :)
================================================================================
Joystick does not work
================================================================================
If you compiled or are using a version of SDL with udev support (and you should!)
there's a few issues that may cause SDL to fail to detect your joystick. To
debug this, start by installing the evtest utility. On Ubuntu/Debian:
sudo apt-get install evtest
Then run:
sudo evtest
You'll hopefully see your joystick listed along with a name like "/dev/input/eventXX"
Now run:
cat /dev/input/event/XX
If you get a permission error, you need to set a udev rule to change the mode of
your device (see below)
Also, try:
sudo udevadm info --query=all --name=input/eventXX
If you see a line stating ID_INPUT_JOYSTICK=1, great, if you don't see it,
you need to set up an udev rule to force this variable.
A combined rule for the Saitek Pro Flight Rudder Pedals to fix both issues looks
like:
SUBSYSTEM=="input", ATTRS{idProduct}=="0763", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1"
SUBSYSTEM=="input", ATTRS{idProduct}=="0764", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1"
You can set up similar rules for your device by changing the values listed in
idProduct and idVendor. To obtain these values, try:
sudo udevadm info -a --name=input/eventXX | grep idVendor
sudo udevadm info -a --name=input/eventXX | grep idProduct
If multiple values come up for each of these, the one you want is the first one of each.
On other systems which ship with an older udev (such as CentOS), you may need
to set up a rule such as:
SUBSYSTEM=="input", ENV{ID_CLASS}=="joystick", ENV{ID_INPUT_JOYSTICK}="1"
+240
View File
@@ -0,0 +1,240 @@
Mac OS X
==============================================================================
These instructions are for people using Apple's Mac OS X (pronounced
"ten").
From the developer's point of view, OS X is a sort of hybrid Mac and
Unix system, and you have the option of using either traditional
command line tools or Apple's IDE Xcode.
Command Line Build
==================
To build SDL using the command line, use the standard configure and make
process:
./configure
make
sudo make install
You can also build SDL as a Universal library (a single binary for both
32-bit and 64-bit Intel architectures), on Mac OS X 10.7 and newer, by using
the gcc-fat.sh script in build-scripts:
mkdir mybuild
cd mybuild
CC=$PWD/../build-scripts/gcc-fat.sh CXX=$PWD/../build-scripts/g++-fat.sh ../configure
make
sudo make install
This script builds SDL with 10.5 ABI compatibility on i386 and 10.6
ABI compatibility on x86_64 architectures. For best compatibility you
should compile your application the same way.
Please note that building SDL requires at least Xcode 4.6 and the 10.7 SDK
(even if you target back to 10.5 systems). PowerPC support for Mac OS X has
been officially dropped as of SDL 2.0.2.
To use the library once it's built, you essential have two possibilities:
use the traditional autoconf/automake/make method, or use Xcode.
==============================================================================
Caveats for using SDL with Mac OS X
==============================================================================
Some things you have to be aware of when using SDL on Mac OS X:
- If you register your own NSApplicationDelegate (using [NSApp setDelegate:]),
SDL will not register its own. This means that SDL will not terminate using
SDL_Quit if it receives a termination request, it will terminate like a
normal app, and it will not send a SDL_DROPFILE when you request to open a
file with the app. To solve these issues, put the following code in your
NSApplicationDelegate implementation:
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (SDL_GetEventState(SDL_QUIT) == SDL_ENABLE) {
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
return NSTerminateCancel;
}
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
if (SDL_GetEventState(SDL_DROPFILE) == SDL_ENABLE) {
SDL_Event event;
event.type = SDL_DROPFILE;
event.drop.file = SDL_strdup([filename UTF8String]);
return (SDL_PushEvent(&event) > 0);
}
return NO;
}
==============================================================================
Using the Simple DirectMedia Layer with a traditional Makefile
==============================================================================
An existing autoconf/automake build system for your SDL app has good chances
to work almost unchanged on OS X. However, to produce a "real" Mac OS X binary
that you can distribute to users, you need to put the generated binary into a
so called "bundle", which basically is a fancy folder with a name like
"MyCoolGame.app".
To get this build automatically, add something like the following rule to
your Makefile.am:
bundle_contents = APP_NAME.app/Contents
APP_NAME_bundle: EXE_NAME
mkdir -p $(bundle_contents)/MacOS
mkdir -p $(bundle_contents)/Resources
echo "APPL????" > $(bundle_contents)/PkgInfo
$(INSTALL_PROGRAM) $< $(bundle_contents)/MacOS/
You should replace EXE_NAME with the name of the executable. APP_NAME is what
will be visible to the user in the Finder. Usually it will be the same
as EXE_NAME but capitalized. E.g. if EXE_NAME is "testgame" then APP_NAME
usually is "TestGame". You might also want to use `@PACKAGE@` to use the package
name as specified in your configure.ac file.
If your project builds more than one application, you will have to do a bit
more. For each of your target applications, you need a separate rule.
If you want the created bundles to be installed, you may want to add this
rule to your Makefile.am:
install-exec-hook: APP_NAME_bundle
rm -rf $(DESTDIR)$(prefix)/Applications/APP_NAME.app
mkdir -p $(DESTDIR)$(prefix)/Applications/
cp -r $< /$(DESTDIR)$(prefix)Applications/
This rule takes the Bundle created by the rule from step 3 and installs them
into "$(DESTDIR)$(prefix)/Applications/".
Again, if you want to install multiple applications, you will have to augment
the make rule accordingly.
But beware! That is only part of the story! With the above, you end up with
a bare bone .app bundle, which is double clickable from the Finder. But
there are some more things you should do before shipping your product...
1) The bundle right now probably is dynamically linked against SDL. That
means that when you copy it to another computer, *it will not run*,
unless you also install SDL on that other computer. A good solution
for this dilemma is to static link against SDL. On OS X, you can
achieve that by linking against the libraries listed by
sdl-config --static-libs
instead of those listed by
sdl-config --libs
Depending on how exactly SDL is integrated into your build systems, the
way to achieve that varies, so I won't describe it here in detail
2) Add an 'Info.plist' to your application. That is a special XML file which
contains some meta-information about your application (like some copyright
information, the version of your app, the name of an optional icon file,
and other things). Part of that information is displayed by the Finder
when you click on the .app, or if you look at the "Get Info" window.
More information about Info.plist files can be found on Apple's homepage.
As a final remark, let me add that I use some of the techniques (and some
variations of them) in Exult and ScummVM; both are available in source on
the net, so feel free to take a peek at them for inspiration!
==============================================================================
Using the Simple DirectMedia Layer with Xcode
==============================================================================
These instructions are for using Apple's Xcode IDE to build SDL applications.
- First steps
The first thing to do is to unpack the Xcode.tar.gz archive in the
top level SDL directory (where the Xcode.tar.gz archive resides).
Because Stuffit Expander will unpack the archive into a subdirectory,
you should unpack the archive manually from the command line:
cd [path_to_SDL_source]
tar zxf Xcode.tar.gz
This will create a new folder called Xcode, which you can browse
normally from the Finder.
- Building the Framework
The SDL Library is packaged as a framework bundle, an organized
relocatable folder hierarchy of executable code, interface headers,
and additional resources. For practical purposes, you can think of a
framework as a more user and system-friendly shared library, whose library
file behaves more or less like a standard UNIX shared library.
To build the framework, simply open the framework project and build it.
By default, the framework bundle "SDL.framework" is installed in
/Library/Frameworks. Therefore, the testers and project stationary expect
it to be located there. However, it will function the same in any of the
following locations:
~/Library/Frameworks
/Local/Library/Frameworks
/System/Library/Frameworks
- Build Options
There are two "Build Styles" (See the "Targets" tab) for SDL.
"Deployment" should be used if you aren't tweaking the SDL library.
"Development" should be used to debug SDL apps or the library itself.
- Building the Testers
Open the SDLTest project and build away!
- Using the Project Stationary
Copy the stationary to the indicated folders to access it from
the "New Project" and "Add target" menus. What could be easier?
- Setting up a new project by hand
Some of you won't want to use the Stationary so I'll give some tips:
* Create a new "Cocoa Application"
* Add src/main/macosx/SDLMain.m , .h and .nib to your project
* Remove "main.c" from your project
* Remove "MainMenu.nib" from your project
* Add "$(HOME)/Library/Frameworks/SDL.framework/Headers" to include path
* Add "$(HOME)/Library/Frameworks" to the frameworks search path
* Add "-framework SDL -framework Foundation -framework AppKit" to "OTHER_LDFLAGS"
* Set the "Main Nib File" under "Application Settings" to "SDLMain.nib"
* Add your files
* Clean and build
- Building from command line
Use pbxbuild in the same directory as your .pbproj file
- Running your app
You can send command line args to your app by either invoking it from
the command line (in *.app/Contents/MacOS) or by entering them in the
"Executables" panel of the target settings.
- Implementation Notes
Some things that may be of interest about how it all works...
* Working directory
As defined in the SDL_main.m file, the working directory of your SDL app
is by default set to its parent. You may wish to change this to better
suit your needs.
* You have a Cocoa App!
Your SDL app is essentially a Cocoa application. When your app
starts up and the libraries finish loading, a Cocoa procedure is called,
which sets up the working directory and calls your main() method.
You are free to modify your Cocoa app with generally no consequence
to SDL. You cannot, however, easily change the SDL window itself.
Functionality may be added in the future to help this.
Known bugs are listed in the file "BUGS.txt".
+103
View File
@@ -0,0 +1,103 @@
Native Client
================================================================================
Requirements:
* Native Client SDK (https://developer.chrome.com/native-client),
(tested with Pepper version 33 or higher).
The SDL backend for Chrome's Native Client has been tested only with the PNaCl
toolchain, which generates binaries designed to run on ARM and x86_32/64
platforms. This does not mean it won't work with the other toolchains!
================================================================================
Building SDL for NaCl
================================================================================
Set up the right environment variables (see naclbuild.sh), then configure SDL with:
configure --host=pnacl --prefix some/install/destination
Then "make".
As an example of how to create a deployable app a Makefile project is provided
in test/nacl/Makefile, which includes some monkey patching of the common.mk file
provided by NaCl, without which linking properly to SDL won't work (the search
path can't be modified externally, so the linker won't find SDL's binaries unless
you dump them into the SDK path, which is inconvenient).
Also provided in test/nacl is the required support file, such as index.html,
manifest.json, etc.
SDL apps for NaCl run on a worker thread using the ppapi_simple infrastructure.
This allows for blocking calls on all the relevant systems (OpenGL ES, filesystem),
hiding the asynchronous nature of the browser behind the scenes...which is not the
same as making it disappear!
================================================================================
Running tests
================================================================================
Due to the nature of NaCl programs, building and running SDL tests is not as
straightforward as one would hope. The script naclbuild.sh in build-scripts
automates the process and should serve as a guide for users of SDL trying to build
their own applications.
Basic usage:
./naclbuild.sh path/to/pepper/toolchain (i.e. ~/naclsdk/pepper_35)
This will build testgles2.c by default.
If you want to build a different test, for example testrendercopyex.c:
SOURCES=~/sdl/SDL/test/testrendercopyex.c ./naclbuild.sh ~/naclsdk/pepper_35
Once the build finishes, you have to serve the contents with a web server (the
script will give you instructions on how to do that with Python).
================================================================================
RWops and nacl_io
================================================================================
SDL_RWops work transparently with nacl_io. Two functions control the mount points:
int mount(const char* source, const char* target,
const char* filesystemtype,
unsigned long mountflags, const void *data);
int umount(const char *target);
For convenience, SDL will by default mount an httpfs tree at / before calling
the app's main function. Such setting can be overridden by calling:
umount("/");
And then mounting a different filesystem at /
It's important to consider that the asynchronous nature of file operations on a
browser is hidden from the application, effectively providing the developer with
a set of blocking file operations just like you get in a regular desktop
environment, which eases the job of porting to Native Client, but also introduces
a set of challenges of its own, in particular when big file sizes and slow
connections are involved.
For more information on how nacl_io and mount points work, see:
https://developer.chrome.com/native-client/devguide/coding/nacl_io
https://src.chromium.org/chrome/trunk/src/native_client_sdk/src/libraries/nacl_io/nacl_io.h
To be able to save into the directory "/save/" (like backup of game) :
mount("", "/save", "html5fs", 0, "type=PERSISTENT");
And add to manifest.json :
"permissions": [
"unlimitedStorage"
]
================================================================================
TODO - Known Issues
================================================================================
* Testing of all systems with a real application (something other than SDL's tests)
* Key events don't seem to work properly
+17
View File
@@ -0,0 +1,17 @@
Pandora
=====================================================================
( http://openpandora.org/ )
- A pandora specific video driver was written to allow SDL 2.0 with OpenGL ES
support to work on the pandora under the framebuffer. This driver do not have
input support for now, so if you use it you will have to add your own control code.
The video driver name is "pandora" so if you have problem running it from
the framebuffer, try to set the following variable before starting your application :
"export SDL_VIDEODRIVER=pandora"
- OpenGL ES support was added to the x11 driver, so it's working like the normal
x11 driver one with OpenGLX support, with SDL input event's etc..
David Carré (Cpasjuste)
cpasjuste@gmail.com
+8
View File
@@ -0,0 +1,8 @@
Platforms
=========
We maintain the list of supported platforms on our wiki now, and how to
build and install SDL for those platforms:
https://wiki.libsdl.org/Installation
+68
View File
@@ -0,0 +1,68 @@
Porting
=======
* Porting To A New Platform
The first thing you have to do when porting to a new platform, is look at
include/SDL_platform.h and create an entry there for your operating system.
The standard format is "__PLATFORM__", where PLATFORM is the name of the OS.
Ideally SDL_platform.h will be able to auto-detect the system it's building
on based on C preprocessor symbols.
There are two basic ways of building SDL at the moment:
1. The "UNIX" way: ./configure; make; make install
If you have a GNUish system, then you might try this. Edit configure.ac,
take a look at the large section labelled:
"Set up the configuration based on the host platform!"
Add a section for your platform, and then re-run autogen.sh and build!
2. Using an IDE:
If you're using an IDE or other non-configure build system, you'll probably
want to create a custom SDL_config.h for your platform. Edit SDL_config.h,
add a section for your platform, and create a custom SDL_config_{platform}.h,
based on SDL_config_minimal.h and SDL_config.h.in
Add the top level include directory to the header search path, and then add
the following sources to the project:
src/*.c
src/atomic/*.c
src/audio/*.c
src/cpuinfo/*.c
src/events/*.c
src/file/*.c
src/haptic/*.c
src/joystick/*.c
src/power/*.c
src/render/*.c
src/render/software/*.c
src/stdlib/*.c
src/thread/*.c
src/timer/*.c
src/video/*.c
src/audio/disk/*.c
src/audio/dummy/*.c
src/filesystem/dummy/*.c
src/video/dummy/*.c
src/haptic/dummy/*.c
src/joystick/dummy/*.c
src/main/dummy/*.c
src/thread/generic/*.c
src/timer/dummy/*.c
src/loadso/dummy/*.c
Once you have a working library without any drivers, you can go back to each
of the major subsystems and start implementing drivers for your platform.
If you have any questions, don't hesitate to ask on the SDL mailing list:
http://www.libsdl.org/mailing-list.php
Enjoy!
Sam Lantinga (slouken@libsdl.org)
+19
View File
@@ -0,0 +1,19 @@
PSP
======
SDL port for the Sony PSP contributed by
Captian Lex
Credit to
Marcus R.Brown,Jim Paris,Matthew H for the original SDL 1.2 for PSP
Geecko for his PSP GU lib "Glib2d"
Building
--------
To build for the PSP, make sure psp-config is in the path and run:
make -f Makefile.psp
To Do
------
PSP Screen Keyboard
+188
View File
@@ -0,0 +1,188 @@
Raspberry Pi
================================================================================
Requirements:
Raspbian (other Linux distros may work as well).
================================================================================
Features
================================================================================
* Works without X11
* Hardware accelerated OpenGL ES 2.x
* Sound via ALSA
* Input (mouse/keyboard/joystick) via EVDEV
* Hotplugging of input devices via UDEV
================================================================================
Raspbian Build Dependencies
================================================================================
sudo apt-get install libudev-dev libasound2-dev libdbus-1-dev
You also need the VideoCore binary stuff that ships in /opt/vc for EGL and
OpenGL ES 2.x, it usually comes pre-installed, but in any case:
sudo apt-get install libraspberrypi0 libraspberrypi-bin libraspberrypi-dev
================================================================================
NEON
================================================================================
If your Pi has NEON support, make sure you add -mfpu=neon to your CFLAGS so
that SDL will select some otherwise-disabled highly-optimized code. The
original Pi units don't have NEON, the Pi2 probably does, and the Pi3
definitely does.
================================================================================
Cross compiling from x86 Linux
================================================================================
To cross compile SDL for Raspbian from your desktop machine, you'll need a
Raspbian system root and the cross compilation tools. We'll assume these tools
will be placed in /opt/rpi-tools
sudo git clone --depth 1 https://github.com/raspberrypi/tools /opt/rpi-tools
You'll also need a Raspbian binary image.
Get it from: http://downloads.raspberrypi.org/raspbian_latest
After unzipping, you'll get file with a name like: "<date>-wheezy-raspbian.img"
Let's assume the sysroot will be built in /opt/rpi-sysroot.
export SYSROOT=/opt/rpi-sysroot
sudo kpartx -a -v <path_to_raspbian_image>.img
sudo mount -o loop /dev/mapper/loop0p2 /mnt
sudo cp -r /mnt $SYSROOT
sudo apt-get install qemu binfmt-support qemu-user-static
sudo cp /usr/bin/qemu-arm-static $SYSROOT/usr/bin
sudo mount --bind /dev $SYSROOT/dev
sudo mount --bind /proc $SYSROOT/proc
sudo mount --bind /sys $SYSROOT/sys
Now, before chrooting into the ARM sysroot, you'll need to apply a workaround,
edit $SYSROOT/etc/ld.so.preload and comment out all lines in it.
sudo chroot $SYSROOT
apt-get install libudev-dev libasound2-dev libdbus-1-dev libraspberrypi0 libraspberrypi-bin libraspberrypi-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxinerama-dev libxxf86vm-dev libxss-dev
exit
sudo umount $SYSROOT/dev
sudo umount $SYSROOT/proc
sudo umount $SYSROOT/sys
sudo umount /mnt
There's one more fix required, as the libdl.so symlink uses an absolute path
which doesn't quite work in our setup.
sudo rm -rf $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so
sudo ln -s ../../../lib/arm-linux-gnueabihf/libdl.so.2 $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so
The final step is compiling SDL itself.
export CC="/opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc --sysroot=$SYSROOT -I$SYSROOT/opt/vc/include -I$SYSROOT/usr/include -I$SYSROOT/opt/vc/include/interface/vcos/pthreads -I$SYSROOT/opt/vc/include/interface/vmcs_host/linux"
cd <SDL SOURCE>
mkdir -p build;cd build
LDFLAGS="-L$SYSROOT/opt/vc/lib" ../configure --with-sysroot=$SYSROOT --host=arm-raspberry-linux-gnueabihf --prefix=$PWD/rpi-sdl2-installed --disable-pulseaudio --disable-esd
make
make install
To be able to deploy this to /usr/local in the Raspbian system you need to fix up a few paths:
perl -w -pi -e "s#$PWD/rpi-sdl2-installed#/usr/local#g;" ./rpi-sdl2-installed/lib/libSDL2.la ./rpi-sdl2-installed/lib/pkgconfig/sdl2.pc ./rpi-sdl2-installed/bin/sdl2-config
================================================================================
Apps don't work or poor video/audio performance
================================================================================
If you get sound problems, buffer underruns, etc, run "sudo rpi-update" to
update the RPi's firmware. Note that doing so will fix these problems, but it
will also render the CMA - Dynamic Memory Split functionality useless.
Also, by default the Raspbian distro configures the GPU RAM at 64MB, this is too
low in general, specially if a 1080p TV is hooked up.
See here how to configure this setting: http://elinux.org/RPiconfig
Using a fixed gpu_mem=128 is the best option (specially if you updated the
firmware, using CMA probably won't work, at least it's the current case).
================================================================================
No input
================================================================================
Make sure you belong to the "input" group.
sudo usermod -aG input `whoami`
================================================================================
No HDMI Audio
================================================================================
If you notice that ALSA works but there's no audio over HDMI, try adding:
hdmi_drive=2
to your config.txt file and reboot.
Reference: http://www.raspberrypi.org/phpBB3/viewtopic.php?t=5062
================================================================================
Text Input API support
================================================================================
The Text Input API is supported, with translation of scan codes done via the
kernel symbol tables. For this to work, SDL needs access to a valid console.
If you notice there's no SDL_TEXTINPUT message being emitted, double check that
your app has read access to one of the following:
* /proc/self/fd/0
* /dev/tty
* /dev/tty[0...6]
* /dev/vc/0
* /dev/console
This is usually not a problem if you run from the physical terminal (as opposed
to running from a pseudo terminal, such as via SSH). If running from a PTS, a
quick workaround is to run your app as root or add yourself to the tty group,
then re-login to the system.
sudo usermod -aG tty `whoami`
The keyboard layout used by SDL is the same as the one the kernel uses.
To configure the layout on Raspbian:
sudo dpkg-reconfigure keyboard-configuration
To configure the locale, which controls which keys are interpreted as letters,
this determining the CAPS LOCK behavior:
sudo dpkg-reconfigure locales
================================================================================
OpenGL problems
================================================================================
If you have desktop OpenGL headers installed at build time in your RPi or cross
compilation environment, support for it will be built in. However, the chipset
does not actually have support for it, which causes issues in certain SDL apps
since the presence of OpenGL support supersedes the ES/ES2 variants.
The workaround is to disable OpenGL at configuration time:
./configure --disable-video-opengl
Or if the application uses the Render functions, you can use the SDL_RENDER_DRIVER
environment variable:
export SDL_RENDER_DRIVER=opengles2
================================================================================
Notes
================================================================================
* When launching apps remotely (via SSH), SDL can prevent local keystrokes from
leaking into the console only if it has root privileges. Launching apps locally
does not suffer from this issue.
+86
View File
@@ -0,0 +1,86 @@
Touch
===========================================================================
System Specific Notes
===========================================================================
Linux:
The linux touch system is currently based off event streams, and proc/bus/devices. The active user must be given permissions to read /dev/input/TOUCHDEVICE, where TOUCHDEVICE is the event stream for your device. Currently only Wacom tablets are supported. If you have an unsupported tablet contact me at jim.tla+sdl_touch@gmail.com and I will help you get support for it.
Mac:
The Mac and iPhone APIs are pretty. If your touch device supports them then you'll be fine. If it doesn't, then there isn't much we can do.
iPhone:
Works out of box.
Windows:
Unfortunately there is no windows support as of yet. Support for Windows 7 is planned, but we currently have no way to test. If you have a Windows 7 WM_TOUCH supported device, and are willing to help test please contact me at jim.tla+sdl_touch@gmail.com
===========================================================================
Events
===========================================================================
SDL_FINGERDOWN:
Sent when a finger (or stylus) is placed on a touch device.
Fields:
* event.tfinger.touchId - the Id of the touch device.
* event.tfinger.fingerId - the Id of the finger which just went down.
* event.tfinger.x - the x coordinate of the touch (0..1)
* event.tfinger.y - the y coordinate of the touch (0..1)
* event.tfinger.pressure - the pressure of the touch (0..1)
SDL_FINGERMOTION:
Sent when a finger (or stylus) is moved on the touch device.
Fields:
Same as SDL_FINGERDOWN but with additional:
* event.tfinger.dx - change in x coordinate during this motion event.
* event.tfinger.dy - change in y coordinate during this motion event.
SDL_FINGERUP:
Sent when a finger (or stylus) is lifted from the touch device.
Fields:
Same as SDL_FINGERDOWN.
===========================================================================
Functions
===========================================================================
SDL provides the ability to access the underlying SDL_Finger structures.
These structures should _never_ be modified.
The following functions are included from SDL_touch.h
To get a SDL_TouchID call SDL_GetTouchDevice(int index).
This returns a SDL_TouchID.
IMPORTANT: If the touch has been removed, or there is no touch with the given index, SDL_GetTouchDevice() will return 0. Be sure to check for this!
The number of touch devices can be queried with SDL_GetNumTouchDevices().
A SDL_TouchID may be used to get pointers to SDL_Finger.
SDL_GetNumTouchFingers(touchID) may be used to get the number of fingers currently down on the device.
The most common reason to access SDL_Finger is to query the fingers outside the event. In most cases accessing the fingers is using the event. This would be accomplished by code like the following:
float x = event.tfinger.x;
float y = event.tfinger.y;
To get a SDL_Finger, call SDL_GetTouchFinger(SDL_TouchID touchID, int index), where touchID is a SDL_TouchID, and index is the requested finger.
This returns a SDL_Finger *, or NULL if the finger does not exist, or has been removed.
A SDL_Finger is guaranteed to be persistent for the duration of a touch, but it will be de-allocated as soon as the finger is removed. This occurs when the SDL_FINGERUP event is _added_ to the event queue, and thus _before_ the SDL_FINGERUP event is polled.
As a result, be very careful to check for NULL return values.
A SDL_Finger has the following fields:
* x, y:
The current coordinates of the touch.
* pressure:
The pressure of the touch.
===========================================================================
Notes
===========================================================================
For a complete example see test/testgesture.c
Please direct questions/comments to:
jim.tla+sdl_touch@gmail.com
(original author, API was changed since)
+10
View File
@@ -0,0 +1,10 @@
WinCE
=====
Windows CE is no longer supported by SDL.
We have left the CE support in SDL 1.2 for those that must have it, and we
have support for Windows Phone 8 and WinRT in SDL2, as of SDL 2.0.3.
--ryan.
+45
View File
@@ -0,0 +1,45 @@
Windows
================================================================================
================================================================================
OpenGL ES 2.x support
================================================================================
SDL has support for OpenGL ES 2.x under Windows via two alternative
implementations.
The most straightforward method consists in running your app in a system with
a graphic card paired with a relatively recent (as of November of 2013) driver
which supports the WGL_EXT_create_context_es2_profile extension. Vendors known
to ship said extension on Windows currently include nVidia and Intel.
The other method involves using the ANGLE library (https://code.google.com/p/angleproject/)
If an OpenGL ES 2.x context is requested and no WGL_EXT_create_context_es2_profile
extension is found, SDL will try to load the libEGL.dll library provided by
ANGLE.
To obtain the ANGLE binaries, you can either compile from source from
https://chromium.googlesource.com/angle/angle or copy the relevant binaries from
a recent Chrome/Chromium install for Windows. The files you need are:
* libEGL.dll
* libGLESv2.dll
* d3dcompiler_46.dll (supports Windows Vista or later, better shader compiler)
or...
* d3dcompiler_43.dll (supports Windows XP or later)
If you compile ANGLE from source, you can configure it so it does not need the
d3dcompiler_* DLL at all (for details on this, see their documentation).
However, by default SDL will try to preload the d3dcompiler_46.dll to
comply with ANGLE's requirements. If you wish SDL to preload d3dcompiler_43.dll (to
support Windows XP) or to skip this step at all, you can use the
SDL_HINT_VIDEO_WIN_D3DCOMPILER hint (see SDL_hints.h for more details).
Known Bugs:
* SDL_GL_SetSwapInterval is currently a no op when using ANGLE. It appears
that there's a bug in the library which prevents the window contents from
refreshing if this is set to anything other than the default value.
Vulkan Surface Support
==============
Support for creating Vulkan surfaces is configured on by default. To disable it change the value of `SDL_VIDEO_VULKAN` to 0 in `SDL_config_windows.h`. You must install the [Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) in order to use Vulkan graphics in your application.
+547
View File
@@ -0,0 +1,547 @@
WinRT
=====
This port allows SDL applications to run on Microsoft's platforms that require
use of "Windows Runtime", aka. "WinRT", APIs. Microsoft may, in some cases,
refer to them as either "Windows Store", or for Windows 10, "UWP" apps.
Some of the operating systems that include WinRT, are:
* Windows 10, via its Universal Windows Platform (UWP) APIs
* Windows 8.x
* Windows RT 8.x (aka. Windows 8.x for ARM processors)
* Windows Phone 8.x
Requirements
------------
* Microsoft Visual C++ (aka Visual Studio), either 2017, 2015, 2013, or 2012
- Free, "Community" or "Express" editions may be used, so long as they
include support for either "Windows Store" or "Windows Phone" apps.
"Express" versions marked as supporting "Windows Desktop" development
typically do not include support for creating WinRT apps, to note.
(The "Community" editions of Visual C++ do, however, support both
desktop/Win32 and WinRT development).
- Visual Studio 2017 can be used, however it is recommended that you install
the Visual C++ 2015 build tools. These build tools can be installed
using VS 2017's installer. Be sure to also install the workload for
"Universal Windows Platform development", its optional component, the
"C++ Universal Windows Platform tools", and for UWP / Windows 10
development, the "Windows 10 SDK (10.0.10240.0)". Please note that
targeting UWP / Windows 10 apps from development machine(s) running
earlier versions of Windows, such as Windows 7, is not always supported
by Visual Studio, and you may get error(s) when attempting to do so.
- Visual C++ 2012 can only build apps that target versions 8.0 of Windows,
or Windows Phone. 8.0-targeted apps will run on devices running 8.1
editions of Windows, however they will not be able to take advantage of
8.1-specific features.
- Visual C++ 2013 cannot create app projects that target Windows 8.0.
Visual C++ 2013 Update 4, can create app projects for Windows Phone 8.0,
Windows Phone 8.1, and Windows 8.1, but not Windows 8.0. An optional
Visual Studio add-in, "Tools for Maintaining Store apps for Windows 8",
allows Visual C++ 2013 to load and build Windows 8.0 projects that were
created with Visual C++ 2012, so long as Visual C++ 2012 is installed
on the same machine. More details on targeting different versions of
Windows can found at the following web pages:
- [Develop apps by using Visual Studio 2013](http://msdn.microsoft.com/en-us/library/windows/apps/br211384.aspx)
- [To add the Tools for Maintaining Store apps for Windows 8](http://msdn.microsoft.com/en-us/library/windows/apps/dn263114.aspx#AddMaintenanceTools)
* A valid Microsoft account - This requirement is not imposed by SDL, but
rather by Microsoft's Visual C++ toolchain. This is required to launch or
debug apps.
Status
------
Here is a rough list of what works, and what doesn't:
* What works:
* compilation via Visual C++ 2012 through 2015
* compile-time platform detection for SDL programs. The C/C++ #define,
`__WINRT__`, will be set to 1 (by SDL) when compiling for WinRT.
* GPU-accelerated 2D rendering, via SDL_Renderer.
* OpenGL ES 2, via the ANGLE library (included separately from SDL)
* software rendering, via either SDL_Surface (optionally in conjunction with
SDL_GetWindowSurface() and SDL_UpdateWindowSurface()) or via the
SDL_Renderer APIs
* threads
* timers (via SDL_GetTicks(), SDL_AddTimer(), SDL_GetPerformanceCounter(),
SDL_GetPerformanceFrequency(), etc.)
* file I/O via SDL_RWops
* mouse input (unsupported on Windows Phone)
* audio, via SDL's WASAPI backend (if you want to record, your app must
have "Microphone" capabilities enabled in its manifest, and the user must
not have blocked access. Otherwise, capture devices will fail to work,
presenting as a device disconnect shortly after opening it.)
* .DLL file loading. Libraries *MUST* be packaged inside applications. Loading
anything outside of the app is not supported.
* system path retrieval via SDL's filesystem APIs
* game controllers. Support is provided via the SDL_Joystick and
SDL_GameController APIs, and is backed by Microsoft's XInput API. Please
note, however, that Windows limits game-controller support in UWP apps to,
"Xbox compatible controllers" (many controllers that work in Win32 apps,
do not work in UWP, due to restrictions in UWP itself.)
* multi-touch input
* app events. SDL_APP_WILLENTER* and SDL_APP_DIDENTER* events get sent out as
appropriate.
* window events
* using Direct3D 11.x APIs outside of SDL. Non-XAML / Direct3D-only apps can
choose to render content directly via Direct3D, using SDL to manage the
internal WinRT window, as well as input and audio. (Use
SDL_GetWindowWMInfo() to get the WinRT 'CoreWindow', and pass it into
IDXGIFactory2::CreateSwapChainForCoreWindow() as appropriate.)
* What partially works:
* keyboard input. Most of WinRT's documented virtual keys are supported, as
well as many keys with documented hardware scancodes. Converting
SDL_Scancodes to or from SDL_Keycodes may not work, due to missing APIs
(MapVirtualKey()) in Microsoft's Windows Store / UWP APIs.
* SDLmain. WinRT uses a different signature for each app's main() function.
SDL-based apps that use this port must compile in SDL_winrt_main_NonXAML.cpp
(in `SDL\src\main\winrt\`) directly in order for their C-style main()
functions to be called.
* What doesn't work:
* compilation with anything other than Visual C++
* programmatically-created custom cursors. These don't appear to be supported
by WinRT. Different OS-provided cursors can, however, be created via
SDL_CreateSystemCursor() (unsupported on Windows Phone)
* SDL_WarpMouseInWindow() or SDL_WarpMouseGlobal(). This are not currently
supported by WinRT itself.
* joysticks and game controllers that either are not supported by
Microsoft's XInput API, or are not supported within UWP apps (many
controllers that work in Win32, do not work in UWP, due to restrictions in
UWP itself).
* turning off VSync when rendering on Windows Phone. Attempts to turn VSync
off on Windows Phone result either in Direct3D not drawing anything, or it
forcing VSync back on. As such, SDL_RENDERER_PRESENTVSYNC will always get
turned-on on Windows Phone. This limitation is not present in non-Phone
WinRT (such as Windows 8.x), where turning off VSync appears to work.
* probably anything else that's not listed as supported
Upgrade Notes
-------------
#### SDL_GetPrefPath() usage when upgrading WinRT apps from SDL 2.0.3
SDL 2.0.4 fixes two bugs found in the WinRT version of SDL_GetPrefPath().
The fixes may affect older, SDL 2.0.3-based apps' save data. Please note
that these changes only apply to SDL-based WinRT apps, and not to apps for
any other platform.
1. SDL_GetPrefPath() would return an invalid path, one in which the path's
directory had not been created. Attempts to create files there
(via fopen(), for example), would fail, unless that directory was
explicitly created beforehand.
2. SDL_GetPrefPath(), for non-WinPhone-based apps, would return a path inside
a WinRT 'Roaming' folder, the contents of which get automatically
synchronized across multiple devices. This process can occur while an
application runs, and can cause existing save-data to be overwritten
at unexpected times, with data from other devices. (Windows Phone apps
written with SDL 2.0.3 did not utilize a Roaming folder, due to API
restrictions in Windows Phone 8.0).
SDL_GetPrefPath(), starting with SDL 2.0.4, addresses these by:
1. making sure that SDL_GetPrefPath() returns a directory in which data
can be written to immediately, without first needing to create directories.
2. basing SDL_GetPrefPath() off of a different, non-Roaming folder, the
contents of which do not automatically get synchronized across devices
(and which require less work to use safely, in terms of data integrity).
Apps that wish to get their Roaming folder's path can do so either by using
SDL_WinRTGetFSPathUTF8(), SDL_WinRTGetFSPathUNICODE() (which returns a
UCS-2/wide-char string), or directly through the WinRT class,
Windows.Storage.ApplicationData.
Setup, High-Level Steps
-----------------------
The steps for setting up a project for an SDL/WinRT app looks like the
following, at a high-level:
1. create a new Visual C++ project using Microsoft's template for a,
"Direct3D App".
2. remove most of the files from the project.
3. make your app's project directly reference SDL/WinRT's own Visual C++
project file, via use of Visual C++'s "References" dialog. This will setup
the linker, and will copy SDL's .dll files to your app's final output.
4. adjust your app's build settings, at minimum, telling it where to find SDL's
header files.
5. add files that contains a WinRT-appropriate main function, along with some
data to make sure mouse-cursor-hiding (via SDL_ShowCursor(SDL_DISABLE) calls)
work properly.
6. add SDL-specific app code.
7. build and run your app.
Setup, Detailed Steps
---------------------
### 1. Create a new project ###
Create a new project using one of Visual C++'s templates for a plain, non-XAML,
"Direct3D App" (XAML support for SDL/WinRT is not yet ready for use). If you
don't see one of these templates, in Visual C++'s 'New Project' dialog, try
using the textbox titled, 'Search Installed Templates' to look for one.
### 2. Remove unneeded files from the project ###
In the new project, delete any file that has one of the following extensions:
- .cpp
- .h
- .hlsl
When you are done, you should be left with a few files, each of which will be a
necessary part of your app's project. These files will consist of:
- an .appxmanifest file, which contains metadata on your WinRT app. This is
similar to an Info.plist file on iOS, or an AndroidManifest.xml on Android.
- a few .png files, one of which is a splash screen (displayed when your app
launches), others are app icons.
- a .pfx file, used for code signing purposes.
### 3. Add references to SDL's project files ###
SDL/WinRT can be built in multiple variations, spanning across three different
CPU architectures (x86, x64, and ARM) and two different configurations
(Debug and Release). WinRT and Visual C++ do not currently provide a means
for combining multiple variations of one library into a single file.
Furthermore, it does not provide an easy means for copying pre-built .dll files
into your app's final output (via Post-Build steps, for example). It does,
however, provide a system whereby an app can reference the MSVC projects of
libraries such that, when the app is built:
1. each library gets built for the appropriate CPU architecture(s) and WinRT
platform(s).
2. each library's output, such as .dll files, get copied to the app's build
output.
To set this up for SDL/WinRT, you'll need to run through the following steps:
1. open up the Solution Explorer inside Visual C++ (under the "View" menu, then
"Solution Explorer")
2. right click on your app's solution.
3. navigate to "Add", then to "Existing Project..."
4. find SDL/WinRT's Visual C++ project file and open it. Different project
files exist for different WinRT platforms. All of them are in SDL's
source distribution, in the following directories:
* `VisualC-WinRT/UWP_VS2015/` - for Windows 10 / UWP apps
* `VisualC-WinRT/WinPhone81_VS2013/` - for Windows Phone 8.1 apps
* `VisualC-WinRT/WinRT80_VS2012/` - for Windows 8.0 apps
* `VisualC-WinRT/WinRT81_VS2013/` - for Windows 8.1 apps
5. once the project has been added, right-click on your app's project and
select, "References..."
6. click on the button titled, "Add New Reference..."
7. check the box next to SDL
8. click OK to close the dialog
9. SDL will now show up in the list of references. Click OK to close that
dialog.
Your project is now linked to SDL's project, insofar that when the app is
built, SDL will be built as well, with its build output getting included with
your app.
### 4. Adjust Your App's Build Settings ###
Some build settings need to be changed in your app's project. This guide will
outline the following:
- making sure that the compiler knows where to find SDL's header files
- **Optional for C++, but NECESSARY for compiling C code:** telling the
compiler not to use Microsoft's C++ extensions for WinRT development.
- **Optional:** telling the compiler not generate errors due to missing
precompiled header files.
To change these settings:
1. right-click on the project
2. choose "Properties"
3. in the drop-down box next to "Configuration", choose, "All Configurations"
4. in the drop-down box next to "Platform", choose, "All Platforms"
5. in the left-hand list, expand the "C/C++" section
6. select "General"
7. edit the "Additional Include Directories" setting, and add a path to SDL's
"include" directory
8. **Optional: to enable compilation of C code:** change the setting for
"Consume Windows Runtime Extension" from "Yes (/ZW)" to "No". If you're
working with a completely C++ based project, this step can usually be
omitted.
9. **Optional: to disable precompiled headers (which can produce
'stdafx.h'-related build errors, if setup incorrectly:** in the left-hand
list, select "Precompiled Headers", then change the setting for "Precompiled
Header" from "Use (/Yu)" to "Not Using Precompiled Headers".
10. close the dialog, saving settings, by clicking the "OK" button
### 5. Add a WinRT-appropriate main function, and a blank-cursor image, to the app. ###
A few files should be included directly in your app's MSVC project, specifically:
1. a WinRT-appropriate main function (which is different than main() functions on
other platforms)
2. a Win32-style cursor resource, used by SDL_ShowCursor() to hide the mouse cursor
(if and when the app needs to do so). *If this cursor resource is not
included, mouse-position reporting may fail if and when the cursor is
hidden, due to possible bugs/design-oddities in Windows itself.*
To include these files for C/C++ projects:
1. right-click on your project (again, in Visual C++'s Solution Explorer),
navigate to "Add", then choose "Existing Item...".
2. navigate to the directory containing SDL's source code, then into its
subdirectory, 'src/main/winrt/'. Select, then add, the following files:
- `SDL_winrt_main_NonXAML.cpp`
- `SDL2-WinRTResources.rc`
- `SDL2-WinRTResource_BlankCursor.cur`
3. right-click on the file `SDL_winrt_main_NonXAML.cpp` (as listed in your
project), then click on "Properties...".
4. in the drop-down box next to "Configuration", choose, "All Configurations"
5. in the drop-down box next to "Platform", choose, "All Platforms"
6. in the left-hand list, click on "C/C++"
7. change the setting for "Consume Windows Runtime Extension" to "Yes (/ZW)".
8. click the OK button. This will close the dialog.
**NOTE: C++/CX compilation is currently required in at least one file of your
app's project. This is to make sure that Visual C++'s linker builds a 'Windows
Metadata' file (.winmd) for your app. Not doing so can lead to build errors.**
For non-C++ projects, you will need to call SDL_WinRTRunApp from your language's
main function, and generate SDL2-WinRTResources.res manually by using `rc` via
the Developer Command Prompt and including it as a <Win32Resource> within the
first <PropertyGroup> block in your Visual Studio project file.
### 6. Add app code and assets ###
At this point, you can add in SDL-specific source code. Be sure to include a
C-style main function (ie: `int main(int argc, char *argv[])`). From there you
should be able to create a single `SDL_Window` (WinRT apps can only have one
window, at present), as well as an `SDL_Renderer`. Direct3D will be used to
draw content. Events are received via SDL's usual event functions
(`SDL_PollEvent`, etc.) If you have a set of existing source files and assets,
you can start adding them to the project now. If not, or if you would like to
make sure that you're setup correctly, some short and simple sample code is
provided below.
#### 6.A. ... when creating a new app ####
If you are creating a new app (rather than porting an existing SDL-based app),
or if you would just like a simple app to test SDL/WinRT with before trying to
get existing code working, some working SDL/WinRT code is provided below. To
set this up:
1. right click on your app's project
2. select Add, then New Item. An "Add New Item" dialog will show up.
3. from the left-hand list, choose "Visual C++"
4. from the middle/main list, choose "C++ File (.cpp)"
5. near the bottom of the dialog, next to "Name:", type in a name for your
source file, such as, "main.cpp".
6. click on the Add button. This will close the dialog, add the new file to
your project, and open the file in Visual C++'s text editor.
7. Copy and paste the following code into the new file, then save it.
#include <SDL.h>
int main(int argc, char **argv)
{
SDL_DisplayMode mode;
SDL_Window * window = NULL;
SDL_Renderer * renderer = NULL;
SDL_Event evt;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
return 1;
}
if (SDL_GetCurrentDisplayMode(0, &mode) != 0) {
return 1;
}
if (SDL_CreateWindowAndRenderer(mode.w, mode.h, SDL_WINDOW_FULLSCREEN, &window, &renderer) != 0) {
return 1;
}
while (1) {
while (SDL_PollEvent(&evt)) {
}
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
}
#### 6.B. Adding code and assets ####
If you have existing code and assets that you'd like to add, you should be able
to add them now. The process for adding a set of files is as such.
1. right click on the app's project
2. select Add, then click on "New Item..."
3. open any source, header, or asset files as appropriate. Support for C and
C++ is available.
Do note that WinRT only supports a subset of the APIs that are available to
Win32-based apps. Many portions of the Win32 API and the C runtime are not
available.
A list of unsupported C APIs can be found at
<http://msdn.microsoft.com/en-us/library/windows/apps/jj606124.aspx>
General information on using the C runtime in WinRT can be found at
<https://msdn.microsoft.com/en-us/library/hh972425.aspx>
A list of supported Win32 APIs for WinRT apps can be found at
<http://msdn.microsoft.com/en-us/library/windows/apps/br205757.aspx>. To note,
the list of supported Win32 APIs for Windows Phone 8.0 is different.
That list can be found at
<http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662956(v=vs.105).aspx>
### 7. Build and run your app ###
Your app project should now be setup, and you should be ready to build your app.
To run it on the local machine, open the Debug menu and choose "Start
Debugging". This will build your app, then run your app full-screen. To switch
out of your app, press the Windows key. Alternatively, you can choose to run
your app in a window. To do this, before building and running your app, find
the drop-down menu in Visual C++'s toolbar that says, "Local Machine". Expand
this by clicking on the arrow on the right side of the list, then click on
Simulator. Once you do that, any time you build and run the app, the app will
launch in window, rather than full-screen.
#### 7.A. Running apps on older, ARM-based, "Windows RT" devices ####
**These instructions do not include Windows Phone, despite Windows Phone
typically running on ARM processors.** They are specifically for devices
that use the "Windows RT" operating system, which was a modified version of
Windows 8.x that ran primarily on ARM-based tablet computers.
To build and run the app on ARM-based, "Windows RT" devices, you'll need to:
- install Microsoft's "Remote Debugger" on the device. Visual C++ installs and
debugs ARM-based apps via IP networks.
- change a few options on the development machine, both to make sure it builds
for ARM (rather than x86 or x64), and to make sure it knows how to find the
Windows RT device (on the network).
Microsoft's Remote Debugger can be found at
<https://msdn.microsoft.com/en-us/library/hh441469.aspx>. Please note
that separate versions of this debugger exist for different versions of Visual
C++, one each for MSVC 2015, 2013, and 2012.
To setup Visual C++ to launch your app on an ARM device:
1. make sure the Remote Debugger is running on your ARM device, and that it's on
the same IP network as your development machine.
2. from Visual C++'s toolbar, find a drop-down menu that says, "Win32". Click
it, then change the value to "ARM".
3. make sure Visual C++ knows the hostname or IP address of the ARM device. To
do this:
1. open the app project's properties
2. select "Debugging"
3. next to "Machine Name", enter the hostname or IP address of the ARM
device
4. if, and only if, you've turned off authentication in the Remote Debugger,
then change the setting for "Require Authentication" to No
5. click "OK"
4. build and run the app (from Visual C++). The first time you do this, a
prompt will show up on the ARM device, asking for a Microsoft Account. You
do, unfortunately, need to log in here, and will need to follow the
subsequent registration steps in order to launch the app. After you do so,
if the app didn't already launch, try relaunching it again from within Visual
C++.
Troubleshooting
---------------
#### Build fails with message, "error LNK2038: mismatch detected for 'vccorlib_lib_should_be_specified_before_msvcrt_lib_to_linker'"
Try adding the following to your linker flags. In MSVC, this can be done by
right-clicking on the app project, navigating to Configuration Properties ->
Linker -> Command Line, then adding them to the Additional Options
section.
* For Release builds / MSVC-Configurations, add:
/nodefaultlib:vccorlib /nodefaultlib:msvcrt vccorlib.lib msvcrt.lib
* For Debug builds / MSVC-Configurations, add:
/nodefaultlib:vccorlibd /nodefaultlib:msvcrtd vccorlibd.lib msvcrtd.lib
#### Mouse-motion events fail to get sent, or SDL_GetMouseState() fails to return updated values
This may be caused by a bug in Windows itself, whereby hiding the mouse
cursor can cause mouse-position reporting to fail.
SDL provides a workaround for this, but it requires that an app links to a
set of Win32-style cursor image-resource files. A copy of suitable resource
files can be found in `src/main/winrt/`. Adding them to an app's Visual C++
project file should be sufficient to get the app to use them.
#### SDL's Visual Studio project file fails to open, with message, "The system can't find the file specified."
This can be caused for any one of a few reasons, which Visual Studio can
report, but won't always do so in an up-front manner.
To help determine why this error comes up:
1. open a copy of Visual Studio without opening a project file. This can be
accomplished via Windows' Start Menu, among other means.
2. show Visual Studio's Output window. This can be done by going to VS'
menu bar, then to View, and then to Output.
3. try opening the SDL project file directly by going to VS' menu bar, then
to File, then to Open, then to Project/Solution. When a File-Open dialog
appears, open the SDL project (such as the one in SDL's source code, in its
directory, VisualC-WinRT/UWP_VS2015/).
4. after attempting to open SDL's Visual Studio project file, additional error
information will be output to the Output window.
If Visual Studio reports (via its Output window) that the project:
"could not be loaded because it's missing install components. To fix this launch Visual Studio setup with the following selections:
Microsoft.VisualStudio.ComponentGroup.UWP.VC"
... then you will need to re-launch Visual Studio's installer, and make sure that
the workflow for "Universal Windows Platform development" is checked, and that its
optional component, "C++ Universal Windows Platform tools" is also checked. While
you are there, if you are planning on targeting UWP / Windows 10, also make sure
that you check the optional component, "Windows 10 SDK (10.0.10240.0)". After
making sure these items are checked as-appropriate, install them.
Once you install these components, try re-launching Visual Studio, and re-opening
the SDL project file. If you still get the error dialog, try using the Output
window, again, seeing what Visual Studio says about it.
#### Game controllers / joysticks aren't working!
Windows only permits certain game controllers and joysticks to work within
WinRT / UWP apps. Even if a game controller or joystick works in a Win32
app, that device is not guaranteed to work inside a WinRT / UWP app.
According to Microsoft, "Xbox compatible controllers" should work inside
UWP apps, potentially with more working in the future. This includes, but
may not be limited to, Microsoft-made Xbox controllers and USB adapters.
(Source: https://social.msdn.microsoft.com/Forums/en-US/9064838b-e8c3-4c18-8a83-19bf0dfe150d/xinput-fails-to-detect-game-controllers?forum=wpdevelop)
+63
View File
@@ -0,0 +1,63 @@
Simple DirectMedia Layer {#mainpage}
========================
(SDL)
Version 2.0
---
http://www.libsdl.org/
Simple DirectMedia Layer is a cross-platform development library designed
to provide low level access to audio, keyboard, mouse, joystick, and graphics
hardware via OpenGL and Direct3D. It is used by video playback software,
emulators, and popular games including Valve's award winning catalog
and many Humble Bundle games.
SDL officially supports Windows, Mac OS X, Linux, iOS, and Android.
Support for other platforms may be found in the source code.
SDL is written in C, works natively with C++, and there are bindings
available for several other languages, including C# and Python.
This library is distributed under the zlib license, which can be found
in the file "COPYING.txt".
The best way to learn how to use SDL is to check out the header files in
the "include" subdirectory and the programs in the "test" subdirectory.
The header files and test programs are well commented and always up to date.
More documentation and FAQs are available online at [the wiki](http://wiki.libsdl.org/)
- [Android](README-android.md)
- [CMake](README-cmake.md)
- [DirectFB](README-directfb.md)
- [DynAPI](README-dynapi.md)
- [Emscripten](README-emscripten.md)
- [Gesture](README-gesture.md)
- [Mercurial](README-hg.md)
- [iOS](README-ios.md)
- [Linux](README-linux.md)
- [OS X](README-macosx.md)
- [Native Client](README-nacl.md)
- [Pandora](README-pandora.md)
- [Supported Platforms](README-platforms.md)
- [Porting information](README-porting.md)
- [PSP](README-psp.md)
- [Raspberry Pi](README-raspberrypi.md)
- [Touch](README-touch.md)
- [WinCE](README-wince.md)
- [Windows](README-windows.md)
- [WinRT](README-winrt.md)
If you need help with the library, or just want to discuss SDL related
issues, you can join the [developers mailing list](http://www.libsdl.org/mailing-list.php)
If you want to report bugs or contribute patches, please submit them to
[bugzilla](https://bugzilla.libsdl.org/)
Enjoy!
Sam Lantinga <mailto:slouken@libsdl.org>
+1560
View File
File diff suppressed because it is too large. Load diff
+136
View File
@@ -0,0 +1,136 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL.h
*
* Main include header for the SDL library
*/
#ifndef SDL_h_
#define SDL_h_
#include "SDL_main.h"
#include "SDL_stdinc.h"
#include "SDL_assert.h"
#include "SDL_atomic.h"
#include "SDL_audio.h"
#include "SDL_clipboard.h"
#include "SDL_cpuinfo.h"
#include "SDL_endian.h"
#include "SDL_error.h"
#include "SDL_events.h"
#include "SDL_filesystem.h"
#include "SDL_gamecontroller.h"
#include "SDL_haptic.h"
#include "SDL_hints.h"
#include "SDL_joystick.h"
#include "SDL_loadso.h"
#include "SDL_log.h"
#include "SDL_messagebox.h"
#include "SDL_metal.h"
#include "SDL_mutex.h"
#include "SDL_power.h"
#include "SDL_render.h"
#include "SDL_rwops.h"
#include "SDL_sensor.h"
#include "SDL_shape.h"
#include "SDL_system.h"
#include "SDL_thread.h"
#include "SDL_timer.h"
#include "SDL_version.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* As of version 0.5, SDL is loaded dynamically into the application */
/**
* \name SDL_INIT_*
*
* These are the flags which may be passed to SDL_Init(). You should
* specify the subsystems which you will be using in your application.
*/
/* @{ */
#define SDL_INIT_TIMER 0x00000001u
#define SDL_INIT_AUDIO 0x00000010u
#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
#define SDL_INIT_JOYSTICK 0x00000200u /**< SDL_INIT_JOYSTICK implies SDL_INIT_EVENTS */
#define SDL_INIT_HAPTIC 0x00001000u
#define SDL_INIT_GAMECONTROLLER 0x00002000u /**< SDL_INIT_GAMECONTROLLER implies SDL_INIT_JOYSTICK */
#define SDL_INIT_EVENTS 0x00004000u
#define SDL_INIT_SENSOR 0x00008000u
#define SDL_INIT_NOPARACHUTE 0x00100000u /**< compatibility; this flag is ignored. */
#define SDL_INIT_EVERYTHING ( \
SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS | \
SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER | SDL_INIT_SENSOR \
)
/* @} */
/**
* This function initializes the subsystems specified by \c flags
*/
extern DECLSPEC int SDLCALL SDL_Init(Uint32 flags);
/**
* This function initializes specific SDL subsystems
*
* Subsystem initialization is ref-counted, you must call
* SDL_QuitSubSystem() for each SDL_InitSubSystem() to correctly
* shutdown a subsystem manually (or call SDL_Quit() to force shutdown).
* If a subsystem is already loaded then this call will
* increase the ref-count and return.
*/
extern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags);
/**
* This function cleans up specific SDL subsystems
*/
extern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags);
/**
* This function returns a mask of the specified subsystems which have
* previously been initialized.
*
* If \c flags is 0, it returns a mask of all initialized subsystems.
*/
extern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags);
/**
* This function cleans up all initialized subsystems. You should
* call it upon all exit conditions.
*/
extern DECLSPEC void SDLCALL SDL_Quit(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_h_ */
/* vi: set ts=4 sw=4 expandtab: */
+291
View File
@@ -0,0 +1,291 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_assert_h_
#define SDL_assert_h_
#include "SDL_config.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef SDL_ASSERT_LEVEL
#ifdef SDL_DEFAULT_ASSERT_LEVEL
#define SDL_ASSERT_LEVEL SDL_DEFAULT_ASSERT_LEVEL
#elif defined(_DEBUG) || defined(DEBUG) || \
(defined(__GNUC__) && !defined(__OPTIMIZE__))
#define SDL_ASSERT_LEVEL 2
#else
#define SDL_ASSERT_LEVEL 1
#endif
#endif /* SDL_ASSERT_LEVEL */
/*
These are macros and not first class functions so that the debugger breaks
on the assertion line and not in some random guts of SDL, and so each
assert can have unique static variables associated with it.
*/
#if defined(_MSC_VER)
/* Don't include intrin.h here because it contains C++ code */
extern void __cdecl __debugbreak(void);
#define SDL_TriggerBreakpoint() __debugbreak()
#elif ( (!defined(__NACL__)) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))) )
#define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" )
#elif defined(__386__) && defined(__WATCOMC__)
#define SDL_TriggerBreakpoint() { _asm { int 0x03 } }
#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__)
#include <signal.h>
#define SDL_TriggerBreakpoint() raise(SIGTRAP)
#else
/* How do we trigger breakpoints on this platform? */
#define SDL_TriggerBreakpoint()
#endif
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */
# define SDL_FUNCTION __func__
#elif ((__GNUC__ >= 2) || defined(_MSC_VER) || defined (__WATCOMC__))
# define SDL_FUNCTION __FUNCTION__
#else
# define SDL_FUNCTION "???"
#endif
#define SDL_FILE __FILE__
#define SDL_LINE __LINE__
/*
sizeof (x) makes the compiler still parse the expression even without
assertions enabled, so the code is always checked at compile time, but
doesn't actually generate code for it, so there are no side effects or
expensive checks at run time, just the constant size of what x WOULD be,
which presumably gets optimized out as unused.
This also solves the problem of...
int somevalue = blah();
SDL_assert(somevalue == 1);
...which would cause compiles to complain that somevalue is unused if we
disable assertions.
*/
/* "while (0,0)" fools Microsoft's compiler's /W4 warning level into thinking
this condition isn't constant. And looks like an owl's face! */
#ifdef _MSC_VER /* stupid /W4 warnings. */
#define SDL_NULL_WHILE_LOOP_CONDITION (0,0)
#else
#define SDL_NULL_WHILE_LOOP_CONDITION (0)
#endif
#define SDL_disabled_assert(condition) \
do { (void) sizeof ((condition)); } while (SDL_NULL_WHILE_LOOP_CONDITION)
typedef enum
{
SDL_ASSERTION_RETRY, /**< Retry the assert immediately. */
SDL_ASSERTION_BREAK, /**< Make the debugger trigger a breakpoint. */
SDL_ASSERTION_ABORT, /**< Terminate the program. */
SDL_ASSERTION_IGNORE, /**< Ignore the assert. */
SDL_ASSERTION_ALWAYS_IGNORE /**< Ignore the assert from now on. */
} SDL_AssertState;
typedef struct SDL_AssertData
{
int always_ignore;
unsigned int trigger_count;
const char *condition;
const char *filename;
int linenum;
const char *function;
const struct SDL_AssertData *next;
} SDL_AssertData;
#if (SDL_ASSERT_LEVEL > 0)
/* Never call this directly. Use the SDL_assert* macros. */
extern DECLSPEC SDL_AssertState SDLCALL SDL_ReportAssertion(SDL_AssertData *,
const char *,
const char *, int)
#if defined(__clang__)
#if __has_feature(attribute_analyzer_noreturn)
/* this tells Clang's static analysis that we're a custom assert function,
and that the analyzer should assume the condition was always true past this
SDL_assert test. */
__attribute__((analyzer_noreturn))
#endif
#endif
;
/* the do {} while(0) avoids dangling else problems:
if (x) SDL_assert(y); else blah();
... without the do/while, the "else" could attach to this macro's "if".
We try to handle just the minimum we need here in a macro...the loop,
the static vars, and break points. The heavy lifting is handled in
SDL_ReportAssertion(), in SDL_assert.c.
*/
#define SDL_enabled_assert(condition) \
do { \
while ( !(condition) ) { \
static struct SDL_AssertData sdl_assert_data = { \
0, 0, #condition, 0, 0, 0, 0 \
}; \
const SDL_AssertState sdl_assert_state = SDL_ReportAssertion(&sdl_assert_data, SDL_FUNCTION, SDL_FILE, SDL_LINE); \
if (sdl_assert_state == SDL_ASSERTION_RETRY) { \
continue; /* go again. */ \
} else if (sdl_assert_state == SDL_ASSERTION_BREAK) { \
SDL_TriggerBreakpoint(); \
} \
break; /* not retrying. */ \
} \
} while (SDL_NULL_WHILE_LOOP_CONDITION)
#endif /* enabled assertions support code */
/* Enable various levels of assertions. */
#if SDL_ASSERT_LEVEL == 0 /* assertions disabled */
# define SDL_assert(condition) SDL_disabled_assert(condition)
# define SDL_assert_release(condition) SDL_disabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 1 /* release settings. */
# define SDL_assert(condition) SDL_disabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 2 /* normal settings. */
# define SDL_assert(condition) SDL_enabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition)
#elif SDL_ASSERT_LEVEL == 3 /* paranoid settings. */
# define SDL_assert(condition) SDL_enabled_assert(condition)
# define SDL_assert_release(condition) SDL_enabled_assert(condition)
# define SDL_assert_paranoid(condition) SDL_enabled_assert(condition)
#else
# error Unknown assertion level.
#endif
/* this assertion is never disabled at any level. */
#define SDL_assert_always(condition) SDL_enabled_assert(condition)
typedef SDL_AssertState (SDLCALL *SDL_AssertionHandler)(
const SDL_AssertData* data, void* userdata);
/**
* \brief Set an application-defined assertion handler.
*
* This allows an app to show its own assertion UI and/or force the
* response to an assertion failure. If the app doesn't provide this, SDL
* will try to do the right thing, popping up a system-specific GUI dialog,
* and probably minimizing any fullscreen windows.
*
* This callback may fire from any thread, but it runs wrapped in a mutex, so
* it will only fire from one thread at a time.
*
* Setting the callback to NULL restores SDL's original internal handler.
*
* This callback is NOT reset to SDL's internal handler upon SDL_Quit()!
*
* Return SDL_AssertState value of how to handle the assertion failure.
*
* \param handler Callback function, called when an assertion fails.
* \param userdata A pointer passed to the callback as-is.
*/
extern DECLSPEC void SDLCALL SDL_SetAssertionHandler(
SDL_AssertionHandler handler,
void *userdata);
/**
* \brief Get the default assertion handler.
*
* This returns the function pointer that is called by default when an
* assertion is triggered. This is an internal function provided by SDL,
* that is used for assertions when SDL_SetAssertionHandler() hasn't been
* used to provide a different function.
*
* \return The default SDL_AssertionHandler that is called when an assert triggers.
*/
extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetDefaultAssertionHandler(void);
/**
* \brief Get the current assertion handler.
*
* This returns the function pointer that is called when an assertion is
* triggered. This is either the value last passed to
* SDL_SetAssertionHandler(), or if no application-specified function is
* set, is equivalent to calling SDL_GetDefaultAssertionHandler().
*
* \param puserdata Pointer to a void*, which will store the "userdata"
* pointer that was passed to SDL_SetAssertionHandler().
* This value will always be NULL for the default handler.
* If you don't care about this data, it is safe to pass
* a NULL pointer to this function to ignore it.
* \return The SDL_AssertionHandler that is called when an assert triggers.
*/
extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetAssertionHandler(void **puserdata);
/**
* \brief Get a list of all assertion failures.
*
* Get all assertions triggered since last call to SDL_ResetAssertionReport(),
* or the start of the program.
*
* The proper way to examine this data looks something like this:
*
* <code>
* const SDL_AssertData *item = SDL_GetAssertionReport();
* while (item) {
* printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\\n",
* item->condition, item->function, item->filename,
* item->linenum, item->trigger_count,
* item->always_ignore ? "yes" : "no");
* item = item->next;
* }
* </code>
*
* \return List of all assertions.
* \sa SDL_ResetAssertionReport
*/
extern DECLSPEC const SDL_AssertData * SDLCALL SDL_GetAssertionReport(void);
/**
* \brief Reset the list of all assertion failures.
*
* Reset list of all assertions triggered.
*
* \sa SDL_GetAssertionReport
*/
extern DECLSPEC void SDLCALL SDL_ResetAssertionReport(void);
/* these had wrong naming conventions until 2.0.4. Please update your app! */
#define SDL_assert_state SDL_AssertState
#define SDL_assert_data SDL_AssertData
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_assert_h_ */
/* vi: set ts=4 sw=4 expandtab: */
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more