Commit Graph
123 Commits
Author SHA1 Message Date
LibretroAdmin 60cb421bc0 playlist: pack an entry's slot, runtime status and thumbnail flags
The three ride in one word: the slot index is a subsystem content
slot, the runtime status has three values, and the thumbnail flags
are five bits. struct playlist_entry goes from 120 bytes to 112, so
a large playlist sheds another eighty kilobytes on top of what the
timestamps returned.

The JSON reader gains one more name for the slot, since a packed
field has no address to hand it.
2026-09-12 11:07:32 +02:00
LibretroAdmin 5599a3176b playlist: pack an entry's runtime and last-played values
The nine values ride in three words instead of nine: hours get 20
bits, which is 119 years of play, and the rest are what a calendar
and a clock allow. struct playlist_entry goes from 152 bytes to 120,
and a playlist holds one per item, so a large one sheds hundreds of
kilobytes.

The JSON reader named these fields by taking their address, which a
packed field does not have, so it now names which one it is filling
and goes through the setters.
2026-09-12 10:59:36 +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 a523b12547 runtime_file: bound the offset the last-played string is built from
Twelve writes in runtime_log_get_last_played_str() size themselves as
len - _len, and _len is whatever strlcpy() returned for the label at
the top, which is the length of its source rather than the length it
wrote. A translation longer than the buffer therefore turns every one
of those into a very large size_t with the destination already past
the end, so the label offset is clamped once where it is taken.

The AGO branch holds two octets back and so needs room for them and
for the separator before it writes either, and the helper it calls
takes its own offset from snprintf(), which reports the same way.
2026-08-20 07:18:25 +02:00
libretroadmin cc4b0ba7d4 disk index/runtime log: create record directories at save time
Both record initialisers created their output directory up front:
disk_index_file_init() stat'ed (and if needed mkdir'ed) the
savefile directory on every content load, and runtime_log_init()
did the same for the runtime log directory on every call.  The
runtime log case is the expensive one - the playlist sublabel path
initialises a log per playlist entry purely to *read* recorded
runtime, and each of those inits paid a stat for a directory that
a read never needs: if the directory does not exist, neither does
any log inside it, and the read correctly comes back empty either
way.  The disk index case is one stat per content load for a
record most content (anything single-disc) never writes.

Create the directory in the save functions instead, derived from
the record path, immediately before the write that actually needs
it.  Read paths pay nothing; write paths pay the same stat they
always did, at the moment it is meaningful.

One behavioural edge moves with it: an un-creatable directory no
longer fails init (runtime_log_init() returned NULL, disabling
runtime tracking for the session; disk_index_file_init() disabled
the record).  Reads now proceed - correctly finding nothing - and
the failure is reported by the save that actually hits it.
2026-08-16 09:49:05 +02:00
libretroadmin 3527de5d26 disk index/runtime log: serialize records in memory, write once
The two small-record rjson writers - the disk index record and the
runtime log - opened their output file first and then streamed the
JSON into it through the buffered writer adapter.  For documents
of a few hundred bytes that shape has no streaming benefit and one
real hazard: the open truncates the previous record before a
single byte of the replacement exists, so every failure past that
point - writer allocation, a write error, a crash or power loss
mid-save - destroys the old record and leaves a zero-length file
where it stood.  Those empty files are exactly what the read side
was just taught to tolerate; this removes the machinery that
manufactures them.

Serialise into rjsonwriter_open_memory() and commit the finished
document with a single filestream_write_file() call: one open, one
write, one close, and the previous record is only replaced once a
complete replacement exists.  The failure window collapses from
the whole serialisation to the single write call.

This also makes the disk index writer's failure handling honest:
it logged rjsonwriter_free() reporting a write error, then cleared
the 'modified' flag and returned success anyway, so a failed write
was never retried and the caller never knew.  Failures now leave
the record modified - a later save retries - and return false.
The writer-allocation failure path also no longer costs the old
record its contents.

