Commit Graph
881 Commits
Author SHA1 Message Date
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 45c64b3c73 Fix clang warnings in the Windows build
The Win64 build's -Wshorten-64-to-32 narrowings are made explicit where
the value is bounded: socket()/accept() handles kept as RetroArch's int
descriptors, ai_addrlen passed as socklen_t, UDP and pipe lengths,
COM/D3D counts and shader frame counters, WASAPI/XAudio2 buffer sizes.
net_socket clamps each send/recv to Winsock's int count on _WIN32 and
lets the existing loops move the rest; the remote-input descriptors are
plain ints on every platform, as socket_init returns them.

xaudio29.h declares its interfaces through a macro that, in C, leaves
out DECLARE_INTERFACE's second typedef of the forward-declared names.
2026-11-08 20:17:34 +01:00
LibretroAdmin 4bead9073a netplay: one CRC check for both paths, decided anew after each state load
A client compares the host's CRC for a frame either when it arrives or
once the client reaches that frame, and both now go through one check.
The first check at or after a state loaded from the host decides
whether this core's CRCs can be compared: that state is the host's, so
a mismatch there turns desync checks off with a warning, as a core
whose states carry a timestamp needs. Any later mismatch asks for the
host's state. A client logs each state it loads from the host.

samples/network/netplay_e2e gains a rollback desync lane with input
latency, so some checks wait for the client to reach their frame, and
a lane whose core states never hash alike between peers, which must
stop at one resync past the join with its checks turned off.
NETPLAY_E2E_JUNK puts a per-peer serialize count in the test core's
state.
2026-10-28 06:53:39 +01:00
LibretroAdmin b9c0d2796b netplay: run on from a resync state that arrived past the next frame
A client behind a lockstep host can be handed a state labeled with a
frame it has not reached yet, and when that state is read after the
frame has advanced the forced rewind loads it one frame past run. The
rewind now makes the state's frame the one run next, so the client
never runs an earlier frame's input on top of the host's state and
the resync actually mends the desync.

samples/network/netplay_e2e gains a lane where the client runs slower
than the host and has its RAM upset, and NETPLAY_E2E_PACE_MS to set a
peer's pace.
2026-10-27 20:47:59 +01:00
LibretroAdmin 5361e1bc8f netplay: lockstep for cores whose states are too large to roll back
Rollback keeps a savestate for every buffered frame and serializes every
frame, which a state in the tens of megabytes (Dolphin) cannot afford,
and needs states that restore deterministically enough to rewind on.

Lockstep runs a frame only once every player's real input for it has
arrived and never rewinds, so all delta frames share one state, used
only to hand a joiner the game or to resync. Desync checks hash the
core's system RAM, or the RAM in its memory map, rather than a whole
state; a state is serialized for them only when the core shows neither.
Input latency rises by a frame whenever lockstep has to wait and falls
again once input keeps arriving early, so it holds full speed over a
slow link. A host keeps sending while it waits on a joiner, grows its
buffers if the core's state has grown, and starts on the running game
instead of reloading it. A client takes a state labeled with a frame
whose input it already has, and loads it there.

Lockstep is a local choice and plays with rollback peers of this
protocol, and it is on by itself for cores past 32 MB of state and for
cores whose savestates load but cannot be rewound on, which netplay
used to refuse. The Lockstep setting asks for it everywhere. Older
clients cannot join a lockstep host.

samples/network/netplay_e2e runs a host and a client over the loopback
on a test core: sticks synced or not, lockstep, a lockstep host with a
rollback client, a desync mended and a 40 MB state.
2026-10-27 19:50:48 +01:00
LibretroAdmin a0d408f0ce netplay: sync the analog sticks of joypad ports
Netplay sent a joypad port's buttons only, so a core reading the sticks
of a joypad port (N64, GameCube and others) desynced or saw them at
rest on every remote player. The host now sends joypad ports as analog,
three words instead of one, with bit 30 marking them; each side hands
the core the joypad device it set, so nothing changes for the core.

This is protocol 8. A host with Sync Analog Sticks on, the default,
turns away older clients with the out-of-date message rather than
letting them desync; with it off, any version still joins.
2026-10-27 19:08:12 +01:00
Codex b7436d8ffc Netplay: finish host setup when relay lookup fails
Resume direct hosting after an empty relay response or timeout instead of deferring another lookup. Cover failure, retry, success, deadline and cancellation through the shipping decision functions.
2026-10-26 02:05:24 +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 4eb537eff4 netplay: no bit for a slave's own input, bound core input queries
Real-client masks are built by one helper that skips the slave's own
input, filed under MAX_CLIENTS, so no shift reaches 32. The remaining
client-number masks shift unsigned.

A core's input query reads only the words its device's state carries:
analog sticks by index 0..1 and axis 0..1, analog buttons as their
digital bit at full pressure, joypad and pointer bits below 32, and
keyboard words below the state's size; anything else reads 0.

samples/network/netplay_input covers both helpers.
2026-10-15 23:35:18 +02:00
Anthony Schemel 6dd959ea8d input, netplay: shift unsigned where the bit can be 31
1 << n on an int is undefined when n is 31. Netplay's loops over
MAX_CLIENTS (32) and its input-share loops over 32 bits reach it; the
masks they build are uint32_t, so its variable shifts become 1U << n.

turbo_pressed kept its 'turbo held' flag in the sign bit of an int32_t,
set with 1 << 31 and tested with >= 0. It is now uint32_t, the flag is
1U << 31, and the test reads that bit.

Closes #19837
2026-10-15 23:35:17 +02:00
Acts1631 d3b50802c2 cheevos: bound progress deserialization to supplied state data (#19692) 2026-10-09 10:28:21 +02:00
LibretroAdmin aafec5221f input: settings, netplay and three tasks ask the frontend by name
Outside the frontend's top level and the replay code, five files
still took the input state for a field or two. Each asks by name now:

- netplay switches non-blocking input for catching up
  (input_driver_set_nonblocking()) and asks whether the core's input
  is blocked (input_driver_libretro_input_blocked(), which was there);
- configuration.c marks the remap cache active
  (input_driver_set_remapping_cache_active()), saves and restores the
  devices' names around a configuration swap
  (input_driver_device_info_save(), _restore()), and resets and fills
  a port's sensor axis map through input_driver_set_sensor_map() -
  the map is built whole and set in one call. The getter,
  input_config_get_sensor_map(), moves to input_driver.c;
- the autoconfig task asks a port's display name
  (input_config_get_device_display_name(), which was there);
- the overlay task asks where the eight-way slopes are kept
  (input_driver_overlay_eightway_slopes());
- the AI service presses and reads its buttons
  (input_driver_ai_gamepad_press(), _pressed()).

What is left outside input/ is the frontend's top level (retroarch.c,
runloop.c) and the replay code being handed the state by the commands,
the save-state and movie tasks and rewind.
tools/input_state_grab_check.py now counts tasks/, network/,
command.c, configuration.c and state_manager.c too, with that list.

The overlay task's sample stubs the slopes call instead of the input
state. The AI service and netplay paths are syntax-checked with their
features on, as the Linux build leaves them out; the harness passes.
2026-10-05 08:06:19 +02:00
LibretroAdmin 71318ef1ec Fix build warnings on old GCC, uClibc and old wayland-scanner
Statics rely on implicit zero initialisation instead of {0}, and local
aggregates whose first member is an array get the matching braces, so
GCC 4.x -Wmissing-braces stays quiet. Locals the compiler cannot prove
written are initialised (rh265 keep[], rflac block header, query.c
lengths), loops older VRP misreads are reshaped, the unused SDL2
geometry forward declaration is gone, and task_queue no longer names a
variable main.

rzstd probes BMI2 with __get_cpuid_max/__cpuid_count, which every
cpuid.h the branch accepts provides. Hole punching needs uClibc-ng 1.0
with its Linux-specific API on uClibc. The sinc resampler's pop_options
does not warn on GCC 4.x MIPS. generate_wayland_protos.sh strips the
event type and deprecated-since attributes for scanners whose DTD
predates them, which ignore them anyway.
2026-10-04 04:23:50 +02:00
LibretroAdmin 2a1b412a3f netplay: drop core packets from non-playing clients instead of NAKing
The server answered NETPLAY_CMD_NETPACKET from a client that is not
playing with a NAK, which closes the connection. A client reaches that
state without misbehaving: it calls the core's netpacket start() at the
end of the handshake while still a spectator and only then asks to
play, so an older client whose core sends from start() or in the frames
before its promotion lands, or a client set to start as a spectator,
was disconnected.

Read the packet off the stream as before, then drop it without passing
it to the core or relaying it, so spectators still cannot reach core
packet parsers but stay connected. Logged at debug level, since a
spectator's core may send every frame.
2026-10-01 23:58:56 +02:00
Acts1631 e8c6c72cdb netplay: restrict core packets to playing clients
The server accepts NETPLAY_CMD_NETPACKET from connected spectators,
including clients authenticated with a spectator-only password. It
forwards their payloads to the core or other players, exposing core
packet parsers to unauthorized input.

Reject packets from non-playing clients before dispatch and prevent
spectator clients from sending core packets. Leave client reception
unchanged because cores can send during player admission before the
mode change reaches the client.
2026-10-01 23:38:43 +02:00
libretroadmin 280094adb9 netplay: the password salt from the entropy source; hashes compared in constant time
The password challenge salt came from an LCG seeded with time(NULL):
anyone who saw one salt could predict every later one. It now comes from
crypto_random_bytes(), the platform entropy source on Windows, UWP,
POSIX and the 3DS, Vita and Switch; builds without the crypto library,
or a platform without a source, keep the LCG seeded from the
microsecond clock and the connection's address. The client's password
hash is compared with crypto_memeq_ct() rather than memcmp(), whose
early exit told how much of it matched. The salt travels in the same
field, so older clients are unaffected. As found in #19649.
2026-10-01 04:53:35 +02:00
LibretroAdmin 1fda0518ef netplay: the deferred host setup frees its state
The task carrying the deferral's deadline had no cleanup, so its
state leaked once setup ran; LeakSanitizer on the content_load
harness's host-setup lane reports it.
2026-09-30 04:43:19 +02:00
LibretroAdmin 38c605ae44 netplay: host setup waits for the relay query from the frame loop
Hosting through a lobby relay needs the relay's address, and host
setup waited for the lobby's answer inside CMD_EVENT_NETPLAY_INIT - up
to ten seconds on a slow lobby.  When the query is still out, the
command now puts host setup off to a main-thread task that checks each
frame and reissues CMD_EVENT_NETPLAY_INIT once the answer is in, or
goes direct once the bound has passed; the frame loop keeps running.
netplay_mitm_query no longer waits at all.

