Files
ci-libretro-fceumm/src/boards/187.c

89 lines
2.3 KiB
C
Raw Normal View History

/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2005 CaH4e3
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* A98402 board, A9711, A9746 similar
* King of Fighters 96, The (Unl), Street Fighter Zero 2 (Unl)
*
*/
#include "mapinc.h"
#include "mmc3.h"
core: stdint typedefs, LE optimizations, frame determinism Three follow-up audit passes on top of the memory-safety / leak / savestate-portability work in 1185db8. ============================================================== Pass 1: replace custom typedefs with C99 stdint types throughout ============================================================== The custom uint8 / uint16 / uint32 / uint64 / int8 / int16 / int32 / int64 typedefs in src/fceu-types.h were just simple aliases for the C99 stdint.h types. Replace them with the standard names directly. - 498 files modified - ~3,400 token replacements (uint8 -> uint8_t, etc) - fceu-types.h slimmed down to just INLINE / GINLINE / FASTAPASS macros and the readfunc / writefunc function-pointer typedefs (those now use uint8_t / uint32_t natively) - Build clean on `make platform=unix` with zero new warnings - Output binary size unchanged - confirming semantic equivalence Mechanical replacement done with a Python script that uses word- boundary regex to avoid false positives (e.g. 'uint32_t' was correctly left alone because '_' is a word character so 'uint32' is not a complete word inside it). ================================================================ Pass 2: prefer memcpy on LE hosts for endian read/write helpers ================================================================ fceu-endian.c's write32le_mem, FCEU_en32lsb, and FCEU_de32lsb performed bytewise composition/decomposition unconditionally. On LE hosts the in-memory representation already matches the desired LE on-disk format, so a single memcpy is equivalent and lets the compiler emit a single load/store rather than four byte ops. - The bytewise path is kept inside #ifdef MSB_FIRST for BE hosts where it implements the actual byte swap - Both forms produce identical results; this is a code-clarity change more than a performance one (the optimizer was already merging the shifts on LE), but it documents the intent and removes a strict-aliasing-flavoured cast through *(uint32_t*)Bufo - Added missing #include <string.h> in fceu-endian.c which was relying on transitive includes for memcpy Other MSB_FIRST sites in the codebase (state.c FlipByteOrder guards, ppu.c sprite-line rendering, boards/unrom512.c flash-write- counter access) were already optimized for LE; they were verified correct rather than changed. ================================================================ Pass 3: frame determinism for replay and netplay ================================================================ Two libc rand() sites in core were replaced with a local xorshift32 PRNG so that NES games which read uninitialised memory or hit hardware "weak bit" emulation produce reproducible behaviour across runs. NES titles routinely read uninitialised RAM (variables not zeroed before use, sprite Y-position set by junk-on-stack), so the RAM contents at power-on subtly affect game behaviour. With libc rand(), those contents depend on whether anyone else seeded rand() in the same process - a different libretro frontend, a different audio backend init order, or any frontend that does srand(time(0)) all break replay / netplay frame-determinism. 1. fceu.c FCEU_MemoryRand. Used to fill RAM (PowerNES) and CHR-RAM (iNES_Init) at power-on when option_ramstate=2 (random init). Replaced with a local xorshift32 PRNG, exposed via a new FCEU_MemoryRand_Reseed(uint32_t) function called once per power-on: - PowerNES seeds from the first 4 bytes of GameInfo->MD5 (set by all loaders before PowerNES runs) so identical ROMs produce identical RAM, different ROMs differ - iNES_Init seeds from iNESCart.PRGCRC32 before the CHR-RAM fill so two builds of the same ROM get the same CHR-RAM - The PRNG state advances across multiple FCEU_MemoryRand calls within one power-on so RAM and CHR-RAM get different content (matching NES hardware reality) 2. boards/rt-01.c UNLRT01Read. The RT-01 board has 'weak bit' protected EPROM regions; reads of 0xCE80-0xCEFF and 0xFE80- 0xFEFF return 0xF2 with the low 3 bits randomised. Replaced libc rand() with a local xorshift32 seeded at power-on, and added the PRNG state to the savestate via AddExState with key "WBKS" so save / load / rewind / netplay rollback all stay deterministic. In addition, two long-double-to-int truncations were changed to double for cross-platform FP determinism: - sound.c SetSoundVariables: soundtsinc - boards/n106.c DoNamcoSound: inc long double has platform-dependent precision (80-bit on x87, 64-bit with -mfpmath=sse, 128-bit on PowerPC), so the truncated integer result varied across these platforms. double is guaranteed 64-bit IEEE-754 portably. After this pass, the core has no time(), clock(), gettimeofday(), clock_gettime(), getpid(), getuid(), getgid(), getenv(), gethostid(), pthread, std::thread, OpenMP, signal handler, or non-deterministic- malloc dependency. Verified with a Python scanner that greps the source for these patterns; runs clean. The PPU / APU / CPU power-on already explicitly memset all state buffers to 0 (deterministic), and ROM/CHR-ROM allocation already memsets to 0xFF before partial fread (deterministic regardless of file truncation). Combined with the memory-safety hardening in 1185db8 (which prevents savestate-loaded indices from going out-of-bounds and producing unpredictable behaviour), the core now offers genuine frame-deterministic replay across runs, builds, and host endian.
2026-05-04 02:46:34 +02:00
static void M187CW(uint32_t A, uint8_t V) {
if ((A & 0x1000) == ((MMC3_cmd & 0x80) << 5))
setchr1(A, V | 0x100);
else
setchr1(A, V);
}
core: stdint typedefs, LE optimizations, frame determinism Three follow-up audit passes on top of the memory-safety / leak / savestate-portability work in 1185db8. ============================================================== Pass 1: replace custom typedefs with C99 stdint types throughout ============================================================== The custom uint8 / uint16 / uint32 / uint64 / int8 / int16 / int32 / int64 typedefs in src/fceu-types.h were just simple aliases for the C99 stdint.h types. Replace them with the standard names directly. - 498 files modified - ~3,400 token replacements (uint8 -> uint8_t, etc) - fceu-types.h slimmed down to just INLINE / GINLINE / FASTAPASS macros and the readfunc / writefunc function-pointer typedefs (those now use uint8_t / uint32_t natively) - Build clean on `make platform=unix` with zero new warnings - Output binary size unchanged - confirming semantic equivalence Mechanical replacement done with a Python script that uses word- boundary regex to avoid false positives (e.g. 'uint32_t' was correctly left alone because '_' is a word character so 'uint32' is not a complete word inside it). ================================================================ Pass 2: prefer memcpy on LE hosts for endian read/write helpers ================================================================ fceu-endian.c's write32le_mem, FCEU_en32lsb, and FCEU_de32lsb performed bytewise composition/decomposition unconditionally. On LE hosts the in-memory representation already matches the desired LE on-disk format, so a single memcpy is equivalent and lets the compiler emit a single load/store rather than four byte ops. - The bytewise path is kept inside #ifdef MSB_FIRST for BE hosts where it implements the actual byte swap - Both forms produce identical results; this is a code-clarity change more than a performance one (the optimizer was already merging the shifts on LE), but it documents the intent and removes a strict-aliasing-flavoured cast through *(uint32_t*)Bufo - Added missing #include <string.h> in fceu-endian.c which was relying on transitive includes for memcpy Other MSB_FIRST sites in the codebase (state.c FlipByteOrder guards, ppu.c sprite-line rendering, boards/unrom512.c flash-write- counter access) were already optimized for LE; they were verified correct rather than changed. ================================================================ Pass 3: frame determinism for replay and netplay ================================================================ Two libc rand() sites in core were replaced with a local xorshift32 PRNG so that NES games which read uninitialised memory or hit hardware "weak bit" emulation produce reproducible behaviour across runs. NES titles routinely read uninitialised RAM (variables not zeroed before use, sprite Y-position set by junk-on-stack), so the RAM contents at power-on subtly affect game behaviour. With libc rand(), those contents depend on whether anyone else seeded rand() in the same process - a different libretro frontend, a different audio backend init order, or any frontend that does srand(time(0)) all break replay / netplay frame-determinism. 1. fceu.c FCEU_MemoryRand. Used to fill RAM (PowerNES) and CHR-RAM (iNES_Init) at power-on when option_ramstate=2 (random init). Replaced with a local xorshift32 PRNG, exposed via a new FCEU_MemoryRand_Reseed(uint32_t) function called once per power-on: - PowerNES seeds from the first 4 bytes of GameInfo->MD5 (set by all loaders before PowerNES runs) so identical ROMs produce identical RAM, different ROMs differ - iNES_Init seeds from iNESCart.PRGCRC32 before the CHR-RAM fill so two builds of the same ROM get the same CHR-RAM - The PRNG state advances across multiple FCEU_MemoryRand calls within one power-on so RAM and CHR-RAM get different content (matching NES hardware reality) 2. boards/rt-01.c UNLRT01Read. The RT-01 board has 'weak bit' protected EPROM regions; reads of 0xCE80-0xCEFF and 0xFE80- 0xFEFF return 0xF2 with the low 3 bits randomised. Replaced libc rand() with a local xorshift32 seeded at power-on, and added the PRNG state to the savestate via AddExState with key "WBKS" so save / load / rewind / netplay rollback all stay deterministic. In addition, two long-double-to-int truncations were changed to double for cross-platform FP determinism: - sound.c SetSoundVariables: soundtsinc - boards/n106.c DoNamcoSound: inc long double has platform-dependent precision (80-bit on x87, 64-bit with -mfpmath=sse, 128-bit on PowerPC), so the truncated integer result varied across these platforms. double is guaranteed 64-bit IEEE-754 portably. After this pass, the core has no time(), clock(), gettimeofday(), clock_gettime(), getpid(), getuid(), getgid(), getenv(), gethostid(), pthread, std::thread, OpenMP, signal handler, or non-deterministic- malloc dependency. Verified with a Python scanner that greps the source for these patterns; runs clean. The PPU / APU / CPU power-on already explicitly memset all state buffers to 0 (deterministic), and ROM/CHR-ROM allocation already memsets to 0xFF before partial fread (deterministic regardless of file truncation). Combined with the memory-safety hardening in 1185db8 (which prevents savestate-loaded indices from going out-of-bounds and producing unpredictable behaviour), the core now offers genuine frame-deterministic replay across runs, builds, and host endian.
2026-05-04 02:46:34 +02:00
static void M187PW(uint32_t A, uint8_t V) {
if (EXPREGS[0] & 0x80) {
core: stdint typedefs, LE optimizations, frame determinism Three follow-up audit passes on top of the memory-safety / leak / savestate-portability work in 1185db8. ============================================================== Pass 1: replace custom typedefs with C99 stdint types throughout ============================================================== The custom uint8 / uint16 / uint32 / uint64 / int8 / int16 / int32 / int64 typedefs in src/fceu-types.h were just simple aliases for the C99 stdint.h types. Replace them with the standard names directly. - 498 files modified - ~3,400 token replacements (uint8 -> uint8_t, etc) - fceu-types.h slimmed down to just INLINE / GINLINE / FASTAPASS macros and the readfunc / writefunc function-pointer typedefs (those now use uint8_t / uint32_t natively) - Build clean on `make platform=unix` with zero new warnings - Output binary size unchanged - confirming semantic equivalence Mechanical replacement done with a Python script that uses word- boundary regex to avoid false positives (e.g. 'uint32_t' was correctly left alone because '_' is a word character so 'uint32' is not a complete word inside it). ================================================================ Pass 2: prefer memcpy on LE hosts for endian read/write helpers ================================================================ fceu-endian.c's write32le_mem, FCEU_en32lsb, and FCEU_de32lsb performed bytewise composition/decomposition unconditionally. On LE hosts the in-memory representation already matches the desired LE on-disk format, so a single memcpy is equivalent and lets the compiler emit a single load/store rather than four byte ops. - The bytewise path is kept inside #ifdef MSB_FIRST for BE hosts where it implements the actual byte swap - Both forms produce identical results; this is a code-clarity change more than a performance one (the optimizer was already merging the shifts on LE), but it documents the intent and removes a strict-aliasing-flavoured cast through *(uint32_t*)Bufo - Added missing #include <string.h> in fceu-endian.c which was relying on transitive includes for memcpy Other MSB_FIRST sites in the codebase (state.c FlipByteOrder guards, ppu.c sprite-line rendering, boards/unrom512.c flash-write- counter access) were already optimized for LE; they were verified correct rather than changed. ================================================================ Pass 3: frame determinism for replay and netplay ================================================================ Two libc rand() sites in core were replaced with a local xorshift32 PRNG so that NES games which read uninitialised memory or hit hardware "weak bit" emulation produce reproducible behaviour across runs. NES titles routinely read uninitialised RAM (variables not zeroed before use, sprite Y-position set by junk-on-stack), so the RAM contents at power-on subtly affect game behaviour. With libc rand(), those contents depend on whether anyone else seeded rand() in the same process - a different libretro frontend, a different audio backend init order, or any frontend that does srand(time(0)) all break replay / netplay frame-determinism. 1. fceu.c FCEU_MemoryRand. Used to fill RAM (PowerNES) and CHR-RAM (iNES_Init) at power-on when option_ramstate=2 (random init). Replaced with a local xorshift32 PRNG, exposed via a new FCEU_MemoryRand_Reseed(uint32_t) function called once per power-on: - PowerNES seeds from the first 4 bytes of GameInfo->MD5 (set by all loaders before PowerNES runs) so identical ROMs produce identical RAM, different ROMs differ - iNES_Init seeds from iNESCart.PRGCRC32 before the CHR-RAM fill so two builds of the same ROM get the same CHR-RAM - The PRNG state advances across multiple FCEU_MemoryRand calls within one power-on so RAM and CHR-RAM get different content (matching NES hardware reality) 2. boards/rt-01.c UNLRT01Read. The RT-01 board has 'weak bit' protected EPROM regions; reads of 0xCE80-0xCEFF and 0xFE80- 0xFEFF return 0xF2 with the low 3 bits randomised. Replaced libc rand() with a local xorshift32 seeded at power-on, and added the PRNG state to the savestate via AddExState with key "WBKS" so save / load / rewind / netplay rollback all stay deterministic. In addition, two long-double-to-int truncations were changed to double for cross-platform FP determinism: - sound.c SetSoundVariables: soundtsinc - boards/n106.c DoNamcoSound: inc long double has platform-dependent precision (80-bit on x87, 64-bit with -mfpmath=sse, 128-bit on PowerPC), so the truncated integer result varied across these platforms. double is guaranteed 64-bit IEEE-754 portably. After this pass, the core has no time(), clock(), gettimeofday(), clock_gettime(), getpid(), getuid(), getgid(), getenv(), gethostid(), pthread, std::thread, OpenMP, signal handler, or non-deterministic- malloc dependency. Verified with a Python scanner that greps the source for these patterns; runs clean. The PPU / APU / CPU power-on already explicitly memset all state buffers to 0 (deterministic), and ROM/CHR-ROM allocation already memsets to 0xFF before partial fread (deterministic regardless of file truncation). Combined with the memory-safety hardening in 1185db8 (which prevents savestate-loaded indices from going out-of-bounds and producing unpredictable behaviour), the core now offers genuine frame-deterministic replay across runs, builds, and host endian.
2026-05-04 02:46:34 +02:00
uint8_t bank = EXPREGS[0] & 0x1F;
if (EXPREGS[0] & 0x20) {
if (EXPREGS[0] & 0x40)
setprg32(0x8000, bank >> 2);
else
setprg32(0x8000, bank >> 1); /* hacky hacky! two mappers in one! need real hw carts to test */
} else {
setprg16(0x8000, bank);
setprg16(0xC000, bank);
}
} else
setprg8(A, V & 0x3F);
}
static DECLFW(M187Write8000) {
EXPREGS[1] = 1;
MMC3_CMDWrite(A, V);
}
static DECLFW(M187Write8001) {
if (EXPREGS[1])
MMC3_CMDWrite(A, V);
}
static DECLFW(M187WriteLo) {
if ((A == 0x5000) || (A == 0x6000)) {
EXPREGS[0] = V;
FixMMC3PRG(MMC3_cmd);
}
}
core: OOM safety, sign-compare cleanup, dead-code removal, const-correctness Omnibus cleanup pass. Build is clean on `make platform=unix` with zero errors and zero warnings, including under `-Wsign-compare -Wstrict-aliasing=2 -Wcast-align`. The `-Wsign-compare` flag is now permanently enabled in WARNING_DEFINES. ================================================================ A. FCEU_gmalloc no longer exit()s on OOM ================================================================ A libretro core must not call exit(): doing so tears down the entire frontend. FCEU_gmalloc previously did exactly that on allocation failure ("Doing a hard exit"). It now returns NULL with the same diagnostic message. Loader-level call sites that can fail their parent function (i.e. return 0 from FDSLoad/iNESLoad/NSFLoad to refuse the cart) now check the return value: - ines.c: trainerpoo, ExtraNTARAM - nsf.c: ExWRAM (both branches) - fds.c: FDSBIOS, CHRRAM, FDSRAM Mapper-level callers (~200 sites) are intentionally left as-is: they live in void-returning Init/Power functions where graceful failure isn't possible without a much larger restructuring. With NULL returns those mappers will null-deref on first access, which is contained to the core - the libretro frontend stays up. This is strictly better than the previous behaviour of exit()ing the entire frontend. ================================================================ B. -Wsign-compare cleanup (27 warnings -> 0) ================================================================ Surveyed every signed/unsigned comparison the compiler flagged and fixed each one. Most fell into a few patterns: Loop variables: changed `int x` to `uint32_t x` for loops over uint32_t counts (TotalSides in fds.c, the trainer-copy loop in 6_8_12_17_561_562.c, soundOffset->SOUNDTS in 594.c). scanline (signed) vs totalscanlines/normal_scanlines (unsigned) in ppu.c: cast (unsigned)scanline at the comparison sites. The scanline values are guaranteed >= 0 at every comparison site (the loop initialises scanline=0 and increments). rate_adjust macro in emu2413.c: the ?: was returning either signed or unsigned depending on `rate`. Cast both branches to uint32_t. Mixed ?: branches in cartram.c (PRGRamSaveSize signed vs WRAMSize unsigned): cast PRGRamSaveSize to uint32_t at use. Other one-off casts in libretro.c, n625092.c, nsf.c, sound.c, zapper.c, eeprom_93Cx6.c. The Makefile change keeps -Wsign-compare permanently enabled so new sign-compare bugs trip CI immediately. Files touched: 594.c, 6_8_12_17_561_562.c, cartram.c, eeprom_93Cx6.c, emu2413.c, n625092.c, fds.c, nsf.c, ppu.c, sound.c, input/zapper.c, drivers/libretro/libretro.c, plus Makefile.libretro. ================================================================ C. NULL-deref hardening on libretro callbacks ================================================================ retro_serialize and retro_unserialize now reject NULL data pointers before passing them to memstream_set_buffer (which would have null-deref'd inside the memstream code). Other retro_* entry points that take pointers were already guarded in earlier passes (retro_set_controller_port_device, retro_get_memory_data, retro_get_memory_size, retro_load_game, retro_cheat_set). ================================================================ D. Mapper coverage spot-check ================================================================ Wrote a heuristic scanner to find the savestate-load-array-index bug class fixed in pass 1 (variable masked at write but unmasked at restore -> OOB index). Scanner flagged 3 candidates across 424 mappers; manual review confirmed all three are false positives: - sachen.c `cmd`: theoretical bug, but only one writer is wired per game and that writer masks at use. - unrom512.c `flash_state` and `latcha`: both already clamped in StateRestore (added in pass 1). The systematic bug class was thoroughly addressed in pass 1. ================================================================ E. Strip never-defined #ifdef symbols ================================================================ Surveyed every #ifdef symbol in the build and cross-checked against #defines (in source and in build files). Removed code gated on symbols that are never defined for any platform target: - DEBUG_MAPPER (datalatch.c, 2 sites): a debug-print NROMWrite handler. Dead. - FRAMESKIP (fceu.h, driver.h, ppu.c, 4 sites): a legacy-FCEU frameskip path. The libretro driver's `skip` argument to FCEUI_Emulate is always 0, and FCEUI_FrameSkip is never called by any libretro frontend. Removed the conditional rendering branch in FCEUPPU_Loop along with the FCEU_PutImageDummy declaration. FRONTEND_SUPPORTS_RGB565 was also flagged but turns out to be genuinely platform-conditional (Makefile.common defines it when WANT_32BPP=0). Kept. ================================================================ F. assert() audit ================================================================ Two assert() calls live in src/ntsc/nes_ntsc_impl.h - third-party NTSC filter code from blargg, both NaN sanity checks (`assert(x == x)`). NDEBUG is in the build flags so they compile to no-ops. No fceumm code uses assert. Nothing to do here. ================================================================ G. const-correctness ================================================================ Function signatures that take strings they don't modify now take const char *: FCEU_printf, FCEU_PrintError (const char *format) FCEUD_PrintError, FCEUD_Message (const char *) FCEU_MakeFName (const char *cd1) md5_update (const uint8_t *input) md5_process (const uint8_t data[64]) also made `static` ================================================================ H. Const-fold static lookup tables ================================================================ Marked static lookup tables const where they are never written: x6502.c: CycTable[256] (cycle counts) md5.c: md5_padding[64] (MD5 padding) vsuni.c: secdata[2][32], secptr (VS security data) palette.c: rtmul/gtmul/btmul[7] (palette multipliers) input/cursor.c: GunSight, FCEUcursor (sprite data) input/pec586kb.c, fkb.c, suborkb.c: matrix (key matrices) boards/8237.c: regperm, adrperm, protarray (mapper perms) boards/datalatch.c: M538Banks (bank table) boards/187.c: prot_data boards/121.c: prot_array boards/bonza.c: sim0reset boards/pec-586.c: bs_tbl, br_tbl boards/178.c: step_size, step_adj (ADPCM tables) boards/244.c: prg_perm, chr_perm boards/bmc42in1r.c: banks boards/emu2413.c: SL (sustain levels) NSFROM in nsf.c looks like a lookup table but is rewritten at runtime to patch in addresses, so it stays mutable. ================================================================ I. Reduce strlen calls ================================================================ Replaced `strlen(STRING_LITERAL)` with `sizeof(STRING_LITERAL) - 1` where the argument is a compile-time-known string literal: - libretro.c retro_set_environment APU loop: was calling strlen("fceumm_apu_") on every loop iteration to compute the same constant offset. - nsf.c visualizer: strlen("Song:"). Other strlen sites in cheat.c, libretro.c, unif.c either already cache to a local size_t or operate on runtime-supplied strings where caching would not help. ================================================================ Build status ================================================================ `make platform=unix` clean: zero errors, zero warnings. With -Wsign-compare -Wstrict-aliasing=2 -Wcast-align: zero warnings. audit_determinism.py: 0 issues. Output binary 4,388,408 bytes (was 4,388,576 from upstream 004c147; -168 bytes from dead-code removal).
2026-05-04 03:55:23 +02:00
static const uint8_t prot_data[4] = { 0x83, 0x83, 0x42, 0x00 };
static DECLFR(M187Read) {
return prot_data[EXPREGS[1] & 3];
}
static void M187Power(void) {
EXPREGS[0] = EXPREGS[1] = 0;
GenMMC3Power();
SetReadHandler(0x5000, 0x5FFF, M187Read);
SetWriteHandler(0x5000, 0x6FFF, M187WriteLo);
SetWriteHandler(0x8000, 0x8000, M187Write8000);
SetWriteHandler(0x8001, 0x8001, M187Write8001);
}
void Mapper187_Init(CartInfo *info) {
GenMMC3_Init(info, 256, 256, 0, 0);
pwrap = M187PW;
cwrap = M187CW;
info->Power = M187Power;
AddExState(EXPREGS, 3, 0, "EXPR");
}