Commit Graph
56 Commits
Author SHA1 Message Date
LibretroAdmin cdf84534e2 cheat_manager: search by region, skip ruled-out items, one loop per test
A memory search visited every item of the core's memory in turn: a
region lookup, a branch on item size, a loop over sub-items that at
byte size and wider runs once, and a branch on the search type, even
for items an earlier search had already ruled out - after a search or
two, nearly all of them. Each failing item also cost a memset call,
and the match count was reloaded and stored every item, since stores
through the uint8_t match bytes may alias it.

Now:

- Regions are walked in order, items at multiples of their size lying
  whole inside one, as before, without a lookup per item.
- Runs of clear match bytes are stepped over 16 bytes at a time with
  SSE2, 32 with AVX2 or 64 with AVX-512BW (chosen at run time from
  cpu_features_get(); built per function, and under PlayStation clang
  or clang-cl only where the baseline enables them), or a word at a
  time elsewhere. An item is still judged by its first match byte: a
  set byte part-way through one, which a change of item size between
  searches can leave, rounds back to the item's start.
- At byte, 16- and 32-bit sizes the search type is chosen once and
  each type gets its own loop, with direct stores for a failing item
  and the count held in a local. The 1-, 2- and 4-bit sizes keep the
  general path.

32-bit values were assembled as byte * 256 * 256 * 256 in int, which
overflows (undefined) for a top byte of 0x80 or more; they use
unsigned shifts now, the same value.

33 MB of memory on an AVX-512 Xeon, before -> after:

  8-bit items:  first search 270-344 -> 45-48 ms,
                after one search 146-188 -> 91-126 ms,
                after two 128-162 -> 9-12 ms
  32-bit items: first search 75-125 -> 18-80 ms,
                later searches 49-66 -> 5-11 ms