Both translation units lose their last use of the
formats/rjson_stream.h adapter; the include goes with it.
2026-08-16 09:49:02 +02:00
libretroadmin 8c7b823ac3 rjson callers: fix filestream_read_file failure check
1dfed08090 converted five small-file rjson readers from the
stat + open + chunked-callback pattern to filestream_read_file()
+ rjson_open_buffer(), on the premise that "filestream_read_file's
failure covers missing files".  It does, but not the way the
conversion tested for it: the function returns 1 on success and 0
on failure - never a negative value - and all five call sites
checked '< 0', a condition no return value satisfies.

The failure branch was therefore dead.  For any content whose
record file does not exist - which is the common case the commit
message itself called out - the reader sailed past the check with
buf == NULL and len == 0, handed that to the parser, and logged a
JSON format error for a file that was never there:

  [WARN] [Disk index file] Error parsing disk index file: "...".
  [ERROR] [Disk index file] Error: Invalid JSON at line 1,
  column 1 - reached end without any data.

Reported against the disk index record (single-disc content never
writes one, so every load logged the pair), but all five readers
were affected the same way: the runtime log spams one per playlist
entry without recorded runtime, and the test input drivers and
Remote RetroPad lose their quiet no-file path.  Worse than the
noise: on the exists-but-unreadable branch filestream_read_file
documents len as unspecified (in practice -1), and the missed
check would have sent (size_t)-1 as a buffer length into the
parser alongside a NULL buffer.

Test the return as the boolean it documents and every other caller
in the tree already treats it as.  The failure branches behave as
the conversion intended: silent return for a missing file,
path_is_valid classifying the failure worth logging otherwise.

Verified: all five translation units rebuilt clean; standalone
harness over file_stream + rjson confirms a missing file now takes
the quiet branch, a present record parses to RJSON_DONE, and that
the old '< 0' check misses both failure shapes.
2026-08-16 09:37:31 +02:00
LibretroAdmin 1dfed08090 rjson callers: read small JSON files whole instead of stat + chunked
Audit of every rjson / rxml call site's surrounding file I/O,
following the codecs' decoupling.  The rxml side needs nothing:
its production consumers parse buffers that arrive without the
adapter (logiqx through the scanner's budgeted incremental read,
natt from network payloads), and the filestream adapter is used
only by the sample harness and the treehash tool.  On the rjson
side, the large streaming consumers are already shaped right -
playlist, core info cache and the explore state read through
buffered (and RZIP-aware) streams with no redundant pre-open
checks, cloud sync opens tolerantly with no extra stats, and the
writer flushes in buffered chunks - but the small-file readers all
shared one wasteful pattern: stat the path (path_is_valid), open
it, let the stream adapter fstat it again for io block sizing,
then read a few hundred bytes through the chunked callback
machinery.

Five readers convert to filestream_read_file() +
rjson_open_buffer(): the runtime log (the hot one - playlist
sublabels showing per-core runtime build one of these per entry),
the disk index record, the two test input drivers, and the Remote
RetroPad core (the latter three being the reference code this
pattern kept getting copied from).  One open/size/read/close per
file, parse from memory, no callback crossings - and the
up-front stat is gone: filestream_read_file's failure covers
missing files, and path_is_valid now runs only inside the failure
branch to decide between the old quiet no-file path and the old
error message, so every log line and return value is preserved
while the common case pays one filesystem operation less.  These
files are a few hundred bytes to a few KB and always parsed in
full; holding them in memory for the parse is what the parser's
own input buffer was already doing, minus the chunking.

Verified: strict declaration-placement gates clean on the C89
TUs; the net-retropad translation unit syntax-checked standalone;
full Linux build links with HAVE_QT=1; no rjson_open_filestream
readers remain outside the write-side handles the buffered writer
still streams through.
2026-08-15 06:11:52 +02:00
LibretroAdmin fe5dd9217e rjson: move file I/O out of the codec
The contract for libretro-common/formats is that a codec imposes no
file I/O through its interface: parsing and writing run over
caller-supplied buffers or caller-supplied callbacks, and how bytes
reach the parser - filestream, intfstream, or anything else - is
the caller's decision, not the format's.  rjson violated it four
ways: rjson_open_stream / rjson_open_rfile and their writer
equivalents lived inside rjson.c, coupling the codec translation
unit to both stream layers for the sake of four thin shims.

