2021-04-08 17:06:17 +02:00
/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file :
* Copyright ( C ) 2002 Xodnizel
* Copyright ( C ) 2005 CaH4e3
* Copyright ( C ) 2019 Libretro Team
*
* 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
*/
# include "mapinc.h"
2022-03-02 13:35:56 +01:00
# include "mmc3.h"
2021-04-08 17:06:17 +02:00
void ( * sync ) ( void ) ;
static uint8 allowExtendedMirroring ;
static uint8 mode [ 4 ] ;
static uint8 * WRAM = NULL ;
static uint32 WRAMSIZE ;
static uint8 irqControl ;
static uint8 irqEnabled ;
static uint8 irqPrescaler ;
static uint8 irqCounter ;
static uint8 irqXor ;
static uint32 lastPPUAddress ;
static uint8 prg [ 4 ] ;
static uint16 chr [ 8 ] ;
static uint16 nt [ 4 ] ;
static uint8 latch [ 2 ] ;
static uint8 mul [ 2 ] ;
static uint8 adder ;
static uint8 test ;
static uint8 dipSwitch ;
2025-04-01 18:56:49 +02:00
static uint8 submapper ;
2021-04-08 17:06:17 +02:00
2022-03-02 13:35:56 +01:00
static uint8 cpuWriteHandlersSet ;
2021-04-08 17:46:51 +02:00
static writefunc cpuWriteHandlers [ 0x10000 ] ; /* Actual write handlers for CPU write trapping as a method fo IRQ clocking */
2021-04-08 17:06:17 +02:00
static SFORMAT JYASIC_stateRegs [ ] = {
{ & irqControl , 1 , " IRQM " } ,
{ & irqPrescaler , 1 , " IRQP " } ,
{ & irqCounter , 1 , " IRQC " } ,
{ & irqXor , 1 , " IRQX " } ,
{ & irqEnabled , 1 , " IRQA " } ,
{ mul , 2 , " MUL " } ,
{ & test , 1 , " REGI " } ,
{ mode , 4 , " TKCO " } ,
{ prg , 4 , " PRGB " } ,
{ latch , 2 , " CLTC " } ,
{ chr , 8 * 2 , " CHRB " } ,
{ & nt [ 0 ] , 2 | FCEUSTATE_RLSB , " NMS0 " } ,
{ & nt [ 1 ] , 2 | FCEUSTATE_RLSB , " NMS1 " } ,
{ & nt [ 2 ] , 2 | FCEUSTATE_RLSB , " NMS2 " } ,
{ & nt [ 3 ] , 2 | FCEUSTATE_RLSB , " NMS3 " } ,
{ & dipSwitch , 1 , " TEKR " } ,
{ & adder , 1 , " ADDE " } ,
{ 0 }
} ;
2021-04-08 17:50:56 +02:00
static uint8 rev ( uint8_t val )
{
2021-04-08 17:06:17 +02:00
return ( ( val < < 6 ) & 0x40 ) | ( ( val < < 4 ) & 0x20 ) | ( ( val < < 2 ) & 0x10 ) | ( val & 0x08 ) | ( ( val > > 2 ) & 0x04 ) | ( ( val > > 4 ) & 0x02 ) | ( ( val > > 6 ) & 0x01 ) ;
}
2021-04-08 17:50:56 +02:00
static void syncPRG ( int AND , int OR )
{
2021-04-08 17:06:17 +02:00
uint8_t prgLast = mode [ 0 ] & 0x04 ? prg [ 3 ] : 0xFF ;
uint8_t prg6000 = 0 ;
2021-04-08 17:50:56 +02:00
switch ( mode [ 0 ] & 0x03 )
{
case 0 :
setprg32 ( 0x8000 , prgLast & AND > > 2 | OR > > 2 ) ;
prg6000 = prg [ 3 ] < < 2 | 3 ;
break ;
case 1 :
setprg16 ( 0x8000 , prg [ 1 ] & AND > > 1 | OR > > 1 ) ;
setprg16 ( 0xC000 , prgLast & AND > > 1 | OR > > 1 ) ;
prg6000 = prg [ 3 ] < < 1 | 1 ;
break ;
case 2 :
setprg8 ( 0x8000 , prg [ 0 ] & AND | OR ) ;
setprg8 ( 0xA000 , prg [ 1 ] & AND | OR ) ;
setprg8 ( 0xC000 , prg [ 2 ] & AND | OR ) ;
setprg8 ( 0xE000 , prgLast & AND | OR ) ;
prg6000 = prg [ 3 ] ;
break ;
case 3 :
setprg8 ( 0x8000 , rev ( prg [ 0 ] ) & AND | OR ) ;
setprg8 ( 0xA000 , rev ( prg [ 1 ] ) & AND | OR ) ;
setprg8 ( 0xC000 , rev ( prg [ 2 ] ) & AND | OR ) ;
setprg8 ( 0xE000 , rev ( prgLast ) & AND | OR ) ;
prg6000 = rev ( prg [ 3 ] ) ;
break ;
}
2021-04-08 17:46:51 +02:00
if ( mode [ 0 ] & 0x80 ) /* Map ROM */
2021-04-08 17:06:17 +02:00
setprg8 ( 0x6000 , prg6000 & AND | OR ) ;
else
2021-04-08 17:50:56 +02:00
if ( WRAMSIZE ) /* Otherwise map WRAM if it exists */
setprg8r ( 0x10 , 0x6000 , 0 ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
static void syncCHR ( int AND , int OR )
{
2021-04-08 17:50:56 +02:00
/* MMC4 mode[0] with 4 KiB CHR mode[0] */
if ( mode [ 3 ] & 0x80 & & ( mode [ 0 ] & 0x18 ) = = 0x08 )
{
int chrBank ;
for ( chrBank = 0 ; chrBank < 8 ; chrBank + = 4 )
setchr4 ( 0x400 * chrBank , chr [ latch [ chrBank / 4 ] & 2 | chrBank ] & AND > > 2 | OR > > 2 ) ;
}
2021-04-08 17:46:51 +02:00
else
2021-04-08 17:50:56 +02:00
{
int chrBank ;
switch ( mode [ 0 ] & 0x18 )
{
2021-04-08 17:46:51 +02:00
case 0x00 : /* 8 KiB CHR mode[0] */
setchr8 ( chr [ 0 ] & AND > > 3 | OR > > 3 ) ;
break ;
case 0x08 : /* 4 KiB CHR mode[0] */
2021-04-08 17:50:56 +02:00
for ( chrBank = 0 ; chrBank < 8 ; chrBank + = 4 )
setchr4 ( 0x400 * chrBank , chr [ chrBank ] & AND > > 2 | OR > > 2 ) ;
2021-04-08 17:46:51 +02:00
break ;
case 0x10 :
2021-04-08 17:50:56 +02:00
for ( chrBank = 0 ; chrBank < 8 ; chrBank + = 2 )
setchr2 ( 0x400 * chrBank , chr [ chrBank ] & AND > > 1 | OR > > 1 ) ;
2021-04-08 17:46:51 +02:00
break ;
case 0x18 :
2021-04-08 17:50:56 +02:00
for ( chrBank = 0 ; chrBank < 8 ; chrBank + = 1 )
setchr1 ( 0x400 * chrBank , chr [ chrBank ] & AND | OR ) ;
2021-04-08 17:46:51 +02:00
break ;
}
2021-04-08 17:50:56 +02:00
}
PPUCHRRAM = ( mode [ 2 ] & 0x40 ) ? 0xFF : 0x00 ; /* Write-protect or write-enable CHR-RAM */
2021-04-08 17:46:51 +02:00
}
static void syncNT ( int AND , int OR )
{
if ( mode [ 0 ] & 0x20 | | mode [ 1 ] & 0x08 )
{
/* ROM nametables or extended mirroring */
/* First, set normal CIRAM pages using extended registers ... */
setmirrorw ( nt [ 0 ] & 1 , nt [ 1 ] & 1 , nt [ 2 ] & 1 , nt [ 3 ] & 1 ) ;
2021-04-08 17:50:56 +02:00
if ( mode [ 0 ] & 0x20 )
2021-04-08 17:46:51 +02:00
{
2021-04-08 17:50:56 +02:00
int ntBank ;
for ( ntBank = 0 ; ntBank < 4 ; ntBank + + )
{
/* Then replace with ROM nametables if such are generally enabled */
int vromHere = ( nt [ ntBank ] & 0x80 ) ^ ( mode [ 2 ] & 0x80 ) | ( mode [ 0 ] & 0x40 ) ;
/* ROM nametables are used either when globally enabled via D000.6 or per-bank via B00x.7 vs. D002.7 */
if ( vromHere )
setntamem ( CHRptr [ 0 ] + 0x400 * ( ( nt [ ntBank ] & AND | OR ) & CHRmask1 [ 0 ] ) , 0 , ntBank ) ;
}
2021-04-08 17:46:51 +02:00
}
}
else
switch ( mode [ 1 ] & 0x03 )
{
/* Regularly mirrored CIRAM */
case 0 :
setmirror ( MI_V ) ;
break ;
case 1 :
setmirror ( MI_H ) ;
break ;
case 2 :
setmirror ( MI_0 ) ;
break ;
case 3 :
setmirror ( MI_1 ) ;
break ;
}
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:50:56 +02:00
static void clockIRQ ( void )
{
2021-04-08 17:06:17 +02:00
uint8_t mask = irqControl & 0x04 ? 0x07 : 0xFF ;
2021-04-08 17:50:56 +02:00
if ( irqEnabled )
switch ( irqControl & 0xC0 )
{
core: memory-safety, leak, and savestate-portability audit fixes
Squashed series of ~50 distinct bugs found during a multi-day
security/correctness audit, ranging from ROM-triggerable heap
corruption and savestate-triggered OOB read primitives down to
obscure cross-platform savestate breakage.
Build is clean on `make platform=unix` with zero new warnings.
CRITICAL (ROM-triggerable, exploitable on the user's machine)
=============================================================
* ines.c iNES 2.0 PRG/CHR exponent overflow leading to undersized
allocation followed by heap buffer overflow on fread (pow() with
attacker-chosen exponent up to 63). Cap exponent at 30 and
compute size in uint32 with explicit cap below 2 GiB before
storing in int.
* ines.c miscROMSize int wraparound from attacker-controlled PRG/
CHR sizes; previous '& 0x8000000' check missed common underflow
cases. Compute in int64 and reject <= 0 or > 128 MiB.
* unif.c MAPR chunk OOB heap read on chunks of size < 4. Validate
chunk size before allocating board-name buffer.
* unif.c chunk size truncation: int conversion + missing cap allowed
a 4 GiB chunk size to wrap. Cap at 16 MiB.
* unif.c FixRomSize infinite loop on size > 0x80000000. Cap input.
* unif.c DINF chunk: months[(m - 1) % 12] is UB for m==0; m comes
from the .unf file. Clamp m into [1..12] before subtracting.
* unif.c NAME chunk: GameInfo->name = malloc(...) was unchecked.
* nsf.c size underflow: FCEU_fgetsize() - 0x80 wraps to ~UINT64_MAX
on tiny files, propagating a huge size into uppow2/FCEU_malloc.
Validate size > 0x80 before subtracting.
* nsf.c NSFMaxBank * 4096 cap tightened from 1<<20 (UB on signed-int
overflow) to 1<<19 (fits in int).
* general.c uppow2 had signed-int UB (1 << 32) and wrapped to 0 for
inputs near uint32 max. Cap at 0x80000000.
* cheat.c SubCheats[256] BSS overflow when more than 256 GG/PAR
substitution cheats are active. The array is adjacent to MMapPtrs[64]
in BSS which is exposed via retro_get_memory_data, making this
overflow visible from outside the core.
* libretro.c retro_cheat_set strcpy stack overflow with arbitrary-
length cheat strings from the frontend. Use strlcpy.
CRITICAL (savestate-triggerable on a malicious .fcs file)
=========================================================
* fds.c FDS savestate OOB read primitive: InDisk loaded from
savestate is used as index into 8-element diskdata[] static
pointer array. A value 8..254 dereferences arbitrary memory as
a pointer (heap-read primitive). Also bounds-checked SelectDisk,
mapperFDS_block, mapperFDS_blockstart, mapperFDS_diskaddr,
mapperFDS_blocklen so blockstart+diskaddr stays within the 65500-
byte disk buffer.
* 11 mappers had savestate-loaded variables masked at write time
but not at restore time, used as indices into fixed arrays:
- 88.c, KS7037.c, 112.c cmd indexes reg[8]
- sachen.c (S8259, S74LS374N) cmd indexes latch[8]
- 357.c dipswitch indexes outer_bank[4]
- unrom512.c flash_state indexes erase_a/d/b[5]
- 368.c preg indexes banks[8]
- 69.c sndcmd indexes sreg[14]
- mmc2and4.c latch0/latch1 index creg[4]
None individually exploitable into RCE - the array writes corrupt
adjacent BSS with constrained data flowing in - but each is an
out-of-bounds read or write from attacker-controllable input.
HIGH (memory-safety, reachable on any load)
===========================================
* fceu-memory.c FCEU_malloc deref-of-NULL on allocation failure
('ret = 0; memset(ret, 0, size);').
* file.c multiple FCEUFILE/MakeMemWrap/MakeMemWrapBuffer unchecked
allocations and unchecked filestream_tell return.
* libretro.c GameInfo NULL-derefs in three entry points
(retro_set_controller_port_device, retro_get_memory_data,
retro_get_memory_size) reachable on operations called before a
successful load.
* libretro.c framebuffer leak ~256 KB per failed FCEUI_LoadGame
(the libretro frontend doesn't call retro_unload_game on a
failed load).
* libretro.c 3DS retro_deinit unchecked linearFree.
* libretro.c stereo / NTSC filter unchecked malloc returns.
* fceu.c FCEUI_LoadGame unchecked GameInfo malloc.
* fds.c SubLoad and FDSLoad unchecked FCEU_malloc on diskdatao
backup buffers (NULL-deref in subsequent memcpy).
* fceu.c AllocGenieRW partial-failure leak: AReadG allocated but
BWriteG malloc fails -> 256 KB leak per retry.
* input/bworld.c Update(): unbounded strcpy from attacker-supplied
data into 20-byte bdata. Replaced with length-bounded copy.
* cart.c setprg2r/4r and setchr1r/2r/4r/8r mask-underflow guards.
SetupCartPRGMapping/SetupCartCHRMapping compute (size >> N) - 1
which underflows to 0xFFFFFFFF for chips smaller than the unit.
setprg8r/16r/32r and setchr8r already had defensive size checks;
the smaller units did not. malee.c (2 KB chip) and mapper 218
(2 KB NTARAM-as-CHR) accidentally avoid OOB; the primitive is
unsafe for any future board.
* video.c FCEU_InitVirtualVideo XBuf/XDBuf partial-failure leak.
* video.c, fceu.c FCEU_DispMessage / FCEU_printf / FCEU_PrintError:
vsprintf into fixed stack buffers replaced with vsnprintf.
* core: validate magic-string read length on FDS/UNIF/NSF load
(reject files too short to contain the magic so previous static
buffer / stack garbage doesn't spuriously match).
LEAKS (every cart load/unload cycle)
====================================
* mmc5.c MMC5 cart-side: WRAM (up to 64K) + MMC5fill (1K) + ExRAM
(1K) leaked per cycle. NSFMMC5_Close existed but was only used
for NSF code path.
* onebus.c Mapper 270/436: 8 KB CHRRAM leaked per cycle.
* 330.c, 375.c, 528.c: 8 KB WRAM each, no Close at all.
CORRECTNESS (UB / ABI / endianness)
===================================
* fceu-endian.c FlipByteOrder loop bound was 'count' instead of
'count/2', making it a no-op for every even count and silently
breaking savestate portability for every FCEUSTATE_RLSB-marked
field. The '#ifndef GEKKO' workarounds scattered through the
codebase (sound.c, vrc7.c, vrc6.c) were symptoms of this root
cause.
* state.c AddExState bounds check ran AFTER writing the entry, so
when SFEXINDEX hit the 63-entry cap the next call would write
the entry then immediately overwrite it with the terminator.
* state.c FCEUSS_Save_Mem: post-save callback was guarded by
'if (SPreSave)' instead of 'if (SPostSave)'.
* Sequence-point UB in counter expressions across 4 board files,
e.g. 'x = !x ? a : --x' and 'x = ++x % n'. GCC -Wsequence-point
flags all five sites (285.c, 413.c, asic_mmc3.c, jyasic.c).
* SFORMAT size mismatches between declared variable type and
AddExState size argument:
- asic_vrc3.c VRC3_count/VRC3_reload (uint16, saved as 1 byte)
- mmc3.c m555_count (uint32, saved as 2 bytes), m555_count_-
expired (uint8, saved as 2 bytes - OOB write into adjacent
BSS).
* unrom512.c UNROM-512 mapper 30 .srm save format: host-endian
uint32 flash write counters. Now stored as LE on disk regardless
of host (Battle Kid 2, Twin Dragons, Lizard, Sole, etc.).
* ~70 multi-byte single-variable SFORMAT/AddExState entries across
36 board files were saved as host-byte-order. After the
FlipByteOrder fix, these are now byte-swapped on BE so cross-
platform savestates round-trip correctly.
* coolgirl.c new ExStateLE() macro added; 22 multi-byte sites.
* pic16c5x.c 11 multi-byte AddExState calls (m_PC, m_PREVPC,
m_CONFIG, m_WDT, m_prescaler, m_opcode, m_STACK[0/1], m_icount,
m_delay_timer, m_rtcc, m_inst_cycles, m_clock2cycle).
* onebus.c PowerJoy Supermax submapper detection used non-portable
*(uint32*)&info->MD5 cast that read different bytes on LE vs BE.
* fds.c clean up redundant FCEUSTATE_RLSB encoding in AddExState
calls that also passed type=1 (idempotent OR; readability fix).
DOCUMENTATION
=============
* input.c UpdateGP's *(uint32*)data cast looks like a typical
endian bug but is actually correct (the libretro frontend builds
JSReturn with matching host-uint32 shifts). Comment added to
prevent future "fixes" from breaking it.
Limitations not addressed
=========================
* Element-stride-aware byte swapping. The savestate byte-swap
mechanism (FlipByteOrder over the entire SFORMAT entry buffer)
is structurally wrong for arrays of multi-byte values: it
reverses the whole buffer end-to-end instead of byte-swapping
each element. Several places that need cross-platform-portable
arrays (VRC7 sound state, jyasic chr[8]) work around this by
either splitting arrays into per-element SFORMAT entries (n106
PlayIndex, bandai reg) or by skipping save entirely on BE via
#ifndef GEKKO. A proper fix would extend the size encoding with
an element-stride field. Left for a future change because it
would change the savestate format.
* Strict-aliasing UB in ppu.c (around 9 sites doing
*(uint32*)uint8_buf for fast 4-byte writes via FCEU_dwmemset).
Works in practice with all common compilers because the patterns
are byte-symmetric, but is formally UB.
* FCEU_gmalloc calls exit(1) on OOM. A libretro core should never
exit() because that takes down the whole frontend. Used by
100+ call sites; refactoring to return-NULL is out of scope here.
Testing
=======
* Build: clean on `make platform=unix` with -O2; no new warnings.
* FlipByteOrder fix verified by hand-trace and a standalone unit
test for counts 2, 4, 8.
* uppow2 fix verified by unit test across 13 boundary cases.
* SFORMAT size mismatches and missing-RLSB cases identified by
Python static-analysis scripts that cross-reference SFORMAT
entries against variable declarations.
* iNES 2.0 exponent fix verified by hand-tracing what byte 0xFF
produces post-fix: exp=30 (capped), mult=7, size=3 GiB nominal,
capped to 1 GiB, capped to 2 GiB by uppow2, FCEU_malloc returns
NULL on most systems, loader returns 0. No heap overflow for
any input byte.
* Savestate-loaded array index audit: built a Python scanner that
extracts each AddExState/SFORMAT entry and cross-references the
variable name against array-index uses in the same file. All
flagged sites covered.
* A libFuzzer harness and seed corpus generator (fuzz_main.c,
gen_seed_corpus.py) accompany this submission for ongoing
regression testing.
2026-05-04 02:15:40 +02:00
case 0x40 : {
uint8_t newp = ( irqPrescaler + 1 ) & mask ;
irqPrescaler = ( irqPrescaler & ~ mask ) | newp ;
if ( newp = = 0x00 & & ( irqControl & 0x08 ? irqCounter : + + irqCounter ) = = 0x00 )
2021-04-08 17:50:56 +02:00
X6502_IRQBegin ( FCEU_IQEXT ) ;
break ;
core: memory-safety, leak, and savestate-portability audit fixes
Squashed series of ~50 distinct bugs found during a multi-day
security/correctness audit, ranging from ROM-triggerable heap
corruption and savestate-triggered OOB read primitives down to
obscure cross-platform savestate breakage.
Build is clean on `make platform=unix` with zero new warnings.
CRITICAL (ROM-triggerable, exploitable on the user's machine)
=============================================================
* ines.c iNES 2.0 PRG/CHR exponent overflow leading to undersized
allocation followed by heap buffer overflow on fread (pow() with
attacker-chosen exponent up to 63). Cap exponent at 30 and
compute size in uint32 with explicit cap below 2 GiB before
storing in int.
* ines.c miscROMSize int wraparound from attacker-controlled PRG/
CHR sizes; previous '& 0x8000000' check missed common underflow
cases. Compute in int64 and reject <= 0 or > 128 MiB.
* unif.c MAPR chunk OOB heap read on chunks of size < 4. Validate
chunk size before allocating board-name buffer.
* unif.c chunk size truncation: int conversion + missing cap allowed
a 4 GiB chunk size to wrap. Cap at 16 MiB.
* unif.c FixRomSize infinite loop on size > 0x80000000. Cap input.
* unif.c DINF chunk: months[(m - 1) % 12] is UB for m==0; m comes
from the .unf file. Clamp m into [1..12] before subtracting.
* unif.c NAME chunk: GameInfo->name = malloc(...) was unchecked.
* nsf.c size underflow: FCEU_fgetsize() - 0x80 wraps to ~UINT64_MAX
on tiny files, propagating a huge size into uppow2/FCEU_malloc.
Validate size > 0x80 before subtracting.
* nsf.c NSFMaxBank * 4096 cap tightened from 1<<20 (UB on signed-int
overflow) to 1<<19 (fits in int).
* general.c uppow2 had signed-int UB (1 << 32) and wrapped to 0 for
inputs near uint32 max. Cap at 0x80000000.
* cheat.c SubCheats[256] BSS overflow when more than 256 GG/PAR
substitution cheats are active. The array is adjacent to MMapPtrs[64]
in BSS which is exposed via retro_get_memory_data, making this
overflow visible from outside the core.
* libretro.c retro_cheat_set strcpy stack overflow with arbitrary-
length cheat strings from the frontend. Use strlcpy.
CRITICAL (savestate-triggerable on a malicious .fcs file)
=========================================================
* fds.c FDS savestate OOB read primitive: InDisk loaded from
savestate is used as index into 8-element diskdata[] static
pointer array. A value 8..254 dereferences arbitrary memory as
a pointer (heap-read primitive). Also bounds-checked SelectDisk,
mapperFDS_block, mapperFDS_blockstart, mapperFDS_diskaddr,
mapperFDS_blocklen so blockstart+diskaddr stays within the 65500-
byte disk buffer.
* 11 mappers had savestate-loaded variables masked at write time
but not at restore time, used as indices into fixed arrays:
- 88.c, KS7037.c, 112.c cmd indexes reg[8]
- sachen.c (S8259, S74LS374N) cmd indexes latch[8]
- 357.c dipswitch indexes outer_bank[4]
- unrom512.c flash_state indexes erase_a/d/b[5]
- 368.c preg indexes banks[8]
- 69.c sndcmd indexes sreg[14]
- mmc2and4.c latch0/latch1 index creg[4]
None individually exploitable into RCE - the array writes corrupt
adjacent BSS with constrained data flowing in - but each is an
out-of-bounds read or write from attacker-controllable input.
HIGH (memory-safety, reachable on any load)
===========================================
* fceu-memory.c FCEU_malloc deref-of-NULL on allocation failure
('ret = 0; memset(ret, 0, size);').
* file.c multiple FCEUFILE/MakeMemWrap/MakeMemWrapBuffer unchecked
allocations and unchecked filestream_tell return.
* libretro.c GameInfo NULL-derefs in three entry points
(retro_set_controller_port_device, retro_get_memory_data,
retro_get_memory_size) reachable on operations called before a
successful load.
* libretro.c framebuffer leak ~256 KB per failed FCEUI_LoadGame
(the libretro frontend doesn't call retro_unload_game on a
failed load).
* libretro.c 3DS retro_deinit unchecked linearFree.
* libretro.c stereo / NTSC filter unchecked malloc returns.
* fceu.c FCEUI_LoadGame unchecked GameInfo malloc.
* fds.c SubLoad and FDSLoad unchecked FCEU_malloc on diskdatao
backup buffers (NULL-deref in subsequent memcpy).
* fceu.c AllocGenieRW partial-failure leak: AReadG allocated but
BWriteG malloc fails -> 256 KB leak per retry.
* input/bworld.c Update(): unbounded strcpy from attacker-supplied
data into 20-byte bdata. Replaced with length-bounded copy.
* cart.c setprg2r/4r and setchr1r/2r/4r/8r mask-underflow guards.
SetupCartPRGMapping/SetupCartCHRMapping compute (size >> N) - 1
which underflows to 0xFFFFFFFF for chips smaller than the unit.
setprg8r/16r/32r and setchr8r already had defensive size checks;
the smaller units did not. malee.c (2 KB chip) and mapper 218
(2 KB NTARAM-as-CHR) accidentally avoid OOB; the primitive is
unsafe for any future board.
* video.c FCEU_InitVirtualVideo XBuf/XDBuf partial-failure leak.
* video.c, fceu.c FCEU_DispMessage / FCEU_printf / FCEU_PrintError:
vsprintf into fixed stack buffers replaced with vsnprintf.
* core: validate magic-string read length on FDS/UNIF/NSF load
(reject files too short to contain the magic so previous static
buffer / stack garbage doesn't spuriously match).
LEAKS (every cart load/unload cycle)
====================================
* mmc5.c MMC5 cart-side: WRAM (up to 64K) + MMC5fill (1K) + ExRAM
(1K) leaked per cycle. NSFMMC5_Close existed but was only used
for NSF code path.
* onebus.c Mapper 270/436: 8 KB CHRRAM leaked per cycle.
* 330.c, 375.c, 528.c: 8 KB WRAM each, no Close at all.
CORRECTNESS (UB / ABI / endianness)
===================================
* fceu-endian.c FlipByteOrder loop bound was 'count' instead of
'count/2', making it a no-op for every even count and silently
breaking savestate portability for every FCEUSTATE_RLSB-marked
field. The '#ifndef GEKKO' workarounds scattered through the
codebase (sound.c, vrc7.c, vrc6.c) were symptoms of this root
cause.
* state.c AddExState bounds check ran AFTER writing the entry, so
when SFEXINDEX hit the 63-entry cap the next call would write
the entry then immediately overwrite it with the terminator.
* state.c FCEUSS_Save_Mem: post-save callback was guarded by
'if (SPreSave)' instead of 'if (SPostSave)'.
* Sequence-point UB in counter expressions across 4 board files,
e.g. 'x = !x ? a : --x' and 'x = ++x % n'. GCC -Wsequence-point
flags all five sites (285.c, 413.c, asic_mmc3.c, jyasic.c).
* SFORMAT size mismatches between declared variable type and
AddExState size argument:
- asic_vrc3.c VRC3_count/VRC3_reload (uint16, saved as 1 byte)
- mmc3.c m555_count (uint32, saved as 2 bytes), m555_count_-
expired (uint8, saved as 2 bytes - OOB write into adjacent
BSS).
* unrom512.c UNROM-512 mapper 30 .srm save format: host-endian
uint32 flash write counters. Now stored as LE on disk regardless
of host (Battle Kid 2, Twin Dragons, Lizard, Sole, etc.).
* ~70 multi-byte single-variable SFORMAT/AddExState entries across
36 board files were saved as host-byte-order. After the
FlipByteOrder fix, these are now byte-swapped on BE so cross-
platform savestates round-trip correctly.
* coolgirl.c new ExStateLE() macro added; 22 multi-byte sites.
* pic16c5x.c 11 multi-byte AddExState calls (m_PC, m_PREVPC,
m_CONFIG, m_WDT, m_prescaler, m_opcode, m_STACK[0/1], m_icount,
m_delay_timer, m_rtcc, m_inst_cycles, m_clock2cycle).
* onebus.c PowerJoy Supermax submapper detection used non-portable
*(uint32*)&info->MD5 cast that read different bytes on LE vs BE.
* fds.c clean up redundant FCEUSTATE_RLSB encoding in AddExState
calls that also passed type=1 (idempotent OR; readability fix).
DOCUMENTATION
=============
* input.c UpdateGP's *(uint32*)data cast looks like a typical
endian bug but is actually correct (the libretro frontend builds
JSReturn with matching host-uint32 shifts). Comment added to
prevent future "fixes" from breaking it.
Limitations not addressed
=========================
* Element-stride-aware byte swapping. The savestate byte-swap
mechanism (FlipByteOrder over the entire SFORMAT entry buffer)
is structurally wrong for arrays of multi-byte values: it
reverses the whole buffer end-to-end instead of byte-swapping
each element. Several places that need cross-platform-portable
arrays (VRC7 sound state, jyasic chr[8]) work around this by
either splitting arrays into per-element SFORMAT entries (n106
PlayIndex, bandai reg) or by skipping save entirely on BE via
#ifndef GEKKO. A proper fix would extend the size encoding with
an element-stride field. Left for a future change because it
would change the savestate format.
* Strict-aliasing UB in ppu.c (around 9 sites doing
*(uint32*)uint8_buf for fast 4-byte writes via FCEU_dwmemset).
Works in practice with all common compilers because the patterns
are byte-symmetric, but is formally UB.
* FCEU_gmalloc calls exit(1) on OOM. A libretro core should never
exit() because that takes down the whole frontend. Used by
100+ call sites; refactoring to return-NULL is out of scope here.
Testing
=======
* Build: clean on `make platform=unix` with -O2; no new warnings.
* FlipByteOrder fix verified by hand-trace and a standalone unit
test for counts 2, 4, 8.
* uppow2 fix verified by unit test across 13 boundary cases.
* SFORMAT size mismatches and missing-RLSB cases identified by
Python static-analysis scripts that cross-reference SFORMAT
entries against variable declarations.
* iNES 2.0 exponent fix verified by hand-tracing what byte 0xFF
produces post-fix: exp=30 (capped), mult=7, size=3 GiB nominal,
capped to 1 GiB, capped to 2 GiB by uppow2, FCEU_malloc returns
NULL on most systems, loader returns 0. No heap overflow for
any input byte.
* Savestate-loaded array index audit: built a Python scanner that
extracts each AddExState/SFORMAT entry and cross-references the
variable name against array-index uses in the same file. All
flagged sites covered.
* A libFuzzer harness and seed corpus generator (fuzz_main.c,
gen_seed_corpus.py) accompany this submission for ongoing
regression testing.
2026-05-04 02:15:40 +02:00
}
case 0x80 : {
uint8_t newp = ( irqPrescaler - 1 ) & mask ;
irqPrescaler = ( irqPrescaler & ~ mask ) | newp ;
if ( newp = = mask & & ( irqControl & 0x08 ? irqCounter : - - irqCounter ) = = 0xFF )
2021-04-08 17:50:56 +02:00
X6502_IRQBegin ( FCEU_IQEXT ) ;
break ;
core: memory-safety, leak, and savestate-portability audit fixes
Squashed series of ~50 distinct bugs found during a multi-day
security/correctness audit, ranging from ROM-triggerable heap
corruption and savestate-triggered OOB read primitives down to
obscure cross-platform savestate breakage.
Build is clean on `make platform=unix` with zero new warnings.
CRITICAL (ROM-triggerable, exploitable on the user's machine)
=============================================================
* ines.c iNES 2.0 PRG/CHR exponent overflow leading to undersized
allocation followed by heap buffer overflow on fread (pow() with
attacker-chosen exponent up to 63). Cap exponent at 30 and
compute size in uint32 with explicit cap below 2 GiB before
storing in int.
* ines.c miscROMSize int wraparound from attacker-controlled PRG/
CHR sizes; previous '& 0x8000000' check missed common underflow
cases. Compute in int64 and reject <= 0 or > 128 MiB.
* unif.c MAPR chunk OOB heap read on chunks of size < 4. Validate
chunk size before allocating board-name buffer.
* unif.c chunk size truncation: int conversion + missing cap allowed
a 4 GiB chunk size to wrap. Cap at 16 MiB.
* unif.c FixRomSize infinite loop on size > 0x80000000. Cap input.
* unif.c DINF chunk: months[(m - 1) % 12] is UB for m==0; m comes
from the .unf file. Clamp m into [1..12] before subtracting.
* unif.c NAME chunk: GameInfo->name = malloc(...) was unchecked.
* nsf.c size underflow: FCEU_fgetsize() - 0x80 wraps to ~UINT64_MAX
on tiny files, propagating a huge size into uppow2/FCEU_malloc.
Validate size > 0x80 before subtracting.
* nsf.c NSFMaxBank * 4096 cap tightened from 1<<20 (UB on signed-int
overflow) to 1<<19 (fits in int).
* general.c uppow2 had signed-int UB (1 << 32) and wrapped to 0 for
inputs near uint32 max. Cap at 0x80000000.
* cheat.c SubCheats[256] BSS overflow when more than 256 GG/PAR
substitution cheats are active. The array is adjacent to MMapPtrs[64]
in BSS which is exposed via retro_get_memory_data, making this
overflow visible from outside the core.
* libretro.c retro_cheat_set strcpy stack overflow with arbitrary-
length cheat strings from the frontend. Use strlcpy.
CRITICAL (savestate-triggerable on a malicious .fcs file)
=========================================================
* fds.c FDS savestate OOB read primitive: InDisk loaded from
savestate is used as index into 8-element diskdata[] static
pointer array. A value 8..254 dereferences arbitrary memory as
a pointer (heap-read primitive). Also bounds-checked SelectDisk,
mapperFDS_block, mapperFDS_blockstart, mapperFDS_diskaddr,
mapperFDS_blocklen so blockstart+diskaddr stays within the 65500-
byte disk buffer.
* 11 mappers had savestate-loaded variables masked at write time
but not at restore time, used as indices into fixed arrays:
- 88.c, KS7037.c, 112.c cmd indexes reg[8]
- sachen.c (S8259, S74LS374N) cmd indexes latch[8]
- 357.c dipswitch indexes outer_bank[4]
- unrom512.c flash_state indexes erase_a/d/b[5]
- 368.c preg indexes banks[8]
- 69.c sndcmd indexes sreg[14]
- mmc2and4.c latch0/latch1 index creg[4]
None individually exploitable into RCE - the array writes corrupt
adjacent BSS with constrained data flowing in - but each is an
out-of-bounds read or write from attacker-controllable input.
HIGH (memory-safety, reachable on any load)
===========================================
* fceu-memory.c FCEU_malloc deref-of-NULL on allocation failure
('ret = 0; memset(ret, 0, size);').
* file.c multiple FCEUFILE/MakeMemWrap/MakeMemWrapBuffer unchecked
allocations and unchecked filestream_tell return.
* libretro.c GameInfo NULL-derefs in three entry points
(retro_set_controller_port_device, retro_get_memory_data,
retro_get_memory_size) reachable on operations called before a
successful load.
* libretro.c framebuffer leak ~256 KB per failed FCEUI_LoadGame
(the libretro frontend doesn't call retro_unload_game on a
failed load).
* libretro.c 3DS retro_deinit unchecked linearFree.
* libretro.c stereo / NTSC filter unchecked malloc returns.
* fceu.c FCEUI_LoadGame unchecked GameInfo malloc.
* fds.c SubLoad and FDSLoad unchecked FCEU_malloc on diskdatao
backup buffers (NULL-deref in subsequent memcpy).
* fceu.c AllocGenieRW partial-failure leak: AReadG allocated but
BWriteG malloc fails -> 256 KB leak per retry.
* input/bworld.c Update(): unbounded strcpy from attacker-supplied
data into 20-byte bdata. Replaced with length-bounded copy.
* cart.c setprg2r/4r and setchr1r/2r/4r/8r mask-underflow guards.
SetupCartPRGMapping/SetupCartCHRMapping compute (size >> N) - 1
which underflows to 0xFFFFFFFF for chips smaller than the unit.
setprg8r/16r/32r and setchr8r already had defensive size checks;
the smaller units did not. malee.c (2 KB chip) and mapper 218
(2 KB NTARAM-as-CHR) accidentally avoid OOB; the primitive is
unsafe for any future board.
* video.c FCEU_InitVirtualVideo XBuf/XDBuf partial-failure leak.
* video.c, fceu.c FCEU_DispMessage / FCEU_printf / FCEU_PrintError:
vsprintf into fixed stack buffers replaced with vsnprintf.
* core: validate magic-string read length on FDS/UNIF/NSF load
(reject files too short to contain the magic so previous static
buffer / stack garbage doesn't spuriously match).
LEAKS (every cart load/unload cycle)
====================================
* mmc5.c MMC5 cart-side: WRAM (up to 64K) + MMC5fill (1K) + ExRAM
(1K) leaked per cycle. NSFMMC5_Close existed but was only used
for NSF code path.
* onebus.c Mapper 270/436: 8 KB CHRRAM leaked per cycle.
* 330.c, 375.c, 528.c: 8 KB WRAM each, no Close at all.
CORRECTNESS (UB / ABI / endianness)
===================================
* fceu-endian.c FlipByteOrder loop bound was 'count' instead of
'count/2', making it a no-op for every even count and silently
breaking savestate portability for every FCEUSTATE_RLSB-marked
field. The '#ifndef GEKKO' workarounds scattered through the
codebase (sound.c, vrc7.c, vrc6.c) were symptoms of this root
cause.
* state.c AddExState bounds check ran AFTER writing the entry, so
when SFEXINDEX hit the 63-entry cap the next call would write
the entry then immediately overwrite it with the terminator.
* state.c FCEUSS_Save_Mem: post-save callback was guarded by
'if (SPreSave)' instead of 'if (SPostSave)'.
* Sequence-point UB in counter expressions across 4 board files,
e.g. 'x = !x ? a : --x' and 'x = ++x % n'. GCC -Wsequence-point
flags all five sites (285.c, 413.c, asic_mmc3.c, jyasic.c).
* SFORMAT size mismatches between declared variable type and
AddExState size argument:
- asic_vrc3.c VRC3_count/VRC3_reload (uint16, saved as 1 byte)
- mmc3.c m555_count (uint32, saved as 2 bytes), m555_count_-
expired (uint8, saved as 2 bytes - OOB write into adjacent
BSS).
* unrom512.c UNROM-512 mapper 30 .srm save format: host-endian
uint32 flash write counters. Now stored as LE on disk regardless
of host (Battle Kid 2, Twin Dragons, Lizard, Sole, etc.).
* ~70 multi-byte single-variable SFORMAT/AddExState entries across
36 board files were saved as host-byte-order. After the
FlipByteOrder fix, these are now byte-swapped on BE so cross-
platform savestates round-trip correctly.
* coolgirl.c new ExStateLE() macro added; 22 multi-byte sites.
* pic16c5x.c 11 multi-byte AddExState calls (m_PC, m_PREVPC,
m_CONFIG, m_WDT, m_prescaler, m_opcode, m_STACK[0/1], m_icount,
m_delay_timer, m_rtcc, m_inst_cycles, m_clock2cycle).
* onebus.c PowerJoy Supermax submapper detection used non-portable
*(uint32*)&info->MD5 cast that read different bytes on LE vs BE.
* fds.c clean up redundant FCEUSTATE_RLSB encoding in AddExState
calls that also passed type=1 (idempotent OR; readability fix).
DOCUMENTATION
=============
* input.c UpdateGP's *(uint32*)data cast looks like a typical
endian bug but is actually correct (the libretro frontend builds
JSReturn with matching host-uint32 shifts). Comment added to
prevent future "fixes" from breaking it.
Limitations not addressed
=========================
* Element-stride-aware byte swapping. The savestate byte-swap
mechanism (FlipByteOrder over the entire SFORMAT entry buffer)
is structurally wrong for arrays of multi-byte values: it
reverses the whole buffer end-to-end instead of byte-swapping
each element. Several places that need cross-platform-portable
arrays (VRC7 sound state, jyasic chr[8]) work around this by
either splitting arrays into per-element SFORMAT entries (n106
PlayIndex, bandai reg) or by skipping save entirely on BE via
#ifndef GEKKO. A proper fix would extend the size encoding with
an element-stride field. Left for a future change because it
would change the savestate format.
* Strict-aliasing UB in ppu.c (around 9 sites doing
*(uint32*)uint8_buf for fast 4-byte writes via FCEU_dwmemset).
Works in practice with all common compilers because the patterns
are byte-symmetric, but is formally UB.
* FCEU_gmalloc calls exit(1) on OOM. A libretro core should never
exit() because that takes down the whole frontend. Used by
100+ call sites; refactoring to return-NULL is out of scope here.
Testing
=======
* Build: clean on `make platform=unix` with -O2; no new warnings.
* FlipByteOrder fix verified by hand-trace and a standalone unit
test for counts 2, 4, 8.
* uppow2 fix verified by unit test across 13 boundary cases.
* SFORMAT size mismatches and missing-RLSB cases identified by
Python static-analysis scripts that cross-reference SFORMAT
entries against variable declarations.
* iNES 2.0 exponent fix verified by hand-tracing what byte 0xFF
produces post-fix: exp=30 (capped), mult=7, size=3 GiB nominal,
capped to 1 GiB, capped to 2 GiB by uppow2, FCEU_malloc returns
NULL on most systems, loader returns 0. No heap overflow for
any input byte.
* Savestate-loaded array index audit: built a Python scanner that
extracts each AddExState/SFORMAT entry and cross-references the
variable name against array-index uses in the same file. All
flagged sites covered.
* A libFuzzer harness and seed corpus generator (fuzz_main.c,
gen_seed_corpus.py) accompany this submission for ongoing
regression testing.
2026-05-04 02:15:40 +02:00
}
2021-04-08 17:50:56 +02:00
}
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
static DECLFW ( trapCPUWrite )
{
if ( ( irqControl & 0x03 ) = = 0x03 )
clockIRQ ( ) ; /* Clock IRQ counter on CPU writes */
2021-04-08 17:06:17 +02:00
cpuWriteHandlers [ A ] ( A , V ) ;
}
2021-04-08 17:46:51 +02:00
static void FP_FASTAPASS ( 1 ) trapPPUAddressChange ( uint32 A )
{
if ( ( irqControl & 0x03 ) = = 0x02 & & lastPPUAddress ! = A )
{
int i ;
for ( i = 0 ; i < 2 ; i + + )
clockIRQ ( ) ; /* Clock IRQ counter on PPU "reads" */
}
if ( mode [ 3 ] & 0x80 & & ( mode [ 0 ] & 0x18 ) = = 0x08 & & ( ( A & 0x2FF0 ) = = 0xFD0 | | ( A & 0x2FF0 ) = = 0xFE0 ) )
{
/* If MMC4 mode[0] is enabled, and CHR mode[0] is 4 KiB, and tile FD or FE is being fetched ... */
latch [ A > > 12 & 1 ] = ( A > > 10 & 4 ) | ( A > > 4 & 2 ) ; /* ... switch the left or right pattern table's latch to 0 (FD) or 2 (FE), being used as an offset for the CHR register index. */
sync ( ) ;
}
lastPPUAddress = A ;
}
static void ppuScanline ( void )
{
if ( ( irqControl & 0x03 ) = = 0x01 )
{
int i ;
for ( i = 0 ; i < 8 ; i + + )
clockIRQ ( ) ; /* Clock IRQ counter on A12 rises (eight per scanline). This should be done in trapPPUAddressChange, but would require more accurate PPU emulation for that. */
}
}
2022-03-02 19:53:30 +01:00
static void FP_FASTAPASS ( 1 ) cpuCycle ( int a )
2021-04-08 17:46:51 +02:00
{
if ( ( irqControl & 0x03 ) = = 0x00 )
while ( a - - )
clockIRQ ( ) ; /* Clock IRQ counter on M2 cycles */
}
static DECLFR ( readALU_DIP )
{
if ( ( A & 0x3FF ) = = 0 & & A ! = 0x5800 ) /* 5000, 5400, 5C00: read solder pad setting */
return dipSwitch | X . DB & 0x3F ;
if ( A & 0x800 )
switch ( A & 3 )
{
/* 5800-5FFF: read ALU */
case 0 :
return ( mul [ 0 ] * mul [ 1 ] ) & 0xFF ;
case 1 :
return ( mul [ 0 ] * mul [ 1 ] ) > > 8 ;
case 2 :
return adder ;
case 3 :
return test ;
}
/* all others */
return X . DB ;
}
static DECLFW ( writeALU )
{
switch ( A & 3 )
{
case 0 :
mul [ 0 ] = V ;
break ;
case 1 :
mul [ 1 ] = V ;
break ;
case 2 :
adder + = V ;
break ;
case 3 :
test = V ;
adder = 0 ;
break ;
}
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:50:56 +02:00
static DECLFW ( writePRG )
{
2021-04-08 17:06:17 +02:00
prg [ A & 3 ] = V ;
sync ( ) ;
}
2021-04-08 17:50:56 +02:00
static DECLFW ( writeCHRLow )
{
2021-04-08 17:06:17 +02:00
chr [ A & 7 ] = chr [ A & 7 ] & 0xFF00 | V ;
sync ( ) ;
}
2021-04-08 17:50:56 +02:00
static DECLFW ( writeCHRHigh )
{
2021-04-08 17:06:17 +02:00
chr [ A & 7 ] = chr [ A & 7 ] & 0x00FF | V < < 8 ;
sync ( ) ;
}
2021-04-08 17:50:56 +02:00
static DECLFW ( writeNT )
{
2021-04-08 17:06:17 +02:00
if ( ~ A & 4 )
nt [ A & 3 ] = nt [ A & 3 ] & 0xFF00 | V ;
else
nt [ A & 3 ] = nt [ A & 3 ] & 0x00FF | V < < 8 ;
sync ( ) ;
}
2021-04-08 17:46:51 +02:00
static DECLFW ( writeIRQ )
{
switch ( A & 7 )
{
case 0 :
irqEnabled = ! ! ( V & 1 ) ;
if ( ! irqEnabled )
{
irqPrescaler = 0 ;
X6502_IRQEnd ( FCEU_IQEXT ) ;
}
break ;
case 1 :
irqControl = V ;
break ;
case 2 :
irqEnabled = 0 ;
irqPrescaler = 0 ;
X6502_IRQEnd ( FCEU_IQEXT ) ;
break ;
case 3 :
irqEnabled = 1 ;
break ;
case 4 :
irqPrescaler = V ^ irqXor ;
break ;
case 5 :
irqCounter = V ^ irqXor ;
break ;
case 6 :
irqXor = V ;
break ;
}
}
static DECLFW ( writeMode )
{
switch ( A & 3 )
{
case 0 :
mode [ 0 ] = V ;
if ( ! allowExtendedMirroring )
mode [ 0 ] & = ~ 0x20 ;
break ;
case 1 :
mode [ 1 ] = V ;
if ( ! allowExtendedMirroring )
mode [ 1 ] & = ~ 0x08 ;
break ;
case 2 :
mode [ 2 ] = V ;
break ;
case 3 :
mode [ 3 ] = V ;
break ;
}
2021-04-08 17:06:17 +02:00
sync ( ) ;
}
2022-03-02 13:35:56 +01:00
static void JYASIC_restoreWriteHandlers ( void )
{
int i ;
if ( cpuWriteHandlersSet )
{
for ( i = 0 ; i < 0x10000 ; i + + ) SetWriteHandler ( i , i , cpuWriteHandlers [ i ] ) ;
cpuWriteHandlersSet = 0 ;
}
}
2021-04-08 17:46:51 +02:00
static void JYASIC_power ( void )
{
unsigned int i ;
2021-04-08 17:06:17 +02:00
2021-04-08 17:46:51 +02:00
SetWriteHandler ( 0x5000 , 0x5FFF , writeALU ) ;
SetWriteHandler ( 0x6000 , 0x7fff , CartBW ) ;
SetWriteHandler ( 0x8000 , 0x87FF , writePRG ) ; /* 8800-8FFF ignored */
SetWriteHandler ( 0x9000 , 0x97FF , writeCHRLow ) ; /* 9800-9FFF ignored */
SetWriteHandler ( 0xA000 , 0xA7FF , writeCHRHigh ) ; /* A800-AFFF ignored */
SetWriteHandler ( 0xB000 , 0xB7FF , writeNT ) ; /* B800-BFFF ignored */
SetWriteHandler ( 0xC000 , 0xCFFF , writeIRQ ) ;
SetWriteHandler ( 0xD000 , 0xD7FF , writeMode ) ; /* D800-DFFF ignored */
2021-04-08 17:06:17 +02:00
2022-03-02 13:35:56 +01:00
JYASIC_restoreWriteHandlers ( ) ;
2021-04-08 17:46:51 +02:00
for ( i = 0 ; i < 0x10000 ; i + + ) cpuWriteHandlers [ i ] = GetWriteHandler ( i ) ;
SetWriteHandler ( 0x0000 , 0xFFFF , trapCPUWrite ) ; /* Trap all CPU writes for IRQ clocking purposes */
2022-03-02 13:35:56 +01:00
cpuWriteHandlersSet = 1 ;
2021-04-08 17:06:17 +02:00
2021-04-08 17:46:51 +02:00
SetReadHandler ( 0x5000 , 0x5FFF , readALU_DIP ) ;
SetReadHandler ( 0x6000 , 0xFFFF , CartBR ) ;
2021-04-08 17:06:17 +02:00
2021-04-08 17:46:51 +02:00
mul [ 0 ] = mul [ 1 ] = adder = test = dipSwitch = 0 ;
mode [ 0 ] = mode [ 1 ] = mode [ 2 ] = mode [ 3 ] = 0 ;
irqControl = irqEnabled = irqPrescaler = irqCounter = irqXor = lastPPUAddress = 0 ;
memset ( prg , 0 , sizeof ( prg ) ) ;
memset ( chr , 0 , sizeof ( chr ) ) ;
memset ( nt , 0 , sizeof ( nt ) ) ;
latch [ 0 ] = 0 ;
latch [ 1 ] = 4 ;
2021-04-08 17:06:17 +02:00
2021-04-08 17:46:51 +02:00
sync ( ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
static void JYASIC_reset ( void )
{
dipSwitch = ( dipSwitch + 0x40 ) & 0xC0 ;
}
2022-01-24 02:20:46 +08:00
static void JYASIC_close ( void )
{
if ( WRAM )
FCEU_gfree ( WRAM ) ;
WRAM = NULL ;
}
2021-04-08 17:46:51 +02:00
static void JYASIC_restore ( int version )
{
sync ( ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void JYASIC_init ( CartInfo * info )
{
2022-03-02 13:35:56 +01:00
cpuWriteHandlersSet = 0 ;
2021-04-08 17:46:51 +02:00
info - > Reset = JYASIC_reset ;
info - > Power = JYASIC_power ;
2022-01-24 02:20:46 +08:00
info - > Close = JYASIC_close ;
2021-04-08 17:46:51 +02:00
PPU_hook = trapPPUAddressChange ;
MapIRQHook = cpuCycle ;
GameHBIRQHook2 = ppuScanline ;
AddExState ( JYASIC_stateRegs , ~ 0 , 0 , 0 ) ;
GameStateRestore = JYASIC_restore ;
/* WRAM is present only in iNES mapper 35, or in mappers with numbers above 255 that require NES 2.0, which explicitly denotes WRAM size */
if ( info - > iNES2 )
WRAMSIZE = info - > PRGRamSize + info - > PRGRamSaveSize ;
else
WRAMSIZE = info - > mapper = = 35 ? 8192 : 0 ;
if ( WRAMSIZE )
{
WRAM = ( uint8 * ) FCEU_gmalloc ( WRAMSIZE ) ;
SetupCartPRGMapping ( 0x10 , WRAM , WRAMSIZE , 1 ) ;
FCEU_CheatAddRAM ( WRAMSIZE > > 10 , 0x6000 , WRAM ) ;
}
}
static void syncSingleCart ( void )
{
syncPRG ( 0x3F , mode [ 3 ] < < 5 & ~ 0x3F ) ;
if ( mode [ 3 ] & 0x20 )
{
syncCHR ( 0x1FF , mode [ 3 ] < < 6 & 0x600 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 6 & 0x600 ) ;
}
else
{
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 6 & 0x600 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 6 & 0x600 ) ;
}
}
void Mapper35_Init ( CartInfo * info )
{
/* Basically mapper 90/209/211 with WRAM */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = syncSingleCart ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void Mapper90_Init ( CartInfo * info )
{
/* Single cart, extended mirroring and ROM nametables disabled */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 0 ;
sync = syncSingleCart ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void Mapper209_Init ( CartInfo * info )
{
/* Single cart, extended mirroring and ROM nametables enabled */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = syncSingleCart ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void Mapper211_Init ( CartInfo * info )
{
/* Duplicate of mapper 209 */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = syncSingleCart ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
static void sync281 ( void )
{
syncPRG ( 0x1F , mode [ 3 ] < < 5 ) ;
syncCHR ( 0xFF , mode [ 3 ] < < 8 ) ;
syncNT ( 0xFF , mode [ 3 ] < < 8 ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void Mapper281_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync281 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
static void sync282 ( void )
{
2021-04-08 17:06:17 +02:00
syncPRG ( 0x1F , mode [ 3 ] < < 4 & ~ 0x1F ) ;
2021-04-08 17:46:51 +02:00
if ( mode [ 3 ] & 0x20 )
{
2021-04-08 17:06:17 +02:00
syncCHR ( 0x1FF , mode [ 3 ] < < 6 & 0x600 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 6 & 0x600 ) ;
2021-04-08 17:46:51 +02:00
}
else
{
2021-04-08 17:06:17 +02:00
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 6 & 0x600 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 6 & 0x600 ) ;
}
}
2021-04-08 17:46:51 +02:00
void Mapper282_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync282 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void sync295 ( void )
{
syncPRG ( 0x0F , mode [ 3 ] < < 4 ) ;
syncCHR ( 0x7F , mode [ 3 ] < < 7 ) ;
syncNT ( 0x7F , mode [ 3 ] < < 7 ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void Mapper295_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync295 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void sync358 ( void )
{
syncPRG ( 0x1F , mode [ 3 ] < < 4 & ~ 0x1F ) ;
if ( mode [ 3 ] & 0x20 )
{
syncCHR ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
}
else
{
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
}
}
void Mapper358_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync358 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void sync386 ( void )
{
syncPRG ( 0x1F , mode [ 3 ] < < 4 & 0x20 | mode [ 3 ] < < 3 & 0x40 ) ;
if ( mode [ 3 ] & 0x20 )
{
syncCHR ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
}
else
{
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
}
}
void Mapper386_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync386 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void sync387 ( void )
{
2021-04-08 17:06:17 +02:00
syncPRG ( 0x0F , mode [ 3 ] < < 3 & 0x10 | mode [ 3 ] < < 2 & 0x20 ) ;
2021-04-08 17:46:51 +02:00
if ( mode [ 3 ] & 0x20 )
{
syncCHR ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 7 & 0x600 ) ;
}
else
{
2021-04-08 17:06:17 +02:00
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 7 & 0x600 ) ;
}
}
2021-04-08 17:46:51 +02:00
void Mapper387_Init ( CartInfo * info )
{
/* Multicart */
allowExtendedMirroring = 1 ;
sync = sync387 ;
JYASIC_init ( info ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void sync388 ( void )
{
syncPRG ( 0x1F , mode [ 3 ] < < 3 & 0x60 ) ;
if ( mode [ 3 ] & 0x20 )
{
syncCHR ( 0x1FF , mode [ 3 ] < < 8 & 0x200 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 8 & 0x200 ) ;
}
else
{
syncCHR ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 8 & 0x200 ) ;
syncNT ( 0x0FF , mode [ 3 ] < < 8 & 0x100 | mode [ 3 ] < < 8 & 0x200 ) ;
}
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void Mapper388_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 0 ;
sync = sync388 ;
JYASIC_init ( info ) ;
}
2021-04-08 17:46:51 +02:00
void sync397 ( void )
{
2021-04-08 17:06:17 +02:00
syncPRG ( 0x1F , mode [ 3 ] < < 4 & ~ 0x1F ) ;
syncCHR ( 0x7F , mode [ 3 ] < < 7 ) ;
syncNT ( 0x7F , mode [ 3 ] < < 7 ) ;
}
2021-04-08 17:46:51 +02:00
void Mapper397_Init ( CartInfo * info )
{
/* Multicart */
allowExtendedMirroring = 1 ;
sync = sync397 ;
JYASIC_init ( info ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void sync421 ( void )
{
if ( mode [ 3 ] & 0x04 )
syncPRG ( 0x3F , mode [ 3 ] < < 4 & ~ 0x3F ) ;
else
syncPRG ( 0x1F , mode [ 3 ] < < 4 & ~ 0x1F ) ;
syncCHR ( 0x1FF , mode [ 3 ] < < 8 & 0x300 ) ;
syncNT ( 0x1FF , mode [ 3 ] < < 8 & 0x300 ) ;
2021-04-08 17:06:17 +02:00
}
2021-04-08 17:46:51 +02:00
void Mapper421_Init ( CartInfo * info )
{
/* Multicart */
2021-04-08 17:06:17 +02:00
allowExtendedMirroring = 1 ;
sync = sync421 ;
JYASIC_init ( info ) ;
}
2022-03-02 13:35:56 +01:00
/* Mapper 394: HSK007 circuit board that can simulate J.Y. ASIC, MMC3, and NROM. */
static uint8 HSK007Reg [ 4 ] ;
void sync394 ( void ) /* Called when J.Y. ASIC is active */
{
2025-04-01 18:56:49 +02:00
int prgOR = HSK007Reg [ 3 ] < < 1 & 0x010 | HSK007Reg [ 1 ] < < 5 & 0x060 ;
int chrOR = HSK007Reg [ 3 ] < < 1 & 0x080 | HSK007Reg [ 1 ] < < 6 & 0x100 | HSK007Reg [ 1 ] < < 8 & 0x200 ;
2022-03-02 13:35:56 +01:00
syncPRG ( 0x1F , prgOR ) ;
syncCHR ( 0xFF , chrOR ) ;
syncNT ( 0xFF , chrOR ) ;
}
static void Mapper394_PWrap ( uint32 A , uint8 V )
{
int prgAND = HSK007Reg [ 3 ] & 0x10 ? 0x1F : 0x0F ;
2025-04-01 18:56:49 +02:00
int prgOR = HSK007Reg [ 3 ] < < 1 & 0x010 | HSK007Reg [ 1 ] < < 5 & 0x060 ;
2022-03-02 13:35:56 +01:00
if ( HSK007Reg [ 1 ] & 0x08 )
setprg8 ( A , V & prgAND | prgOR & ~ prgAND ) ;
else
if ( A = = 0x8000 )
setprg32 ( A , ( prgOR | HSK007Reg [ 3 ] < < 1 & 0x0F ) > > 2 ) ;
}
static void Mapper394_CWrap ( uint32 A , uint8 V )
{
int chrAND = HSK007Reg [ 3 ] & 0x80 ? 0xFF : 0x7F ;
2025-09-09 00:13:05 +02:00
int chrOR = submapper = = 1 ? ( HSK007Reg [ 3 ] < < 1 & 0x080 | HSK007Reg [ 1 ] < < 8 & 0x200 | HSK007Reg [ 1 ] < < 6 & 0x100 ) : ( HSK007Reg [ 3 ] < < 1 & 0x080 | HSK007Reg [ 1 ] < < 8 & 0x300 ) ;
2022-03-02 13:35:56 +01:00
setchr1 ( A , V & chrAND | chrOR & ~ chrAND ) ;
}
static DECLFW ( Mapper394_Write )
{
uint8 oldMode = HSK007Reg [ 1 ] ;
A & = 3 ;
HSK007Reg [ A ] = V ;
if ( A = = 1 )
{
if ( ~ oldMode & 0x10 & & V & 0x10 ) JYASIC_power ( ) ;
if ( oldMode & 0x10 & & ~ V & 0x10 )
{
JYASIC_restoreWriteHandlers ( ) ;
GenMMC3Power ( ) ;
}
}
else
{
if ( HSK007Reg [ 1 ] & 0x10 )
sync ( ) ;
else
{
FixMMC3PRG ( MMC3_cmd ) ;
FixMMC3CHR ( MMC3_cmd ) ;
}
}
}
static void Mapper394_restore ( int version )
{
int i ;
JYASIC_restoreWriteHandlers ( ) ;
if ( HSK007Reg [ 1 ] & 0x10 )
{
SetWriteHandler ( 0x5000 , 0x5FFF , writeALU ) ;
SetWriteHandler ( 0x6000 , 0x7fff , CartBW ) ;
SetWriteHandler ( 0x8000 , 0x87FF , writePRG ) ; /* 8800-8FFF ignored */
SetWriteHandler ( 0x9000 , 0x97FF , writeCHRLow ) ; /* 9800-9FFF ignored */
SetWriteHandler ( 0xA000 , 0xA7FF , writeCHRHigh ) ; /* A800-AFFF ignored */
SetWriteHandler ( 0xB000 , 0xB7FF , writeNT ) ; /* B800-BFFF ignored */
SetWriteHandler ( 0xC000 , 0xCFFF , writeIRQ ) ;
SetWriteHandler ( 0xD000 , 0xD7FF , writeMode ) ; /* D800-DFFF ignored */
for ( i = 0 ; i < 0x10000 ; i + + ) cpuWriteHandlers [ i ] = GetWriteHandler ( i ) ;
SetWriteHandler ( 0x0000 , 0xFFFF , trapCPUWrite ) ; /* Trap all CPU writes for IRQ clocking purposes */
cpuWriteHandlersSet = 1 ;
SetReadHandler ( 0x5000 , 0x5FFF , readALU_DIP ) ;
SetReadHandler ( 0x6000 , 0xFFFF , CartBR ) ;
sync ( ) ;
}
else
{
SetWriteHandler ( 0x8000 , 0xBFFF , MMC3_CMDWrite ) ;
SetWriteHandler ( 0xC000 , 0xFFFF , MMC3_IRQWrite ) ;
SetReadHandler ( 0x8000 , 0xFFFF , CartBR ) ;
FixMMC3PRG ( MMC3_cmd ) ;
FixMMC3CHR ( MMC3_cmd ) ;
}
}
static void Mapper394_power ( void )
{
HSK007Reg [ 0 ] = 0x00 ;
HSK007Reg [ 1 ] = 0x0F ;
HSK007Reg [ 2 ] = 0x00 ;
2025-04-01 18:56:49 +02:00
HSK007Reg [ 3 ] = 0x90 ;
irqEnabled = 0 ;
2022-03-02 13:35:56 +01:00
GenMMC3Power ( ) ;
SetWriteHandler ( 0x5000 , 0x5FFF , Mapper394_Write ) ;
}
void Mapper394_Init ( CartInfo * info )
{
2025-04-01 18:56:49 +02:00
submapper = info - > submapper ;
2022-03-02 13:35:56 +01:00
allowExtendedMirroring = 1 ;
sync = sync394 ;
JYASIC_init ( info ) ;
GenMMC3_Init ( info , 128 , 128 , 0 , 0 ) ;
pwrap = Mapper394_PWrap ;
cwrap = Mapper394_CWrap ;
info - > Reset = Mapper394_power ;
info - > Power = Mapper394_power ;
AddExState ( HSK007Reg , 4 , 0 , " HSK " ) ;
GameStateRestore = Mapper394_restore ;
}