samples/cheats/cheat_search keeps the previous algorithm as its
reference and checks the match bytes, the match count and the saved
memory after each of 14400 chained searches: random region layouts,
every item size, both byte orders, every search type, memory changed
between searches in runs or scattered, the item size changed without
starting over, and the scan capped at each SIMD tier in turn.
samples/cheats/cheat_regions reports no SIMD, so it runs the baseline
scan.
2026-10-28 05:43:40 +01:00
Acts1631andLibretroAdmin eeeaa77a37 Cheats: validate ranges before applying memory writes (#19807)
* Cheats: validate ranges before applying memory writes

Cheat files can specify addresses outside the core memory map or place a
multi-byte value across the end of a memory region. The apply path used
the resulting offset for unchecked native memory reads and writes.

Resolve the complete access range against one core memory buffer before
reading it and before every repeated write. Skip entries and stop repeat
sequences when their requested range is invalid.

* cheats: one region lookup for every memory access

Cheats and cheat searches reach core memory through cheat_region_seek,
which finds the region holding a whole item and keeps it, so a walk
that stays inside a region does not search the region list again. The
three search paths read through it too: an item crossing a region's end
is left out of the matches when a search starts, and browsing one
leaves the values as they were. A condition whose address cannot be
read does not hold, so the cheat it guards does not run.

samples/cheats/cheat_regions maps three regions of awkward sizes, each
allocated exactly, and runs cheats and searches across their edges
under the sanitizers. The .gitignore rule for the cheats directory is
anchored to the root so the sample can be tracked.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-10-14 19:51:27 +02:00
LibretroAdmin e39e641802 runloop: put cheats, presence, camera and BSV behind frame_work bits
The post-core_run product block called into four translation units
every frame to find out nothing needed doing: cheat_manager_apply_
retro_cheats() loads a cold global to see there is no cheat list,
presence_update() calls discord_update() and steam_update_presence()
which each compare a status word and return, the camera poll reads
settings_t for camera_allow before the caps check, and
bsv_movie_next_frame() pulled two settings through config_get_ptr()
before checking whether a movie handle exists at all.

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

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

BSV needs no bit: the movie handles live on input_st, which the frame
already has in cache, so the iterate tests the pointers directly and
bsv_movie_next_frame() checks its handle before touching settings.
2026-09-29 20:11:58 +02:00
libretroadmin 137d495ab1 Remove eleven write-only state fields
Each of these is assigned and never read anywhere in the tree, so the
work that feeds them is spent for nothing: content_label_len on the
thumbnail path data, sink_discarded on the audio state,
runahead_save_state_size, task_count and msg_queue_regular_padding_x on
the widgets, pipeline_active on the display draw struct,
resolution_hd_enable on the D3D8 and D3D9 states,
memory_search_initialized on the cheat manager, window_title_len and
video_frame_delay_auto_t::frame_time_avg on the video state, and
input_dialog_kb_type on the menu state. Where a write captured a
strlcpy() or fill_pathname() result the call stays and only the
assignment goes.

Two of them were holding up more than themselves.
gfx_widgets_update_icon_layout() branched on whether icons are loaded
solely to pick a padding value, so that conditional computed nothing
and is gone with the field. memory_search_initialized sat beside
memory_initialized, which is read, leaving two near-identical names for
the next reader to tell apart.
2026-09-14 19:06:30 +02:00
libretroadmin af165889ef Drop write-only frame limit field and read the clock once per cheat pass
runloop_state_t::frame_limit_last_time is written on content load, on the
quit path and once per iteration inside the timer pacing block, and is read
nowhere - the nanosecond anchor carries the schedule on its own. The field
goes, and with it the divide the pacing path did to feed it.

cheat_manager_apply_rumble() takes the timestamp from
cheat_manager_apply_retro_cheats() rather than reading the clock itself. It
runs once per cheat per frame and returns immediately for every entry whose
rumble type is disabled, so one reading now serves the whole pass and every
cheat in a frame is applied at the same instant. The function is file-local
and is marked static.
2026-09-14 17:25:07 +02:00
LibretroAdmin 7d98d16295 config_file: stop walking the list to find its end on every insert
config_set_string() and config_unset() went through
config_get_entry_internal(), which on a miss walked the entire entry
list to hand back its last node. The insert path needed that node to
append to. It does not any more - conf->tail is authoritative since
the trackers were collapsed - but the walk stayed, and it is
quadratic: 203701 fresh inserts spend 126 seconds in it against 0.17
seconds past it.

That walk is the whole reason
CONF_FILE_FLG_GUARANTEED_NO_DUPLICATES exists. Setting it skips the
lookup, and skipping the lookup skipped the walk. With the walk gone
the flag is worth one hash probe per set - 11ms across those same
203701 inserts - and config_get_entry_internal() is just
config_get_entry(), so it goes.

The flag mattering less is the point, because it was being set where
it is not true. cheat_manager_save(!overwrite) parses the existing
.cht file and then promises the setters that none of the keys it is
about to write are present - when every one of them is. Each set
appended a second entry instead of replacing, the file was written
with both, and since the first of a duplicate pair wins on reload,
the save looked correct in memory while the file on disk kept its old
values and grew by a full duplicate set each time. For a cheat file
from libretro-database that is 203701 lines added per save. The flag
now goes on only in the branch that allocates the config empty, which
is the only branch that can keep the promise; the menu's 'save as a
named cheat file' path (menu_cbs_ok.c) is the one that reaches the
other branch.

The flag's declaration says all of this now, including what it is
worth, since the reason to reach for it has mostly evaporated.
Deprecating it outright is defensible - one hash probe per set
against a footgun that silently corrupts saved files - but that is a
separate decision and both in-tree users are correct as of this
commit.

Tests: setting over keys a parsed config already holds must survive a
dump and reparse with no duplicates, and 40000 inserts without the
flag must not take seconds. 47 checks, clean under ASan+UBSan+LSan.
2026-09-12 17:21:16 +02:00
Rob Loach 559962cae0 SDL3: Fix On-Screen Keyboard, opt-in for System Keyboard (#19389)
* sdl3: Add On-Screen Keyboard Input

See this thread for all the details
https://github.com/libretro/RetroArch/pull/19389
2026-09-11 12:16:34 +02:00
LibretroAdmin 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 cdd5a2feca menu_input_dialog_end: not available if HAVE_MENU not defined 2026-07-29 10:56:50 +02:00
libretroadmin 96e767c48e Silence warnings 2026-07-19 19:02:48 +02:00
libretroadmin 90f1d285bd cheats: heap-allocate the editor code scratch on first use
The cheat manager state carried a sixteen-kilobyte code-editing
scratch buffer resident in every binary, used only when the cheat
editor runs. It is now a pointer allocated by an ensure helper with
two choke points: the editor entry in copy-idx-to-working, and the
cheat settings builder just before the rows that bind the scratch's
address - necessary since under the lazy settings cache that
builder can run at any moment a lookup first needs it. The scratch
is deliberately never freed once allocated: menu rows hold its
address across content sessions, exactly as they held the old
static array; freeing with the manager would dangle them. The
sizeof at the two binding sites becomes the scratch-size constant
it always meant. Both dumps byte-identical - the settings dump
prints the cheat rows through the ensured buffer.
2026-07-07 16:56:42 +02:00
Aramis ff00d957cc cheat_manager: fix realloc (p, 0) leading to double free (#19106) 2026-06-14 16:53:37 +02:00
RWCandbdm110 90d631c610 menu: allow direct input for +/- cheat search values (#19071)
Co-authored-by: bdm110 <[email protected]>
2026-05-28 02:40:47 +02:00
RWCandbdm110 62b81b6a22 menu: allow direct input for exact cheat search value (#19070)
* (menu) Add input callback for exact cheat search and update menu action

* Updated to fix the C89 CI failure by removing the C++-style comment.

---------

Co-authored-by: bdm110 <[email protected]>
2026-05-27 07:53:57 +02:00
libretroadmin 2547c1351e Revert msg_hash_to_str_pair API and call-site conversions
Reverts the following four commits as a single change:

  c6e570a msg_hash: fix orphan _msg references after _pair conversion
  a50bb8d msg_hash_us: skip msg_hash_to_str_us wrapper on hotkey-bind path
  2c13b7c msg_hash: convert 56 runloop_msg_queue_push sites to _pair API
  25266fb msg_hash: add msg_hash_to_str_pair / _len (compile-time length)

Reasons:

  * The PS3 / PSL1ght build (PPC64 ELF ABI, 64K TOC limit) breaks with
    relocation truncated to fit: R_PPC64_TOC16_DS against '.toc'
    in runtime_file.c after these commits.  The added per-locale
    msg_hash_to_str_pair_us function carries a second copy of the
    ~5000-case dispatch through msg_hash_us.h, each case touching a
    string literal that needs a TOC entry, doubling TOC pressure in
    the griffin unified-build object and pushing it past the 64K
    threshold that the PPC64 small-model linker can address.

  * The measured gains were modest (1.18x on regular entries, 1.10x
    on the hotkey-bind range) for an event-driven path that fires on
    user actions, not per-frame.  The cost in TOC budget on a 256 MiB
    platform with strict ABI constraints is not justified by the
    win on platforms where the budget is essentially unlimited.

Net delta: 14 files, -776 lines (the helpers, the 56 call-site
conversions, the hotkey-bind specialization, and the orphan fixups
all reverted).  msg_hash_to_str remains the sole dispatch as before.
2026-05-20 02:45:30 +02:00
libretroadmin 2c13b7c456 msg_hash: convert 56 runloop_msg_queue_push sites to _pair API
The dominant pattern across the codebase was:

  const char *_msg = msg_hash_to_str(MSG_X);
  runloop_msg_queue_push(_msg, strlen(_msg), prio, dur, ...);

Two operations were paying for one: msg_hash_to_str dispatched
through a per-locale switch returning the literal, then strlen
walked the returned string at runtime to recover a length that
was already a compile-time constant inside the switch.

Convert mechanical declaration-and-push sites to:

  msg_hash_str_pair_t _p = msg_hash_to_str_pair(MSG_X);
  runloop_msg_queue_push(_p.s, _p.len, prio, dur, ...);

One dispatch returns both fields.  Each MSG_HASH case sets .s
to the literal and .len to sizeof(literal) - 1 (constant), so
the per-case body is two register stores + a struct return.
Strict MSVC C89 throughout — declarations stay at the top of
their enclosing block exactly as before.

Why _pair and not _len here?  The naive substitution
'strlen(_msg)' -> 'msg_hash_to_str_len(MSG_X)' doubles the
switch dispatch — the parent commit's bench measured that at
0.61x (a 1.6x slowdown) vs the original strlen.  _pair runs
at 1.18x (faster) because it fuses both lookups into one
dispatch.  See the parent commit message for the full table.

Sites converted (56 total):
  retroarch.c                        20
  runloop.c                          13
  runahead.c                          6
  cheat_manager.c                     4
  tasks/task_database.c               3
  tasks/task_movie.c                  2
  tasks/task_content.c                1
  tasks/task_netplay_find_content.c   1
  tasks/task_pl_thumbnail_download.c  1
  tasks/task_screenshot.c             1
  ui/drivers/ui_qt_widgets.cpp        4

Intermediate uses of _msg in adjacent RARCH_LOG / RARCH_WARN /
RARCH_ERR calls between the declaration and the push were
rewritten to use _p.s in lockstep, so the converted blocks
remain self-consistent and the log output is byte-identical.

Strict C89 verified across all 11 touched files
(-Werror=declaration-after-statement -Werror=vla).  Behavior
is byte-identical to the prior pattern for every (msg, locale)
combination, since the API contract preserves
  p.s == msg_hash_to_str(msg)  (byte-equal)
  p.len == strlen(p.s)
exactly.

About 17 _msg-related sites remain in the same files using
shapes outside this script's safe-rewrite set — function-scope
'_msg' that is assigned multiple times in different branches,
multi-line ternary expressions, and a couple of cases where
_msg holds a string literal rather than a msg_hash_to_str
result.  Those are mechanical but per-site and worth a careful
follow-up commit rather than bundling here.
2026-05-20 01:03:24 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 31103bbd5c cheat_manager: fix dangling pointer + double-free in working_cheat desc/code copy path
cheat_manager_copy_working_to_idx had a memcpy-aliasing bug
that could cause a double-free when the user edited cheats
after prior add/delete churn.

=== Pointer aliasing via shallow struct copy ===

struct item_cheat holds 'char *desc' and 'char *code' pointer
fields.  cheat_manager_copy_idx_to_working populates
working_cheat via a shallow byte-copy:

    memcpy(&cheat_st->working_cheat,
           &cheat_st->cheats[idx], sizeof(struct item_cheat));
    if (cheat_st->cheats[idx].desc)
       strlcpy(cheat_st->working_desc, cheat_st->cheats[idx].desc,
               CHEAT_DESC_SCRATCH_SIZE);
    ...

After this memcpy, working_cheat.desc == cheats[idx].desc
(pointer alias, not strdup'd).  The string contents are also
copied into the working_desc / working_code scratch buffers,
but the struct-level pointer fields still alias.

The aliased pointers survive across subsequent menu
operations.  If anything frees cheats[src].desc between the
idx_to_working call and a later copy_working_to_idx call,
working_cheat.desc dangles.

=== How the dangling pointer becomes a double-free ===

cheat_manager_copy_working_to_idx was:

    memcpy(&cheats[idx], &working_cheat, sizeof(struct item_cheat));
    if (cheats[idx].desc) free(cheats[idx].desc);
    cheats[idx].desc = strdup(working_desc);
    if (cheats[idx].code) free(cheats[idx].code);
    cheats[idx].code = strdup(working_code);

After the memcpy, cheats[idx].desc == working_cheat.desc.
This has two failure modes:

  1. If working_cheat.desc aliases cheats[src].desc for some
     src != idx, the subsequent free(cheats[idx].desc) frees
     the string that still logically belongs to cheats[src].
     cheats[src].desc now dangles, and a later menu refresh
     that reads cheats[src].desc use-after-frees.

  2. If working_cheat.desc dangles (cheats[src] has since been
     freed), the free(cheats[idx].desc) is a double-free.
     The classic trigger path is:
       a. User opens cheat edit on cheats[N]
          -> copy_idx_to_working(N)  [working_cheat.desc = P
                                      aliases cheats[N].desc]
       b. User backs out without saving and deletes cheats[N]
          via the delete-cheat menu action
          -> cheats[N].desc freed (P freed), working_cheat.desc
             still = P (dangling)
       c. User opens cheat edit on what is now cheats[N] (the
          shifted-down next entry) and hits cancel, triggering
          menu_cbs_cancel.c:99
              cheat_manager_copy_working_to_idx(
                 working_cheat.idx);
          -> memcpy copies the dangling P into cheats[N].desc
          -> free(cheats[N].desc) double-frees P

The exact menu churn varies and many real-world shuffles
defuse the dangling pointer before it reaches the free; but
the shape is reliably reproducible with enough add/delete
sequences, and the underlying invariant ('cheats[i]'s
desc/code are owned solely by cheats[i]') was broken by the
shallow memcpy pattern.

=== Fix: save-restore pattern ===

Save cheats[idx]'s own desc/code pointers before the memcpy
overwrites them with working_cheat's aliases; restore them
after the memcpy; then free and reassign from the scratch
buffers.  Ownership of each cheats[i]'s desc/code stays
local to that slot regardless of what working_cheat's
pointer fields happen to alias or dangle to.

    saved_desc = cheat_st->cheats[idx].desc;
    saved_code = cheat_st->cheats[idx].code;

    memcpy(&cheat_st->cheats[idx], &cheat_st->working_cheat,
           sizeof(struct item_cheat));

    cheat_st->cheats[idx].desc = saved_desc;
    cheat_st->cheats[idx].code = saved_code;

    if (cheat_st->cheats[idx].desc)
       free(cheat_st->cheats[idx].desc);
    cheat_st->cheats[idx].desc = strdup(cheat_st->working_desc);
    ...

The scalar fields (idx, handler, address, value, memory_search_
size, cheat_type, rumble_*, repeat_*, state, big_endian, etc.)
still come from working_cheat via the memcpy - those are the
edited values the user entered in the menu and they are what
we actually want to copy.  Only the string pointers need the
save-restore.

=== Scope: the underlying aliasing remains ===

cheat_manager_copy_idx_to_working and the menu_cbs_ok.c insert/
copy operations (action_ok_cheat_add_new_before,
action_ok_cheat_copy_before, action_ok_cheat_add_new_after,
etc.) still populate working_cheat via shallow memcpy, so
working_cheat.desc and working_cheat.code can still alias or
dangle.  The fix above defuses the one path that turns that
aliasing into a double-free (copy_working_to_idx) rather than
eliminating the underlying invariant violation.

A deeper fix would strdup desc/code on copy_idx_to_working
and free them on the next copy_idx_to_working / teardown,
making working_cheat fully own its strings.  That's a larger
change: every memcpy-to-working_cheat site across menu_cbs_ok.c
would need a matching strdup, and a new tear-down path would
be needed (e.g. on cheat_manager_free).  Out of scope for
this single-file fix which targets the reachable crash.

=== No direct reads of working_cheat.desc / .code ===

A grep for 'working_cheat.desc' and 'working_cheat.code'
across the whole tree finds zero field accesses - only memcpy
sources and destinations.  That means the dangling pointers
in working_cheat themselves are never directly dereferenced;
the crash only surfaces when they get memcpy'd back into a
cheats[] slot and then free()'d.  This is consistent with
the bug being latent for years and only noticed via careful
static audit.

Thread-safety: all cheat_manager operations run on the main
menu thread.  No concurrency concerns.

Reachability: reachable via normal menu use.  The trigger is
any sequence of 'edit cheat A, cancel, delete cheat A, edit
cheat B, cancel' with enough add/delete churn that the new
cheats[N] slot's desc pointer happens to equal the stale
working_cheat.desc.
2026-04-24 07:29:30 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 3a5775d3fe cheat_manager: fix three OOM bug clusters in cheats realloc and memory buffer init
Three separate bug clusters in cheat_manager.c, all OOM paths,
all on hot paths (cheat loading, cheat list grow, memory-map
init at core start).

=== cheat_manager_realloc: realloc-assign-self + leak ===

    val = (struct item_cheat*)
          realloc(cheat_st->cheats,
          new_size * sizeof(struct item_cheat));

    cheat_st->cheats = val ? val : NULL;

This looks like a safe realloc-to-tmp but isn't.  On OOM 'val'
is NULL and 'cheats' is still the valid old buffer per the C
realloc contract - but the line above explicitly sets cheats
to NULL, dropping the only reference and leaking the entire
container.  Worse, each entry in that container has live
.code and .desc strdup'd strings that were about to be freed
by the shrink branch above (lines 561-569 handled indices
[new_size, orig_size) but [0, min(new_size, orig_size))
still held live strings at the moment of the realloc call).

Fix: free the old buffer AND its per-entry .code/.desc strings
explicitly on OOM before NULL'ing cheats.  Preserves the
existing failure contract (size=0, cheats=NULL) that callers
at lines ~515 and ~1206 rely on:

    /* caller at 515: gates iteration on cheats non-NULL */
    for (i = orig_size; cheat_st->cheats && i < cheats; i++)

    /* caller at 1206: returns false if realloc returned false */
    if (!cheat_manager_realloc(new_size, CHEAT_HANDLER_TYPE_RETRO))
       return false;

=== cheat_manager_initialize_memory descriptor loop: two stacked bugs ===

    cheat_st->num_memory_buffers++;

    if (!cheat_st->memory_buf_list)
       cheat_st->memory_buf_list = calloc(1, sizeof(uint8_t *));
    else
       cheat_st->memory_buf_list = realloc(
             cheat_st->memory_buf_list,
             sizeof(uint8_t *) * cheat_st->num_memory_buffers);

    if (!cheat_st->memory_size_list)
       cheat_st->memory_size_list = calloc(1, sizeof(unsigned));
    else
    {
       unsigned *val = realloc(...);
       if (val)
          cheat_st->memory_size_list = val;
    }

    cheat_st->memory_buf_list [num - 1] = ...;
    cheat_st->memory_size_list[num - 1] = ...;

Two bugs:

  1. memory_buf_list uses realloc-assign-self: on OOM the old
     buffer leaks and the [num - 1] write below NULL-derefs.
  2. memory_size_list uses realloc-into-tmp with a NULL-check
     but silently ignores the failure.  That leaves the array
     one element too short while num_memory_buffers claims the
     new size.  The [num - 1] write below is then a
     heap-buffer-overflow past the end of memory_size_list.

Plus num_memory_buffers++ happens eagerly at the top, so on
OOM the count and the array lengths are out of sync.

Fix: compute new_count into a local temp, grow both lists into
temp pointers, commit both and bump num_memory_buffers only
after both succeed.  On either OOM continue to the next
descriptor (the post-loop 'if (num_memory_buffers == 0)' check
then takes the RETRO_MEMORY_SYSTEM_RAM fallback path).  The
one-slot overallocation on a partial-success path (buf_list
grew, size_list failed) is a minor waste of memory but can't
corrupt state because num_memory_buffers never advanced.

=== cheat_manager_initialize_memory fallback path: unchecked callocs ===

    cheat_st->memory_buf_list  = calloc(1, sizeof(uint8_t *));
    cheat_st->memory_size_list = calloc(1, sizeof(unsigned));
    cheat_st->num_memory_buffers = 1;
    cheat_st->memory_buf_list[0]  = ...;    /* NULL-deref on OOM */
    cheat_st->memory_size_list[0] = ...;    /* NULL-deref on OOM */

When num_memory_buffers == 0 after the descriptor loop, the
RETRO_MEMORY_SYSTEM_RAM fallback allocates two one-element
arrays and writes to [0].  Both callocs are unchecked.

Fix: NULL-check both and bail via the same MSG_CHEAT_INIT_FAIL
path used by the meminfo-failed branch a few lines above.
Free whichever calloc succeeded (free(NULL) is safe for the
other).

=== Not a bug, verified clean ===

Other alloc sites in cheat_manager.c, also checked during this
pass:
  * line 366 (cheats initial calloc) - NULL-checked with
    graceful zero-out.
  * line 552 (cheats create-if-null branch in realloc) - flows
    into the same post-alloc check that fires in the realloc
    case.
  * line 939 (prev_memory_buf) - NULL-checked with
    MSG_CHEAT_INIT_FAIL bail.
  * line 957 (matches) - NULL-checked with matching teardown
    (frees prev_memory_buf on failure).

Other top-level files swept in this pass and found clean:
  * configuration.c, dynamic.c, retroarch.c - zero raw alloc
    sites.
  * core_option_manager.c - 13 sites, all use the 'if (!(x =
    alloc(...)))' idiom.
  * core_info.c - 8 sites NULL-checked including the
    realloc-to-tmp at line 400.
  * database_info.c - 3 sites NULL-checked (lines 988, 1022,
    1204).
  * runloop.c - 2 sites NULL-checked (lines 2746, 2794) in the
    SET_SUBSYSTEM_INFO and SET_CONTROLLER_INFO environ handlers.

=== Thread-safety ===

cheat_manager_realloc runs on the main thread (invoked from
menu or cheat-file load).  cheat_manager_initialize_memory
runs on the main thread at core load (after retro_load_game).
No shared-state changes; no lock discipline changes.

=== Reachability ===

  * cheat_manager_realloc: every cheat file load, every user-
    driven cheat list grow/shrink via the menu.
  * cheat_manager_initialize_memory: every core load with
    HAVE_CHEEVOS or cheats feature enabled.  On handhelds with
    sub-256MB RAM running a memory-hungry core, the one-element
    allocs on the fallback path are cheap but the multi-
    descriptor realloc path can realloc arrays with dozens of
    entries for cores that expose many memory regions (arcade
    cores, multi-chip emulators).
2026-04-24 01:53:49 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 166b09657a Remove some if 0/if 1 blocks 2026-04-08 17:03:14 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 9708810444 More string_is_empty removal 2026-04-07 04:53:28 +02:00
sonninnos ec51281203 Cheat menu rework 2026-03-08 13:42:12 +01:00
sonninnos b2ca569521 Logging unification cleanups 2025-07-10 05:59:06 +03:00
pstef 59c71b8db4 Rewrite part of cheat_manager_load_cb_second_pass()
This is to silence a stringop warning that I believe to be a false
positive.  Nevertheless, this change reduces verbosity of the code
and introduces a couple of checks that weren't there previously.

Note that the base parameter of this strtoul call is changed from 0
to 10, because previously the while loop rejected characters other
than 0-9 so strtoul didn't have to. Now that the loop is gone, the
call has to reject characters that are not decimal digits to keep
the logic as it was.
2025-04-08 06:16:59 +00:00
LibretroAdmin ef7b9830db (cheat_manager) No more dependency on configuration.h 2025-02-10 16:48:56 +01:00
LibretroAdmin ddd7ff2d33 get rid of some settings_t pointer passing 2025-02-10 15:47:18 +01:00
LibretroAdmin 91aa8034b1 Style nits/conventions 2025-02-09 16:43:51 +01:00
BinBashBanana ed1810de86 Emscripten improvements (#17422) 2025-01-29 05:29:16 +01:00
LibretroAdmin 0b329018ee Less string buffers and less string copies 2025-01-16 23:59:22 +01:00
LibretroAdmin 7e7224196a Avoid some strlens, and also return size_t in more string
modification functions
2025-01-12 23:39:29 +01:00
LibretroAdmin 1e656261b0 Local len variables need to have '_' prefix 2024-12-30 14:03:58 +01:00
LibretroAdmin 18c85b5ccd Cleanups -
* Less string copies
* Some general cleanups
* Add extra param to runloop_message_queue_push so we can pass size_t
of the message
* Consistent conventions for local variable usage for certain things
2024-12-27 15:13:45 +01:00
libretroadmin 9efb498bde (config_file) Use flags 2024-09-08 18:12:12 +02:00
libretroadmin a4212061d4 Cleanup some unused variables 2024-04-06 20:12:15 +02:00
libretroadmin 89376e3c41 Do away with one temp buffer 2023-09-06 02:50:56 +02:00
libretroadmin cd8fffe5d3 Rename all local variables for retro_system_info to sysinfo 2023-07-15 07:45:20 +02:00
libretroadmin d514f1ded3 Avoid false positives with code analysis tools - rename
variables called 'system'
2023-07-05 03:29:49 +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 8c9c9b3845 Localize string and other cleanups 2023-05-28 23:48:26 +02:00
Bernhard Schelling 18f79a8a8d Allow RETRO_ENVIRONMENT_SET_MEMORY_MAPS also after core startup
Change the comment in libretro.h about the removed limit and handle the environment call during core runtime in RetroArch.
2023-05-28 05:23:12 +02:00
libretroadmin 91ea92e50b Get rid of some menu_driver_ctl commands 2023-05-10 21:30:09 +02:00
Bobby Smith 440264778d Fix incorrect lines in .cht files for 'cheat10' and above (#14436) 2022-09-25 17:15:07 +02:00
LibretroAdmin f3c13cf669 * (cheat_manager_save) Reduce amount of snprintf calls from 4 to 1 2022-08-26 23:35:45 +02:00
LibretroAdmin b2634ea588 * Create fill_pathname_join_special - and specify fill_pathname_join
as deprecated.
* Use fill_pathname_join_special in the vast majority of cases where
we can ensure out_path is a new empty string
* Get rid of some extension concatenation with strlcat where encountered
* Some general cleanups with NULL termination of strings that get immediately
passed to strlcpy/strlcpy-adjacent functions
2022-08-04 14:19:38 +02:00
libretroadmin 8f37c2e3c2 Don't call config_set_bool, call config_set_string directly 2022-07-18 01:59:32 +02:00
libretroadmin d706c9c5bf Start deprecating trivial functions in file_path.c 2022-07-11 19:56:46 +02:00
twinaphex 460f5e745d Silence some MSVC 2019 code analysis warnings 2022-03-05 14:39:56 +01:00
twinaphex f671ce4f8c Move global->name to runloop_st 2021-11-09 06:03:00 +01:00
twinaphex 83ce4259a0 Have only one getter for runloop_state 2021-09-21 19:08:26 +02:00
Mark W. Kidd 5f834a8cb3 input_driver refactor 2021-08-19 20:02:39 -04:00