2017-12-17 13:39:16 +08:00
|
|
|
|
/* FCE Ultra - NES/Famicom Emulator
|
|
|
|
|
|
*
|
|
|
|
|
|
* Copyright notice for this file:
|
|
|
|
|
|
* Copyright (C) 2007-2010 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
|
|
|
|
|
|
*
|
|
|
|
|
|
* VR02/VT03 Console and OneBus System
|
|
|
|
|
|
*
|
|
|
|
|
|
* Street Dance (Dance pad) (Unl)
|
|
|
|
|
|
* 101-in-1 Arcade Action II
|
|
|
|
|
|
* DreamGEAR 75-in-1, etc.
|
|
|
|
|
|
*
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
#include "mapinc.h"
|
|
|
|
|
|
|
2022-03-01 18:18:49 +01:00
|
|
|
|
static uint8 submapper;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static void (*Sync)(void);
|
|
|
|
|
|
static uint8 *CHRRAM;
|
|
|
|
|
|
static uint32 CHRRAMSIZE;
|
2022-03-01 18:18:49 +01:00
|
|
|
|
|
2017-12-17 13:39:16 +08:00
|
|
|
|
/* General Purpose Registers */
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static uint8 cpu410x[64], ppu201x[16], apu40xx[64], reg4242, dipswitch;
|
|
|
|
|
|
static const uint8 *cpuMangle, *ppuMangle, *mmc3Mangle;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
|
|
|
|
|
/* IRQ Registers */
|
|
|
|
|
|
static uint8 IRQCount, IRQa, IRQReload;
|
|
|
|
|
|
#define IRQLatch cpu410x[0x1] /* accc cccc, a = 0, AD12 switching, a = 1, HSYNC switching */
|
|
|
|
|
|
|
|
|
|
|
|
/* MMC3 Registers */
|
|
|
|
|
|
#define mmc3cmd cpu410x[0x5] /* pcv- ----, p - program swap, c - video swap, v - internal VRAM enable */
|
|
|
|
|
|
#define mirror cpu410x[0x6] /* ---- ---m, m = 0 - H, m = 1 - V */
|
|
|
|
|
|
|
|
|
|
|
|
/* APU Registers */
|
|
|
|
|
|
static uint8 pcm_enable = 0, pcm_irq = 0;
|
|
|
|
|
|
static int16 pcm_addr, pcm_size, pcm_latch, pcm_clock = 0xE1;
|
|
|
|
|
|
|
|
|
|
|
|
static writefunc defapuwrite[64];
|
|
|
|
|
|
static readfunc defapuread[64];
|
|
|
|
|
|
|
|
|
|
|
|
static SFORMAT StateRegs[] =
|
|
|
|
|
|
{
|
2025-04-01 22:54:58 +02:00
|
|
|
|
{ cpu410x, 64, "REGC" },
|
2017-12-17 13:39:16 +08:00
|
|
|
|
{ ppu201x, 16, "REGS" },
|
|
|
|
|
|
{ apu40xx, 64, "REGA" },
|
|
|
|
|
|
{ &IRQReload, 1, "IRQR" },
|
|
|
|
|
|
{ &IRQCount, 1, "IRQC" },
|
|
|
|
|
|
{ &IRQa, 1, "IRQA" },
|
|
|
|
|
|
{ &pcm_enable, 1, "PCME" },
|
|
|
|
|
|
{ &pcm_irq, 1, "PCMI" },
|
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
|
|
|
|
{ &pcm_addr, 2 | FCEUSTATE_RLSB, "PCMA" },
|
|
|
|
|
|
{ &pcm_size, 2 | FCEUSTATE_RLSB, "PCMS" },
|
|
|
|
|
|
{ &pcm_latch, 2 | FCEUSTATE_RLSB, "PCML" },
|
|
|
|
|
|
{ &pcm_clock, 2 | FCEUSTATE_RLSB, "PCMC" },
|
2025-04-01 22:54:58 +02:00
|
|
|
|
{ ®4242, 1, "4242" },
|
|
|
|
|
|
{ &dipswitch, 1, "DIPS" },
|
2017-12-17 13:39:16 +08:00
|
|
|
|
{ 0 }
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2022-03-01 18:04:34 +01:00
|
|
|
|
static uint8 *WRAM;
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static void PSync(int AND, int OR) {
|
2017-12-17 13:39:16 +08:00
|
|
|
|
uint8 bankmode = cpu410x[0xb] & 7;
|
|
|
|
|
|
uint8 mask = (bankmode == 0x7) ? (0xff) : (0x3f >> bankmode);
|
|
|
|
|
|
uint32 block = ((cpu410x[0x0] & 0xf0) << 4) + (cpu410x[0xa] & (~mask));
|
|
|
|
|
|
uint32 pswap = (mmc3cmd & 0x40) << 8;
|
|
|
|
|
|
|
2022-03-01 18:18:49 +01:00
|
|
|
|
uint8 bank0 = cpu410x[0x7];
|
|
|
|
|
|
uint8 bank1 = cpu410x[0x8];
|
2017-12-17 13:39:16 +08:00
|
|
|
|
uint8 bank2 = (cpu410x[0xb] & 0x40) ? (cpu410x[0x9]) : (~1);
|
|
|
|
|
|
uint8 bank3 = ~0;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
|
|
|
|
|
|
setprg8(0x8000 ^ pswap,(block | (bank0 & mask)) &AND | OR);
|
|
|
|
|
|
setprg8(0xa000, (block | (bank1 & mask)) &AND | OR);
|
|
|
|
|
|
setprg8(0xc000 ^ pswap,(block | (bank2 & mask)) &AND | OR);
|
|
|
|
|
|
setprg8(0xe000, (block | (bank3 & mask)) &AND | OR);
|
2017-12-17 13:39:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static void CSync(int AND, int OR) {
|
2017-12-17 13:39:16 +08:00
|
|
|
|
static const uint8 midx[8] = { 0, 1, 2, 0, 3, 4, 5, 0 };
|
|
|
|
|
|
uint8 mask = 0xff >> midx[ppu201x[0xa] & 7];
|
|
|
|
|
|
uint32 block = ((cpu410x[0x0] & 0x0f) << 11) + ((ppu201x[0x8] & 0x70) << 4) + (ppu201x[0xa] & (~mask));
|
|
|
|
|
|
uint32 cswap = (mmc3cmd & 0x80) << 5;
|
|
|
|
|
|
|
|
|
|
|
|
uint8 bank0 = ppu201x[0x6] & (~1);
|
|
|
|
|
|
uint8 bank1 = ppu201x[0x6] | 1;
|
|
|
|
|
|
uint8 bank2 = ppu201x[0x7] & (~1);
|
|
|
|
|
|
uint8 bank3 = ppu201x[0x7] | 1;
|
|
|
|
|
|
uint8 bank4 = ppu201x[0x2];
|
|
|
|
|
|
uint8 bank5 = ppu201x[0x3];
|
|
|
|
|
|
uint8 bank6 = ppu201x[0x4];
|
|
|
|
|
|
uint8 bank7 = ppu201x[0x5];
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
setchr1(0x0000 ^ cswap,(block | (bank0 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x0400 ^ cswap,(block | (bank1 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x0800 ^ cswap,(block | (bank2 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x0c00 ^ cswap,(block | (bank3 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x1000 ^ cswap,(block | (bank4 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x1400 ^ cswap,(block | (bank5 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x1800 ^ cswap,(block | (bank6 & mask)) &AND | OR);
|
|
|
|
|
|
setchr1(0x1c00 ^ cswap,(block | (bank7 & mask)) &AND | OR);
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
|
|
|
|
|
setmirror((mirror ^ 1) & 1);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static void Sync256(void) {
|
|
|
|
|
|
PSync(0x0FFF, 0x000);
|
|
|
|
|
|
CSync(0x7FFF, 0x000);
|
2025-04-25 01:01:56 +02:00
|
|
|
|
encryptOpcodes =0;
|
|
|
|
|
|
if (submapper ==12 && cpu410x[0x1C] &0x40) encryptOpcodes =12;
|
|
|
|
|
|
if (submapper ==14 && cpu410x[0x1C] &0x40) encryptOpcodes =14;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static const uint8 cpuMangles[16][4] = {
|
2022-03-01 18:36:34 +01:00
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 0: Normal */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 1: Waixing VT03 */
|
|
|
|
|
|
{ 1, 0, 2, 3 }, /* Submapper 2: Trump Grand */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 3: Zechess */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 4: Qishenglong */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 5: Waixing VT02 */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 6: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 7: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 8: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper 9: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper A: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper B: unused so far */
|
2025-04-25 01:01:56 +02:00
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper C: Cheertone (CPU opcode encryption only) */
|
2022-03-01 18:36:34 +01:00
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper D: Cube Tech (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3 }, /* Submapper E: Karaoto (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3 } /* Submapper F: Jungletac (CPU opcode encryption only) */
|
2022-03-01 18:18:49 +01:00
|
|
|
|
};
|
2017-12-17 13:39:16 +08:00
|
|
|
|
static DECLFW(UNLOneBusWriteCPU410X) {
|
|
|
|
|
|
/* FCEU_printf("CPU %04x:%04x\n",A,V); */
|
2025-04-01 22:54:58 +02:00
|
|
|
|
A &=0x3F;
|
2022-03-01 18:18:49 +01:00
|
|
|
|
switch (A) {
|
2017-12-17 13:39:16 +08:00
|
|
|
|
case 0x1: IRQLatch = V & 0xfe; break; /* <20><> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|
|
|
|
|
case 0x2: IRQReload = 1; break;
|
|
|
|
|
|
case 0x3: X6502_IRQEnd(FCEU_IQEXT); IRQa = 0; break;
|
|
|
|
|
|
case 0x4: IRQa = 1; break;
|
|
|
|
|
|
default:
|
2025-04-01 22:54:58 +02:00
|
|
|
|
if (A >=0x7 && A <=0xA) A =0x7 +cpuMangle[A -0x7];
|
2022-03-01 18:18:49 +01:00
|
|
|
|
cpu410x[A] = V;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static DECLFW(UNLOneBusWriteCPU4242) {
|
|
|
|
|
|
reg4242 =V;
|
|
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static const uint8 ppuMangles[16][6] = {
|
2022-03-01 18:36:34 +01:00
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 0: Normal */
|
|
|
|
|
|
{ 1, 0, 5, 4, 3, 2 }, /* Submapper 1: Waixing VT03 */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 2: Trump Grand */
|
|
|
|
|
|
{ 5, 4, 3, 2, 0, 1 }, /* Submapper 3: Zechess */
|
|
|
|
|
|
{ 2, 5, 0, 4, 3, 1 }, /* Submapper 4: Qishenglong */
|
|
|
|
|
|
{ 1, 0, 5, 4, 3, 2 }, /* Submapper 5: Waixing VT02 */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 6: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 7: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 8: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper 9: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper A: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper B: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper C: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper D: Cube Tech (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 }, /* Submapper E: Karaoto (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5 } /* Submapper F: Jungletac (CPU opcode encryption only) */
|
2022-03-01 18:18:49 +01:00
|
|
|
|
};
|
2017-12-17 13:39:16 +08:00
|
|
|
|
static DECLFW(UNLOneBusWritePPU201X) {
|
|
|
|
|
|
/* FCEU_printf("PPU %04x:%04x\n",A,V); */
|
2022-03-01 18:18:49 +01:00
|
|
|
|
A &=0x0F;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
if (A >=2 && A <=7) A =2 +ppuMangle[A -2];
|
2022-03-01 18:18:49 +01:00
|
|
|
|
ppu201x[A] = V;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static const uint8 mmc3Mangles[16][8] = {
|
2022-03-01 18:36:34 +01:00
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 0: Normal */
|
|
|
|
|
|
{ 5, 4, 3, 2, 1, 0, 6, 7 }, /* Submapper 1: Waixing VT03 */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 7, 6 }, /* Submapper 2: Trump Grand */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 3: Zechess */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 4: Qishenglong */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 5: Waixing VT02 */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 6: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 7: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 8: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper 9: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper A: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper B: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper C: unused so far */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper D: Cube Tech (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 }, /* Submapper E: Karaoto (CPU opcode encryption only) */
|
|
|
|
|
|
{ 0, 1, 2, 3, 4, 5, 6, 7 } /* Submapper F: Jungletac (CPU opcode encryption only) */
|
2022-03-01 18:18:49 +01:00
|
|
|
|
};
|
2017-12-17 13:39:16 +08:00
|
|
|
|
static DECLFW(UNLOneBusWriteMMC3) {
|
|
|
|
|
|
/* FCEU_printf("MMC %04x:%04x\n",A,V); */
|
2025-04-01 22:54:58 +02:00
|
|
|
|
if (~cpu410x[0x0B] &0x08) /* FWEN bit must be 0 */
|
2017-12-17 13:39:16 +08:00
|
|
|
|
switch (A & 0xe001) {
|
2022-03-01 18:18:49 +01:00
|
|
|
|
case 0x8000:
|
2025-04-01 22:54:58 +02:00
|
|
|
|
V =V &0xF8 | mmc3Mangle[V &0x07];
|
2022-03-01 18:18:49 +01:00
|
|
|
|
mmc3cmd = (mmc3cmd & 0x38) | (V & 0xc7);
|
|
|
|
|
|
Sync();
|
|
|
|
|
|
break;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
case 0x8001:
|
|
|
|
|
|
{
|
|
|
|
|
|
switch (mmc3cmd & 7) {
|
2025-04-01 22:54:58 +02:00
|
|
|
|
case 0: ppu201x[0x6] = V; Sync(); break;
|
|
|
|
|
|
case 1: ppu201x[0x7] = V; Sync(); break;
|
|
|
|
|
|
case 2: ppu201x[0x2] = V; Sync(); break;
|
|
|
|
|
|
case 3: ppu201x[0x3] = V; Sync(); break;
|
|
|
|
|
|
case 4: ppu201x[0x4] = V; Sync(); break;
|
|
|
|
|
|
case 5: ppu201x[0x5] = V; Sync(); break;
|
|
|
|
|
|
case 6: cpu410x[0x7] = V; Sync(); break;
|
|
|
|
|
|
case 7: cpu410x[0x8] = V; Sync(); break;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
2025-04-01 22:54:58 +02:00
|
|
|
|
case 0xa000: mirror = V; Sync(); break;
|
2025-09-12 14:40:27 +02:00
|
|
|
|
case 0xc000: IRQLatch = V; break;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
case 0xc001: IRQReload = 1; break;
|
|
|
|
|
|
case 0xe000: X6502_IRQEnd(FCEU_IQEXT); IRQa = 0; break;
|
|
|
|
|
|
case 0xe001: IRQa = 1; break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void UNLOneBusIRQHook(void) {
|
|
|
|
|
|
uint32 count = IRQCount;
|
|
|
|
|
|
if (!count || IRQReload) {
|
|
|
|
|
|
IRQCount = IRQLatch;
|
|
|
|
|
|
IRQReload = 0;
|
|
|
|
|
|
} else
|
|
|
|
|
|
IRQCount--;
|
|
|
|
|
|
if (count && !IRQCount) {
|
|
|
|
|
|
if (IRQa)
|
|
|
|
|
|
X6502_IRQBegin(FCEU_IQEXT);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static DECLFW(UNLOneBusWriteAPU40XX) {
|
|
|
|
|
|
/* if(((A & 0x3f)!=0x16) && ((apu40xx[0x30] & 0x10) || ((A & 0x3f)>0x17)))FCEU_printf("APU %04x:%04x\n",A,V); */
|
|
|
|
|
|
apu40xx[A & 0x3f] = V;
|
|
|
|
|
|
switch (A & 0x3f) {
|
|
|
|
|
|
case 0x12:
|
|
|
|
|
|
if (apu40xx[0x30] & 0x10) {
|
|
|
|
|
|
pcm_addr = V << 6;
|
|
|
|
|
|
}
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 0x13:
|
|
|
|
|
|
if (apu40xx[0x30] & 0x10) {
|
|
|
|
|
|
pcm_size = (V << 4) + 1;
|
|
|
|
|
|
}
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 0x15:
|
|
|
|
|
|
if (apu40xx[0x30] & 0x10) {
|
|
|
|
|
|
pcm_enable = V & 0x10;
|
|
|
|
|
|
if (pcm_irq) {
|
|
|
|
|
|
X6502_IRQEnd(FCEU_IQEXT);
|
|
|
|
|
|
pcm_irq = 0;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (pcm_enable)
|
|
|
|
|
|
pcm_latch = pcm_clock;
|
|
|
|
|
|
V &= 0xef;
|
|
|
|
|
|
}
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
defapuwrite[A & 0x3f](A, V);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static DECLFR(UNLOneBusReadAPU40XX) {
|
|
|
|
|
|
uint8 result = defapuread[A & 0x3f](A);
|
|
|
|
|
|
/* FCEU_printf("read %04x, %02x\n",A,result); */
|
|
|
|
|
|
switch (A & 0x3f) {
|
|
|
|
|
|
case 0x15:
|
|
|
|
|
|
if (apu40xx[0x30] & 0x10) {
|
|
|
|
|
|
result = (result & 0x7f) | pcm_irq;
|
|
|
|
|
|
}
|
|
|
|
|
|
break;
|
2025-09-12 11:32:19 +02:00
|
|
|
|
case 0x17:
|
|
|
|
|
|
if (cpu410x[0x0B] == 0x14) result = result &~0x04 | (dipswitch &1? 0x04: 0x00); /* Super Joy III pad */
|
2017-12-17 13:39:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
return result;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-12 11:32:19 +02:00
|
|
|
|
static DECLFR(readDIP_FamilyPocket) {
|
|
|
|
|
|
return dipswitch &1? 8: 0;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2017-12-17 13:39:16 +08:00
|
|
|
|
static void UNLOneBusCpuHook(int a) {
|
|
|
|
|
|
if (pcm_enable) {
|
|
|
|
|
|
pcm_latch -= a;
|
|
|
|
|
|
if (pcm_latch <= 0) {
|
|
|
|
|
|
pcm_latch += pcm_clock;
|
|
|
|
|
|
pcm_size--;
|
|
|
|
|
|
if (pcm_size < 0) {
|
|
|
|
|
|
pcm_irq = 0x80;
|
|
|
|
|
|
pcm_enable = 0;
|
|
|
|
|
|
X6502_IRQBegin(FCEU_IQEXT);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
uint16 addr = pcm_addr | ((apu40xx[0x30]^3) << 14);
|
|
|
|
|
|
uint8 raw_pcm = ARead[addr](addr) >> 1;
|
|
|
|
|
|
defapuwrite[0x11](0x4011, raw_pcm);
|
|
|
|
|
|
pcm_addr++;
|
|
|
|
|
|
pcm_addr &= 0x7FFF;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void UNLOneBusPower(void) {
|
|
|
|
|
|
uint32 i;
|
|
|
|
|
|
IRQReload = IRQCount = IRQa = 0;
|
|
|
|
|
|
|
|
|
|
|
|
memset(cpu410x, 0x00, sizeof(cpu410x));
|
|
|
|
|
|
memset(ppu201x, 0x00, sizeof(ppu201x));
|
|
|
|
|
|
memset(apu40xx, 0x00, sizeof(apu40xx));
|
2025-04-05 21:13:59 +02:00
|
|
|
|
cpu410x[0x0F] =0xFF;
|
2025-04-25 01:01:56 +02:00
|
|
|
|
cpu410x[0x1C] =submapper ==12 || submapper ==14? 0x40: 0x00;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
|
|
|
|
|
SetupCartCHRMapping(0, PRGptr[0], PRGsize[0], 0);
|
|
|
|
|
|
|
|
|
|
|
|
for (i = 0; i < 64; i++) {
|
|
|
|
|
|
defapuread[i] = GetReadHandler(0x4000 | i);
|
|
|
|
|
|
defapuwrite[i] = GetWriteHandler(0x4000 | i);
|
|
|
|
|
|
}
|
|
|
|
|
|
SetReadHandler(0x4000, 0x403f, UNLOneBusReadAPU40XX);
|
|
|
|
|
|
SetWriteHandler(0x4000, 0x403f, UNLOneBusWriteAPU40XX);
|
|
|
|
|
|
|
2025-09-12 11:32:19 +02:00
|
|
|
|
SetReadHandler(0x412C, 0x412C, readDIP_FamilyPocket);
|
2022-03-01 18:04:34 +01:00
|
|
|
|
SetReadHandler(0x6000, 0xFFFF, CartBR);
|
|
|
|
|
|
SetWriteHandler(0x6000, 0x7FFF, CartBW);
|
2017-12-17 13:39:16 +08:00
|
|
|
|
SetWriteHandler(0x2010, 0x201f, UNLOneBusWritePPU201X);
|
2025-04-01 22:54:58 +02:00
|
|
|
|
SetWriteHandler(0x4100, 0x413f, UNLOneBusWriteCPU410X);
|
|
|
|
|
|
SetWriteHandler(0x4242, 0x4242, UNLOneBusWriteCPU4242);
|
2017-12-17 13:39:16 +08:00
|
|
|
|
SetWriteHandler(0x8000, 0xffff, UNLOneBusWriteMMC3);
|
|
|
|
|
|
|
2022-03-01 18:04:34 +01:00
|
|
|
|
FCEU_CheatAddRAM(8, 0x6000, WRAM);
|
|
|
|
|
|
setprg8r(0x10, 0x6000, 0);
|
2025-04-01 22:54:58 +02:00
|
|
|
|
dipswitch =0;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void UNLOneBusReset(void) {
|
|
|
|
|
|
IRQReload = IRQCount = IRQa = 0;
|
|
|
|
|
|
|
|
|
|
|
|
memset(cpu410x, 0x00, sizeof(cpu410x));
|
|
|
|
|
|
memset(ppu201x, 0x00, sizeof(ppu201x));
|
|
|
|
|
|
memset(apu40xx, 0x00, sizeof(apu40xx));
|
2025-04-05 21:13:59 +02:00
|
|
|
|
cpu410x[0x0F] =0xFF;
|
2025-04-25 01:01:56 +02:00
|
|
|
|
cpu410x[0x1C] =submapper ==12 || submapper ==14? 0x40: 0x00;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
reg4242 =0;
|
2025-09-12 11:32:19 +02:00
|
|
|
|
dipswitch++;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
|
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void StateRestore(int version) {
|
|
|
|
|
|
Sync();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-03-01 18:04:34 +01:00
|
|
|
|
void UNLOneBus_Close(void) {
|
|
|
|
|
|
if (WRAM)
|
|
|
|
|
|
FCEU_gfree(WRAM);
|
|
|
|
|
|
WRAM = NULL;
|
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
|
|
|
|
/* Mapper270_Init / Mapper436_Init allocate an additional CHRRAM after
|
|
|
|
|
|
* UNLOneBus_Init returns; free that here too to avoid leaking it on
|
|
|
|
|
|
* every load/unload cycle. */
|
|
|
|
|
|
if (CHRRAM)
|
|
|
|
|
|
FCEU_gfree(CHRRAM);
|
|
|
|
|
|
CHRRAM = NULL;
|
2022-03-01 18:04:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2017-12-17 13:39:16 +08:00
|
|
|
|
void UNLOneBus_Init(CartInfo *info) {
|
|
|
|
|
|
info->Power = UNLOneBusPower;
|
|
|
|
|
|
info->Reset = UNLOneBusReset;
|
2022-03-01 18:04:34 +01:00
|
|
|
|
info->Close = UNLOneBus_Close;
|
2025-04-01 22:54:58 +02:00
|
|
|
|
Sync =Sync256;
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
2022-03-01 18:18:49 +01:00
|
|
|
|
if (info->iNES2)
|
|
|
|
|
|
submapper =info->submapper;
|
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
|
|
|
|
else {
|
|
|
|
|
|
/* Compare the first four MD5 bytes literally to avoid the previous
|
|
|
|
|
|
* endian-dependent (uint32) reinterpretation, which silently
|
|
|
|
|
|
* mismatched on big-endian hosts and disabled the PowerJoy Supermax
|
|
|
|
|
|
* variant detection. */
|
|
|
|
|
|
const uint8 *md5 = info->MD5;
|
|
|
|
|
|
int is_305fcdc3 = (md5[0] == 0xc3 && md5[1] == 0xcd && md5[2] == 0x5f && md5[3] == 0x30);
|
|
|
|
|
|
int is_6abfce8e = (md5[0] == 0x8e && md5[1] == 0xce && md5[2] == 0xbf && md5[3] == 0x6a);
|
|
|
|
|
|
submapper = (is_305fcdc3 || is_6abfce8e) ? 2 : 0; /* PowerJoy Supermax Carts */
|
|
|
|
|
|
}
|
2017-12-17 13:39:16 +08:00
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
cpuMangle =cpuMangles[submapper];
|
|
|
|
|
|
ppuMangle =ppuMangles[submapper];
|
|
|
|
|
|
mmc3Mangle =mmc3Mangles[submapper];
|
|
|
|
|
|
|
2017-12-17 13:39:16 +08:00
|
|
|
|
GameHBIRQHook = UNLOneBusIRQHook;
|
|
|
|
|
|
MapIRQHook = UNLOneBusCpuHook;
|
|
|
|
|
|
GameStateRestore = StateRestore;
|
|
|
|
|
|
AddExState(&StateRegs, ~0, 0, 0);
|
2022-03-01 18:04:34 +01:00
|
|
|
|
|
|
|
|
|
|
WRAM = (uint8*)FCEU_gmalloc(8192);
|
|
|
|
|
|
SetupCartPRGMapping(0x10, WRAM, 8192, 1);
|
2017-12-17 13:39:16 +08:00
|
|
|
|
}
|
2022-03-01 18:04:34 +01:00
|
|
|
|
|
2025-04-01 22:54:58 +02:00
|
|
|
|
static void Sync270(void) {
|
|
|
|
|
|
int OR =0;
|
|
|
|
|
|
switch(submapper) {
|
|
|
|
|
|
case 1: OR = cpu410x[0x2C] &0x02? 0x0800: 0x0000;
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 2: OR =(cpu410x[0x2C] &0x02? 0x0800: 0x0000) |
|
|
|
|
|
|
(cpu410x[0x2C] &0x01? 0x1000: 0x0000);
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 3: OR = cpu410x[0x2C] &0x04? 0x0800: 0x0000;
|
|
|
|
|
|
break;
|
|
|
|
|
|
default: OR =(cpu410x[0x2C] &0x06? 0x0800: 0x0000) |
|
|
|
|
|
|
(cpu410x[0x2C] &0x01? 0x1000: 0x0000);
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
PSync(0x07FF, OR);
|
|
|
|
|
|
if (reg4242 &1) {
|
|
|
|
|
|
setchr8r(0x10, 0);
|
|
|
|
|
|
setmirror((mirror ^ 1) & 1);
|
|
|
|
|
|
} else
|
|
|
|
|
|
CSync(0x3FFF, OR <<3);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void Mapper270_Init(CartInfo *info) {
|
|
|
|
|
|
UNLOneBus_Init(info);
|
|
|
|
|
|
cpuMangle =cpuMangles[0];
|
|
|
|
|
|
ppuMangle =ppuMangles[0];
|
|
|
|
|
|
mmc3Mangle =mmc3Mangles[0];
|
|
|
|
|
|
|
|
|
|
|
|
CHRRAMSIZE = 8192;
|
|
|
|
|
|
CHRRAM = (uint8*)FCEU_gmalloc(CHRRAMSIZE);
|
|
|
|
|
|
SetupCartCHRMapping(0x10, CHRRAM, CHRRAMSIZE, 1);
|
|
|
|
|
|
AddExState(CHRRAM, CHRRAMSIZE, 0, "CHRR");
|
|
|
|
|
|
|
|
|
|
|
|
Sync =Sync270;
|
|
|
|
|
|
}
|
2025-04-05 21:13:59 +02:00
|
|
|
|
|
|
|
|
|
|
static void Sync436(void) {
|
|
|
|
|
|
int AND =0xFFFF, OR =0;
|
|
|
|
|
|
switch(submapper) {
|
|
|
|
|
|
case 1: OR = cpu410x[0x1C] &0x01 && ~cpu410x[0x1C] &0x04? 0x0800: 0x0000;
|
|
|
|
|
|
PSync(0xF7FF, OR);
|
|
|
|
|
|
CSync(0xBFFF, OR <<3);
|
|
|
|
|
|
break;
|
|
|
|
|
|
default: PSync(0xF3FF, (cpu410x[0x0F] &0x20? 0x0400: 0x0000) | (cpu410x[0x00] &0x40? 0x0800: 0x0000));
|
|
|
|
|
|
CSync(0x9FFF, (cpu410x[0x0F] &0x20? 0x2000: 0x0000) | (cpu410x[0x00] &0x04? 0x4000: 0x0000));
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void Mapper436_Init(CartInfo *info) {
|
|
|
|
|
|
UNLOneBus_Init(info);
|
|
|
|
|
|
cpuMangle =cpuMangles[0];
|
|
|
|
|
|
ppuMangle =ppuMangles[0];
|
|
|
|
|
|
mmc3Mangle =mmc3Mangles[0];
|
|
|
|
|
|
|
|
|
|
|
|
CHRRAMSIZE = 8192;
|
|
|
|
|
|
CHRRAM = (uint8*)FCEU_gmalloc(CHRRAMSIZE);
|
|
|
|
|
|
SetupCartCHRMapping(0x10, CHRRAM, CHRRAMSIZE, 1);
|
|
|
|
|
|
AddExState(CHRRAM, CHRRAMSIZE, 0, "CHRR");
|
|
|
|
|
|
|
|
|
|
|
|
Sync =Sync436;
|
|
|
|
|
|
}
|