The shims move to a new opt-in, header-only adapter
(formats/rjson_stream.h) as static INLINE functions with names that
say what they couple to: rjson_open_intfstream /
rjson_open_filestream and the rjsonwriter equivalents, preserving
the size-scaled io block heuristic.  Including the adapter couples
the including translation unit - and only it - to the stream
layers; rjson.c and rjson.h now reference no I/O at all, and a user
with their own I/O wires rjson_open_user / rjsonwriter_open_user
directly, exactly as the in-tree callers now demonstrate.

All sixteen call sites across the nine in-tree callers migrate
mechanically (core_info, net-retropad, disk_index_file, the two
test input drivers, menu_explore, playlist, runtime_file,
cloudsync).  One latent bug surfaced: rjson.c used INLINE while
reaching retro_inline.h only transitively through the stream
headers it no longer includes; it now includes it explicitly.

Verified: rjson.c passes the strict C89 gate standalone (it could
not before - the missing include was masked); full Linux build
links with HAVE_QT=1; strict gates clean on the migrated C89
callers; net-retropad translation unit syntax-checked; no
remaining references to the removed constructors anywhere in the
tree.
2026-08-15 05:51:06 +02:00
Ryunam 521e4f0f8e Playlists: Fix state_slot in runtime logs being saved to entry_slot (ex.: in History) (#19223) 2026-07-17 19:34:47 +02:00
libretroadmin 059ca263df build: fix CXX_BUILD=1 compilation
Compiling the C sources as C++ (CXX_BUILD=1) failed in 12 places where
the code relied on implicit conversions that C permits but C++ rejects.
All are mechanical and behaviour-preserving:

void* -> typed pointer (explicit cast):
  - input/common/linux_common.c  (illuminance sensor data)
  - tasks/task_screenshot.c       (copy.buffer -> uint32_t*)
  - libretro-db/rmsgpack_dom.c    (alloca result -> dom_value**)

const char* -> char* (strrchr/strchr return values):
  - libretro-common/file/file_path.c  (cast strrchr result; matches the
    char* return contract of the C function)
  - configuration.c                   (extra_path points at a mutable
    stack buffer that is written through -> make it char*)
  - menu/menu_displaylist.c           (hash_type likewise -> char*)

integer -> enum (explicit cast at use site):
  - runloop.c           (unsigned pending_cmd -> enum event_command)
  - runtime_file.c      (settings uints -> last_played style/separator)
  - tasks/task_database.c (int iterate result -> enum scan_verdict)
  - menu/menu_driver.c  (unsigned confirm_msg -> enum msg_hash_enums)

std::atomic copy:
  - cheevos/cheevos.c: the static rcheevos_locals aggregate brace-init
    of the two retro_atomic_int_t members used a bare '0', which under
    CXX_BUILD (std::atomic<int>) selects the deleted copy constructor.
    Use {0} so C++ list-initializes via the converting constructor;
    for the C atomic/int/volatile backends {0} is an equivalent scalar
    initializer.

With these, the tree compiles cleanly under CXX_BUILD=1 (every object
builds and the link stage is reached). This addresses the compilation
failures from #6009; note that CXX_BUILD has no CI coverage, so it will
regress again as new C-idiomatic code lands unless a build job is added.
2026-06-25 09:47:38 +02:00
sonninnos 65fe838e00 Add Load State to Run menu (#18997) 2026-05-02 04:59:06 +02:00
Eric Warmenhoven 2a5497bba8 asan 2026-04-16 19:19:45 -04:00
U-DESKTOP-SPFP6AQ\twistedtechre 9708810444 More string_is_empty removal 2026-04-07 04:53:28 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre d6d483c885 (runtime_file.c) Include missing header errno.h 2026-04-06 09:35:42 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre a158a37d92 Replace sscanf 2026-04-06 09:27:08 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 8ee461a66d replace more string_is_equal cases with memcmp 2026-04-02 21:10:15 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 7f53f79e2a * less stdstring dependencies
* replace string_is_equal with memcmp
2026-04-02 17:35:07 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 902aaac598 core_info improvements:
* Bugfixes:
1.  Fixed operator precedence in core_info_core_file_id_is_equal — moved ) so sizeof(core_file_id_a) is passed as the buffer size (256) instead of sizeof(...) == 0 which evaluated to 1.
2. core_info_list_free now frees the struct itself. Removed the redundant free(core_info_list) calls in core_info_list_new error paths, and core_info_deinit_list no longer leaks.
3. core_info_get_core_updater_info now calls config_file_free(conf) before returning NULL on malloc failure.
4. core_info_init_current_core now calls core_info_free_current_core() first if there's an existing allocation.
5. Removed dead if (!info) continue checks in core_info_cache_find and core_info_check_uninstalled (address-of array element is never NULL).
6. Removed redundant double-assignments of capacity, refresh, and version in core_info_cache_list_new.
7. Cache writer now tracks a first_written flag instead of relying on i > 0, preventing a leading comma when early entries are skipped.
8. Added NULL guard for display_name in core_info_qsort_cmp before strcasecmp.
* Performance:
1. Collapsed four identical core_info_current_supports_* functions into one core_info_current_supports_savestate_level helper.
2. Batched consecutive rjsonwriter_raw calls (e.g. ":" + " " → ": ", "," + "\n" → ",\n"), roughly halving function call overhead in the JSON write loop.
* Memory:
1. Replaced 8 bool fields in core_info_t with a single uint8_t flags bitfield and CORE_INFO_FLAG_* defines. Saves ~28 bytes per struct with typical alignment.
2. Cache hits in core_info_list_new now use core_info_transfer instead of core_info_copy, moving pointers instead of deep-copying ~30 strings/lists per cached core.
3. core_info_init_current_core now uses calloc instead of malloc + 25 manual zeroing assignments.
2026-03-12 19:09:09 +01:00
U-DESKTOP-SPFP6AQ\twistedtechre 191e3ee252 runtime_file.c - improvements:
* Bugfixes:
1. Loop bound fix — sizeof(periods) - 1 → ARRAY_SIZE(periods) - 1 with the bounds check moved before the value check to prevent out-of-bounds read
2. Format mismatch — (int)delta → (unsigned)delta to match %u
3. Consistent sscanf format — %04u → %u for state_slot parsing (matches the write side)
4. NULL guard — added if (!runtime_log) return; to runtime_log_get_last_played_time
5. Parse failure bailout — rjson_parse failure now frees the parser and jumps to end: instead of falling through to process potentially corrupt data
6. Bounds check — added if (_len + 2 >= len) return _len; before the manual space/NUL write in runtime_last_played_human
7. Symmetric NULL handling — runtime_log_get_last_played now zeros all output pointers when runtime_log is NULL, consistent with the _str variant
2026-03-12 18:11:05 +01:00
sonninnos 019c078c6e Buildfix with menu disabled 2026-01-23 19:11:39 +02:00
libretroadmin babd363987 Style nits/cleanups - control flow refactors 2025-08-05 04:22:41 +02:00
sonninnos 563b687db8 Auto+entry state sanity checks and reorderings 2025-08-04 19:17:12 +03:00
sonninnos 5eca25067a Add play count to runtime log (#18141) 2025-08-03 01:19:37 +02:00
sonninnos 405c3476f5 Save state slot improvements (#18140)
* Stop polluting playlists with redundant entry_slot numbers

* Playlist entry_slot improvements and cleanups

* Save current state slot to runtime log
2025-08-02 23:38:18 +02:00
libretroadmin efc1f7f8e1 Variable naming cleanups 2025-07-17 06:10:48 +02:00
sonninnos b2ca569521 Logging unification cleanups 2025-07-10 05:59:06 +03:00
libretroadmin e13140ba04 Rewrite some strlcat calls into strlcpy 2025-06-26 14:47:53 +02:00
LibretroAdmin 0b329018ee Less string buffers and less string copies 2025-01-16 23:59:22 +01:00
LibretroAdmin 47d199297a runtime_file.c - Move scope of menu_driver_ident call 2025-01-15 12:45:05 +01:00
LibretroAdmin fb338b90bf Turn some functions to returntype size_t 2025-01-12 23:03:41 +01:00
LibretroAdmin 0a7b409a04 (runtime_file.c) Use fill_pathname 2024-12-28 19:41:10 +01:00
LibretroAdmin a3f631e310 Fix label - 'Never' was always shown for playlist runtime 2024-12-28 18:43:46 +01:00
LibretroAdmin ed58e4a8d8 Conventionalize len variables:
* In function arguments, use 'size_t len'
* Inside the function, use '_len'
* If you need a seciondary len variable inside the function, use '__len'
2024-12-27 05:51:33 +01:00
libretroadmin 8074a833aa Cleanups/less string copies and indirection 2024-12-24 21:07:31 +01:00
LibretroAdmin 739f2ff55c Reduce calls to path_remove_extension - use fill_pathname instead (#17270)
* Reduce calls to path_remove_extension - use fill_pathname instead

* More fill_pathname usage
2024-12-20 21:40:58 -08:00
libretroadmin 29f011acef * Inline find_last_slash
* explore_load_icons - fill_pathname_slash is equivalent to usage
of strlen here, no need to call strlen
2024-09-10 16:02:06 +02:00
libretroadmin 27ffd4f00b Buildfix 2024-09-09 16:02:15 +02:00
libretroadmin 73e5d955c3 Downgrade some more variables to NAME_MAX_LENGTH 2024-09-09 16:01:29 +02:00
libretroadmin b8391e233f * PATH_MAX_LENGTH redefined from 4096 to 2048
* Massive reduction in heap space allocation, going from settings struct
264kb to 119Kb
* Use NAME_MAX_LENGTH for base paths/names, etc
* Use DIR_MAX_LENGTH for directory sizes
2024-09-09 05:47:32 +02:00
zoltanvb 7a475c7195 Remove some temporary buffers (#15624) 2023-08-20 10:59:15 -07:00
zoltanvb 7198f10875 Remove a needless temporary buffer from runtime_log_get_runtime_str() (#15585) 2023-08-12 05:47:00 -07:00
zoltanvb 0c64a07cdb Fix runtime display. (#15581)
Due to an error in 631301b3f7, the
runtime display string was working well only when the label had
a length of 7. Even the English "Runtime:" was a bit truncated
as a space was supposed to be added after the :, but it was
even more noticeable in other languages.
2023-08-11 14:16:50 -07:00
libretroadmin 6e06f14180 Cut some more strlcat calls 2023-07-16 22:21:43 +02:00
libretroadmin 9e34f22a29 Silence Xcode code warnings + general cleanups 2023-07-14 18:05:54 +02:00
libretroadmin 46d6240f21 Rewrite some more strlcat calls 2023-06-20 19:52:38 +02:00
libretroadmin bdc398d79f - Safer code - use strlcpy where possible instead of manual character
assignments for strings longer than 2 chars
- Use strlcpy concatenation instead of strlcat
- Make sure that what remains of iteration of the '_len' variable
for manual char assignment
is done in a safer way so mistakes are less possible
2023-06-20 16:33:55 +02:00
libretroadmin 631301b3f7 * Cut down on strlcat calls when possible and replace them with clever
usage of strlcpy (when position/offset of previous strlcpy/snprintf call
is known. strlcat implementation in libretro-common makes implicit strlen
call, using strlcpy avoids this
* Reduce a bunch of local char variables by use of said clever usage,
should save up on local stack size usage
2023-06-18 12:06:12 +02:00
libretroadmin 373d1307c0 (runtime_file.c) Cleanups - remove functions that are never used 2023-06-16 01:23:24 +02:00