Commit Graph
52 Commits
Author SHA1 Message Date
LibretroAdmin 4bcd9a6c82 Rename the identifiers the Windows SDK turns into types
rpcndr.h, which windows.h and the D3D, DXGI and EGL headers pull in,
defines small as char and hyper as __int64. The glow named the small
image's dims 'small', which broke the UWP ANGLE build in gl_common.c;
vulkan.c had the same name, and the replay index another. They are
small_dims and inline_idxs now, and the Wii U and Metal glow code is
named alike.

tools/win_macro_names_check.py finds either name used as an
identifier anywhere outside deps/ and the samples, comments, strings,
preprocessor lines and member names left out, and the new
Win-Macro-Names-Check workflow runs it, so the next one is caught on
Linux rather than by the MSVC builds.
2026-11-16 05:36:51 +01:00
LibretroAdmin 4c5cb57668 replay: lend the frame's input events instead of copying them
Each input query copied every event it looked at out of the array and,
on big-endian, byte-swapped its id again. Compare in place against an id
converted once, with the id checked first as it differs most between a
frame's events. The netplay recorder's own lookup does the same.

Key and input events were read and written one record at a time, though
the arrays already have the file's layout: move each frame's events with
one stream call straight to or from the array, and none for an empty
list, which is most frames. The push functions build the event in its
slot, after the capacity check, and playback passes key events on from
the array.
2026-11-09 18:52:40 +01:00
LibretroAdmin f386b14d74 replay: byte-swap the checkpoint size when skipping a frame on big-endian
The frame scan read a CHECKPOINT2 frame's compressed size and seeked
past the state without converting it from the file's little-endian
order, unlike the older checkpoint branch next to it and the checkpoint
loader. On PS3, Wii and other big-endian targets it seeked to the wrong
place.
2026-11-09 18:52:40 +01:00
JCorrêa e31d1c85de fix(replay): decode input event IDs on big-endian systems (#20035)
Convert little-endian event IDs before matching input queries.
This restores recorded inputs, including joypad masks, on PS3.
2026-11-09 18:55:56 +01:00
LibretroAdmin ab070c1132 Fix the remaining clang 64-to-32 and comma warnings
The narrowings the Linux build reports under -Wshorten-64-to-32 are
made explicit where the value is bounded (read() returns into small
buffers, X11 property lengths, statestream index counts, clamped H.265
weights, VP9 transform outputs), and the joypad scan loops count with
the unsigned index their callees take. gl1 sizes its readback with
VIDEO_SCALE_AREA directly, and rdds' swap is three statements.

The VP9 casts sit only on the stores into the rvp9_tran output arrays,
so the decoder's object code stays instruction-identical under gcc and
clang.
2026-11-08 19:52:07 +01:00
LibretroAdmin ee4525c5ae Replay: keep a checkpoint's buffers from one checkpoint to the next
A replay records or plays back a checkpoint every few seconds, in the
middle of the game, and each took fresh state-sized buffers: the
statestream encoding (half again the state), the compressed copy -
calloc'd, zeroed only to be overwritten by the compressor - and on
playback the compressed copy read from the file and a calloc'd
buffer to decode into, then copied into cur_save for a raw state.

The handle now keeps the encoding and compression buffers
(bsv_movie_scratch()), grown only when a state outgrows them, never
zeroed, freed with the movie. A raw state is inflated straight into
cur_save, so its copy is gone too. A zlib checkpoint whose buffer
could not be taken now fails instead of compressing into NULL, and a
checkpoint that fails part way marks cur_save as holding no state.

The buffers a zstd checkpoint of a raw state takes and touches, per
checkpoint (the codec's own work aside): 4 MiB 0.81 -> 0.41 ms,
16 MiB 2.66 -> 1.35 ms, 64 MiB 45.5 -> 9.0 ms.

bsv_statestream_test gains a lane that records and plays back eight
checkpoints, raw and statestream, plain and zstd, each decoding to the
bytes written, with nothing state-sized of the replay's own allocated
after the first two (what zstd allocates inside a call is measured
through rzstd directly and allowed for). It fails on the previous
bsvmovie.c. bsv_checkpoint_bounds_test's copy of
bsv_movie_load_checkpoint() follows the shipping one again, with
bsv_movie_set_end() and the size checks it had fallen behind on.
2026-11-03 00:58:21 +01:00
LibretroAdmin 6cda3a9dac statestream and the PS4 shader cache hash with libretro-common's
The statestream block index keys its blocks with xxh3_64(), against
XXH32 a tenth of the time on a 16 KiB block and under half on 64 and
128 octets. The PS4 shader cache keeps its XXH64 keys, now from
xxh64_update() on the stack, so cached binaries still match. Nothing
else used deps/xxHash, which goes.
2026-10-28 07:32:17 +01:00
Nelfe80andlibretroadmin 0afe7f41d1 netplay: record confirmed multi-player input in BSV replays (#19870)
* replay: accept captured normal states for BSV checkpoints

Let netplay supply a frame's saved state after confirmation without serializing the current speculative core state. Preserve the existing on-disk format and local recording path.

* netplay: commit BSV input frames after rollback confirmation

Stage the input queries seen by the core and replace them during rollback. Commit each confirmed frame once, using portable initial states and checkpoints captured at its emulated boundary. Keep local input sampling and stalled iterations out of the movie. Reject unsynchronized starts and stop at state discontinuities.

* test: cover confirmed netplay BSV recording and offline replay

Exercise the shipping recorder and rollback loop with delayed input, ring wrap, mid-session starts, stalls, absent ports and checkpoints. Compare host, client and spectator recordings, then replay through the ordinary BSV reader. Add sanitizer and Windows CI coverage.

* netplay: keep replay state access in the input frontend

Keep recording flags, checkpoint requests and notifications in the input frontend. Exercise the same frontend calls in the netplay BSV harness.

* netplay: free BSV staging and keep netplay movies out of savestates

Free each staged frame's states once it is committed, and drop all
staging when a netplay recording stops, so a session no longer holds a
normal savestate per ring slot. Skip the speculative initial state at
record start, keep netplay movies out of savestates since they lag the
core by unconfirmed frames, and keep the recorder's state in flag words.

The netplay BSV tests check that committed and stopped recordings keep
no states, and the MinGW lane links statically like the other wine lanes.

---------

Co-authored-by: libretroadmin <[email protected]>
2026-10-24 04:34:26 +02:00
LibretroAdmin 52841a2258 bsv: a compressed checkpoint decodes to exactly its header's size
A zlib or zstd checkpoint that decodes short of its encoded size is
refused, rather than restored with the rest of the state left as the
decode buffer held it.
2026-10-09 10:33:57 +02:00
b4109477cb bsv: refuse a short replay copy; store the checkpoint config little-endian (#19714)
* bsv: refuse a short replay copy; store the checkpoint config little-endian

replay_get_serialized_data logged a short read of the replay into a
savestate and still returned true, so the savestate kept a replay block
whose tail was whatever the buffer held. It now returns false, as it
already does for a frame counter too large to store. Both callers in
task_save.c handle false by leaving the replay block out, so the
savestate is still written, without its replay.

The header's checkpoint-config word was written and read in native byte
order, while every other header field goes through swap_if_big32. It
now does too. On a little-endian machine the swap is a no-op, so files
from those builds are unchanged; a big-endian build now writes the same
bytes as everyone else.

Tests (samples/tasks/bsv_replay_init): serialize_short places a handle
past the end of a file shorter than its position. It fails without the
fix (128 / 256 bytes copied, copy accepted) and passes with it, in the
plain, ASan, ASan + STATESTREAM=1 and valgrind runs of the sweep.
config_read_order and config_write_order check the word's byte layout;
they pass with or without the fix on little-endian and were not run on
a big-endian machine. header_sizes now writes its fixture word through
swap_if_big32. bsv_replay and bsv_statestream pass; RetroArch builds;
both changed files compile with -std=c89.

write-test: route 1, inline; red run proved for serialize_short only,
the byte-order lanes are unproven here (no big-endian toolchain); no
mutation probe beyond the red run.
write-code: gate make -j4 retroarch rc 0; bsv_replay_init sweep clean;
bsv_replay and bsv_statestream pass; -std=c89 syntax check; diff read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* bsv: the short replay copy's log passes its counts as ints

The message formats both with %d; read_amt is 64-bit, which on a
32-bit target shifts every argument after it.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: LibretroAdmin <[email protected]>
2026-10-09 07:15:35 +02:00
Anthony SchemelandClaude Opus 5.5 38c7b6fb06 bsv: free the replay buffers a failed read leaves behind (#19713)
bsv_movie_reset_playback leaked the state buffer of a version 0/1
replay whose initial state is shorter than the header says.

bsv_movie_read_deduped_state freed the rmsgpack item on some refusals
and not others, so a statestream checkpoint carrying a string or
array where a token, an index, a superblock or the sequence belongs
leaked it. The item now starts as RDT_NULL, is reset to RDT_NULL when
a block is handed to the index, and is freed once at the exit label;
rmsgpack_dom_value_free leaves it RDT_NULL, so the existing frees stay
harmless.

Tests: bsv_replay_init gains v1_short_state and bsv_statestream gains
wrong_type. Under ASan both leak before the fix (64 bytes from
bsv_movie_reset_playback; 7 allocations, one per position) and pass
after it, with every other lane still passing, in the plain and
STATESTREAM=1 builds of bsv_replay_init. RetroArch builds; bsvmovie.c
also compiles with -std=c89.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-09 07:07:47 +02:00
Rob Loach 62d5954fbc mcp: answer tools once their work is through
A tool whose work runs over later frames answers when that work is
through, with what came of it, or with its name, ERROR and the reason:
LOAD_CONTENT, START_CORE, CLOSE_CONTENT and UNLOAD_CORE once the load or
close ends; LOAD_STATE_SLOT and SAVE_STATE_SLOT once the state is
applied or written; PLAY_REPLAY_SLOT, RECORD_REPLAY, SEEK_REPLAY and the
replay checkpoint tools once the replay has started or the seek or
checkpoint has run; SET_SHADER once the preset has compiled; AI_SERVICE
with the service's text. A line-based interface keeps the answers it
had.

The waiting is one shape, task_notify_t (tasks/task_notify.h), held by
the work's owner: the content load, the save and load tasks, the movie
tasks, the deferred shader load and the translation service. State and
replay work a command starts runs from a main-thread task, outside the
core's own input poll. The command interfaces outlive a content load,
remade only when their settings change, and what arrives during a load
waits for it.

samples/tasks/content_load gains lanes for the state-slot, replay, seek and
content replies; samples/network/mcp_server follows.

Closes #19702
2026-10-05 11:33:27 +02:00
LibretroAdmin 73dde88f91 replay: a header with no block layout plays without an index
A recorder built without statestream writes block and superblock sizes
of 0 and RAW checkpoints. A statestream build plays such a replay with
no index built for it; a statestream checkpoint in it is refused, as
for a version-1 header. Non-zero sizes are bounded as before.

Lane header_no_layout in samples/tasks/bsv_replay_init.
2026-10-05 09:50:05 +02:00
Anthony Schemel ee8a24a447 replay: harden replay file parsing
Each read is reachable from a damaged .replay file or from replay data
inside a loaded savestate.

- uint32s_index_commit: a commit interval of 1 (from the header) read
  the addition one past the end of the log and freed wild pointers;
  below 2 nothing is collected. The bucket lookup is guarded as pop's.
- reset_playback: block and superblock sizes from the header are
  bounded (REPLAY_MAX_*) and must be a multiple of 4.
- A statestream checkpoint in a replay whose header built no indexes
  is refused instead of read through NULL.
- replay_check_same_timeline: a frame claiming more inputs than a frame
  holds overflowed its 128 KB compare buffers.
- replay_set_serialized_data takes the savestate block's length; the
  replay length it declares must fit inside it.
- push_input_event / push_key_event drop events past their arrays.
- uint32s_index_pop freed nothing it dropped (a leak per rewind).
- movie_find_checkpoint_before returned the frame as a bool: "no
  checkpoint" read as found, frame 0 as not found.
- A checkpoint size of 2^63 or more seeked backwards and hung the scan;
  every file-sized skip now moves forward within the file.
- A checkpoint that fails to load ends playback rather than playing on
  out of step with its indexes, and a failed statestream decode clears
  cur_save_valid.
- Legacy checkpoint frames: a size too large to allocate, or to fit a
  size_t, read into a NULL cur_save; the movie now ends instead.
- bsv_movie_load_checkpoint no longer sets last_save_size to cur_save's
  size. last_save is the recorder's other buffer, swapped back in on
  the next write, so it could claim more than it holds. The reader's
  last_save_size check goes with it; superblock_seq_len already sizes
  the sequence.
- write_checkpoint recorded a size before its buffer existed; a log
  line printed a pointer as %c; a message length used sizeof.

bsv_checkpoint_bounds_test's verbatim copy of bsv_movie_load_checkpoint
follows the two changes to that function.

Tests: samples/tasks/bsv_replay_init gains lanes checkpoint,
statestream, index_gc, index_interval1, index_pop, header_sizes,
no_index, decode_fail_ends (STATESTREAM) and timeline_inputs,
state_replay_len, event_capacity, seek_no_checkpoint, checkpoint_seek.
CI builds it with STATESTREAM=1 too; the ASan runs set
allocator_may_return_null=1, and the test sets it for TSan.

Closes #19695
2026-10-05 09:50:02 +02:00
LibretroAdmin 6da6466e88 input: no file under input/ takes a state pointer but the frontend
The last 23, in 11 files, are gone. Nothing under input/ calls
config_get_ptr(), input_state_get_ptr(), runloop_state_get_ptr(),
menu_state_get_ptr() or video_driver_get_ptr() any more, apart from
the frontend itself (input_driver.c, input_driver_choice.c).

The replay code (input/bsv/bsvmovie.c), seven:
- its four entry points that took no state are handed the input state
  by their callers, the save-state task and the rewind;
- its two inner functions used the state only to say the replay is
  over, fifteen times between them. That is bsv_movie_set_end() now,
  and they are handed the replay alone.

The platform drivers, fourteen settings reads: named calls, as the
others became - Apple (keyboard as gamepad, mouse index, rumble gain,
device vibration), Wii and GameCube (mouse index and scale, joypad
index), Vita (back touch), Switch (split Joy-Con), webOS
(screensaver), udev (the five touch options).

Two drivers wrote to the settings, and each has a call that says what
it is doing:
- the Wii and GameCube joypad driver puts port 1 back on the first pad
  when only one is left: input_config_set_joypad_index();
- the udev input driver, finding no device on the very first start,
  makes linuxraw the configured driver:
  input_driver_first_start_fallback().

The SDL2 input driver took the video driver's data to grab the pointer
in its window. The video driver does the grab, sdl2_video_grab_window(),
and the input driver asks.

The Android input driver held the code that writes SRAM, core options
and the configuration when Android takes the application away. That is
frontend work; it is retroarch_save_for_suspend() in retroarch.c, as
it was, and the driver calls it.

tools/input_state_grab_check.py has an empty list, and no exemption
for the replay code: a file under input/ that takes one of these
fails.

Built for Linux and Android; the frontend harness, the four replay
tests and the udev devices test pass. The Apple, Wii, GameCube, Vita,
Switch and webOS files are not built here.
2026-10-05 04:31:56 +02:00
LibretroAdmin 2a9892606a input: the replay code and the Android drivers ask by name
The replay code took the run loop's state for two things, and the
settings twice a frame:

- whether the run loop is paused is runloop_get_flags();
- whether the keyboard callback in place is the frontend's own, which
  is where a replay sends its recorded keys, is
  runloop_key_event_is_frontend();
- the checkpoint interval and whether a checkpoint is loaded are
  handed to bsv_movie_next_frame() by the run loop, which has the
  settings in hand. With a replay on, that is two calls for the
  settings a frame that are no longer made.

It still takes the input state, and stays that way: its state is kept
there, so it is the frontend's own code reaching its own data. The
check says so (OWN_STATE): that file may take the input state and
nothing else.

The Android input and joypad drivers read nine settings; each is a
named call now, the Android-only ones under ANDROID - sensors, the
stylus's four, the disconnect workaround, the physical keyboard, the
block timeout, device vibration.

One read is left in the Android input driver: it saves the
configuration when Android takes the application away. That is
frontend work sitting in an input driver, and belongs out of it.

Left in tools/input_state_grab_check.py: 16 in 10 files - that one,
Apple, the consoles, udev's touch options, webOS, and the SDL2 input
driver taking the video driver's window.

Built for Linux and Android; the four replay tests and the frontend
harness pass. input/bsv/bsvmovie.c fails the syntax gate before this
change as after it, on a type the gate's C89 lane does not define.
2026-10-05 04:01:41 +02:00
libretroadmin 35080c9ffc bsv: a bucket that cannot grow fails the insert
uint32s_bucket_expand reports whether it took the index, and the
inserts give it the index before storing the object, so an object is
never kept where a lookup cannot find it: uint32s_index_insert returns
UINT32S_INDEX_NONE and insert_exact false, with the index unchanged.
The garbage-collection log prints its frame counter with
STRING_REP_UINT64 and its indices as unsigned.

The hash can be defined by the build; samples/tasks/bsv_statestream
runs once more with every object hashing alike, which puts the
buckets' growth under the oom lanes.
2026-10-03 01:18:57 +02:00
libretroadmin 82d728d59e bsv: the replay header's state size is written as 32 bits
bsv_movie_reset_recording writes the header's state size field from a
uint32_t, at REPLAY_HEADER_STATE_SIZE_INDEX. On a 64-bit big-endian
host the four bytes written from a size_t were its high half, so the
field read back as 0 and playback's starting position for seeking,
rewind and the timeline check fell inside the initial checkpoint.
2026-10-03 01:07:03 +02:00
libretroadmin b12ae7c1ee bsv: statestream checkpoints fail cleanly when an allocation fails
uint32s_index_insert reserves room in every per-object list and
allocates its copy before it changes the index, and reports
UINT32S_INDEX_NONE when it cannot; insert_exact reserves the same way.
uint32s_index_new returns NULL when its table, zero object or first
entry cannot be had, and both callers stop there. The statestream
writer checks its own buffers and the inserts, and fails the
checkpoint, which ends the recording since its indices may hold blocks
the file never got; bsv_movie_write_checkpoint also checks cur_save
and its encode buffer, and passes the failure on rather than writing
a size of -1. A recording whose first checkpoint cannot be written
does not start, and one rewound to its start ends if the checkpoint
cannot be rewritten.

samples/tasks/bsv_statestream gains oom and oomload lanes, which wrap
malloc, calloc and realloc at link time and fail each allocation of a
checkpoint write and of a load in turn.
2026-10-03 00:26:17 +02:00
libretroadmin c6f3adb51a bsv: refuse statestream checkpoints that point outside the replay
A statestream checkpoint names superblocks and blocks by index and
lists the superblocks of the state in order, all from the replay file.
The decoder refuses an index the replay never defined instead of
copying from it, and a replay whose header gives no block layout. The
superblock list now carries its length, superblock_seq_len, and grows
when a sequence or a recorded state needs more entries than it holds;
growing it drops the unchanged-superblock shortcut until the next save,
as the writer already did. The decoder's allocations are checked, and
an item it bails out on is freed.

uint32s_index_get reads the last frame addition from additions[len - 1]
when it logs where a collected index came from.
2026-10-03 00:00:56 +02:00
libretroadmin d7c14a0ac8 bsv: hold replay checkpoints to the sizes in their header
A checkpoint's state, encoded and compressed sizes come from the replay
file. Uncompressed data has to be as long as its encoding, and a raw
state as long as the state, before anything is read: cur_save holds the
state size, and uncompressed raw data is read into it directly. A
checkpoint whose sizes disagree ends the movie. cur_save_size changes
only once cur_save holds a decoded checkpoint, so a skipped or failed
one leaves it describing the buffer, and the cleanup never frees
cur_save, which the movie keeps.

samples/tasks/bsv_checkpoint runs the function against mismatched,
truncated and skipped checkpoints under ASan and UBSan, in the
samples/tasks workflow.
2026-10-03 00:00:52 +02:00
Anthony Schemel 02028ea990 Check allocations that were dereferenced unchecked
- menu_driver: driver_ctx->init() returns NULL when an allocation fails
  (xmb, ozone, rgui and materialui all can), but the result was
  written through before the !menu_st->driver_data check below.
- task_screenshot: task_init() returns NULL on OOM; the threaded
  screenshot path wrote through it. Free the state and fail instead.
- bsvmovie: bsv_movie_load_checkpoint read into handle->cur_save and
  into compressed_data without checking either malloc, and decompressed
  into an unchecked calloc on the zlib and zstd paths.
- uint32s_index: uint32s_bucket_expand memcpy'd into an unchecked
  calloc, and assigned realloc's result over the only pointer to the
  old block. On failure leave the bucket as it was.
2026-10-02 23:53:20 +02:00
LibretroAdmin e39e641802 runloop: put cheats, presence, camera and BSV behind frame_work bits
The post-core_run product block called into four translation units
every frame to find out nothing needed doing: cheat_manager_apply_
retro_cheats() loads a cold global to see there is no cheat list,
presence_update() calls discord_update() and steam_update_presence()
which each compare a status word and return, the camera poll reads
settings_t for camera_allow before the caps check, and
bsv_movie_next_frame() pulled two settings through config_get_ptr()
before checking whether a movie handle exists at all.

Give each an up/down owner and a bit on runloop_state_t::frame_work,
raised and dropped by the product itself through
runloop_frame_work_set():

  RUNLOOP_WORK_CHEATS   - cheat_manager_new/realloc raise it when a
                          list is allocated, cheat_manager_free drops it
  RUNLOOP_WORK_PRESENCE - raised with Discord init and with Steam
                          (mist) init; dropped with whichever of the
                          two is the last compiled-in sink
  RUNLOOP_WORK_CAMERA   - driver_camera_start raises it when the core's
                          start succeeds, driver_camera_stop and the
                          driver teardown drop it. The remaining
                          camera_allow/caps/driver checks stay behind
                          the bit; a camera the core registered but
                          never started is no longer polled.

BSV needs no bit: the movie handles live on input_st, which the frame
already has in cache, so the iterate tests the pointers directly and
bsv_movie_next_frame() checks its handle before touching settings.
2026-09-29 20:11:58 +02:00
Anthony SchemelandClaude Opus 5.5 4ee62a575f security: validate replay, UPnP and cloud sync input (#19628)
Three places trust data that comes from outside RetroArch:

- replay_set_serialized_data reads the embedded replay length from the
  save state. A negative value, or one shorter than the replay header,
  was passed on to the seek and write that restore the replay. Refuse
  such states.
- natt_parse_desc_node walks the IGD description XML a router serves.
  On a node without children it recursed with a NULL child and then
  read child->next, so a leaf node or an empty root crashed it. It
  also recursed only into childless nodes, so a <service> nested in
  <root>/<device>/<serviceList>, the normal UPnP shape, was never
  found. It now always recurses into children and checks the
  serviceType and controlURL text before using it.
- task_cloud_sync_fetch_server_file took the local path from a
  server-supplied manifest key as strchr(key, '/') + 1. A key without
  '/' read from address 1, and a key containing ".." or an absolute
  path was joined onto the sync directory, so a hostile server could
  write outside it. Such keys are now refused and counted as a
  failure.

The description walk moves to network/natt_desc.c and the key check
to tasks/task_cloudsync_path.c, so the new sample tests
(samples/tasks/natt_desc, and cloudsync_path_safety_test beside the
existing cloudsync test) compile the shipped code directly. Both are
added to Linux-samples-tasks.yml.

Tested on Linux: full build; touched files also compile with
C89_BUILD=1 without warnings. The workflow's commands for both new
steps pass, and the existing cloudsync test still passes under
SANITIZER=address. With the old parser or the old key handling
substituted, each test segfaults.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-09-26 17:22:37 +02:00
LibretroAdmin fee695d45c statestream: insert the real index on hash collision
uint32s_index_insert_exact declared a shadowing 'uint32_t idx = 0' in
the RHMAP_HAS branch, so every object whose hash collided with an
existing bucket was recorded in that bucket as index 0 instead of its
own index. Lookups through the bucket then compared against the
all-zeros pattern rather than the new object, and pop/remove could
never find the entry to take it back out. Use the caller's idx.
2026-09-26 16:28:34 +02:00
Anthony SchemelandClaude Opus 5.5 67c857e163 misc: fix crashes and leaks in wayland, drm, replay index and drivers (#19630)
Small, independent fixes for crashes and leaks on reachable paths:

- wayland: gfx_ctx_wl_get_video_size_common dereferenced a NULL output
  when no window output was set and all_outputs was empty. The DnD
  drop handler leaked the received buffer when fmemopen failed, and
  always leaked the line getline allocated.
- drm: drm_plane_setup logged a NULL drmModeGetPlaneResources result
  and then dereferenced it. init_drm read `connector` uninitialised
  when the card reported no connectors.
- uint32s_index (replay statestream): uint32s_bucket_free left the
  freed pointer and length in the bucket. RHMAP_CLEAR keeps value
  slots, so a later RHMAP_PTR on the same slot could see them and free
  the vector again. uint32s_index_pop now also refuses an empty index
  and checks RHMAP_HAS before RHMAP_PTR, which would otherwise create
  a bucket for a missing hash.
- ozone: ozone_context_reset_horizontal_list allocated a node for an
  entry without one but never stored it in the list, so it leaked.
- discord: discord_json_next_strdup leaked the previous string when a
  key repeated.
- core_backup: core_backup_add_entry leaked an empty filename.
- audioworklet, caca, sixel, vga: the init functions leaked their
  struct when the second allocation or the font renderer failed.

Tested on Linux: full build. The touched Linux files show no new
warnings; the C89 build of the Wayland and DRM files fails on this
host in system headers and existing lines, with no diagnostic on a
changed line. drm_gfx.c was compiled although HAVE_PLAIN_DRM is off.
samples/tasks/core_backup passes. The audioworklet, caca, sixel and
vga drivers are not buildable here and were not compiled.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-09-26 16:18:37 +02:00
LibretroAdmin c33b44231e replay: play back a zero-frame recording, halt a pending one, add init/shutdown regression test (#19622)
Follow-up to 368b842. Two more ways the replay state machine could
get stuck, both found by the test added here, plus the test.

1. A recording halted before its first frame produced a file with a
   header and a checkpoint and nothing after it. The player rejected
   it: bsv_movie_reset_playback() reads the first frame's events at
   init, hit EOF, raised BSV_FLAG_MOVIE_END and failed - the same path
   the truncated-file deadlock came from, now landing as "failed to
   load movie file" for a file the recorder itself wrote. Treat it as
   what it is, a replay of zero frames: leave the checkpoint pending
   at init and let the first frame restore it and hit EOF, which ends
   playback through the normal end-of-replay path.

2. movie_stop_record() only looked at the promoted handle. The record
   task installs the handle as next_handle and the run loop promotes
   it on the next frame, so halting from the menu before a frame ran
   (core paused) found no handle, returned false and left the
   RECORDING flag set and the pending handle allocated: the session
   was stuck "recording" and every later Record/Play Replay refused
   until restart. Finish a pending recording like any other; it is a
   recording of zero frames.

samples/tasks/bsv_replay_init: links the shipping tasks/task_movie.c
and input/bsv/bsvmovie.c against a stub core through the real task
queue, intfstream and VFS, in the iOS configuration (HAVE_RZSTD on,
HAVE_STATESTREAM off) the issue was filed against, and mirrors the
run loop's two-line replay protocol. Lanes: record/play round trip
(raw and zstd, core restored to the checkpoint), truncated first
checkpoint (start fails, user told, no MOVIE_END left, nothing pauses,
Close Content clears), zero-frame replay (plays and ends on frame one),
stray MOVIE_END (movie_stop clears it). Against b40db22 the truncated
lane reproduces the report exactly - paused after every frame, carried
across Close Content - and the empty lane fails on both bugs above.
Clean under ASan+UBSan with leak detection. Wired into
Linux-samples-tasks.yml next to bsv_replay_bounds_test.

Not changed: retro_vfs_file_truncate_impl calls ftruncate() with no
fflush() first. The recorder truncates every frame, so this was a
suspect for the reporter's short file, but the preceding
fseek(0, SEEK_CUR) flushes on glibc and BSD libc alike and the round
trip lane cannot make it lose a byte. The origin of the short file on
iOS is still unconfirmed; the new OSD message and the [Replay] log
lines will name the read that came up short.

Signed-off-by: LibretroAdmin <[email protected]>
2026-09-26 01:54:55 +02:00
LibretroAdmin 9516f454b8 The reference Zstandard library goes; the built-in codec is the one
With every platform build on HAVE_RZSTD, HAVE_ZSTD had no user: the
configure option, the deps/zstd tree it built, griffin's inclusion
of it, the Makefile.common objects, the UWP and Android include
paths, and the other branch of every site that could take either
backend - the input replays, the RVZ hashing, the .zst archive and
zip-member readers, the CHD hunk decoder - are gone, and each site
is the one path. Every gate that read 'either backend' reads
HAVE_RZSTD.
2026-09-09 10:55:28 +02:00
libretroadmin 5e4f6232b7 bsvmovie: carve the superblock list and the padded tail block out of one allocation
The checkpoint encoder allocated its superblock index list up front and
a zero-padded copy of the final partial block lazily, freeing both at
the end. They now come out of one zeroed allocation per call, the
padded block behind the list on a 64-byte boundary; it is only written
when the state size is not a multiple of the block size, and the memset
that clears its tail before reuse is kept behind a flag instead of the
former pointer test.
2026-08-29 19:18:33 +02:00
libretroadmin 2e8514e739 rzstd: keep the repeated offsets for the frame, not the block
The encoder declared the three remembered offsets inside its block loop
and set them to the defaults there, so it started every block from
1, 4 and 8.  A decoder carries them across block boundaries within a
frame (3.1.1.5), so from the first repeat code that resolved differently
the two disagreed and the output was wrong.

This arrived with the commit that started naming repeated offsets at
all.  Before that the encoder never emitted a repeat code, so where the
list was reset could not matter.

It took 256 KB to show.  Inputs up to two blocks round-tripped correctly
and the first wrong byte was the first byte of the third block, which is
why three thousand round trips, eight hundred fuzz cases and five
multi-block inputs from 130 KB to 1.2 MB had all passed: none of them
combined enough size with data periodic enough to lean on repeats.  A
512 KB savestate-shaped checkpoint does both, and found it.

A test that round-trips periodic data across block boundaries is added
alongside the others, since nothing existing covered this.

Also in this commit, input/bsv/bsvmovie.c and tasks/task_movie.c learn
HAVE_RZSTD beside HAVE_ZSTD.  Only one of the two is ever active; the
reference path is untouched.  This is not cosmetic: the four platform
build files moved to HAVE_RZSTD last commit, which left the zstd cases
in bsvmovie compiled out entirely - so a replay with Zstandard-compressed
checkpoints would have been refused with "unrecognized compression
scheme" rather than loaded.

Verified: replay-shaped checkpoints of 4 KB, 64 KB and 512 KB round trip;
sizes from 130 KB to 1 MB round trip and are accepted by the reference;
three thousand round trips, forty chunks of real file data and eight
hundred fuzz cases pass; a frame the reference wrote still reads, and a
frame this wrote is still read by the reference.
2026-07-26 20:40:19 +02:00
Joe Osborn 8a8cc448b9 Fix replay seek while recording v2 (#19136)
* bug fixes to checkpoint recording and seekback

When garbage collecting rare datablocks in checkpoints is used to keep
RAM usage down, removing later blocks during seek doesn't work
properly and can cause an infinite loop.  This change correctly
handles GC'd blocks rather than try to remove them again.

* bsvmovie.c: add an intfstream_seek before writing frame data

In 1abde384c8 @amcknight identified a
bug involving rewinding writable streams. This should resolve that
type of issue going forward at the cost of a no-op seek.
2026-06-24 21:45:14 +02:00
Andrew McKnight 1abde384c8 input/bsv: seek after read in replay_get_serialized_data (#19022)
The in-progress recording stream is rewound and read back to embed
in a .state file; per C99 §7.19.5.3, an input op on an update-mode
stream must precede output with a positioning call. Without this
seek, subsequent intfstream_writes from bsv_movie_next_frame
silently no-op, truncating the .replay at the SAVE_STATE.
2026-05-10 11:09:50 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 003a1ff74b input/bsv: bound key_event_count and input_event_count against array size
bsv_movie_handle_read_input_event's read path read attacker-
controlled event counts straight from the .bsv replay file
and used them as loop bounds, indexing into fixed-size
arrays:

  uint8_t   key_event_count;            (.bsv format)
  uint16_t  input_event_count;          (.bsv format)

  bsv_key_data_t   key_events[128];     (struct bsv_movie)
  bsv_input_data_t input_events[512];   (struct bsv_movie)

Pre-this-patch the read loops at lines 822-836 (key) and
848-862 (input) iterated count-times into the fixed-size
arrays with no upper-bound check.  A malformed .bsv could
supply:

  - key_event_count = 255 -> (255-128)*sizeof(bsv_key_data_t)
                         = 1524 bytes of OOB heap-write past
                         key_events[]
  - input_event_count = 65535 ->
                         (65535-512)*sizeof(bsv_input_data_t)
                         = 520184 bytes of OOB heap-write
                         past input_events[]

bsv_movie_t is heap-allocated via calloc in
tasks/task_movie.c::bsv_movie_init_internal so this is a
heap-buffer-overflow with attacker-chosen 8- or 12-byte
payloads at attacker-chosen offsets, producing corruption
of the rest of the bsv_movie_t struct (rewind state,
statestream pointers, save buffers) and far beyond it.

Reachability: the user opens a malformed .bsv file via
Menu -> "Load Replay File" or the --bsvplay command-line
argument.  Same threat class as CDFS / CHD / BPS file-load
bugs -- requires the user to deliberately load attacker-
supplied content.  Initial audit notes flagged this as
netplay-reachable but verification of network/netplay/
netplay_frontend.c shows that netplay's "replay" terminology
refers to internal frame-replay from the netplay ring buffer
and does not invoke the .bsv file-read path; this is a
file-loading bug only.

Fix: in input/bsv/bsvmovie.c, reject the file as malformed
and end playback if either count exceeds its array's
ARRAY_SIZE.  A legitimate writer cannot produce more events
than the array holds because the writer's append path at
lines 489-490 / 475-476 shares the same backing array.

Adds samples/tasks/bsv_replay/bsv_replay_bounds_test as a
regression test, registered in
.github/workflows/Linux-samples-tasks.yml as an ASan-enabled
step.  Four cases covering legitimate counts up to and
including the cap, and out-of-range counts being rejected
without writes.

Test follows the existing samples/tasks pattern (verbatim
copy of the post-fix predicate with maintenance-contract
comment, ASan as the discriminator).  Verified to fire
under ASan when the predicate always returns true:
heap-buffer-overflow WRITE of size 1 at offset 1536 of a
1536-byte allocation in simulate_key_event_read.  With the
predicate the test passes clean.

Note on writer side: the append site at line 489
   movie->input_events[movie->input_event_count++] = data;
has no bound check either, but it's not fed by attacker
data and a single frame is unlikely to produce more than
512 events in practice.  Not addressed by this commit; left
for a separate audit pass.
2026-04-28 03:47:05 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 1fe435a905 bsv, cdfs: free intfstream_t after intfstream_close at five remaining leak sites
Audit pass over every intfstream_close call site in production
code: out of 53 sites, 48 were already followed by free() (the
established libretro-common convention -- intfstream_close
closes the inner backend, the caller owns the struct).  Five
were not, leaking 48 bytes per call.

Five fixed:

  - input/bsv/bsvmovie.c:1315  check_stream  (open_memory)
  - input/bsv/bsvmovie.c:1643  out_stream    (open_writable_memory)
  - input/bsv/bsvmovie.c:1845  read_mem      (open_memory)
  - libretro-common/formats/cdfs/cdfs.c:433  cue_stream  (alloc-fail path)
  - libretro-common/formats/cdfs/cdfs.c:438  cue_stream  (success path)

The bsv leaks are the more interesting set: those code paths
run on every replay verification (check_stream), every
checkpoint encode (out_stream), and every checkpoint decode
(read_mem) -- so during a long netplay session with an active
replay or in checkpointed playback the leak compounds linearly
with elapsed time.  Each instance is small (48 bytes per
intfstream_t struct) but they accumulate.

The cdfs leak is per-cue-file: every time RetroArch parses a
.cue (loading a multi-track CD image, bulk database scan over
a CD library) it leaks 48 bytes.  Both close paths in
cdfs_open_cue_path were affected.

Note on contract: changing intfstream_close to free the struct
itself was considered and rejected.  intfstream_close ships in
libretro-common which is vendored into many cores; cores that
correctly compensate for the existing convention by calling
free() after close (the same pattern this commit standardises
on inside RetroArch itself) would silently double-free under a
contract change.  Fix-the-call-sites is the only safe path.

The 48 already-correct call sites are left as-is.  This commit
is a pure addition of missing free() calls; no behavioural or
cleanup-order changes.
2026-04-28 03:07:55 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 55bd49cefc libretro-db: fix OOM bugs in rmsgpack_dom reader state and query parser
Five related fixes across libretro-db's runtime code (the subset
linked into RetroArch itself - c_converter.c and similar offline
tools are out of scope for this patch).

=== rmsgpack_dom.c: rmsgpack_dom_reader_state_new unchecked callocs ===

    struct rmsgpack_dom_reader_state *s = calloc(1, ...);
    s->i        = 0;          /* NULL-deref on OOM */
    s->capacity = 1024;
    s->growable = true;
    s->stack    = calloc(1024, ...);
    return s;

Both callocs unchecked.  The outer calloc's failure NULL-derefs
on the immediate field writes.  The inner (stack) calloc's
failure is caught later when callers iterate - rmsgpack_dom_read
at line ~422 does 's->stack[0] = out' unconditionally.

Fix: NULL-check the outer calloc and return NULL.  NULL-check
the inner calloc and free the outer struct + return NULL on
failure.  Callers must now tolerate NULL return.

=== rmsgpack_dom.c: rmsgpack_dom_reader_state_free NULL-deref ===

    free(state->stack);     /* NULL-deref if state is NULL */
    free(state);

state could not be NULL pre-patch (construction couldn't fail)
but with reader_state_new now able to return NULL, callers that
defer cleanup (like input/bsv/bsvmovie.c's decompress path)
would hit this free with NULL.

Fix: early return on NULL state.

=== rmsgpack_dom.c: rmsgpack_dom_reader_state_push realloc-assign-self ===

    s->capacity *= 2;
    s->stack     = realloc(s->stack, s->capacity * ...);
    if (!s->stack)
       return -1;

Two stacked bugs:
  1. Classic realloc-assign-self: on OOM s->stack goes NULL,
     leaking the old buffer (the only reference).
  2. 'capacity *= 2' happens BEFORE the realloc, so on failure
     the capacity claimed the new size while the allocation is
     still the old size (or NULL).  The -1 return is checked by
     the direct caller, but the out-of-sync state is a heap-
     buffer-overflow trap if anything later ignored the error
     return.

Fix: realloc-to-tmp.  Compute new_capacity into a local, realloc
into new_stack, commit both only on success.  Preserves the -1
OOM signal semantics.

=== query.c: query_parse_method_call zero-arg false-OOM ===

    invocation->argv = (argi > 0) ? malloc(...) : NULL;

    if (!invocation->argv)
    {
       /* emit 'OOM' error */
       goto clean;
    }

argv is legitimately NULL when argi == 0 (a zero-argument
function call like 'foo()') but the next block treated that as
OOM and raised the 'OOM' error string.

This was a pre-existing logic bug tangentially exposed by OOM
auditing.  The observable symptom pre-patch was that any
genuinely-zero-argument function call would fail query parsing
with a bogus 'OOM' error.

Fix: gate the OOM branch on 'argi > 0 && !invocation->argv'.
Skip the memcpy when argv is NULL (nothing to copy when argi==0).

=== input/bsv/bsvmovie.c: bsv_movie_read_deduped_state consumer ===

    struct rmsgpack_dom_reader_state *reader_state =
       rmsgpack_dom_reader_state_new();
    ...
    rmsgpack_dom_read_with(read_mem, &item, reader_state);

With rmsgpack_dom_reader_state_new now able to return NULL, this
caller needs to NULL-check before passing reader_state into
rmsgpack_dom_read_with (which dereferences it freely).

Fix: early bail to the existing 'exit' cleanup label on NULL.
The cleanup already calls rmsgpack_dom_reader_state_free (now
NULL-tolerant), intfstream_close (already NULL-tolerant), and
sets ret=false, so the user-visible outcome on OOM is the same
as the existing 'malformed frame' error paths.

=== Scope notes ===

Other libretro-db files checked during this pass:
  * bintree.c - the single alloc site at line 35 is already
    NULL-checked.
  * libretrodb.c - two sites at lines 771 (buff in create_index)
    and 831 (cursor_new) both use the NULL-check idiom.
  * rmsgpack.c - zero raw alloc sites.
  * Inner callocs in rmsgpack_dom.c:145 (dom_read_map_start) and
    :173 (dom_read_array_start) use the 'if (!(items = ...))'
    idiom and propagate -1 up the rmsgpack callback chain.

Not in scope (standalone offline utilities, not linked into
RetroArch runtime - see libretro-db/Makefile TARGETS):
  * c_converter.c - 7 alloc sites
  * libretrodb_tool.c
  * rmsgpack_test.c

=== Thread-safety ===

All touched paths run synchronously on whichever thread invoked
the db query.  In practice RetroArch accesses libretro-db from
the main thread (menu content scanning, explore-by-metadata)
and from task threads (background scan).  No shared-state
changes; no lock discipline changes.

=== Reachability ===

  * rmsgpack_dom_reader_state_new/free: the allocating variant
    is only called from input/bsv/bsvmovie.c's STATESTREAM
    decode path, used during savestate runahead on cores that
    support bsv movie recording.
  * rmsgpack_dom_reader_state_push: called recursively while
    parsing deep msgpack maps/arrays inside a libretrodb .rdb
    query result.  Capacity doublings trigger on deeply nested
    data (the default capacity is 1024 for the allocating
    variant, MAX_DEPTH stack-alloca for rmsgpack_dom_read - the
    stack variant sets growable=false so never reaches this
    realloc path).
  * query_parse_method_call: every libretrodb query string
    parse - menu-driven 'Explore' category navigation and any
    core's database-backed metadata lookup.
2026-04-24 02:03:35 +02:00
Joe Osborn fbc972b39e Fix compressed size calculation for the zstd condition (#18420)
There was a variable shadowing issue.

I also fixed a few clang analyzer warnings.
2025-11-19 16:16:44 +01:00
libretroadmin b5e2956a5a Fix uninitialized variable warning 2025-11-18 00:15:48 +01:00
Joe Osborn cf30bc29bb fix -Wshorten64-to-32 warnings in bsvmovie (#18416) 2025-11-17 20:22:42 +01:00
libretroadmin 74c03d26d2 (BSV) Cleanups 2025-11-13 18:55:49 +01:00
libretroadmin 0a253e341f Silence warnings backport 2025-11-11 19:28:40 +01:00
libretroadmin c2d5bd57f7 C89_BUILD fixes 2025-11-10 19:28:21 +01:00
libretroadmin 7ad9852bc5 More CXX_BUILD fixes 2025-11-10 19:09:44 +01:00
libretroadmin 2526b375e7 More CXX_BUILD buildfixes 2025-11-10 19:03:03 +01:00
libretroadmin 16025e51b8 C89_BUILD buildfixes
CXX_BUILD buildfixes
Fix for conflicting types in uncompress prototype
2025-11-10 18:52:42 +01:00
Joe Osborn 1fb62ff4ac fix v0 replay sync and a crash that occurs at the end of playback (#18347) 2025-11-04 08:52:14 +01:00
Joe Osborn ff7b84ba5a Improve backwards scanning to skip no more than one checkpoint (#18328) 2025-11-04 08:51:54 +01:00
Joe Osborn 3c7cd3511c Maybe make bsvmovie more tolerant of msgpack encoding (#18342) 2025-11-04 08:51:13 +01:00
libretroadmin b3a2f802b9 Remove unused variables/warnings 2025-10-12 20:31:56 +02:00
Joe Osborn e416cfb763 Fix an off-by-one error in replay checkpoint loading. (#18261)
The issue is that a replay frame read on core frame K stores the
inputs for frame K along with the core state as of *the end of frame
K*, in other words the beginning of frame K+1. To fix it, and to make
sure existing replays play back properly, the `core_unserialize` call
in bsvmovie.c has been deferred to the following invocation of
`bsv_movie_read_next_events`, so that frame K+1 is deserialized just
before reading the inputs for frame K+1.

Some refactoring has also been done to simplify the number and timing
of calls to bsv_movie functions from runloop.c.
2025-09-16 19:57:12 +02:00
Joe Osborn fa42321488 Seek backwards/forwards in replays by checkpoint (#18238)
* Add save checkpoint, prev/next checkpoint commands and hotkeys

* Fix copy paste error in meta binds

* Implement save_replay_checkpoint command

* Implement prev/next checkpoint commands

* Update per @jamiras review

* add command to seek to a specific frame number

* Add message queue toasts for seek forward/back

* Fix basis for seek, produce full message on reply

* fix bugs seeking back during record

* Tidy up

* Allow back and forwards seeking of recording replays while paused

* Update changelog
2025-09-09 07:53:08 +02:00