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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
* 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.
* 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
* 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
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.
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
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