mirror of
https://github.com/libretro/RetroArch.git
synced 2026-11-23 09:49:34 -10:00
codex/android-native-streaming
263
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ec27910f77 |
State tasks: a Load State cannot slip between a save's backup load and the save
A save over an existing file is two tasks: a load of that file for the undo, whose callback pushes the save. With threaded tasks the queue stops refusing a blocking task once the one in flight has finished on its thread, so a Load State pressed after the backup load was done and before its callback had run was pushed there and then, and read the file the save was about to replace. The state tasks' own counts say whether one is in flight - pushed, its callback still to come - and a request is held behind it until then, as it is behind one still running. The state-load-latency lane of content_load_test takes that case, and bounds a load by a display's frames where the machine is too busy for the harness's own, microseconds long, to mean anything. |
||
|
|
583785e886 |
save, task_save: bulk writes for save RAM and save states
Save RAM is written in one piece and flushed; a save state in one piece (the synchronous path) or in 100 KB to 16 MB pieces (the task). These uncompressed writers now ask for descriptor writes: on the desktops and Android the bytes go to the file with no copy through a stdio buffer, and the save RAM flush has nothing left to push. The compressed (rzip) writers are unchanged. Where descriptor writes are not available the hint is ignored. |
||
|
|
f9c77d8e80 |
Savestates: keep the replaced file for undo as it is, not inflated
A save over a slot first reads the file there into the undo buffer, so Undo Save State can put it back. That read went through rzip: on every save over a compressed slot the old state was inflated in full, and kept inflated in memory for the rest of the session. Undo then wrote it back through rzip, deflated afresh, compressed or not as the setting had since become rather than as the file was. The backup is now the file's own bytes, read plainly, and undo writes them back as they are. Nothing is inflated on a save, nothing deflated on undo, the buffer held for undo is the file's size rather than the state's, and the slot comes back byte for byte. An 8 MiB state that compresses to 4 MiB: 2.1 -> 0.6 ms for the backup on every save over the slot, 12.4 -> 3.3 ms for the undo, and 4 MiB less held for it. At 32 MiB: 9.9 -> 3.8 ms and 41.6 -> 25.3 ms. save_state_io_test gains an RZIP=1 build with HAVE_COMPRESSION, as the frontend ships it, where every lane also passes, and a lane that saves over a slot with the compression setting turned in between, both ways, then undoes: the slot must come back byte for byte. It fails on the previous tree. Linux-samples-tasks runs that build under ASan. |
||
|
|
f0c0dea7d5 |
Savestates: move compressed states in whole rzip chunks
The save and load tasks moved a state in 100 KiB quanta, and rzip cuts its stream into 128 KiB chunks. A write shorter than a chunk never met rzipstream_write()'s direct path, so every byte was first copied into the stream's buffer and compressed one chunk at a time, and the parallel chunk compressor (two or more whole chunks in one write) never ran for a savestate at all. A read always inflated each chunk into the stream's own buffer and copied it out. A compressed save now writes two whole chunks per quantum: they are compressed straight from the state, across the worker pool. A compressed load reads two whole chunks per quantum, and rzipstream_read() now inflates a whole chunk wanted by the caller straight into the caller's buffer, the read-side mirror of the write's direct path; a chunk that would inflate past chunk_size is corrupt and fails as it did. What a quantum moves to or from the device is the compressed size, about half the state, so the slowest storage the quantum is sized for is not asked for more per tick. Uncompressed states keep the 100 KiB quantum, and Emscripten its 16 MiB one, already a multiple of the chunk. RZIP_DEFAULT_CHUNK_SIZE moves to rzip_stream.h for writers that want to meet it. For a 16 MiB state on two cores, a compressed save goes from about 217 ms to 118 ms and the output is byte for byte the same; a load in whole chunks goes from about 31.5 ms to 29.5 ms (best of six). The rzip codec sample reads both codecs back in quanta from one byte to past several chunks, around a rewind and a short last chunk, and checks that 100 KiB and two-chunk writes make the same file. |
||
|
|
557107b598 |
task_save: a save or load pressed during another is held, not dropped
State tasks are TASK_TYPE_BLOCKING, so the queue takes one at a time and refused the rest, which were then thrown away without a word. Load State pressed while a save was still writing did nothing, nor Save State during a load, an undo or an automatic save: the hotkey had to be pressed again once the other was through. A state task the queue turns away is now held, in order, and pushed as the one ahead of it finishes; past a bound of four it is refused as before. The save a backup load was taken for goes ahead of anything held, so a Load State pressed straight after Save State loads what that save wrote, not the file it replaced. The pending flags become counts, so a content close, a quit and a movie recording wait for held requests too. Anything still held when the savestate backups are reset is discarded and its caller told. All of it is on the frame thread, where every state push and every state callback runs: no lock, and nothing per frame. save_state_io_test's exclusion test now expects the hold and its bound, and a new test checks that a load pressed during a save is taken, counted as pending, and applies what the save wrote. The state-load-latency lane gains Load State in the same frame as Save State. Both fail on the old code. |
||
|
|
6240401af4 | Save task logging capitalization cleanup | ||
|
|
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]> |
||
|
|
ad2d961e10 |
task_save: a state load waiting for the core's second frame parks
Until the frame loop has run the core twice the load handler parks for about a frame and looks again, instead of running back to back on the worker. save_state_io_test's threaded lane pushes a load before the second frame and counts its parks. |
||
|
|
d3b50802c2 | cheevos: bound progress deserialization to supplied state data (#19692) | ||
|
|
250e2d1b48 | save: write states, SRAM and disk index through a temporary file (#19629) | ||
|
|
dab803e6bf |
task_save: a finishing save or load task hands its state to the callback
The state is the callback's task_data instead of a copy allocated when the task finishes, so the callback always gets it: a caller of content_save_state_notify() or content_load_state_notify() is told how its task ended even when nothing more can be allocated by then. The callbacks' NULL task_data branches go with the copy. save_state_io_test wraps calloc and fails the allocations a finishing task would make while the task runs; the notified save and load are both told. |
||
|
|
62d5954fbc |
mcp: answer tools once their work is through
A tool whose work runs over later frames answers when that work is through, with what came of it, or with its name, ERROR and the reason: LOAD_CONTENT, START_CORE, CLOSE_CONTENT and UNLOAD_CORE once the load or close ends; LOAD_STATE_SLOT and SAVE_STATE_SLOT once the state is applied or written; PLAY_REPLAY_SLOT, RECORD_REPLAY, SEEK_REPLAY and the replay checkpoint tools once the replay has started or the seek or checkpoint has run; SET_SHADER once the preset has compiled; AI_SERVICE with the service's text. A line-based interface keeps the answers it had. The waiting is one shape, task_notify_t (tasks/task_notify.h), held by the work's owner: the content load, the save and load tasks, the movie tasks, the deferred shader load and the translation service. State and replay work a command starts runs from a main-thread task, outside the core's own input poll. The command interfaces outlive a content load, remade only when their settings change, and what arrives during a load waits for it. samples/tasks/content_load gains lanes for the state-slot, replay, seek and content replies; samples/network/mcp_server follows. Closes #19702 |
||
|
|
ee8a24a447 |
replay: harden replay file parsing
Each read is reachable from a damaged .replay file or from replay data inside a loaded savestate. - uint32s_index_commit: a commit interval of 1 (from the header) read the addition one past the end of the log and freed wild pointers; below 2 nothing is collected. The bucket lookup is guarded as pop's. - reset_playback: block and superblock sizes from the header are bounded (REPLAY_MAX_*) and must be a multiple of 4. - A statestream checkpoint in a replay whose header built no indexes is refused instead of read through NULL. - replay_check_same_timeline: a frame claiming more inputs than a frame holds overflowed its 128 KB compare buffers. - replay_set_serialized_data takes the savestate block's length; the replay length it declares must fit inside it. - push_input_event / push_key_event drop events past their arrays. - uint32s_index_pop freed nothing it dropped (a leak per rewind). - movie_find_checkpoint_before returned the frame as a bool: "no checkpoint" read as found, frame 0 as not found. - A checkpoint size of 2^63 or more seeked backwards and hung the scan; every file-sized skip now moves forward within the file. - A checkpoint that fails to load ends playback rather than playing on out of step with its indexes, and a failed statestream decode clears cur_save_valid. - Legacy checkpoint frames: a size too large to allocate, or to fit a size_t, read into a NULL cur_save; the movie now ends instead. - bsv_movie_load_checkpoint no longer sets last_save_size to cur_save's size. last_save is the recorder's other buffer, swapped back in on the next write, so it could claim more than it holds. The reader's last_save_size check goes with it; superblock_seq_len already sizes the sequence. - write_checkpoint recorded a size before its buffer existed; a log line printed a pointer as %c; a message length used sizeof. bsv_checkpoint_bounds_test's verbatim copy of bsv_movie_load_checkpoint follows the two changes to that function. Tests: samples/tasks/bsv_replay_init gains lanes checkpoint, statestream, index_gc, index_interval1, index_pop, header_sizes, no_index, decode_fail_ends (STATESTREAM) and timeline_inputs, state_replay_len, event_capacity, seek_no_checkpoint, checkpoint_seek. CI builds it with STATESTREAM=1 too; the ASan runs set allocator_may_return_null=1, and the test sets it for TSan. Closes #19695 |
||
|
|
6da6466e88 |
input: no file under input/ takes a state pointer but the frontend
The last 23, in 11 files, are gone. Nothing under input/ calls config_get_ptr(), input_state_get_ptr(), runloop_state_get_ptr(), menu_state_get_ptr() or video_driver_get_ptr() any more, apart from the frontend itself (input_driver.c, input_driver_choice.c). The replay code (input/bsv/bsvmovie.c), seven: - its four entry points that took no state are handed the input state by their callers, the save-state task and the rewind; - its two inner functions used the state only to say the replay is over, fifteen times between them. That is bsv_movie_set_end() now, and they are handed the replay alone. The platform drivers, fourteen settings reads: named calls, as the others became - Apple (keyboard as gamepad, mouse index, rumble gain, device vibration), Wii and GameCube (mouse index and scale, joypad index), Vita (back touch), Switch (split Joy-Con), webOS (screensaver), udev (the five touch options). Two drivers wrote to the settings, and each has a call that says what it is doing: - the Wii and GameCube joypad driver puts port 1 back on the first pad when only one is left: input_config_set_joypad_index(); - the udev input driver, finding no device on the very first start, makes linuxraw the configured driver: input_driver_first_start_fallback(). The SDL2 input driver took the video driver's data to grab the pointer in its window. The video driver does the grab, sdl2_video_grab_window(), and the input driver asks. The Android input driver held the code that writes SRAM, core options and the configuration when Android takes the application away. That is frontend work; it is retroarch_save_for_suspend() in retroarch.c, as it was, and the driver calls it. tools/input_state_grab_check.py has an empty list, and no exemption for the replay code: a file under input/ that takes one of these fails. Built for Linux and Android; the frontend harness, the four replay tests and the udev devices test pass. The Apple, Wii, GameCube, Vita, Switch and webOS files are not built here. |
||
|
|
c734bc66a6 |
tasks: a refused blocking task is freed and reported, never left pending
The task queue refuses a blocking task while another runs, and four pushers ignored the refusal. content_load_state() had already marked the load pending, so a load pushed while a save state, a screenshot or a Wi-Fi or Bluetooth task ran left the flag set for the rest of the session: closing content waited on it forever, and a movie recording never started. It now clears the flag, frees the task and returns false, which every caller already handles. The undo save state, the Wi-Fi and the Bluetooth pushers leaked the refused task and reported success; they free it and return false. samples/tasks/save_state checks that a load pushed while a save runs is refused and not left pending - both fail without this change - with LeakSan covering what the refusal frees. |
||
|
|
7e4b79ea54 |
Document the waits the frame loop still allows
Each is commented where it is, and CODING-GUIDELINES lists them. |
||
|
|
f890800f72 |
content: the load is a chain of main-thread tasks
Each stage of the staged load is a task of the frontend's queue with RETRO_TASK_FLG_MAIN_THREAD: its handler runs one stage per check and returns unfinished while the stage waits, its callback pushes the next stage, and the last one runs the after-work. The hand-stepped task_content_load_check and its hook in runloop_iterate go; the prefetch continuation starts the load from its own callback. The close, now a handler, asks whether a save state task is inside the core from inside the gather, where the unthreaded runner has lifted every task off the queue and a finder sees none: it judged nothing pending and unloaded the core under a save still writing. content_save_state_in_progress is now a flag that transitions on the main thread - set at the push, cleared in the callback - as the load-state one already is. The harness lane that closes content over a save in flight is what found it. |
||
|
|
d06baf07af |
savestate: time the automatic interval from the frame's clock, not time() per frame
With savestate_automatic_interval set, content_save_state_automatic() called time(NULL) every frame to see whether the interval had passed. The iterate already has the frame's cpu_features_get_time_usec() reading in hand; pass that in and keep the last-save stamp in the same units, so the check is a subtract and compare with no clock call of its own. |
||
|
|
e49962f114 |
video: no thread entry reaches the video singleton's getter
video_state_get_ptr() stays - the main thread and the wrapper's finder-entries locate ra-video state through it - but nothing that runs on a task worker or on the video thread calls it any longer, and the audit now proves that with no allowlisted exceptions: both entries (video_thread_loop's owner-domain reads and task_load_handler's frame-count poll) are deleted from tools/thread_read_allow.list, and the audit reports 0 findings with 0 allowlisted pairs. Every conversion is a stable-pointer capture taken on the main thread before the consuming thread exists: - task_load_handler polls core readiness through a frame-counter pointer captured into save_task_state_t at both load-task push sites; the read keeps its documented single-benign-poll-per-tick semantics. - thread_video_t carries the singleton's address from init; the loop's statistics publishes, video_thread_pace_hold(), and the loop-called video_thread_convert()/video_thread_filter() (which now take the wrapper instance as their first argument) go through it. A file-scope capture of the wrapper instance, set at init and cleared first thing in video_thread_free(), serves the entries callable from the video thread itself - call_on_waiter, font_init, texture_handle - where NULL now covers both "no wrapper" and the driver-reinit window the thread_wrapper_active check used to guard. - The font driver binds the singleton's address once, from video_driver_init_internal() before any driver or wrapper exists, because under threaded video the OSD fonts live on the video thread. Unbound degrades exactly as pre-video-init always has: no shared OSD font, lifecycle calls no-op, width queries return the no-font -1. - gfx_widgets captures the address at init, before the draw worker exists, for the worker's state-lock dispatch. The font_lifecycle harness gains an unbound-phase probe and binds the capture the way production does, so the degradation contract stays pinned. |
||
|
|
940c37ba03 |
comments: explain the code moving forward
CODING-GUIDELINES line 275: explain how the code works moving
forward, not how it worked historically - and the rule applies to
code comments. A sweep of this engagement's comments for
diff-narration - 'used to', 'old code', 'is gone', 'moved out of',
'has been removed' - rewritten as what each site must do and what
breaks otherwise, with the measurements and failure modes kept:
the invariant is the point, the archaeology is not. Touches
video_driver, retroarch, runloop, the save/database/updater/backup/
image tasks, the companion latch, the widgets producer, gl1's
swizzle staging and the audit allowlist. Lifecycle wording that
happens to read as history ('the driver itself is gone', 'no
longer valid') describes present teardown states and stands.
Comments only; the build, the fifty-entry audit zero and every
touched file's syntax check all hold.
|
||
|
|
14afda06aa |
save: the serialized size is read only where it is filled
GCC's -Wmaybe-uninitialized was right that it could not prove size.total_size initialized at the assignment after the serialize block: when the sizing call returns zero the struct is never filled, and only the state->data guard - an implication outside the compiler's reach - kept the read on the safe arm. The size now starts at zero and takes total_size inside the one branch where the sizing call has necessarily succeeded, so the proof is local and the warning is gone by construction rather than by a dummy initializer that would also mask a real future miss. Behavior is identical on every arm; the save suite, including the background-serialize timing lane, passes. |
||
|
|
5ba2b04d23 |
save: the background worker serializes the core and nothing else
A background save's handler ran the whole rastate write on the threaded task queue's worker: the core's serialize - which is what the core's SET_SAVE_STATE_IN_BACKGROUND request vouches for - but also the replay block, the rewind direction and the achievement block, live frontend state read while the main thread mutates it. The push captures the frontend blocks on the main thread, and the worker's sizing and writing run on a captured-only path with no live frontend read in it at all: the core serializes live, the capture fills in around it. The foreground path is untouched. The save suite pins the timing from the feature's side: a background push serializes nothing and the handler serializes the core exactly once, a foreground push pays at push - so the deferral the env request exists for cannot quietly become a push-time serialize. tools/thread_read_audit.py --binary retroarch: 11 findings become 8, and task_save_handler no longer appears. |
||
|
|
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]> |
||
|
|
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]> |
||
|
|
746f096e82 |
movie: fix the record ordering guard, and stop waiting on the whole queue
Two of the interactive task_queue_wait sites, both around the movie tasks, and both resolved by the same underlying discovery. runloop.c waited for the ENTIRE task queue to drain before starting a movie recording, under a FIXME that admitted it did not know why the guard inside task_moviectl_record_handler was insufficient and guessed at either enqueue timing or a wrong finder call. The guess about the finder was right, and the mechanism is worth stating plainly: retro_task_regular_gather() lifts every running task off tasks_running into a local list, then puts each one BACK as it processes it. Whether content_load_state_in_progress() - a task_queue_find() - sees a pending load therefore depends on where that load sits in the pass relative to the caller. It is not reliably blind, which is worse than if it were: it answers correctly most of the time and wrongly some of the time, which is exactly the shape of an intermittent ordering bug. content_load_state_in_progress() now reads a main-thread flag, set when a load task is pushed and cleared when its callback has applied the state, including on the push-refused path where no callback will run. That is the same correction already made in task_database_info.c for the same class of window. With the guard working, the whole-queue wait in runloop.c is deleted rather than kept - the record task defers itself correctly now. The finder it replaced is removed. command.c's PLAY_REPLAY_SLOT handler waited on the whole queue so that the movie task's callback would have installed the replay handle before the reply was formatted. The handler it waits for is trivial and finishes on its first invocation, so the wait was already only about letting one tick happen - but a NULL condition means "until the queue is empty", so a network command blocked on every unrelated scan or download in flight. It now waits on a predicate for that task alone. Producing the reply from the movie callback instead would remove the wait entirely, but that needs deferred-reply support in the command layer and is left for that work. A new oracle (samples/tasks/ordering) drives the shipping queue and pins the contract this rests on: that a finder called from inside a handler disagrees with the truth on at least one invocation, that a main-thread flag does not, and that a task guarded by the flag runs after the task it waits on. Reinstating the finder-based guard makes the ordering lane fail with the dependent task running first - the bug the FIXME described, reproduced. Writing it corrected my own diagnosis: I expected the finder to be uniformly blind for the whole pass, and the first version of the lane asserted that and failed. Position dependence is the accurate property and is what the lane now pins, so a future change to the gather's put-back behaviour trips it deliberately. Verified: strict C89 gates on task_save.c, task_movie.c, command.c and runloop.c; full Linux build links with HAVE_QT=1; three lanes pass plain, under ASan+UBSan+LSan and under TSan; the save_state oracle - which covers the translation unit whose predicate changed - still passes, as do the dirwalk, playlist, playlist_manager, overlay, scan, NAT and watchdog oracles. |
||
|
|
c464c6620a |
Emscripten libretro-common fixes, use __EMSCRIPTEN__ (#19297)
* Emscripten libretro-common fixes
* memmap: gate the reserve/commit path off for emscripten instead of dropping mman
Emscripten was added to the "No mman available" platform list in
memmap.h, which reaches further than intended. That branch does not
just disable things: it makes memmap.c define mmap(), munmap() and
mprotect() as global symbols with malloc/free semantics on a platform
whose libc already provides working ones, and it declares mmap() with
a size_t offset where <sys/mman.h> uses off_t, so any translation unit
that pulls in both headers gets conflicting declarations. The shim's
mmap() also ignores fildes and offset, so a file-backed request would
return uninitialised memory; that is invisible today only because
Makefile.emscripten never sets HAVE_MMAP and the mapping path in
vfs_implementation.c is therefore compiled out.
What is actually unusable on emscripten is the reserve/commit model,
and that is unusable by construction rather than by omission: a wasm
linear memory grows monotonically, is committed in full, and has no
unmap, no shrink and no page protection. An anonymous PROT_NONE
mapping is a memalign of the whole length followed by a memset over
it, so memreserve() commits and touches every byte the reservation
existed to avoid, mprotect() and madvise() cannot make commit or
decommit mean anything, and munmap() only accepts an exact length
match, so the range cannot be released. Opening large content through
data_transfer would allocate the whole file up front and never give it
back.
Leave memmap.h alone and gate MEMMAP_HAVE_RESERVE instead, so
mempagesize() reports 0, memreserve() returns NULL and callers take
the bounded-allocation fallback they already have for platforms
without virtual memory. memsync() is excluded from the msync() branch
for the same reason: emscripten's msync() only accepts the exact base
of a live mapping and returns -EINVAL for an arbitrary range, while a
wasm linear memory has no separate instruction cache to flush, so the
fallthrough's 0 is both correct and the only honest answer.
mmap(), munmap(), mprotect() and memprotect() keep working through
libc as before.
* memmap: round memrelease() to the page size memreserve() rounded to
memreserve() rounds the requested length up to a whole number of pages
and maps that, but memrelease() passed the caller's unrounded length
straight to munmap(). Linux rounds the length up internally so the
mismatch is invisible there, which is how it survived; an
implementation that takes the length literally and declines a partial
unmap fails the call outright and leaks the entire reservation
whenever the length was not already page-aligned.
Apply the same rounding on the way out. mempagesize() is non-zero
wherever this branch compiles - MEMMAP_HAVE_RESERVE is only defined
when _SC_PAGESIZE is available - but the guard costs nothing and keeps
the expression from dividing the range by zero if that ever changes.
* Revert "memmap: gate the reserve/commit path off for emscripten instead of dropping mman"
This reverts commit
|
||
|
|
bbdd85235f | tasks/task_save: stop reallocating and copying the undo snapshot on every state load (#19315) | ||
|
|
43d6fe0caf |
tasks/task_save: bound a transfer tick by time, fix three fall-through terminals, harden the rastate parser (#19314)
* tasks/task_save: bound the rastate parser against short and hostile input
A savestate is a file that arrives from outside. They get shared,
synced between devices, recovered off failing media, and the load
handler's own short-read path hands the parser a truncated buffer
directly. The rastate reader treated its input as trusted in four
places; ASan and UBSan report all four against a state file that is
merely truncated, with no craft involved.
content_deserialize_state read seven bytes for the "RASTATE" magic
and input[7] for the version with no length check at all. Any file
shorter than eight bytes overran the buffer before the block walker
was ever reached.
content_load_rastate1's loop bound was 'input < stop', so the body
could be entered with as little as one byte remaining and then read
the block length out of input[4..7] - up to six bytes past the end.
Any state truncated to 9..15 bytes. The bound is now
'input + 8 <= stop': a header that is not entirely present is not a
header. The END-block test moves above the new extent check so a
well-formed terminator, which carries no payload, is not rejected by
it.
A block's declared 32-bit length was never checked against the bytes
actually remaining, and was then passed to core_unserialize,
rcheevos_set_serialized_data and replay_set_serialized_data as the
size of a buffer that is not that large. Cores read what they are
told the buffer holds; that is the whole hazard. Blocks are now
refused when they declare more than the state contains. The
alignment advance is computed after that check - CONTENT_ALIGN_SIZE
of a length near UINT32_MAX would overflow a 32-bit size_t - and
clamped rather than rejected, since padding is written after every
block but the last one may sit flush against the end of the buffer.
The length itself was assembled as 'input[7] << 24 | ...' on an int:
input[7] is an unsigned char, which promotes to int, and int << 24 is
undefined for any top byte >= 0x80. That is every length at or above
2 GB - precisely the range a corrupt or hostile length lands in - and
the value it produces is the one the new bound check is asked to
trust. Assembled through uint32_t now. UBSan reports the old form.
No format change: every well-formed state parses byte-for-byte as
before, and the rejections are all of inputs that previously produced
an out-of-bounds read.
Verified: ASan reports nine distinct overflows against the pre-fix
file for the truncation and over-long-block cases, ending in a SEGV
inside the core's read of an unchecked block length; clean after.
UBSan clean. Full RetroArch build and link clean. Griffin-shape
single-TU compile clean.
* tasks/task_save: reach a terminal on the paths that used to fall through
Three ways a save or load task ended somewhere other than a terminal
state, all of them silent.
A failed core_serialize left state->data NULL and state->size 0, and
every test in the save handler then read as success: remaining was
MIN(0 - 0, CHUNK) == 0, so written == remaining, and written ==
size, so the handler took the completion branch. The task reported
COMPLETED, the user got a "state saved" notification, and because
the file had already been opened - and therefore truncated - the
slot was left holding zero bytes. The next load of that slot is the
first time anyone finds out.
The serialize now happens before the open rather than after it, so a
failure cannot have destroyed the previous contents of the slot on
its way out, and the failure is reported as an error on the task.
That reordering is the fix; the guard that used to stand around the
write is what let the fall-through happen and is gone with it.
A failed open was a bare return. The task was neither errored nor
finished, so the queue re-entered it on the next tick and it retried
the open forever. An open that failed once - read-only medium, bad
path, no space - is not going to succeed on retry, so this was not a
retry loop, it was a wedge: save tasks are TASK_TYPE_BLOCKING, which
means the queue admits at most one of them at a time, so that task
held the single blocking slot for the rest of the session. No state
could be saved or loaded again without restarting RetroArch. Both
new failure paths run through task_save_handler_finished, which now
tolerates a NULL state->file, since neither of them has one.
task_load_handler opened with a spin - while (frame_count < 2)
retro_sleep(1) - waiting for the core to be ready to accept a state
(Dolphin, via the CLI). Under the regular queue the handler runs on
the same thread that advances frame_count, so the condition it waits
on cannot become true and the spin is an unconditional hang; it goes
unnoticed only because frame_count is long past 2 by the time anyone
loads a state interactively, and CLI autoload is the one path that
arrives here early. Under the threaded queue it terminates, but it
is an unsynchronised read of a counter the video thread writes, and
TSan says so. Yielding does both jobs: the task stays queued and is
re-entered on the next tick, by which time the runloop has advanced
the counter. The read remains unsynchronised - it is a single poll
of a monotonic counter with no progress depending on observing it
promptly - and making it otherwise means changing the type of
video_driver_state_t::frame_count, which is a tree-wide change and
not this one.
Verified: against the pre-fix file, a failed serialize leaves a
zero-byte state file in the slot and the task reports success, and a
failed open leaves the task queued and blocking after 500 ticks;
both fixed. ASan/UBSan/LeakSan clean, with leak detection strict
since the new terminals are exactly where the serialized buffer and
the intfstream could be dropped. TSan clean under a threaded queue.
Full RetroArch build and link clean. Griffin-shape single-TU
compile clean.
* tasks/task_save: bound a transfer tick by time, not by one chunk
Both handlers transferred exactly one SAVE_STATE_CHUNK per queue
tick and then returned. That makes throughput a function of the
tick rate rather than of the device: 100 KB per tick at 60Hz is
about 6 MB/s no matter what the storage underneath can do. A 16 MB
core state took 164 ticks - 2.7 seconds at 60Hz - to write, and 164
to read back.
The frame was almost entirely idle while that happened. Measured on
NVMe, one 100 KB intfstream_write costs ~62us out of a 16667us
frame: 99.6% of every frame's budget spent not transferring, on a
task the user is waiting for.
The chunk constant was doing two jobs. It was the size of one
read/write call - which is what its comment describes, and which is
correctly sized for the worst storage RetroArch supports, a speed
class 6 SD card at 6 MB/s, so that a single call fits inside a frame
even there - and it was also, by being the whole of a tick, the
amount of work a tick could do. Only the first job needs a byte
count. The second needs a clock, because the quantity that has to
be bounded is the stall the user sees, and a byte count is a guess
about device speed that is wrong by two orders of magnitude across
the range of devices this runs on.
A tick now transfers quanta until a wall-clock budget is spent:
SAVE_STATE_TICK_BUDGET_US, 2000us, about 12% of a 60Hz frame. The
quantum keeps its old size and its old justification - it is what
bounds how far a handler can overshoot the budget, since a
read/write cannot be interrupted partway - which is why it stays
sized for the slowest device rather than the fastest.
The loop is do/while, so exactly one quantum is always transferred.
On a device slow enough that a single quantum exceeds the budget the
behaviour is therefore byte-for-byte what it was before this budget
existed. There is no worst case to regress, and that is asserted
rather than argued: the oracle drives the handler with a clock that
spends the whole budget on its first observation and requires
exactly one quantum per tick and a correct file.
Declined: raising SAVE_STATE_CHUNK instead. It would help the fast
devices and hurt the slow ones in the same motion, since the quantum
is also the granularity at which the handler can yield at all.
Verified: a 6.25 MB state that took 64 ticks to write takes 1;
round-trips byte-exact under both pacings, including an unaligned
tail. ASan/UBSan/LeakSan clean. TSan clean with the transfer loop
running on the queue worker. Full RetroArch build and link clean.
Griffin-shape single-TU compile clean.
* samples/tasks/save_state: regression oracle for task_save.c file I/O
Compiles the shipping tasks/task_save.c from the tree with the
frontend stubbed at link time, and drives it through the real task
queue. The core, the settings and the clock are the test's;
everything on the I/O path - both handlers, the rastate writer, the
block walker, intfstream, the VFS - is production code.
The clock is the instrument. cpu_features_get_time_usec() is
provided by the sample rather than linked from features_cpu.c, and
advances a fixed step per observation, which is what turns the tick
budget into something assertable exactly instead of measured: step 0
is a budget that never expires, step >= the budget is one that
expires on first observation. Neither depends on how many times
anything else reads the clock, since extra reads can only advance it
further.
Seventeen checks over two lanes.
The throughput property is asserted from both ends. With a budget
that never expires a 64-quantum state must be written in a single
tick, which is the point of the change; with a budget that expires
on first observation the handler must fall back to exactly one
quantum per tick and still produce a correct file, which is the
behaviour it replaced. A time budget is only an improvement if it
cannot be worse than the fixed count it replaced, so that is checked
rather than reasoned about. Round-trips run under both pacings with
an unaligned tail, because throughput work that corrupts the payload
is worse than the slow path it replaced.
The rest pin the audit's findings, each verified to fail against the
pre-fix tree: 65 ticks instead of 1; a zero-byte state file left in
the slot after a failed serialize, reported to the user as a
success; a save task still queued and blocking after 500 ticks
because it was retrying a failed open; three truncations accepted by
the block walker; and then a crash. Under ASan the pre-fix tree
produces nine distinct overflow reports across content_
deserialize_state and content_load_rastate1, ending in a SEGV inside
the core's read of an unchecked block length.
One thing worth stating about how that last one is caught. The stub
core reads every byte it is told the buffer holds before deciding
whether the size is one it likes, because that is what a real core
does and it is the entire hazard in an unchecked block length. A
stub that checked the size first would report the over-long block as
refused while the read never happened, and would pass against the
unfixed walker. ASan is the discriminator here, not the stub's own
opinion of the size.
Mutual exclusion between blocking tasks is pinned too. It is not
incidental: a save task that retried a failed open forever did not
merely fail to save, it held the single blocking slot for the whole
session, and that is only true because the queue admits one blocking
task at a time. The refusal path is also where task_push_save_state
has to undo everything it built - the task, its title, the state
struct, and the caller's serialized buffer, which it took ownership
of - so leak detection is strict and is the assertion for that half.
The threaded queue is a lane of this binary ("conc") rather than a
separate one. The pacing protocol is identical with and without
HAVE_THREADS - the locks only serialise it - so every tick-count
assertion belongs to the default lane, which is exactly
reproducible. What the threaded lane adds is a TSan target: the
transfer loop now carries a deadline across iterations and runs on
the worker, while content_deserialize_state and the undo bookkeeping
run on whichever thread gathers. It is one task at a time by
design, not by simplification - TASK_TYPE_BLOCKING means the
frontend cannot produce concurrent save tasks, so a lane that pushed
them would be asserting against a configuration that cannot occur.
Not asserted: compressed (rzip) states, which wrap the same handler
loop but are compiled out here; cheevos and replay blocks, likewise.
Wired into the samples/tasks workflow, running both lanes under all
three configurations.
Verified: both lanes pass; every failure mode above confirmed to
fail the oracle on the pre-fix tree; ASan/UBSan/LeakSan clean with
detect_stack_use_after_return; TSan clean; workflow YAML parses.
---------
Co-authored-by: libretroadmin <>
|
||
|
|
b5bdb0387a |
compression: route rzip-based compression through HAVE_COMPRESSION
The RZIP stream and everything built on it -- savestate and SRAM file
compression, playlist compression, the core-info cache, core backups and
the download auto-extract paths -- were gated on HAVE_ZLIB. RZIP goes
through the trans_stream DEFLATE backend, which now falls back to the
built-in codec, so all of these work without zlib. Switch their guards
from HAVE_ZLIB to HAVE_COMPRESSION.
Covered:
- interface_stream.c: the INTFSTREAM_RZIP stream type,
- task_save.c / save.c: savestate and SRAM compression,
- playlist.c: compressed playlists,
- core_info.c: the compressed core-info cache and the .zip content
extension,
- task_core_backup.c: compressed core backups,
- the SAVE_FILE_COMPRESSION / SAVESTATE_FILE_COMPRESSION settings and
their menu rows (settings_def_saving.h, menu_displaylist.c),
- menu_cbs_ok.c: the cb_decompressed download callback, whose
definition was still HAVE_ZLIB while its use had moved to
HAVE_COMPRESSION,
- retroarch.c: the save_file_compression reads passed to
event_save_files/autosave_init,
- runloop.c: the default ".zip" content extension,
- griffin.c: task_decompress.c is now included under HAVE_COMPRESSION
to match the Makefile.
Genuinely zlib-specific sites are left untouched: the replay checkpoint
and netplay wire formats that negotiate zlib specifically (bsvmovie.c,
task_movie.c, netplay_private.h), the CRC32 fallback in lrc_hash.c, and
the SUPPORTS_ZLIB capability advertisement. zlib builds are unchanged.
|
||
|
|
68972e7870 |
savestates: gate loading on the artifact, not on save-capability
Follow-up to 9a20309/f7790dc: the runtime probe unlocked SAVING on cores with stale metadata, but every LOAD path was still gated on save-capability, which measures the wrong thing twice over: - content_load_state() (the funnel all load paths go through) refused with 'Core does not support save states' based purely on metadata; - command_load_state_slot() additionally re-checked core_serialize_size() > 0 before loading - so even a core with CORRECT metadata could not load a state wherever it cannot currently serialize. Cores like boom3 legitimately report size 0 at the game's own main menu, which is exactly where users load a state to resume a session, while retro_unserialize() performs a full restore from there without issue. Principle: for loading, the artifact outranks the metadata. A state file the user produced (or a populated undo buffer) is sufficient grounds to attempt the load; retro_unserialize() is the final arbiter and fails gracefully. Concretely: - content_load_state(): allow when the state file exists (or when loading the backup buffer), regardless of metadata; - content_undo_load_state(): allow when the undo buffer is populated; - command_load_state_slot(): replace the core_serialize_size() > 0 recheck with path validity; - command_event_load_entry_state() / command_event_load_auto_state(): drop the early metadata gates; the funnel decides. Save paths are untouched: they keep the metadata gate with the runtime probe, which measures exactly the right thing for saving. |
||
|
|
4db4efcd16 |
state: add auto-increment savestate diagnostics (no behavior change)
Issue #18651 reports that with "Increment Save State Index Automatically" + "Maximum Auto-Increment Save States to Keep", the slot index advances but no file is saved in the new slot, the index sometimes stops advancing partway through the range, and loads then fail because the slot points at an empty file. This is not reliably reproducible without device-specific (Android) save-write behavior, so add targeted logging to pin down which of the linked defects fires, without changing any behavior: - command_event() CMD_EVENT_SAVE_STATE: log the auto-index slot advance (old -> new) that happens *before* the save is attempted. - command_event_main_state(): capture content_save_state()'s previously-discarded return value and log it, noting that the actual disk write is asynchronous so a "queued" save is not yet a successful one. - task_save_handler(): log the three terminal outcomes with the slot and path - the silent file-open failure (prime suspect on Android scoped storage, where the slot was already advanced), the mid-write failure, and successful completion. This is what shows whether the slot the frontend advanced to actually received a file. - command_event_set_savestate_auto_index(): the on-load scan already logged the found slot; also log the previous slot so a destructive reset (slot snapping back to the on-disk max index) is visible. With these, a user log will show the exact sequence: slot advanced to N, save task for slot N failed to open / failed to write / completed, and on reload the slot reset from N back to a lower on-disk index. That distinguishes "advanced-but-write-failed" from "scan-reset-the-index" and lets the underlying fix target the right defect (tying the slot advance to async save-task completion, and making the on-load scan non-destructive on gaps). |
||
|
|
def562b585 | Remove dead unused-variable declarations across core subsystems | ||
|
|
6c1a7ff79b |
Add timed automatic savestate (#18980)
* add autosavestate task * use auto slot for autosavestate, fix message hash * buildfix for platforms without thread support * fix compiler warning with slang cache while I'm at it * follow menu wording conventions and improve help text * put function call behind settings check --------- Co-authored-by: hunterk <[email protected]> |
||
|
|
e08f23d25a |
task_save / task_screenshot / command: migrate to cached_frame API
Commit 4 of 5 in the frame-cache redesign. Migrates the remaining
consumers off direct video_driver_state_t::frame_cache_* field
reads onto the lifetime-safe API introduced in 2ceb575.
tasks/task_save.c (5 sites):
Five identical 'is the cached frame HW-render?' sentinel checks
used to gate the SAVE_TASK_FLAG_HAS_VALID_FB flag on savestate
task creation. All replaced with the new
video_driver_cached_frame_is_hw_render() accessor. Behaviour
is identical (the new helper computes the same
(data && data == RETRO_HW_FRAME_BUFFER_VALID) predicate).
tasks/task_screenshot.c (screenshot_dump savestate path):
Reading frame_cache_width / frame_cache_height to decide the
savestate thumbnail dimensions. Replaced with
cached_frame_info() out-parameters. The remaining direct
frame_cache_data uses in this file (the
supports_read_frame_raw save-and-restore block) are not in
the async UAF surface and will become internal calls when the
field is made private in the next commit.
command.c (command_event_reinit defensive snapshot):
This code was already implementing exactly the
copy-inside-callback pattern that cached_frame_read makes
general -- it was the proof-of-concept that the redesign
generalises. Refactor the snapshot phase to use
cached_frame_read with command_reinit_snapshot_cb as the
callback; the publish phase (writing frame_cache_* fields
to hand the snapshot to the new driver) stays as direct
writes for now and becomes an internal call through the
setter API in commit 5.
Historical note: a 2018 patch series by Dwedit ("cached_frame_hack2"
on github.com/Dwedit/RetroArch) added the lifecycle-boundary
NULL-outs that this codebase has carried since. Those addressed
the synchronous UAF; this series closes the async window that
hack2 didn't reach, while keeping the CPU-side cached frame
that hack2's alternative branch (cached_frame_removal2) would
have removed entirely.
|
||
|
|
14a5cc00a0 | Fix Dolphin autostate load hang by sleeping a bit first | ||
|
|
5b73ff737c |
tasks: fix OOM bugs across save/load/patch/database/audio/decompress/http/wifi/steam/blissbox completion paths
Swept through tasks/ looking for unchecked malloc/calloc/realloc
returns followed by dereferences that would NULL-segv on OOM.
Fixes span 12 files and 22 individual sites; split by file:
* task_save.c (5 fixes):
- task_save_handler_finished: task_data calloc was
unchecked before a memcpy(task_data, state, ...) that
NULL-derefs on OOM. Now NULL-checked; on failure the
task_set_data attachment is skipped and save_state_cb /
undo_save_state_cb consume NULL via their own NULL checks
(added below).
- save_state_cb (consumer for task_save_handler_finished):
previously assumed task_data non-NULL and called
strdup(state->path) unconditionally. Now early-returns on
NULL task_data.
- content_load_state_cb (consumer for task_load_handler_
finished): previously dereferenced load_data->size / ->data
at variable initialisation time. Now NULL-checks first,
hoisting the field reads past the guard.
- content_load_and_save_state_cb: previously dereferenced
load_data->path / ->undo_data / ->undo_size / ->flags.
Now delegates to content_load_state_cb on NULL (which
handles NULL safely) and skips the save push.
- task_load_handler_finished: on calloc failure the
old code early-returned without freeing the on-thread
'state' struct or setting a task error - a pre-existing
leak plus silent failure. Now frees state->data + state
and sets a task error so the user sees the failure.
* task_translation.c (1 fix):
- PNG decode path: raw_image_data malloc unchecked;
the indexed write in the conversion loop NULL-derefs.
NULL-check + 'goto finish' (which NULL-safely frees
raw_image_data_alpha and rpng).
* task_patch.c (2 fixes):
- apply_patch_xdelta: *targetdata malloc unchecked;
xd3_decode_memory writes into it. NULL-check + set
PATCH_TARGET_ALLOC_FAILED + goto cleanup_stream (matching
the explicit ENOSPC handling below).
- indexed patch scan: four mallocs for
name_ips_indexed / name_bps_indexed / name_ups_indexed /
name_xdelta_indexed were unchecked before four strlcpy
calls that NULL-deref. Joint NULL-check returns true
early (same observable result as no extra patches found).
* task_database.c (1 fix):
- database_info_list_iterate_found_match: db_crc +
entry_path_str mallocs unchecked before the '[0] = \\0;'
stores that NULL-deref. Joint NULL-check frees whichever
succeeded and returns SCAN_VERDICT_ERROR so the scanner
moves on to the next content entry cleanly.
* task_audio_mixer.c (2 fixes):
- task_push_audio_mixer_load: nbio->path strdup was
unchecked; downstream strdup(nbio->path) in the ogg
upload handler is UB on NULL (POSIX). NULL-check +
goto error.
- task_push_audio_mixer_load_and_play: identical twin
pattern, identical fix.
(Note: these are NOT the audio_mixer UAF that was separately
reverted upstream as
|
||
|
|
0563af5c32 |
tasks/task_save: NULL-check temp_data malloc in content_undo_load_state
/* We need to make a temporary copy of the buffer, to allow the swap below */
temp_data = malloc(undo_load_buf.size);
temp_data_size = undo_load_buf.size;
memcpy(temp_data, undo_load_buf.data, undo_load_buf.size);
Unchecked malloc; the memcpy on the next line NULL-derefs on
OOM. This is the undo-load-state path triggered from the menu
('Undo Load State' action) - takes the previous savestate that
content_load_state overwrote and swaps it back in.
Fix: NULL-check temp_data. On OOM tear down the 'blocks' SRAM-
backup array that was built earlier in this same function (lines
190-212 pre-patch - it mirrors current SRAM into a scratch buffer
across the deserialize). Mirrors the normal-return cleanup path
at the bottom of the function.
Not using goto-cleanup because the existing function structure
doesn't have a single exit point and retrofitting one would
churn unrelated code. The inline cleanup at the OOM exit
reproduces the same two-loop teardown verbatim.
=== Not a bug ===
The pre-existing 'blocks[i].data = malloc(blocks[i].size)' at
line 212 and the matching one in content_load_state at line
1087 are both unchecked, but they don't crash: every downstream
use of blocks[i].data is gated on 'if (blocks[i].data)' (lines
217 and 1092 in the respective functions). On OOM the
corresponding SRAM block just isn't backed up / restored, which
is a graceful degrade.
=== Thread-safety ===
content_undo_load_state runs on the main/runloop thread. No
shared-state mutations; no lock discipline changes.
=== Reachability ===
User-triggered via menu 'Undo Load State' or the configured
hotkey. undo_load_buf.size is the size of the previous save-
state, typically tens of KB to a few MB depending on core.
Realistic OOM site on memory-tight embedded/handheld targets.
|
||
|
|
5bbec5f7f3 |
Use task error message if there is one. (#18944)
The task->error field was in practice only used as a flag, actual message was never shown to the user. |
||
|
|
3cf47f2489 |
task_save optimizations pt.1:
The buffer is calloc'd (zero-filled) to prevent inconsistent compressed output, but core_serialize() overwrites most of it. Use malloc() + memset only the alignment padding bytes (the gap between coremem_size and CONTENT_ALIGN_SIZE). Saves zeroing 2-16MB. Savings: Up to 80% of allocation time for large states Difficulty: Easy Risk: Low — padding bytes are the only source of nondeterminism |
||
|
|
59ead13c02 | Don't include stdstring in task_save.c | ||
|
|
b0624a720a |
Revert "task_save_handler improvements:"
This reverts commit
|
||
|
|
6e17be0d3f |
task_save_handler improvements:
1. Division by zero: early return when size <= 0 or data is NULL, avoiding the divide and handling the degenerate case cleanly 2. Separated cancellation from write failure: cancel just cleans up silently, write failure still reports the error — these are different situations 3. Eliminated unnecessary allocations: the old code did strdup into msg, then conditionally passed it to task_set_title, then freed it if unused. Now strdup only happens inside the !MUTE branch, so every allocation is consumed by task_set_title directly 4. Stack buffers scoped tighter: char msg[128] only lives in the blocks that need it, not across the whole trailing portion of the function 5. Removed dead write path: the old code skipped the intfstream_write when data was NULL but still checked written != remaining, which would always trigger the error path with written=0. Now that case is handled by the early return |
||
|
|
9dc9d16f63 | Reduce memory allocations | ||
|
|
1d5d8d58f4 | Revert code back | ||
|
|
70d8a97b2c | Replace some files inside dungeon# Please enter the commit message for your changes. Lines starting | ||
|
|
f724cc370f |
Allow savestate undo disable for pcsx_rearmed on old3ds (#18755)
* Makefile.ctr: enable gc-sections This frees ~160k of RAM without any downsides that I know of. It's not much, but helps pcsx_rearmed on old3ds where it barely fits in RAM. * remove some dupe logic Regardless if `save_state_in_background` is enabled or not, it does exactly the same so the check can be removed. * optimize RAM state load content_load_state_from_ram() doesn't need the backup copy, content_save_state() never touches the ram_buf. It seems the whole logic was copy-pasted from content_undo_load_state() without thinking. * avoid useless memory use and copying Just take the source pointer instead of making a copy and then freeing it. This is a big deal on slow platforms having to deal with large states, like psx on old3ds. * allow the core to disable the savestate undo feature The undo feature may amount to at least 4 simultaneous buffers: save undo, load undo, the current save/load buffer, temporary buffer. When emulating a system with relatively large states on a system with little RAM (like PSX on old3ds) that amounts to something like ~18MB of ~42MB available to the core. Under memory pressure the libctru variation in RetroArch tries to salvage some memory from the main stack and linear memory, but since those are variable, they start to overlap creating instability. The solution is to just disable the undo feature. |
||
|
|
5b6c93a5bc | Incremental statestream checkpoints for replays (#18213) | ||
|
|
661e5b55cb | Some more malloc/realloc casts for C++ | ||
|
|
546388a5bd | Reduce some gotos in tasks | ||
|
|
195c19a1c9 | Fix more static code analysis errors/warnings |