The room reset at the start of host setup also cleared an answer
already in hand, so the prefetched query was asked - and waited for -
again every time; the answer is now carried across the reset.

content_load harness lane: with a relay configured and the query out,
the command returns in microseconds with host setup queued, frames
keep presenting, and setup runs once the query settles.
2026-09-30 04:16:57 +02:00
Acts1631 9a19e7a94d netplay: validate assigned client number before use
A host can send an out-of-range client number in SYNC and later grant
play mode, causing the client to write past fixed per-client arrays.

Reject invalid assigned numbers during SYNC and require MODE/YOU
updates to name the assigned client.
2026-09-28 01:38:29 +02:00
Acts1631 7a39d86aa4 netplay: bound remote savestate size (#19614)
LOAD_SAVESTATE carries a peer-controlled output size. The client used it
to grow and zero every rollback buffer before checking decompression,
letting a remote host request excessive memory with a small packet.

Bound output size to the fixed per-session zbuffer limit before any
rollback buffer is resized.
2026-09-26 18:02:23 +02:00
libretroadmin ad6af1eb8d netplay: carry the session's bools in one flag word
struct netplay keeps its fourteen boolean states - server or client,
CRC checking, pausing, replay and catch-up, the forced rewind, reset
and savestate send, and the host settings - as bits of one uint16_t,
enum netplay_flags, rather than as separate bools. Conditions test the
bit; the one value sent to peers, whether pausing is allowed, is
converted to 1 or 0 before it goes on the wire.
2026-09-25 19:00:57 +02:00
LibretroAdmin 7673d8a171 gfx: the quad, the cursor and the keyboard take their sizes as words
gfx_display_draw_quad carried three width/height pairs in one
signature and two of them were output sizes with nothing in the names
to tell them apart: video_width/video_height went to the driver, and
width/height was the space the quad's coordinates are measured
against, which the body divides x and w by and flips y against. They
are video_dims and ref_dims now, and the quad's own w/h is dims.

At 133 of the 141 call sites the two are the same value passed twice.
The eight where they are not are the ones the names were hiding: the
menu screensaver measures against its own last size, and four draws in
xmb measure against the view rather than the window.

draw_cursor and draw_keyboard take the output size as a word with it,
which is the shape draw_texture_slice and the scissor calls already
had.

The line count is the argument lists: a pair that took two lines takes
one, so eighteen files lose 837 lines and gain 558.

Full matrix clean, the menu drivers and widgets under mingw, a C89 pass
over every file touched, and call_arity_check at its baseline.
2026-09-22 20:42:22 +02:00
LibretroAdmin b8093d23d1 gfx: the widget frame path takes the size word
gfx_widgets_iterate, iterate_layout, the per-widget iterate callback,
gfx_widgets_draw_text and gfx_widgets_flush_text all carry the output
size as one word. The two scale caches compare one word, and the layout
check compares against last_video_dims directly.
2026-09-22 19:22:43 +02:00
LibretroAdmin b4d16d67bc video: the frame info's output size travels as one word
video_frame_info_t::dims carries both axes beside the scale_dims and
custom_vp_dims words already there, and the two writers hand over the
packed word they already held. The widget tick takes it straight
through; the netplay widgets read their axes once into locals.
2026-09-22 18:30:43 +02:00
Davey HughesandLibretroAdmin e94fb63134 Fix WSOLA fastforward crackle (#19554)
* audio: average the 1.0x flush interval in the fast-forward estimate

The speed estimate divided a sixteen-flush average of the flush interval
by the interval this flush's audio takes at 1.0x. Cores whose batch size
varies from flush to flush - mupen64plus_next alternates 185 and 551
frames - then get a multiplier that swings with the batch size, and the
pitch-preserving stretch runs some 6% short of real time, opening gaps in
every long fast-forward hold.

Average the expected interval the same way, so the ratio compares like
with like. The integer average of the measured interval is kept as it is;
the threaded producer's harness depends on its rounding.

* audio: seed the fast-forward speed estimate at the configured ratio

The first flush of a hold seeded the estimate at 1.0x, and the average
took some fifty flushes to reach the real speed. The frame limiter has the
core at the configured ratio within a frame, so for that long the audio
was compressed too little and ran up to three times real time into a
device the blocking 1x writes had left full. With the non-blocking driver
fast-forward uses, 100-250 ms was dropped at every press, and a 150 ms
hold lost more audio than plain discard does.

Seed at the fast-forward ratio and return its multiplier at once; the
measured speed takes over from there. An uncapped ratio still starts at
1.0x. Measured with 150 ms presses at 3x: 4.0 s dropped in 12.8 s of
fast-forward became 0.06 s on OoT, 5.7 s became 0.05 s on FF7.

* audio: let pitch preservation follow fast-forward speed on its own

Pitch-Preserving Speed Changes only measured the fast-forward speed when
Fast-Forward Audio Speedup was on; with it off the stretch stayed at unity
and the flush fell back to discarding samples, so the setting appeared to
do nothing for fast-forward.

Follow the measured speed when Speedup asks for it or when pitch
preservation owns the transport, on both pipelines. The filter-only
transport keeps the Speedup-or-discard behaviour, since it has no way to
hold pitch.

* audio: widen the WSOLA search to four hops

The similarity search reached half a hop either side of the nominal
position: 64 samples at 48 kHz. A splice can only land on matching phase
if the search reaches a full period, so nothing below about 375 Hz was
being preserved. At 3x a 55 Hz tone came out at 165 Hz with 98% amplitude
modulation, 110 Hz at 143 Hz, 220 Hz at 285 Hz; 440 Hz and up were clean.
Bass lines and low mids in a game's music were transposed and wobbling
while the rest kept its pitch.

Four hops (512 samples at 48 kHz) cover fundamentals down to about 47 Hz
and keep every test tone within 6% of steady amplitude. The search costs
four times as much correlation, under 1% of a desktop core at 3x, and the
ring and its retained lookahead grow with the radius: the harness bounds,
drain scenarios and README figures follow.

* audio: keep the inline stretch active at unity once it has started

The inline transport returned to raw copying whenever the speed came
back to 1.0x. Leaving the engine drains the source lookahead its search
kept, up to twice the radius, as one flush onto a device the hold left
full, and with the VRR runloop's non-blocking frames after a release most
of it is dropped: 2-4 ms per release at the old radius, 10-40 ms at four
hops. The next engage then pauses output while the lookahead fills
again. Leaving the lookahead behind instead shorts the device by as much
and rapid presses run it dry.

Once the engine has started, keep it active at unity. Unity synthesis
lands every splice on its own continuation, or a period of it in a
stationary passage, so the audio passes through all but unchanged; the
cost is the lookahead as holdback, 16 ms at 48 kHz, from the first speed
change until the transport is reset. Measured with 150 ms presses at 3x:
0.5 s dropped per 40 presses became 7 ms.

* audio: end the stream on a ramp at a pause, and bring it back on one

Opening the menu pauses the core, and the audio stream ended wherever
the waveform happened to be: a step at both ends, heard as a click. And
between the last write of the pause and the first of resumed core audio
the runloop hands nothing over, ~33 ms with the menu, so the device
drains through the hole and rate control refills it at half a percent
of real time: PipeWire's pulls came up short for seconds after every
close, 10-48 ms of fabricated silence after a single close and 50-138 ms
per close when tapping the menu key, which is heard as a crackle.

Every frame has already gone to the device by the time the pause is
known, so a plain ramp has only the last sample to decay. Keep a copy of
the last frames of output instead, find the period that best matches the
last few milliseconds, and repeat it under a raised cosine, as a packet-
loss concealer does. The period is scored by distance, since correlation
is blind to level. The tail is written straight to the device under the
state lock, ahead of what the resampler and the stretch still hold:
pause_mute_frames drops the resampler's leftovers, and the inline
stretch is reset so its lookahead does not come out behind the tail.

The ramp back up is owed to the core's first audio after the resume,
not to the menu's silence in between, so every publish says whether it
is the core's own and the ramp is armed on the first that is. The same
flush first fills the device with silence up to write_avail(): silence
is free, the device has been playing it, and the surplus is what rate
control already takes out. It has to be the first flush rather than the
resume itself, since a top-up at the resume is undone by a pull landing
inside the hole.

A core with its own audio thread kept handing frames over after the
tail, since menu_pause_libretro never sets RUNLOOP_FLAG_PAUSED.
audio_driver_pause_fade() publishes core_silenced, which gates the
core's input paths and only those.

Under the threaded pipeline the ring behind the tail still held frames
of the core's audio, and the stretch stage its lookahead. The pause
records the ring's head, and the consumer takes the ring out up to it
and drops what the stage holds; the resume marks where the core's audio
starts, and the consumer never takes a chunk across that point and arms
the ramp on reaching it.

The ramp hangs off retroarch_menu_running() and its finished
counterpart, which the menu hotkey reaches where CMD_EVENT_MENU_TOGGLE
does not, and follows what the runloop will do rather than the setting
alone: under netplay the core keeps running behind the menu. The pause
hotkey, the setting toggled from inside the menu, an audio reinit while
held, the paused rewind step, the BSV checkpoint seek and a netplay
session starting or ending behind the menu go through the same call.
write_raw drivers get the resume ramp and the mute but no tail: they
hand the driver the core's buffer at the input rate, so there is nothing
at the output rate to keep as history.

Measured headless against PipeWire, with 8 toggles of 1.5 s and 12 of
0.3 s on mupen64plus_next and swanstation: the RMS of the 3 ms at each
edge against the 15-25 ms beside it went from 1.0 (a hard cut) to 0.1
(the ramp) at both edges, and the silence fabricated across a run from
64-285 ms to none, on the inline and the threaded pipeline.

* audio: bracket the frontend's state jumps with the pause fade

Loading a state splices the game's own audio, and the frontend does the
splicing on top of a device that may already have run dry: the undo
backup and the core's unserialize both run on the main thread inside the
load task's callback, for a main-loop gap that can exceed the device's
buffer on a large state.

Use the pause tail and the resume ramp the menu already uses, so the
splice and whatever gap the stall leaves both land in silence. The other
three ways the frontend throws the game's audio away mid-waveform get
the same bracket: a core reset re-initialises the machine, an undo pays
the same two serialisations as the load it is undoing, and a load from
the RAM slot is a load. All run on the thread that would otherwise be
feeding the device.

audio_driver_jump_fade_begin/_end name the bracket rather than repeating
its invariant at four call sites - the stream may already be down,
because the jump was made from the menu or while paused, and then the
ramp back up has to stay with whatever took it down.

core_reset() is bracketed at the CMD_EVENT_RESET site rather than inside
it, so netplay's own reset path is untouched.

* runloop: publish the audio snapshot before the frame runs

The snapshot the audio producers read is refreshed at frame end, after
retro_run(), while the runloop flips fast-forward, slow motion and pause
before it. The first frame after every toggle flushed on the previous
state: at a fast-forward press, a full 1x block into a device already
non-blocking and full, 7 ms refused per press.

* audio: wait for device room on the pitch-preserving path

Fast-forward writes the device without blocking, and a write the ring
cannot take is cut short. The discard path means to lose the rest; the
pitch-preserving stream is continuous, so the cut is a gap. At 1x the
blocking writes leave the ring at the brim, and the first stretch output
after a press lands before the device has pulled again: 3-9 ms refused at
every press that follows a second or more at 1x, heard as a click.

Complete a short write with one blocking write for the remainder, on the
inline pitch-preserving path only; the wait is bounded by the remainder.
Measured on the desktop over nine presses: 0 ms lost, 84 ms recovered.

* audio: the fast-forward seed reads the published ratio

The seed of the speed estimate read the fastmotion override and the
fast-forward ratio setting inside the flush - the submit path, which
is the audio thread when the core owns its audio callback, and the
override is rewritten by the environment call at exactly the moments
the seed fires. The publisher resolves the override against the
setting where both belong to the main thread and publishes the result
as a float bit pattern beside the slowmotion ratio; the seed reads
that, and the ratio-seed fixtures publish after setting the ratio,
as fixtures do for everything the audio side consults.

* samples: the pause fade holds its promises under test

The inline half in ff_speedup: the pause tail opens where the stream
stopped and only the join correction can carry that level - the
fixture's history steps 0.3 above its cycles at the end, the way real
content moves - the envelope only decays and reaches silence, keeps
the waveform's pitch, and fits the room a full non-blocking device
has left; the mute drops the resampler's leftovers; the resume ramp
waits for the core's first audio, opens from silence, stands halfway
at its middle and hands over at full level; the jump bracket leaves a
stream someone else took down alone. The test object now depends on
the audio_driver.c it includes: without that an edited driver leaves
a stale binary that silently keeps passing.

The threaded half in pipeline_wakeups, as check-pause: through the
wrapper's parked control transactions the pause lands with the ring
provably holding unplayed source, and the device tap shows none of it
is ever played while the resumed stream reaches the device under the
ramp, opening below 2% of its level and climbing. Sequenced against
the real consumer thread and clean under TSan; the load sweep's
conversion-volume assertion stays with the load sweep.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-09-15 13:21:19 +02:00
libretroadmin 99d852a93b gfx_widgets: the menu state a widget iterate reads travels with the frame
The netplay ping widget asked the menu whether it was open, from
gfx_widget_netplay_ping_iterate(), which the threaded wrapper runs on
the video thread. The menu's flags are a read-modify-write on the main
thread - runloop_check_state() clears two of them in the same
expression - so the read raced the write, on a word the whole menu
keeps its state in.

The frame already carries those flags: video_driver_frame() copies them
where the menu cannot be changing. The worker latches that copy before
it iterates, and the widget reads the latch.

Found with networking on. The threaded video suites had been run
against a build configured without it, so the file this lives in was
never compiled and the widget never ran.
2026-09-13 15:23:36 +02:00
libretroadmin 436d4408ed netplay_nsnetservice: the discovery snapshot is released by the method holding it
-finishBrowsing: copies the browser's service array so it can enumerate
it without racing the delegate callbacks that mutate the live one, and
-copy hands back a reference the method owns. It runs on the task
worker, which has no autorelease pool, so the snapshot is released
where it is finished with rather than handed to a pool that is not
there. A discovery scan no longer leaves the array behind.

The two allocation failures inside the enumeration leave the loop
instead of the method, so the release sits on the one path out.
2026-09-13 08:52:34 +02:00
libretroadmin 42f62daa8a netplay_nsnetservice: the Bonjour TXT record owns what it is handed once
The methods behind -TXTdataFromNetplay: hand their NSData straight to a
dictionary literal, which retains it, so each one autoreleases the
reference its allocation carries. Nine of the ten did not, and that
record is rebuilt on every announce, so a session left publishing
accumulated them. -content_crc and -frontend already returned data the
pool owns and are the shape the rest now follow.

The NSNetService and NSNetServiceBrowser stored in the strong service
and browser properties release their own reference once the property
holds them, for the same reason. RARCH_RELEASE and RARCH_AUTORELEASE
carry the ownership rather than bare messages, so the file reads the
same way under ARC, where they compile to nothing.
2026-09-13 08:50:21 +02:00
Rob Loach 559962cae0 SDL3: Fix On-Screen Keyboard, opt-in for System Keyboard (#19389)
* sdl3: Add On-Screen Keyboard Input

See this thread for all the details
https://github.com/libretro/RetroArch/pull/19389
2026-09-11 12:16:34 +02:00
LibretroAdmin 487726ae22 Open files that are CRC'd whole with FREQUENT_ACCESS
ac368f4 taught intfstream_crc_step() to fold the checksum straight
out of the VFS's mapping when the file was opened with
RETRO_VFS_FILE_ACCESS_HINT_FREQUENT_ACCESS, and bade0b7 moved the
content scanner onto it.  The other places that open a file only to
hash all of it were still HINT_NONE: the core updater's sliced CRC
of the installed core, the core backup and restore CRCs of the
backup file, and netplay's CRC of the content at session start.
Same hint at all four; where the VFS cannot map (a URL scheme, a
huge file on a 32-bit host) it is a hint and the read path is what
it was.

Compiled through the real build rule; core_crc_slice_test and
core_backup_io_test pass under ASan.
2026-09-11 03:48:35 +02:00
LibretroAdmin bb346a25ec (Audio) A float core's rewind buffer is float, and netplay gates its batch entry
The reverse buffer for a float core holds its frames as it gave them
and plays them back as float: no conversion in, none out, and the
rewound audio is not quantised. The recorder still takes int16, from
the same staging as the forward path, converted only while it
records. Netplay intercepts the int16 callbacks by swapping them; the
float batch entry the core holds by pointer cannot be swapped, so it
asks a gate netplay sets - the same skip as the int16 batch, for a
replayed frame during rollback or a stall - and drops the audio the
same way.
2026-09-09 06:30:30 +02:00
libretroadmin 2016641e24 netplay: stop the savestate container walk at the END block
Every netplay state buffer is state_size bytes, budgeted for the
largest container this side can build, but the container written
into it is usually shorter: a client builds without the ACHV block,
and a peer's state can be a different size again. The block walk in
netplay_process_savestate1 and netplay_get_savestate_coremem ran to
the end of the buffer instead of the END block, so once a slot had
held a server state (rcheevos data) or been grown by realloc, the
walk read the stale tail as block headers. A header byte with the
top bit set went through 'input[7] << 24' as int, sign-extended
into the size_t step, and wrapped the cursor to a wild address;
that is the client-side SIGSEGV in netplay_sync_input_post_frame
reported since 1.21, with the faulting address of the form
0xf963241f.

Read the size field through uint32_t, stop at END, reject a block
whose padded size does not fit before stepping over it, and return
NULL from the coremem lookup for a malformed container so the CRC
path reports a mismatch (which requests a fresh state) instead of
hashing past the buffer. The ACHV reader stepped the cursor an extra
8 bytes past the flags word, and the writer stepped by the unpadded
cheevos size, so the END header did not sit where a walk that stops
at END looks for it; both now use the padded block size. Grown
buffers get their new tail zeroed.

Fixes #17858
2026-09-08 01:47:01 +02:00
LibretroAdmin b12d1d0684 strl: include compat/strl.h where strlcpy_lit() is used
The literal conversion left 39 files calling strlcpy_lit() without
including the header that declares it. They built anyway: the files were
already calling strlcpy() without including compat/strl.h either, and on
glibc 2.38 and later that resolves to the C library's own strlcpy(), so
nothing ever forced the include. strlcpy_lit() has no such fallback --
it is an implicit declaration that compiles and then fails to link.

RetroArch itself did not notice, because its translation units pull the
header in through something else. The standalone samples do not, and
samples/tasks/database is where it surfaced:

  scan_begin_budget_test.c: undefined reference to `strlcpy_lit'

Adding the include to each of them fixes that and removes the reliance
on the accidental libc fallback for strlcpy() at the same time.

Checked by building every sample rather than the one that failed: 42
under samples/, 38 under libretro-common/samples and libretro-db/samples,
with libxrandr, libdrm and libvulkan headers installed so the X11, KMS
and Vulkan ones actually compile instead of being skipped. All build
except samples/gfx/font_lifecycle, which fails identically on a clean
tree (undefined reference to video_driver_thread_wrapper_active in its
HAVE_THREADS variant) and is unrelated.

The sample binaries were run as their workflows run them, including
"make fixtures" for gfx_thumbnail_preview and a long enough timeout for
the 1000000-iteration SPSC stress in gfx_thumbnail_status_atomic: all
pass. samples/tasks/database builds, passes "test -x database_task" and
exits 1 with its usage line, which is what the smoke step expects.
2026-08-30 02:53:03 +02:00
LibretroAdmin b9be38fd55 strl: copy string literals without scanning them at runtime
strlcpy() begins with strlen() of its source. It lives in another
translation unit, so with no LTO that scan happens at runtime even when
the source is a literal whose length the compiler already measured, and
the call itself cannot be folded away either.

strlcpy_lit() passes the length over as sizeof(). When the destination
size is also a constant -- sizeof(buf), the usual case -- nothing is
left but the stores memcpy() compiles to:

  strlcpy      "core_options"  sizeof(buf)   7.01 ns
  strlcpy_lit  "core_options"  sizeof(buf)   0.42 ns
  strlcpy      41-char literal sizeof(buf)   7.74 ns
  strlcpy_lit  41-char literal sizeof(buf)   0.71 ns
  strlcpy      "core_options"  runtime len   7.11 ns
  strlcpy_lit  "core_options"  runtime len   0.70 ns

The destination bound is kept. When the literal does not fit it defers
to strlcpy(), so the copy truncates as before rather than overrunning;
a form that took only the literal would have turned every one of these
sites into an overflow waiting for a small buffer. The literal is
concatenated with "" so a non-literal source is a compile error rather
than a sizeof() that silently measures a pointer.

818 sites across 104 files were converted by parsing arguments rather
than by pattern-matching text: only a three-argument call whose second
argument is a bare string literal is rewritten, so a macro that happens
to expand to a literal is left alone. Line endings are preserved, so
the CRLF files carry only their own changed lines.

test/compat/test_strl.c compares the two against each other over every
destination size from 0 past the literal's length, for literals that
are empty, single-character, path-shaped, adjacently concatenated and
escape-bearing, checking the return, the terminator and the whole
buffer so an overrun past the terminator is caught. ASan+UBSan+LSan and
TSan both 4/4. The full menu_displaylist_build_list walk over every
displaylist type is byte-identical to before the change
(md5 a2a081bcac09cdc8d72d67efd14ac40e).
2026-08-30 02:10:20 +02:00
libretroadmin 83e6ab9545 netplay: do not announce a pause a server has forbidden
A server running with pausing disabled answers NETPLAY_CMD_PAUSE from a
client with a NAK and hangs the connection up, and the client sent that
command for any frontend pause at all. Pushing the Quick Menu parks the
runloop for a single frame, which is the path both opening the menu and
opening the chat prompt take, so a client on such a server lost the
connection the instant it opened either.

A client whose server disallows pausing now keeps the announcement to
itself. Its local_paused stays clear with it, so the resume that
netplay_pre_frame would send off the back of the pause is suppressed in
the same stroke, and a server that permits pausing still receives the
command exactly as before.

Fixes #19028
2026-08-26 16:36:01 +02:00
LibretroAdminandLibretroAdmin 334e8b7baf UI non-blocking, part 3: netplay host init and content close (#19417)
* netplay: bound the wait for tunnel information

Stage 1 of making netplay host init non-blocking: the hang becomes an
error, with no new states and no restructuring.

Hosting through a relay waits for the lobby server to answer with a
tunnel address.  The wait was already narrowed to that one query, but
it was still unbounded - and it is a round trip to a machine we do
not control.  A lobby server that is down, blackholed or merely slow
left the frontend hung with no way out but killing it.  It now gives
up after ten seconds and reports failure like any other query, so the
caller falls back to direct mode with the warning it already has.
Generous on purpose: timing out a query that would have succeeded
costs the user their session, while waiting a few seconds longer
costs only patience.

task_queue_wait_timeout() is the bound.  It wraps the caller's
condition in one that also goes false at a deadline and hands that to
the existing wait, so every queue implementation - regular, threaded
and GCD - keeps its own waiting behaviour and no platform-specific
code is touched.  Adding a variant to the implementation vtable would
have meant editing the GCD path blind, which is the shape of a recent
break and not worth repeating for this.

A timeout alone would have been a bug, not a fix.  The query is still
in flight when we give up, and its callback writes
host_room->mitm_address and mitm_port unconditionally - so it would
land after the fallback and publish a tunnel address for a session
running direct.  Each query now carries a generation token and the
callback ignores results that are no longer current; abandoning a
query bumps the generation.  That also closes the pre-existing case
of two queries overlapping.

The oracle covers the primitive rather than netplay's HTTP, because
that is where the risk is: the netplay side is a few lines routing
into an else branch that already existed.  Five lanes over both queue
implementations assert that a satisfiable wait returns as soon as it
is satisfied - not after sitting out the timeout, which would pass a
naive check - and that an unsatisfiable one gives up near the
deadline rather than early or never.  Removing the deadline hangs the
lane until CI kills it, which is the behaviour being removed.

Verified: builds with networking ENABLED and DISABLED, the latter
being the configuration class that broke recently; task_queue.c links
for ARM32 without NEON; all nine task oracles still pass, since that
file is shared; the new lanes pass plain, under ASan+UBSan+LSan and
twice under TSan.

Not verified: behaviour against a real unresponsive lobby server.

* netplay: split the tunnel query into begin / await / result

Stage 2 of making netplay host init non-blocking: a refactor that
changes no behaviour, so it can be reviewed on its own before
anything moves.

netplay_mitm_query() welded "ask the lobby server" to "wait for the
answer".  Those are now netplay_mitm_query_begin(),
netplay_mitm_query_ready(), netplay_mitm_query_await() and
netplay_mitm_query_result(), with netplay_mitm_query() calling them
back to back at the same call site.  Nothing is deferred and nothing
moves; the point is that the next step - issuing the query when the
user opens the host UI, so the answer is already there when host
setup runs - becomes a change of WHERE begin() is called rather than
a restructuring of host init.

Every path was walked against the original:

  handle NULL/empty       false                 begin() false
  custom, decode fails    false                 begin() false
  custom, decode ok       address set, result   begin(), await(), result()
  http push fails         pending cleared,false begin() false
  http ok, reply in time  wait, then result     await() waits, result()
  http ok, timeout        warn, bump gen, false await() identical

One deliberate difference, because the split exposed an edge the old
shape hid.  The custom-relay path answers synchronously and the old
code returned without ever consulting the pending flag - so an
earlier query left outstanding could not make it wait.  Routed
through await() it would have, so the custom path now supersedes any
query in flight: it bumps the generation and clears the flag.  That
also stops a late callback from overwriting the address it just set,
which the old code would have allowed.

Verified: builds with networking enabled AND disabled; the
wait_timeout CI step replayed verbatim; the netplay NAT, task
ordering and watchdog oracles still pass.

Not verified: behaviour against a real lobby server.

* netplay: start the tunnel query when the user commits to hosting

Stage 3, and the one that removes the stall the user actually feels.

Host setup needs the relay address, and the query for it was issued
at the moment of need - so the wait was the full round trip, every
time.  It is now issued at CMD_EVENT_NETPLAY_ENABLE_HOST, where the
user commits to hosting, which is well before the address is wanted:
on the content-reload path, before content has even started loading.
The round trip overlaps work that was going to happen anyway, so by
the time host setup asks, the answer is usually already there and the
wait costs nothing.

Nothing is deferred and host init is not restructured.  The wait
stays exactly where it was, as the backstop for the case where the
answer has not arrived yet - which is what makes this cheap to
reason about and cheap to revert.

Prefetching only matters if asking twice is avoided, so the query
records the handle it was issued for, and host setup reuses an
answer that is already in hand or on its way.  It deliberately does
NOT reuse a prefetch that came back empty: a transient lobby failure
at prefetch time would otherwise doom a session that asking again
would have got, and one extra request is the better trade.  Every
state was walked:

  no prefetch                query issued as before
  prefetch in flight, same   reused, one query, overlapped
  prefetch answered          reused, no wait at all
  prefetch came back empty   re-issued
  relay changed since        re-issued, picks the new server
  custom relay               answered synchronously, reused

The prefetch is best effort in the strictest sense: skipped when the
relay is off or unconfigured, and if it fails for any reason host
setup asks exactly as it did before.  It is not speculative - the
user has already chosen to host, so no request is made for anyone who
merely opens a menu.

Verified: the call site sits inside #ifdef HAVE_NETWORKING, computed
from the preprocessor nesting rather than eyeballed, and both builds
were made - networking enabled AND disabled, the configuration class
that broke recently.  The wait_timeout CI step was replayed verbatim
from the workflow, and the netplay NAT and task ordering oracles
pass.

Not verified: behaviour against a real lobby server, including
whether the overlap is long enough in practice to hide the round
trip on the content-reload path.

* content close: pin the save wait, and say what it is waiting for

Stages 0 and 1 of unblocking content close.  Nothing about the wait
changes; this establishes what it guarantees and stops it looking
like a hang.

Stage 0, the oracle lane.  Closing content waits for in-flight save
and load tasks because their handlers call into core function
pointers - retro_serialize via content_get_serialized_data,
retro_unserialize via core_unserialize - while
runloop_event_deinit_core() unloads the dylib underneath them.  A
worker mid-call when the library goes away dispatches into freed
code.  That is why this wait, unlike the others removed in this
series, cannot simply be deleted.

The lane pins the property the unload depends on: the file is
checked incomplete before content_wait_for_save_state_task() and
complete after, so a wait that returned early - on a budget
boundary, say - fails here rather than becoming a crash on a device.
Neutering the wait fails it, as it should.

Stage 1, legibility.  The wait cannot be shortened without deferring
the teardown itself, which is later work, but an unexplained frozen
frame and a frame that says "saving state" are very different
experiences - and on slow storage this is seconds, not milliseconds.
The message is pushed and one frame forced out before blocking,
since nothing draws once the wait starts.

It fires only when there is something to wait for, using the same
condition the wait itself uses, so an ordinary close with no save in
flight is untouched and shows nothing.  That predicate had to become
public to be asked from here; its load counterpart already was.

Verified: builds with networking enabled and disabled; the
save_state oracle passes, including the new lane, and fails when the
wait is neutered.

Not verified on a device: whether the message reads well in the case
that matters, which is the slow-storage close it exists for.

* runloop: introduce the content-closing state, observed by nothing

Stage 2 of unblocking content close.  A no-op by construction: the
state is set and cleared around the teardown that already exists, so
while it is true the main thread is inside that teardown and no
frame runs to ask about it.

It is introduced on its own precisely because the work that makes it
observable - returning to the frame loop instead of blocking on the
save wait - is a lifecycle change, and this is the piece the rest
will key off.  Reviewing the two separately means a problem with the
lifecycle change is one revert, not an unpicking.

A plain bool in runloop_state_t rather than a RUNLOOP_FLAG bit.
Bits 0-30 of that word are taken and bit 31 was deliberately vacated
to avoid a cross-thread race with the AppIntents entity query;
reusing it would undo that reasoning for no gain, and this is
main-thread only.

The clear is placed at the block's single exit, which was checked
rather than assumed: there is no early return or goto between the
set and the break, so one clear covers every path.  A leaked true
would be harmless today and would wedge the frame loop at stage 3,
which is exactly the kind of thing worth getting right while it
still cannot bite.

Verified: nothing reads the state except its own accessor, which
nothing calls - grepped rather than asserted, since "no-op" is the
entire claim here; builds with networking enabled and disabled; the
save_state oracle passes and the wait_timeout CI step was replayed
verbatim from the workflow.

* task_queue: fix two data races TSan found in CI

Two separate races, one mine and one older.

Mine, in the oracle: work_pending was cleared by the task HANDLER,
which runs on the worker thread, and read by the waiting main
thread.  A plain bool across two threads - a race on inspection,
with no tooling needed to see it.  It was also a misrepresentation
of the thing under test: the code being modelled,
netplay_mitm_query_cb(), clears its flag in the CALLBACK, which runs
on the thread pumping the queue.  Clearing it there fixes the race
and makes the test match what it claims to model.

The older one is in the queue itself.  retro_task_threaded_reset()
set RETRO_TASK_FLG_CANCELLED under running_lock, while the worker
reads task->flags under property_lock - two locks for one field.
It needed a reset to land while a worker was mid-task, which is why
it sat undisturbed until a lane that cancels an unfinished task
turned up.  The flags are now set under property_lock as well.
Nesting is safe: property_lock is never held while any other lock is
taken anywhere in this file, checked by walking every lock/unlock
pair, so it can only be an inner lock and no cycle exists.

Both are load-bearing, measured rather than assumed: 40 TSan runs
report 0 races with both fixes, and reverting the queue fix alone
brings it back at 6/40.

On the reporting of this: the commit that introduced the oracle said
it passed twice under TSan.  That was true - I ran it, three times
including the CI replay, and it passed each time.  The race
reproduces about once in twelve runs here, so three clean runs were
about a 78% chance of missing it.  The claim was accurate and the
verification was not adequate, which is the more useful way to say
it.  Repeat counts for anything threaded are now sized against how
rare the failure can be, not against how many runs feel like
enough - and a shared mutable flag written from a handler should
have been caught by reading it, which is where this should have
stopped.

Verified: 40 TSan runs clean on the changed lane; 8 each on the
other threaded oracles, since task_queue.c is shared by all of them;
every task oracle passes on a plain build; desktop build clean; the
CI step replayed verbatim from the workflow.

* runloop: don't run the core while content is closing

Stage 3 of unblocking content close.  Still inert, and deliberately
so: it establishes what the frame loop must do while the closing
state is set, before anything can set it with frames running.

retro_run() must not be entered once closing has begun, because the
teardown unloads the library that function lives in.  The guard
therefore has to exist before the wait moves out of the close path,
not with it - otherwise the change that lets frames run would be
introducing both the opportunity and the protection at once.

That it cannot fire today was checked rather than assumed: both
core_run() call sites are inside runloop_iterate(), and the content
close block in CMD_EVENT_CORE_DEINIT reaches neither - it calls no
iterate, no core_run and no run_ahead, so the main thread cannot be
in the frame loop while the flag is set.

It polls input and presents a cached frame rather than returning
bare, matching the netplay-paused case immediately below, and for
the same reason: a frame that simply stops being produced reads as a
hang, which is the whole complaint being worked on here.

Verified: builds with networking enabled and disabled; the
save_state oracle passes, including the lane that pins the close
wait; the wait_timeout CI step replayed verbatim from the workflow.

Worth stating before stage 4: at that point this guard stops being
inert, and video_driver_cached_frame() will be running while a core
is being torn down.  That is the first thing to look at if the frame
loop misbehaves during a close, and it is why the harness lane for
content close belongs before that change rather than after it.

* runloop: fix C89 violation in core_run

The content-closing guard was placed before netplay_preframe's
declaration, so that declaration followed a statement:

  runloop.c:8808: error: ISO C90 forbids mixed declarations and code

netplay_preframe is now declared with the other locals and assigned
where it was, so the guard still returns before netplay's pre-frame
call and the declarations stay at the top of the block.

My own standing rule is that every C file gets the strict C89 gate
before commit, and I did not run it on this one - the ordinary
desktop build does not use those flags, so it compiled clean and I
took that as sufficient.  It is not, and the gate exists precisely
because it is not.

Verified with the flags the C89 build actually uses, on runloop.c
with networking both enabled and disabled, and with a full
C89_BUILD=1 compile of the tree; reinstating the original ordering
reproduces the reported error, so the check is real rather than
vacuous.

* samples: drive the content-closing guard against the real frame loop

Stage 4 will stop blocking on the save wait and let frames run while
a close finishes.  The guard that makes that safe - core_run()
refusing to enter retro_run() while content_closing is set - is
already in place, and is at present completely unexercised: closing
is synchronous, so no frame runs during it, and the guard would go
live in the same change that first creates the situation it protects
against.  If it were wrong, the symptom would be a call into an
unloaded dylib.

So it is driven here first, directly: the real core_run(), in a real
frontend brought up headless, with the flag set.  Links the shipping
objects with only main() replaced; nothing is stubbed.

Three assertions, and the first exists to stop the others passing
vacuously: with the flag CLEAR the core must actually be entered, or
this harness would be proving nothing about a core_run() that never
reaches retro_run() in this environment anyway.  Then with the flag
set it must not be entered, and once cleared it must resume - a
sticky guard would leave the frame loop dead after a close.  A
second lane runs 240 frames with the flag set, the shape of a close
on slow storage, checking core_run() returns cleanly every time
rather than faulting or wedging.

Removing the guard fails both lanes with exactly the message they
exist to produce.

It joins the existing menu-harness workflow, which already makes the
non-Qt build these harnesses need - with Qt enabled ui_qt.o defines
main and the link collides - so it adds about two seconds rather
than another full build.  The step was replayed verbatim from the
workflow before commit, and the menu harness alongside it still
passes.

Verified: strict C89 gate on runloop.c with networking on and off,
which is the check I skipped last time and should not have.

* retroarch: extract the content-close teardown into its own function

Preparation for removing the close freeze, and nothing else: the
sixty lines that run after the save/load wait move into
command_event_finish_content_deinit(), still called from exactly
where they used to run.

They have to become resumable.  The wait above them is the freeze
this work is about, and removing it means this half runs later -
from the frame loop, once the tasks have finished - so it needs to
be callable from somewhere other than the middle of a switch case.
Doing the extraction on its own makes the next change a question of
WHEN it is called rather than what it does, which is the difference
between a revert and an unpicking if that goes wrong.

Every local is re-derived from its accessor rather than passed in,
so the function carries no dependency on the caller's frame - which
is what lets it be called from the frame loop later.

The extracted body was compared statement by statement against the
original block: 53 statements, zero differences.  That check was
worth writing, because the first attempt at this anchored on a
comment that appears twice in the file and silently swallowed an
unrelated case - it failed to compile, but a subtler overshoot would
not have.

Verified: strict C89 gate on retroarch.c with networking on and off;
builds with Qt and headless; both full-program harnesses pass, and
the save_state oracle with them.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-08-16 22:11:06 +02:00
LibretroAdmin 89e03b5031 netplay: bound the MITM and UPnP waits to their own work
task_queue_wait(NULL, ...) does not mean "wait for my task".  A NULL
condition makes both queue implementations loop until the queue is
EMPTY, so a caller blocking on a single HTTP round trip also waits
out every unrelated task in flight.  Starting a hosted session
through a relay server therefore blocked the UI not for the tunnel
query but for whatever else happened to be running - a content scan,
a core download, a thumbnail pack - which is minutes, not
milliseconds, and is a far worse freeze than the one the site looks
like it has.

The MITM query now waits on a condition that describes its own work:
a flag set before the transfer is pushed and cleared by its
callback, on every path that callback can take (the queue runs the
callback of every task it retires, so no completion leaves it set).
The same change closes four latent copies of the pattern in
natt.c's blocking variants, which now wait on the device's own busy
flag - every one of those callbacks clears it.  Those four are a
trap being closed rather than a live freeze: no in-tree caller
passes block = true today, because the NAT task drives them
non-blocking and steps its own state machine.

What this does NOT do is make hosting non-blocking.  Host setup
reads the tunnel address decided by the query - sockets,
announcement and lobby registration all depend on it - so a wait
remains, now bounded by that one query.  Removing it means
deferring the rest of netplay host initialisation into the query's
callback, which is a restructuring of netplay init rather than a
change to this wait, and is not attempted here.

A CI guard keeps the unbounded form from returning to network/ or
tasks/, where every remaining wait now names a condition.  It does
not sanction waiting: the menu paths are held to the stricter
no-wait guard alongside it.

Verified: strict C89 gate on natt.c, netplay_frontend syntax-checked
under its feature set; full Linux build links with HAVE_QT=1; the
NAT, playlist and dirwalk oracles still pass; the guard was
falsified by restoring an unbounded wait, which it catches.

Reviewed rather than exercised: neither site is reachable from a
test harness here - the MITM path needs a lobby server and lives in
a translation unit too large to link standalone, and the natt.c
blocking variants have no in-tree caller.  The reasoning above is
the evidence, and the queue semantics it rests on are the ones the
NAT oracle already pins.
2026-08-15 07:54:57 +02:00
libretroadmin 7d8bd62a15 netplay/discovery: fix the ad server's cursor arithmetic and response addrlen
Two defects on the host side of LAN discovery, both in
netplay_lan_ad_server().  Neither is reachable today; both are the same
mistakes that were live on the client side.

strlcpy() returns the length of the *source*, not the number of bytes
written, so its result is only usable as a cursor after clamping.  The
frontend field was built as

   _len  = strlcpy(buf.frontend, frontend_drv->ident, sizeof(...));
   _len += strlcpy(buf.frontend + _len, " ", sizeof(...) - _len);
          strlcpy(buf.frontend + _len, arch,  sizeof(...) - _len);

An ident of 32 characters or more leaves _len past the end of the
32-byte field, at which point 'sizeof(frontend) - _len' underflows to a
huge size_t and the remaining copies land in core[] and beyond.  It
happens not to fire because every ident in the driver table is short -
the longest is "emscripten" at 10 - which is a thin thing for it to be
resting on.  Clamp the cursor and append the separator directly.

sendto() was passed addr_size, which still holds whatever recvfrom()
reported for the source address as it arrived.  addr_6to4() may since
have rewritten a v4-mapped v6 address into a shorter AF_INET one in
place, so the family and the length disagree.  Linux accepts the
mismatch (verified: addrlen of 16, 28 and 128 all send for an AF_INET
sockaddr; only 8 is rejected), but Winsock validates namelen more
strictly, and ipv4_is_lan_address() has already established the family
by that point.  Pass sizeof(struct sockaddr_in).

Verified by copying both blocks into a harness that writes to
exact-size heap allocations, so ASan redzones bracket the fields:
idents of 31, 32, 47 and 0 characters, and the subsystem content
builder across 11 boundary cases (exact fit, one over, far over, no
room left for the second name, the separator seam, 64 entries, empty
basenames).  ASan, UBSan (-fno-sanitize-recover=all) and LeakSan clean.

The subsystem builder itself needed no change - its 'buf_len + 1 <
avail' guard caps the cursor at 254 before the separator write, so
'avail - buf_len' cannot underflow.
2026-08-02 14:35:07 +02:00
LibretroAdminandlibretroadmin 6b4d55aecd netplay: fix remote heap overflow in mDNS discovery, bound the LAN host list, honour the scan deadline (#19328)
* netplay/nsnetservice: fix remotely triggerable heap overflow in mDNS discovery

-[NetplayBonjourMan finishBrowsing:] copied every TXT record value into
a fixed-size struct netplay_host field with

   strlcpy(host->nick, [txt[@"nick"] bytes], [txt[@"nick"] length] + 1);

which is wrong in three separate ways, all of them reachable from any
device on the same LAN:

 - strlcpy()'s third argument is the size of the *destination*.  Passing
   the source length instead means a TXT value longer than the field
   overruns it: host->nick is 32 bytes, an mDNS TXT string may be 255,
   so a crafted advertisement writes up to 223 bytes past the field.
   The same applies to frontend/core/core_version/retroarch_version
   (32 bytes each); subsystem_name is the last member, so its overflow
   runs off the end of the allocation entirely.

 - NSData contents are not NUL-terminated.  Both the libretro-common
   and the platform strlcpy() walk the source to measure it, reading
   past the end of the NSData buffer.

 - A key absent from the TXT dictionary yields a nil NSData, whose
   -bytes is NULL, and strlcpy() then dereferences it.

Replace the whole set with txt_field_copy(), which takes the
destination size, bounds the copy by the NSData length, stops at an
embedded NUL and treats a nil value as an empty string.

The address loop had its own overflow.  -[NSNetService addresses]
returns NSData objects sized to the concrete sockaddr - 16 bytes for
sockaddr_in, 28 for sockaddr_in6 - but the buffer was cast straight to
struct sockaddr_storage* and handed to addr_6to4(), which rewrites its
argument with a sizeof(struct sockaddr_storage) memset.  For a
v4-mapped v6 address that is a 100-byte write past the end of the
NSData, through a pointer to immutable contents.  getnameinfo_retro()
was likewise told the address was 128 bytes long.  Copy into a real
sockaddr_storage first and pass the true length.

The duplicate check could never fire: every arm of the test ended in
'continue', so the loop ran to completion and the host was appended
regardless.  Give it a break and an actual result.

content_crc was read uninitialised whenever -scanHexInt: failed to
parse - including when the key was missing, where the NSString is nil.

Finally, the browser and its services array live on the main run loop,
where the delegate callbacks mutate them, but finishBrowsing: runs on
the task worker thread: enumerating the live array there races
-didFindService: and mutation during fast enumeration raises
NSGenericException.  Stop the browser and snapshot the array on the
main queue, with a same-thread path for the non-threaded task queue,
where the handler already runs on the main thread and dispatch_sync()
would deadlock.

Cap the list at NETPLAY_MAX_DISCOVERED_HOSTS while here; see the
following commit.

* netplay/discovery: bound and de-duplicate the LAN host list

netplay_lan_ad_client_response() appended one entry per accepted
datagram, with no ceiling and no duplicate check.  Responses are
unsolicited - nothing ties one to a query we sent - so a single peer
answering in a loop grows the list forever.  Measured against the
response loop in isolation: 20000 datagrams from one address produced
20000 entries and 13.6MB of heap, and there is nothing to stop it
there.

Reject a response whose address/port pair is already listed, and stop
accepting new entries at NETPLAY_MAX_DISCOVERED_HOSTS.  The same flood
now yields a single entry.

While in here:

 - Growth was 1 then +4 forever, which is quadratic: 4096 entries copy
   1.4GB through realloc() against 2.9MB for doubling, and 4.4x the
   wall time to fill.  Make it geometric, clamped to the cap.

 - The advertised port is remote input and was carried through
   unchecked: ntohl(0xffffffff) reaches struct netplay_room as -1, and
   that is what the menu offers to connect to.  Require 1..65535.

 - struct sockaddr_storage was declared inside the loop with a {0}
   initialiser, so every datagram paid a 128-byte memset that
   recvfrom() immediately overwrote.  Hoist it and reset only the
   length, which is the part recvfrom() actually requires.

 - getnameinfo_retro() was told the address was sizeof(sockaddr_storage)
   bytes long.  addr_6to4() has already established it is AF_INET by
   that point, so pass sizeof(struct sockaddr_in).

 - net_driver_state_t is a zero-initialised static, so lan_ad_client_fd
   starts at 0, not -1.  Every '>= 0' guard reads that as a live
   socket, and deinit_netplay_discovery() would close descriptor 0.
   Unreachable today because the scan task always inits first, but only
   by luck.  Set it explicitly.

 - discovered_hosts.hosts is never freed anywhere in the tree; it is
   only truncated (size = 0) between scans.  LeakSan does not flag it
   because the head is reachable from a global, which is presumably why
   it has gone unnoticed.  Add netplay_discovery_free_hosts() and call
   it from the RARCH_CTL_MAIN_DEINIT teardown that already frees
   room_list.

 - One HAVE_NETPLAYDISCOVERY_NSNET test used #if where the other four
   in this file use #ifdef.  It works because -D without a value
   implies 1, but it breaks silently if the macro is ever defined
   empty.

Verified by extracting netplay_lan_ad_client_response() and
netplay_discovery_driver_ctl() verbatim into a harness with a scripted
socket layer: well-formed streams across the growth seam, fully
unterminated string fields, truncated/oversized datagrams, wrong magic,
non-LAN sources, clear-then-refill, and the flood case.  ASan, UBSan
and LeakSan clean.

* task_netplay_lan_scan: honour the deadline, and stop spinning

Two problems in the poll branch of the handler.

The timeout was only consulted when the discovery driver reported that
no host had answered:

   if (!netplay_discovery_driver_ctl(...GET_RESPONSES, NULL))
      if (cpu_features_get_time_usec() >= data->timeout)
         goto finished;

netplay_lan_ad_client_response() returns true whenever at least one
host was added this poll, so a peer answering continuously keeps the
scan alive forever - modelled against the real queue, still running
400s into an 800ms scan.  The preceding commit stops a single peer from
being counted repeatedly, but the deadline should not depend on that:
test it unconditionally.

The handler also returns immediately after each poll with task->when
left at 0, so the threaded worker re-enters it with no delay at all.
That is a full core spent on back-to-back recvfrom() calls for the
whole 800ms of every scan.  Set task->when to poll every 4ms instead;
datagrams that arrive in between are waiting in the socket buffer, so
nothing is missed.  (task_cloudsync.c already sets task->when from
inside its handler this way.)

Finally, the handler never looked at RETRO_TASK_FLG_CANCELLED, so
task_queue_cancel_task() on a running scan had no effect and the
discovery socket stayed open until the deadline.  Check it up front and
fall through to the normal teardown.

---------

Co-authored-by: libretroadmin <>
2026-08-02 13:59:41 +02:00
LibretroAdmin f5e70a8461 rzip, netplay: a true return from trans() does not mean the stream ended
trans() returns true in two different situations: the stream was
finalized, and the codec ran out of input while still mid-stream.  The
second is reported as TRANS_STREAM_ERROR_AGAIN, so the return value on
its own says nothing about whether a chunk actually decompressed.

rzipstream_read_chunk_data() passed NULL for the error code and then
qualified the call with checks that a truncated chunk also passes - all
of the declared input consumed, some output written, output not larger
than the buffer.  Its partial contents were then published as
out_buf_occupancy.  Demonstrated at the backend level with a stream cut
to 60%, output buffer sized for the whole thing:

  zlib        in= 63906 rd=     0 wn=     0/200000 ret=false err=5
  clean-room  in= 63906 rd= 63906 wn=117958/200000 ret=true  err=1

The clean-room backend is what HAVE_ZLIB=0 builds use, so that arm
accepted 118 KB of a 200 KB chunk as a complete read.  In practice the
short chunk propagates and rzipstream_read_file's own length check
rejects the file, so this was not silent corruption through that entry
point - but it made the failure land somewhere other than where the
problem is, and rzipstream_read callers that tolerate short reads had
nothing protecting them.  Demand TRANS_STREAM_ERROR_NONE, which both
backends set only on a finalized stream.

Netplay's savestate load ignored the return value entirely, and checked
the result only by memcmp'ing a 7-byte magic at the head of the buffer -
which a partial decompression passes as long as the first 7 bytes came
out.  A truncated or malformed payload from a peer was loaded as a
partially-filled state buffer with whatever the tail held before.  Check
the return, the error code, and that the output is the full declared
state size, and NAK otherwise.

The other consumers were audited and are correct: archive_file_zlib
(both entry points), libchdr_zlib and rchd all bind a full-size output
window and loop until END or no progress, and rpng_encode already
documents and handles the AGAIN-as-success case on its flush drain.

Validation: rzip write/read round-trip byte-exact at 900 KB for
HAVE_ZLIB=0 and =1, 20 truncation points per backend all rejected, under
-fsanitize=address,undefined.  netplay_frontend.c syntax-checked with
HAVE_NETPLAY.  C89 verified on x86-64 and aarch64.
2026-07-27 04:26:06 +02:00
libretroadmin a79435a8d1 netplay: define netplay_content_crc only where netplay is built
Two mistakes, one fix.

It was placed beside netplay_lan_ad_server, inside
HAVE_NETPLAYDISCOVERY and #ifndef VITA, while its callers - the
handshake, the lobby announce, the lobby content search - are built
whenever netplay is. Any target with netplay but without LAN discovery
compiled the calls and not the definition and failed to link; 3DS
among them.

And it was declared unconditionally in netplay.h, so a target built
without networking at all saw a prototype for a function that does not
exist there.

Both now sit under HAVE_NETWORKING, matching the gate on every file
that calls it and on netplay_frontend.o itself. The function depends
on nothing else conditional: a content path, an archive helper and an
intfstream.

Checked by preprocessing rather than by building one configuration:
the definition is emitted with HAVE_NETWORKING both with and without
HAVE_NETPLAYDISCOVERY, and absent without networking; the declaration
tracks it. A full link with HAVE_NETWORKING=0 succeeds.
2026-07-23 13:40:15 +02:00
libretroadmin c657524143 netplay: own the content CRC, and derive it only when asked
The frontend computed a CRC32 of the loaded content and offered it
through content_get_crc. Netplay was the only thing left that read it,
and the value was still being produced at load time for archived and
soft-patched content - so a session that never went near netplay paid
for a number nothing would ever look at.

Move it to the only consumer. netplay_content_crc derives the value
from the content path on first use and caches it; six call sites - LAN
discovery, the Bonjour advertisement, the handshake's send and compare,
the internet lobby announce, and the lobby's content search - now go
through it. Load no longer hashes anything at all, in any shape:
verified for a plain ROM, a zip entry, a soft-patched ROM and a
need_fullpath WAD.

The path is the whole input, and it has to be read the way the scanner
reads it, because the lobby searches the playlists the scanner wrote.
An "archive#entry" path is hashed by decompressing the entry; anything
else by hashing the file. That split is not optional: the archive
function returns zero for a plain file, and zero reads as "no CRC" -
it skips the handshake comparison and finds nothing in the playlists,
silently. Checked against known content in all four shapes, including
the disc-image case.

One deliberate behaviour change. Soft-patched content now reports the
CRC of the ROM on disk rather than of the patched bytes. The patched
value matched no playlist entry anywhere - the scanner hashes files and
knows nothing about patches - so it had been breaking the lobby's
lookup for every patched user, while two peers running the same patch
agree on the unpatched file regardless. What goes is the mismatch
warning when one peer has patched and the other has not, which never
blocked the session it warned about. Peers on older builds report the
patched value for patched content and will disagree with this one;
that surfaces as the same advisory warning, nothing more.

content_get_crc, content_state_t::rom_crc, the pending-CRC flag and
its stored path are all gone; the frontend no longer has the concept.
2026-07-23 13:13:34 +02:00
libretroadmin 16cb566b7d netplay: fix operator precedence in frontend pause connection count
netplay_frontend_paused() counts how many connections are both active
and paused, to decide whether our proxy status is "unpaused" relative to
each peer. The condition placed the == comparison inside the bitmask
parentheses:

    connection->flags &
        ((NETPLAY_CONN_FLAG_ACTIVE | NETPLAY_CONN_FLAG_PAUSED)
     == (NETPLAY_CONN_FLAG_ACTIVE | NETPLAY_CONN_FLAG_PAUSED))

so the inner expression evaluates to (3 == 3) == 1, collapsing the whole
test to (connection->flags & 1), i.e. it only checks the ACTIVE bit and
ignores PAUSED entirely. Every active connection is therefore counted as
paused, over-counting paused_ct and corrupting the pause/resume
notification that is sent (with an immediate buffer flush) when the core
is paused -- e.g. when a client opens the on-screen keyboard to chat.

Mask first, then compare, so only connections that are genuinely both
active and paused are counted:

    (connection->flags & (ACTIVE | PAUSED)) == (ACTIVE | PAUSED)

This regressed during the recent --disable-menu conditional rework.
2026-06-25 13:46:21 +02:00
libretroadmin 9932b5fb7a Eliminate Schlemiel strlcat-in-loop patterns (5 sites)
A 'Schlemiel the painter' string-building loop calls strlcat() in
each iteration to append onto the same destination buffer.  Each
strlcat() does an implicit strlen(dst) to find the end before
appending, so the cost of N appends is O(N * final_buffer_length),
i.e. quadratic in the segment count.  The fix is mechanical: track
the running length explicitly and append at the known offset using
memcpy (or snprintf-at-offset where the source length is already
known).  Each iteration then costs only O(strlen(src)) — bounded
per-step — for total O(N).

Five sites converted in this commit, sharing the same shape:

  gfx/drivers_shader/shader_glsl.c (alias_define)
    Building '#define <alias>_ALIAS\n' lines, one per shader pass.
    With up to ~20 passes and a 4 KiB alias_define buffer this is
    the worst-shaped of the five.  The fix is the cleanest variant
    since snprintf already returns the bytes written — no strlen
    needed at all.

  network/netplay/netplay_frontend.c (ad_packet_buffer.content)
    Building 'name1|name2|name3' for the netplay session-announce
    packet from the subsystem list.

  network/netplay/netplay_frontend.c (host_room->gamename via buf)
    Same shape as above, for the lobby host-room gamename field.

  network/drivers_wifi/connmanctl.c (entry.ssid)
    Joining ssid tokens with spaces; the prior form also called
    strlen() at the end to strip the trailing space, which is now
    avoided by simply not writing the final separator.  Drops a
    now-unused 'size_t ssid_len' local.

  gfx/display_servers/dispserv_x11.c (outputs list)
    Building 'out1|out2|out3' from XRRGetOutputInfo over the
    XRandR outputs.  Also fixes a latent bug: the static buffer
    's' was not reset at the start of the function, so a second
    call would have appended to leftover content from the first.

Microbench of the shape (segment=24 bytes, 16 KiB buffer):

  N=4      247.1 ns ->   8.2 ns    30.2x   (subsystems, x11 outputs)
  N=8      881.8 ns ->  13.1 ns    67.4x   (subsystems, x11 outputs)
  N=16    3272.0 ns ->  14.5 ns   225.7x   (shader passes, wifi nets)
  N=32   10942.9 ns ->  25.9 ns   423.2x   (shader passes, wifi nets)
  N=64   40494.7 ns ->  52.3 ns   774.0x
  N=128 153226.6 ns -> 101.3 ns  1512.4x
  N=256 583079.9 ns -> 211.1 ns  2762.3x

The fixes are most visible at large N, but the win at realistic N
(4-16, where these loops actually run) is still 30x-226x.  Absolute
per-call savings are modest in wall-clock terms (250 ns to 3 us),
but the shape is wrong in the original and right in the fix — the
classic concern with Schlemiel patterns is that someone tomorrow
adds another segment type and a 4-iteration loop quietly becomes a
40-iteration loop with a thousand-fold cost increase.

Correctness verified: byte-identical output to the prior strlcat
form across all realistic shapes and 128 truncation-boundary
cases (every bufsize from 1 to 64), checked under ASan + UBSan.
No new compiler warnings introduced; the connmanctl change
removes one pre-existing unused-variable warning.
2026-05-19 23:08:34 +02:00
LibretroAdmin 3f5424df69 netplay: convert netplay_platform_magic to a compile-time macro
After the previous switch from `1 == htonl(1)` to RETRO_IS_BIG_ENDIAN,
every operand in netplay_platform_magic()'s body is an integer constant
expression (RETRO_IS_BIG_ENDIAN is a preprocessor 0/1, sizeof is an ICE
per C89). The function therefore returns the same value on every call
in a given build and can be expressed as a #define.

Unlike netplay_impl_magic(), which still has to iterate PACKAGE_VERSION
at runtime, NETPLAY_PLATFORM_MAGIC is purely a compile-time constant —
the macro form makes that explicit and matches the SCREAMING_CASE used
for NETPLAY_MAGIC and NETPLAY_COMPRESSION_SUPPORTED nearby. uint32_t
casts on each term keep the bit-30 shift well-defined and future-proof
the reserved-bit slot.

No wire-format change: all three call sites just swap the parenthesised
function call for the macro expansion.
2026-05-16 22:14:33 +02:00
LibretroAdmin 78dc48b522 netplay: replace runtime endianness probe in platform magic
netplay_platform_magic() encoded the host endianness into bit 30 of a
'platform magic' word sent to peers via:
    ((1 == htonl(1)) << 30)

htonl() is a libc call whose folding to a compile-time constant is not
guaranteed — on platforms where it is not inlined as a builtin this is
a genuine runtime call on every magic-word build. RETRO_IS_BIG_ENDIAN
from retro_endianness.h is a preprocessor constant (0 or 1) and is the
canonical way to express this in the libretro tree.

Wire-format semantics unchanged: bit 30 set <=> big-endian host.
2026-05-16 21:27:07 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 0760c29a0c netplay: only reinit preempt frames if core is running
deinit_netplay unconditionally calls preempt_init at the bottom
of its body. This is appropriate when netplay is being toggled
off mid-session - we want to restore preempt frames so the user
gets runahead back. But deinit_netplay is also called from two
shutdown contexts where the call is wasted work or worse:

  - RARCH_CTL_MAIN_DEINIT (retroarch.c:8511) at full app
    shutdown: preempt frames will be torn down moments later
    by CMD_EVENT_CORE_DEINIT's preempt_deinit.

  - retroarch_main_init's error: label (retroarch.c:8431) at
    init failure: same teardown follows.

Beyond the wasted allocation, preempt_init at runahead.c:1501
synchronously calls runloop_st->current_core.retro_run() when
frame_count is 0. Firing a synchronous retro_run from inside
a deinit chain - while RARCH_CTL_MAIN_DEINIT is on the stack
or while we're unwinding from a failed init - is a surprising
side effect that any future change to retro_run could turn
into a bug.

Gate the call on RUNLOOP_FLAG_CORE_RUNNING. The flag is cleared
at the top of CMD_EVENT_UNLOAD_CORE (retroarch.c:3749), so the
shutdown paths see it unset and skip preempt_init. The mid-
session toggle paths (CMD_EVENT_NETPLAY_DEINIT from the netplay
menu actions in CMD_EVENT_NETPLAY_ENABLE_HOST etc.) see it set
and call preempt_init as before.
2026-05-03 08:56:32 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 4375682df3 Buildfixes 2026-05-01 07:41:36 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 8fd7aa48c6 network/netplay/netplay_frontend: NULL-check istate_out in frame real_input copy path
netplay_sync_pre_frame's frame-replay loop had one unchecked
netplay_input_state_for return value:

    else
    {
       /* Copy the previous input */
       istate_out = netplay_input_state_for(&frame->real_input[device],
             client_num, istate_in->size, true, false);
       memcpy(istate_out->data, istate_in->data,
             istate_in->size * sizeof(uint32_t));
    }

netplay_input_state_for can return NULL on three paths:

  1. Internal calloc OOM (the fresh-slot allocation path).
  2. must_not_create = true and no matching slot found.
  3. must_create = true and an existing slot exists with a
     different size (the 'return NULL' at line 2218).

Path 3 is the realistic one here.  The callsite passes
must_create = true (4th param) and the frame's real_input
slot list for this device might already have a state entry
for client_num at a different size - e.g. if the client
changed device type since this frame was initially written.
Under that condition netplay_input_state_for returns NULL
and the subsequent memcpy through istate_out->data
NULL-derefs.

All other callsites of netplay_input_state_for in this file
already NULL-check the return:

  - netplay_device_client_state: 'if (simstate)
    return simstate' pattern.
  - several sites use 'if (!state)
    continue;' in per-client loops.
  - one netplay_cmd_nak callsite: 'if (!istate) return netplay_cmd_nak(...)'
  - sibling to this fix: just calls netplay_
    input_state_for without using the result, so NULL is
    harmless.
  - one site: 'if (!istate) continue;' with an explicit
    /* FIXME: More severe? */ comment.

This one site was the outlier.  Match the convention of the
other callsites in the surrounding sync-loop context by
guarding the memcpy with an 'if (istate_out)'.  The outer
loop's frame->have_real[client_num] = true marker
still fires, so the sync pass treats the frame as
processed; the next sync iteration re-attempts the copy with
a fresh state_for request.

=== Swept-clean in the same pass ===

Verified NULL-checked in network/netplay/:

- netplay_frontend.c 22 alloc sites: discovered_hosts.hosts
  malloc + realloc (both guarded), sbuf->data malloc
  (guarded), sram_buf malloc (guarded), netplay_input_state
  callocs with shared NULL-check, newdata malloc
  (guarded), netplay->connections calloc + realloc (guarded),
  netplay->buffer[i].state realloc
  (guarded), mitm_handler calloc (guarded with 'if' wrap),
  netplay->buffer[i].state / zbuffer / buffer callocs
  (all guarded), netplay_t calloc (guarded), initial
  connections calloc in netplay_new (goto failure), input-
  handler buf mallocs (guarded), ban_list
  malloc + realloc (guarded), client_info calloc (guarded),
  core_netpacket_interface malloc (guarded with prior audit
  comment).

- netplay_room_parse.c 3 sites: head / tail room callocs
  and rooms_data wrapper calloc, all guarded with prior
  audit comments (the head/tail pair specifically gates on
  rooms_data->cur being non-NULL to avoid the 'prior room
  failed' NULL-deref cascade).

- All other netplay_input_state_for callsites NULL-check
  or intentionally ignore the return.

Thread-safety: netplay_sync_pre_frame and the surrounding
frame-replay code run on the main netplay thread.  No
concurrent mutation of frame->real_input from other threads.

Reachability: the size-mismatch path is triggered by device
reconfiguration mid-game - e.g. a player switching their
controller between Joypad and Analog types while netplay is
running.  Not common, but realistic for long-duration
sessions where a player wants to switch to a different
control scheme.  Under the pre-patch code that triggered a
NULL-deref crash in the server's sync handler; post-patch
the copy is skipped for that device/client and the next
sync pass retries.
2026-04-24 16:02:32 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 9faa65418d network/netplay/netplay_room_parse: NULL-check inner per-room callocs
The two per-room struct netplay_room callocs inside the
netplay_json_start_object rjson callback were unchecked; on
OOM subsequent code in the same function (->connectable = true,
->is_retroarch = true) and every field-handler callback below
(object_member, string, number, boolean) would NULL-deref
net_st->rooms_data->cur or NULL-deref the wrong field via
'&net_st->rooms_data->cur->port' style address-of expressions.

This finishes off a deferred item called out in the commit
message for '3785495 scattered OOM fixes: core_backup entries
leak, netplay core_netpacket_interface and rooms_data' (this
series), which added the outer rooms_data NULL-check but left
the inner per-room allocations noted as out-of-scope.

=== The original code ===

    static bool netplay_json_start_object(void* ctx)
    {
       if (p_ctx->state == STATE_FIELDS_START)
       {
          p_ctx->state = STATE_FIELDS_OBJECT_START;

          if (!net_st->rooms_data->head)
          {
             net_st->rooms_data->head = calloc(1, ...);   /* A */
             net_st->rooms_data->cur  = net_st->rooms_data->head;
          }
          else if (!net_st->rooms_data->cur->next)
          {
             net_st->rooms_data->cur->next = calloc(1, ...);  /* B */
             net_st->rooms_data->cur       = net_st->rooms_data->cur->next;
          }

          net_st->rooms_data->cur->connectable  = true;    /* NULL-deref */
          net_st->rooms_data->cur->is_retroarch = true;    /* NULL-deref */
       }
       ...
    }

Two ways this goes wrong on OOM:

1. calloc A or B returns NULL -> cur becomes NULL -> the two
   immediate field writes at the bottom of this if-block
   NULL-deref.
2. If a *previous* room's calloc failed, cur is NULL coming into
   this call.  The 'else if (!cur->next)' branch NULL-derefs
   cur->next before we even get to the calloc.

Every downstream callback (object_member, string, number,
boolean) then accesses 'net_st->rooms_data->cur->fieldname'
unconditionally and NULL-derefs too.

=== The fix ===

1. Add a new parser state STATE_SKIP_OBJECT to the
   netplay_parse_state enum.  When the inner calloc fails or
   when cur is NULL from a prior failure, transition into
   SKIP_OBJECT instead of STATE_FIELDS_OBJECT_START.

2. Every field-handler callback (boolean, string, number,
   object_member) already gates on state ==
   STATE_FIELDS_OBJECT_START, so they silently skip when state
   is SKIP_OBJECT.  No changes needed in those handlers.

3. netplay_json_end_object transitions both
   STATE_FIELDS_OBJECT_START and STATE_SKIP_OBJECT back to
   STATE_ARRAY_START, so the next JSON object in the rooms
   array can be attempted.

4. Restructure start_object to use a local 'struct netplay_room
   *new_room' temporary so the calloc return can be NULL-checked
   before wiring it into head/cur.  Guard the 'else if' branch
   on cur being non-NULL.

=== Self-healing behaviour ===

The fix lets the parser self-heal across rooms:

  * If the first room's calloc fails: head stays NULL.  The
    next iteration of start_object sees !head true and
    retries calloc.  If it succeeds, the new room becomes head
    as normal.
  * If a later room's calloc fails: cur points to the last
    successfully-allocated room, which still has next==NULL.
    The next iteration re-enters the 'else if (cur &&
    !cur->next)' branch, retries calloc, and links the new
    room in as if the failed room never existed.  No holes
    in the linked list; only the failed room is dropped.

=== netplay_rooms_free robustness ===

Walks the linked list from head, freeing each room.  Handles
head==NULL (no rooms were allocatable) and partial lists (some
rooms succeeded, some failed) correctly - it just walks what
was successfully linked in.  No changes needed.

=== Thread-safety ===

netplay_rooms_parse is called on the main thread (from task
callbacks in menu_cbs_ok.c after an HTTP fetch completes).
The rjson parser runs synchronously on the same thread.  No
new locking required.

=== Reachability ===

Every netplay lobby browse triggers this parser with the
server response.  OOM here is plausible on memory-pressured
handheld targets (Retroid, Anbernic, etc) where users are
most likely to be browsing for netplay opponents.  The pre-
patch behaviour was a segfault on the first unchecked field
write; the post-patch behaviour is a partially-populated
rooms list (with the failing rooms silently dropped).

=== Verification ===

Compile-tested with:
  gcc -c -I. -Iinclude -Ilibretro-common/include \
      -DHAVE_CONFIG_H -DRARCH_INTERNAL -DHAVE_NETWORKING \
      network/netplay/netplay_room_parse.c

No warnings or errors.  State machine walked through by hand
for: empty JSON, one-room success, two-room success, first-
room OOM, second-room OOM followed by successful third room.
2026-04-24 03:22:21 +02:00