Commit Graph
69 Commits
Author SHA1 Message Date
LibretroAdmin 258877057f tasks/task_patch: a patch that fails to apply must not mask the other formats
apply_patch_content() returned true unconditionally.  The failure branch
only logged, then fell through to the same "return true" the success
path used, so try_ips_patch() answered "handled" for any .ips that
merely existed - applied or not.

patch_content() picks a format with

  if (     try_ips_patch(allow_ips, name_ips, buf, size)
        || try_bps_patch(allow_bps, name_bps, buf, size)
        || try_ups_patch(allow_ups, name_ups, buf, size)
        || try_xdelta_patch(allow_xdelta, name_xdelta, buf, size))

so a rejected .ips short-circuits the chain and the .bps or .ups sitting
beside it is never tried.  This is visible in libretro/RetroArch#18774,
where the reporter had to delete the .ips before the .bps of the same
hack would load.  The indexed "*.ips1" loop below reads the same return
value and had the same problem in reverse: it kept iterating past a
patch that had not been applied.

Return whether the patch actually applied.

Also push the failure to the OSD.  Until now a patch that was found and
rejected produced one RARCH_ERR line and nothing else: the content boots
unpatched and looks like the patch was ignored, which is the confusing
part of that report.  The applied-patch notification stays behind its
setting - a failure is an error, not a notification the user opted into.
2026-08-09 04:41:35 +02:00
LibretroAdmin 316c00abc4 tasks: reject IPS records whose payload runs past the end of the patch
Both IPS appliers bounded a copy record's payload with

  if (off > patch_len - len)

len is a 16-bit field read from the patch and patch_len is the size of
the patch file, so a patch smaller than the length its own record
declares wraps the subtraction to a value near SIZE_MAX.  The test then
passes for every off and the record is accepted with a payload that
extends past the buffer.

In tasks/patch_stream.c the consequence is direct: the record is entered
into recs[] and off += len walks past patch_len, so the scan stops on
the next iteration having already committed it.  patch_stream_ips_finish
then overlays it and memcpy() reads off the end of the patch allocation
into the target.  ASan, on a mutated but header-valid .ips of 3.5 kB:

  ERROR: AddressSanitizer: heap-buffer-overflow
  READ of size 35156
    #2 patch_stream_put        tasks/patch_stream.c:135
    #3 patch_stream_ips_overlay tasks/patch_stream.c:352
    #4 patch_stream_ips_finish  tasks/patch_stream.c:405

Those bytes land in the buffer handed to the core, so this is heap
contents disclosed into the running content, not only a fault.  Since
soft patching applies whatever .ips sits beside the content, the patch
file is untrusted input.

tasks/task_patch.c carries the same wrapped comparison in both of its
passes.  There it is currently masked - ips_alloc_targetdata() runs the
same walk first and returns PATCH_PATCH_INVALID before ips_apply_patch()
gets to write anything - but the guard is wrong in the same way and is
one restructuring away from mattering, so correct it in place.

Use the remaining-bytes form instead.  off is at most patch_len at that
point in each of the three loops, so patch_len - off cannot wrap, and
comparing the declared length against it is exact.
2026-08-09 04:41:31 +02:00
LibretroAdmin fed4e55dc1 tasks/task_patch: stop a truncating IPS patch from overrunning its target buffer
ips_alloc_targetdata() took the size named by the IPS truncation
extension and made it both the size of the allocation and the reported
length of the result.  ips_apply_patch() then copied the whole source
into that buffer:

  memcpy(*targetdata, sourcedata, (size_t)sourcelength);

For any patch that shrinks the content - EOF followed by a three-byte
size smaller than the source - that is a heap write of sourcelength
bytes into an allocation of the smaller truncated size.  Records sitting
past the truncation point, which the format permits, overran it as well.
A twelve-byte .ips is enough:

  50 41 54 43 48 45 4f 46 00 00 10   "PATCH" "EOF" truncate-to-16

Soft patching applies whatever .ips sits next to the content, so the
patch file is the input here, not something the user has vetted.

Split the two lengths.  targetlength stays what the content becomes;
alloclength is what the applier may touch, and covers the source and
every record end so that both the wholesale copy and the writes past a
truncation point stay inside the buffer.  The copy is clamped to the
allocation rather than trusting sourcelength on its own.

Allocate with calloc().  A patch that grows the content need not write
every byte it adds, and the gap between the end of the source and the
first record beyond it was previously uninitialised heap that went
straight into the buffer handed to the core.  tasks/patch_stream.c
zero-fills the same gap, so this also stops the two appliers disagreeing
on the output for the same patch.

Reference behaviour matches Floating IPS, which allocates
max(outlen, outlen_min_mem) and zero-fills beyond the source.
2026-08-09 04:41:27 +02:00
Auditor ac68342dd4 patch: verify a patch's own checksum before allocating its target
Both formats close with a CRC-32 of the patch file's own bytes, little
endian, in the last four.  It depends on nothing but the patch, which is
already whole in memory at every one of these call sites - and yet all
four allocation paths act on a length the patch merely claims long
before either applier reaches its trailer:

  tasks/task_patch.c    bps_apply_patch()        malloc(target_size)
  tasks/task_patch.c    ups_apply_patch()        malloc(*targetlength)
  tasks/patch_stream.c  patch_stream_ups_open()  reserve(tgt_len)
  tasks/patch_stream.c  patch_stream_bps_open()  fill(0, 0, tgt_len)

A UPS length field names up to 4 GiB, so a 22-byte file that is not a
patch at all can ask for and get the whole of it, and the streaming
reader then walks it a byte at a time in finish().  malloc failing is
the only thing between that and the frontend, which on a host with
overcommit is not a great deal.

Settle the patch's own checksum first.  A 22-byte UPS declaring a
4 GiB target: 9.7 ms through the allocator path before, 0.0 ms and no
allocation after.  The cost on a real patch is one CRC-32 fold over a
file measured in kilobytes, against source and target folds that are
already being done over the content itself.

Both appliers still verify the checksum in place at the end.  This is a
gate in front of the allocator, not a replacement for that check.

No change on valid input: whole-buffer and streaming equivalence against
the parent commit hold over 3000 and 4000 randomised patches, and 4000
randomised BPS command streams remain byte-identical to flips.  The
randomised-input sweeps had to be taught to stamp a correct self-CRC or
the gate would have short-circuited them into testing nothing; with that
done, 40061 of 60000 generated inputs still reach the parser, and the
sweep is clean under ASan and UBSan.
2026-08-08 18:57:35 +02:00
Auditor 52f9e6b082 patch: decode BPS copy offsets as unsigned sign-magnitude
The seek carried by SourceCopy and TargetCopy is sign-magnitude inside
the varint itself - the spec writes it as "number negative |
(abs(offset) << 1)" - so it has to stay unsigned all the way to the
cursor.  The whole-buffer applier routed it through int:

    int  offset = (int)bps_decode(&bps);
    bool negative = offset & 1;
    offset >>= 1;
    if (negative) offset = -offset;

which fails a full bit earlier than the width suggests, because the
encoded number is the magnitude shifted up by one.  A magnitude of 2^30
encodes as 2^31, (int) of that is INT_MIN, bit 0 reads back as zero, and
the arithmetic >>1 hands back -2^30: a forward seek 1 GiB into the file
turns into a backward one.  At 2^31 the number truncates to zero
outright and the copy is taken from the wrong place with nothing but the
trailing target CRC to notice.  The conversion is also
implementation-defined for any value above INT_MAX.

Measured against flips (Alcaro/Flips, libbps.cpp, which keeps the
distance in size_t and never casts) on a 1 GiB and a 2 GiB source, one
SourceCopy per patch, seek swept across the boundary:

    seek        HEAD                          fixed
    1000000     ok                            ok
    2^30 - 1    ok                            ok
    2^30        SOURCE_INVALID                ok
    2^31 - 1    SOURCE_INVALID                ok
    2^31        TARGET_CHECKSUM_INVALID       ok

Every "ok" is byte-identical to flips' output.  So a .bps against any
content over a gigabyte - a disc image - is refused today, and the two
failure modes differ: at 2^30 the sign flip runs the cursor out of
bounds and the patch is rejected at the seek, while at 2^31 the seek is
silently wrong and only the target checksum stops it.

Keep the distance in uint64_t, split the two directions so each is
computed inside the buffer rather than wrapped and caught afterwards,
and reject a distance wider than size_t, which no 32-bit host could
address even if it were in bounds.  The existing range checks are
unchanged and still run.

tasks/patch_stream.c gets the same treatment, but as cleanup rather
than a fix: its int64_t form is correct up to a magnitude of 2^62, and
it was verified correct at both 2^30 and 2^31 before this change.  What
it had was the implementation-defined pair - (int64_t)(uint64) above
INT64_MAX and the right shift of the negative it produces - on input a
patch can encode.  With a self-consistent patch carrying a magnitude of
2^62 or more the whole-buffer applier reaches the end of the action loop
either way; before, it copied from a truncated offset and was caught by
the target CRC, and now it is rejected at the seek as SOURCE_INVALID.

Verified with flips arbitrating every iteration of 4000 randomised BPS
command streams covering all four actions and both seek directions:
4000/4000 confirmed, no divergence from the parent commit.  Whole-buffer
and streaming equivalence against the parent are unchanged over 3000 and
4000 randomised patches respectively, and the randomised-input sweeps
are clean under ASan and UBSan.
2026-08-08 18:57:32 +02:00
Acts1631 61727d57f2 patch: reject truncated BPS and UPS varints (#19367)
The BPS and UPS decoders synthesize zeroes after EOF while waiting for
a terminating varint byte. A malformed sidecar patch can therefore spin
the content loader indefinitely.

Make both streaming and whole-buffer decoders fail on truncated or
overflowing varints and propagate the error to their callers.
2026-08-08 18:25:32 +02:00
libretroadmin 50af7092ae task_patch: fold the BPS and UPS checksums in spans, copy runs in bulk
The BPS and UPS appliers moved every byte through a helper that
folded a one-byte CRC as it went - one encoding_crc32() call per
patch byte read, per source byte read and per target byte written.
Every one of those checksums covers a byte span that sits whole in
memory: the patch bytes consumed, the source bytes read, the target
bytes emitted, all strictly sequential.  Each is now one fold at the
point it is compared, the same shape the BPS source checksum has
always had, and the readers and writers keep only their cursor
semantics - reads past the end yield zeroes, the patch and source
cursors only advance in bounds, the UPS target cursor counts on past
the end while writes stop.  The folded spans are clamped exactly the
way the byte folds were: to the bytes actually consumed or emitted,
never past a buffer's length.

With the folds gone the byte loops had nothing left to do per byte,
so the runs move in bulk: BPS SOURCE_READ, TARGET_READ and
SOURCE_COPY are memcpy; TARGET_COPY takes memcpy only when the run
does not overlap its own output, since an overlapping run is an
LZ-style repeat that memcpy cannot express; the UPS skip runs and
end-of-patch drains - the whole unchanged remainder of the file - go
through one bulk helper with the byte loop's exact cursor behaviour.

Applying a patch with edits every ~4 KB to a 24 MB file, best of 5:

  bps   103.9 ms  ->   9.9 ms
  ups   219.7 ms  ->  10.2 ms

Two pre-existing bugs surfaced by the differential sweep are fixed
in passing.  bps_read() had no bounds check, so a truncated or
malformed patch - a varint near the trailer with no terminator -
drove reads arbitrarily far past modify_length: a real
heap-buffer-overflow READ under ASan with an exactly-sized patch
buffer, and with a larger allocation the old code would read past
the truncation point and could report success on a truncated file.
It now yields zeroes without advancing into the fold, as the UPS
reader always has, and truncated patches fail their checksum.  And
all six trailer reads shifted a promoted uint8_t by 24 - a signed
left-shift overflow flagged by UBSan on any checksum byte with the
high bit set; the shifts are widened to uint32_t.

Verified against the previous appliers extracted verbatim: 2980
differential cases - six sizes from empty to 1 MB at three edit
densities through a generator exercising all four BPS action modes
including overlapping TARGET_COPY runs, plus a corruption flip at
every stride and a truncation at every stride of every patch - with
identical return codes, target lengths and target bytes throughout.
Clean under ASan, UBSan and LeakSanitizer across the whole fuzz set,
and under ThreadSanitizer with four concurrent appliers.  The
patch_stream suite passes.  C90 clean.
2026-08-02 10:42:42 +02:00
libretroadmin 471cb7c9a9 tasks: stream .xdelta patches alongside the load
The other three patch formats advance as the content arrives; xdelta
was the exception, excluded from the streaming path because the vendored
decoder's interface was not shaped for it. That reason is gone: the
VCDIFF decoder in libretro-common is ours, so it can be given the shape
the load path needs.

A VCDIFF window names the source segment it requires, which makes the
suspend boundary the window rather than the instruction: a window
decodes as soon as its segment has been fed and waits otherwise, with
the cursor left on its header so the retry starts clean. Source bytes
are retained in full, because a window may name any part of the source
however far the stream has got - as with BPS, the gain is overlapping
the decode with the read, not a smaller footprint.

The streaming form is now the implementation and the whole-buffer entry
point is a wrapper over it, so there is one decoder rather than two
that must agree. That wrapper points at the caller's buffer instead of
copying it, since it decodes against multi-megabyte ROMs and the copy
would cost more than the decode; the incremental form owns its copy
because it has no choice.

finish() refuses a stream fed less than the source length declared at
open. A decoder cannot tell a truncated feed from a genuinely shorter
source, and would otherwise return a target confidently built from a
partial one - the same failure the other appliers guard against.

Verified: the whole-buffer path is unchanged, still 3013 differential
cases against the reference implementation with zero mismatches. The
streamed path was checked against its own whole-buffer output over 240
decodes spanning chunk sizes from one byte to a megabyte, across
lightly edited, wholly unrelated, and resized targets, with zero
differences; a deliberately short feed is refused. Clean under address
and undefined-behaviour sanitizers, and both patch_stream.c and the
decoder compile under -std=c89 -pedantic -Wall -Wextra with and
without HAVE_XDELTA.
2026-07-23 09:18:44 +02:00
libretroadmin 3d87968233 encodings: replace deps/xdelta3 with a VCDIFF decoder
.xdelta softpatching pulled in the whole of xdelta3 - some 30 kLOC
across thirteen files, a liblzma link, and enough macro pollution that
griffin had to #undef adler32, Q, W and Z after including it - to do
one thing the frontend actually needs: apply a patch. It never creates
one, so the encoder, the merge logic, the secondary compressors and the
command line tool were all carried for nothing.

Replace it with a decoder written from RFC 3284. One translation unit
and one header, no dependencies, no macros escaping into the unity
build. liblzma stops being a build requirement and the qb probe for it
goes with it.

The subset is what xdelta3 emits for content patches, established by
inspecting its output rather than assumed: the default code table, both
window kinds, every instruction type, and the full address-mode set
including the near and same caches. Anything outside it - a secondary
compressor, a replacement code table - is refused outright rather than
guessed at, so a patch this cannot apply leaves the content unpatched
instead of quietly producing something plausible and wrong. The code
table is generated from the rules in section 5.5 rather than
transcribed, since 256 hand-written rows is where an error would hide.

It is also faster, which was not a foregone conclusion. Decoding a
32 MiB target, with both sides allocating their output as a real caller
must: +33% on a one-byte edit, +43% on twenty thousand scattered edits,
+93% on long runs and +112% on a target sharing nothing with its
source. Across a sweep of instruction density from one edit per MiB to
one per 64 bytes - patches from 114 bytes to 1 MiB - it stays ahead
everywhere, by between 87% and 334%. Two things account for it: the
output is sized by one pass over the window headers instead of grown by
doubling, which on a 32 MiB target had been costing a dozen
reallocations and twice the target in copying, and an overlapping COPY
advances in chunks of the repeat distance rather than a byte at a time.

A SIMD kernel was evaluated and is not included, because the
measurements do not support one. At low instruction density the decode
is bound by memcpy and memset, which the C library already vectorises
better than a hand-rolled kernel would; at high density it is bound by
varint decoding and table dispatch, which is branchy serial work with
no data parallelism to exploit. There is no middle regime where wider
lanes would pay.

Verified against the implementation being removed, which was kept
outside the tree as an oracle: 3013 differential cases - identical
files, single-byte edits at both ends, insertions, runs, unrelated
content, targets longer and shorter than their source, multi-window
2 MiB targets, and a randomised sweep - with zero mismatches and zero
refusals. Separately, 300000 random byte strings behind a valid magic
number were decoded under address and undefined-behaviour sanitizers
without a crash or a diagnostic. The sanitizers did report undefined
behaviour in xdelta3 itself, in the misaligned loads its hash function
performs; the replacement has none.

samples/encodings/vcdiff carries the regression test. Its golden
vectors were produced by the reference encoder and checked against the
reference decoder before being frozen, so they are real patches rather
than this decoder marking its own homework, and the malformed-input
fuzz travels with them.
2026-07-23 09:08:29 +02:00
libretroadmin 7a3f5e1c04 tasks: report the streamed patch's file name, stop feeding a dead stream
The notification differed depending on which path applied the patch.
apply_patch_content reports the patch's file name - "Applying patch:
Mario.ips" - but the streamed path was passing the format instead, so
the same patch announced itself as "Applying patch: IPS" purely because
the content happened to take the streaming route. Resolve the patch's
path out of patch_content_stream_open rather than its format name, and
report the base name exactly as the whole-buffer path does; the format
is still what the log line names, which is where it is actually useful.

The pump also kept feeding a stream that had already failed. A
malformed patch or a failed allocation puts the applier into a state it
cannot leave, and finish will refuse it, but the load still has the
rest of the content to deliver - so every remaining span was being
pushed through an applier that could only keep failing, retrying the
allocation that already did not work for each one. Expose the state and
stop feeding when it is set. The load itself still completes, finish
still refuses, and the ordinary whole-buffer pass still patches the
finished buffer, so behaviour is unchanged; only the wasted work goes.

Verified: the query reports a fresh stream and a fully fed one as
healthy, a completed finish still succeeds, and NULL counts as dead so
callers need no separate check. The differential suite is unaffected
(300000 comparisons, zero mismatches) and the short-feed guard still
rejects partial feeds and accepts complete ones. Compiles under
-std=c89 -pedantic -Wall -Wextra, and task_content.c with and without
each of HAVE_PATCH and HAVE_COMPRESSION.
2026-07-23 08:23:42 +02:00
libretroadmin 7f8be7cdf0 tasks: stream soft patches alongside the content load
Soft patching ran as a separate pass: content_file_load_into_memory
brought the whole file in - inflating it, for compressed content - and
only then did patch_content walk the finished buffer end to end. The
compressed path already pumps its entry source through data_transfer in
budgeted slices, so the bytes were arriving incrementally with nothing
consuming them until the load had finished.

Resolve the patch before the load and advance it over each span as that
span arrives. Which patch applies depends only on the preference flags
and which patch files exist - never on the content - so the decision
hoists cleanly ahead of the read, and patch_content_stream_open makes
that decision with patch_content's own gating and IPS to BPS to UPS
attempt order.

Falling back is the default rather than the exception: the resolver
returns NULL - and the existing whole-buffer pass runs untouched - when
nothing applies, when the winner is xdelta (no streaming applier yet),
when indexed continuation patches are present (patch_content chains
"<name>1", "<name>2", ... onto the first result, which a streamed first
patch cannot carry), or on any read or header-parse failure. A patch
that turns out to be malformed mid-application costs nothing either:
the source is still fully resident in the transfer buffer at that
point, so the unpatched buffer is kept and the normal pass retries it,
which is what happens today when an applier rejects a patch.

patch_stream.c gains its build entries now that it has a consumer.

Verified: the selection logic is parity-checked against patch_content
across all 256 combinations of the four preference flags and the four
patch-file-presence states, with zero divergence - 38 combinations
stream, the other 218 fall back. task_content.c compiles clean with and
without each of HAVE_PATCH and HAVE_COMPRESSION, task_patch.c under
HAVE_PATCH, and patch_stream.c under -std=c89 -pedantic -Wall -Wextra.
The appliers themselves remain covered by samples/tasks/patch_stream
(300000 differential comparisons against the whole-buffer oracle).

Not runtime-tested against real content in this environment: the load
path needs a built frontend, so the first-run checks worth doing are a
compressed ROM with an .ips and with a .bps beside it, one with an
indexed .ips1 (must take the fallback), and one with a deliberately
corrupt patch (must play unpatched).
2026-07-23 07:43:04 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre c41e955464 tasks/task_patch: bound BPS patch action-loop and size-prelude against attacker-controlled inputs
bps_apply_patch (tasks/task_patch.c) implemented BPS patch
application without bounds checks on any of the per-command
reads or writes.  The action loop:

  while (bps.modify_offset < bps.modify_length - 12)
  {
     size_t _len = bps_decode(&bps);    /* attacker-chosen */
     unsigned mode = _len & 3;
     _len = (_len >> 2) + 1;

     switch (mode)
     {
        case TARGET_READ:
           while (_len--) {
              uint8_t data = bps_read(&bps);
              bps.target_data[bps.output_offset++] = data;   /* OOB write */
           }
        case SOURCE_READ:
           while (_len--) {
              uint8_t data = bps.source_data[bps.output_offset];   /* OOB read */
              bps.target_data[bps.output_offset++] = data;
           }
        case SOURCE_COPY:
           bps.source_offset += offset;       /* unbounded signed offset */
           while (_len--) {
              uint8_t data = bps.source_data[bps.source_offset++];   /* OOB read */
              bps.target_data[bps.output_offset++] = data;
           }
        case TARGET_COPY:
           bps.target_offset += offset;
           while (_len--) {
              uint8_t data = bps.target_data[bps.target_offset++];
              bps.target_data[bps.output_offset++] = data;
           }
     }
  }

A malicious .bps could:
  - Write attacker-chosen bytes far past the malloc'd
    target_data buffer (heap-buffer-overflow WRITE) via any
    of the four modes.
  - Read past source_data via SOURCE_COPY's unbounded signed
    offset.  Negative offsets underflow source_offset to a
    huge size_t; positive offsets push it past
    source_length.  The leaked bytes flow into target_data
    and the patch checksum, exposing heap contents.
  - Read past modify_data via TARGET_READ when _len exceeds
    the remaining patch bytes.  The action-loop guard
    confirms only "at least one command's worth of bytes",
    not the full read range.

The size prelude (modify_source_size / modify_target_size /
modify_markup_size, decoded by bps_decode immediately after
the "BPS1" header) was also unchecked:

  - modify_target_size declared as size_t silently truncated
    the uint64 bps_decode result on 32-bit hosts.  A value of
    0x100000000 wraps to 0; the subsequent malloc(0) returns
    a tiny allocation while bps.target_length is set to the
    raw uint64.  The next target_data[output_offset++] write
    OOB by the truncated delta.
  - modify_markup_size was used as a loop bound consuming
    bytes from modify_data via bps_read.  A value above the
    remaining patch bytes ran the read loop off the end of
    modify_data.

Reachability: user has soft-patching enabled (the default
when a .bps file with the same basename as the loaded ROM is
present) and loads a ROM whose .bps was supplied by an
attacker.  Same threat class as CDFS / CHD / BSV file-load
bugs.

Fix:

  1. Capture the three size-prelude values as raw uint64,
     reject anything above SIZE_MAX (so the size_t cast is
     guaranteed lossless), and reject markup_size that would
     drive bps_read past modify_length.

  2. At the top of every action-loop iteration, bound _len
     against (target_length - output_offset).  This single
     bound covers the target_data write in all four modes.

  3. In each mode, bound the source-side read range:
     - SOURCE_READ: output_offset + _len <= source_length
     - TARGET_READ: modify_offset + _len <= modify_length - 12
     - SOURCE_COPY: source_offset (post-offset-add) + _len
                    <= source_length
     - TARGET_COPY: target_offset (post-offset-add) + _len
                    <= target_length

Adds samples/tasks/bps_patch/bps_patch_bounds_test as a
regression test, registered in
.github/workflows/Linux-samples-tasks.yml as an ASan-enabled
step.  Five cases covering OOB-write rejection, OOB-read
rejection, legitimate operations, and the exact-capacity
boundary.

Test follows the existing samples/tasks pattern (verbatim
copy of the post-fix predicates with maintenance-contract
comment, ASan as the discriminator).  Verified to fire
under ASan when the bounds are removed: heap-buffer-overflow
WRITE of size 1 at offset 4 of a 4-byte allocation in
apply_action_loop.  With the bounds the test passes clean.
2026-04-28 06:08:15 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 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 4be8b20.  Those were in
  audio/audio_driver.c; these are in the task enqueue path.)

* task_decompress.c (3 fixes):

  - file_archived: callback_error malloc unchecked
    before strlcpy.  NULL-gate the error-string population
    (skipping leaves task->error NULL, which task_set_error
    and downstream consumers handle).

  - file_decompressed: same twin pattern, same fix.

  - task_decompress_handler_finished: data calloc
    unchecked before data->source_file = ... write.  On OOM
    free source_file (which would otherwise leak via the
    skipped task_set_data) and set a task error.

* task_database_cue.c (3 fixes):

  - PS2 detect_ps2_game: disc_data malloc unchecked
    before intfstream_read, which writes via fread (no NULL
    guard on destination).  NULL-check + return 0, matching
    the PS1/PSP twin patterns above/below which already had
    this check.

  - track_extract first variant: data malloc unchecked before
    intfstream_read.  NULL-check + goto error.

  - track_extract second variant: twin pattern, twin fix.

* task_http.c (1 fix):

  - task_http_transfer_handler: http_transfer_data_t malloc
    unchecked before data->data / ->len / ->headers /
    ->status writes.  On OOM free the already-fetched 'tmp'
    buffer (data was about to take ownership) and set a task
    error.  Moved 'bool mute;' declaration into the success
    branch to avoid an unused-variable warning on the failure
    branch.

* task_wifi.c (1 fix):

  - task_push_wifi_connect: task->user_data malloc
    unchecked before memcpy.  On OOM free task->title and the
    task itself, return false so the caller sees a clean
    failure.

* task_content_disc.c (1 fix):

  - dump-cue DUMP_STATE_WRITE_CUE: cue_data calloc
    unchecked before filestream_read.  NULL-gate the read;
    cue_data is actually unused after the read (only passed
    to free at the bottom of this block), so skipping the
    read has no further consequence beyond the failed read
    itself.

* task_autodetect_blissbox.c (2 fixes):

  - lp_device_path LocalAlloc unchecked before
    strlcpy NULL-derefs.  NULL-check + 'continue' to advance
    the inner SetupDiEnumDeviceInterfaces 'for (i = 0; ...;
    i++)' loop to the next device interface.

  - device_path malloc unchecked before the indexed
    copy loop NULL-derefs.  NULL-check + free the
    LocalAlloc'd lp_device_path + continue.

  Both 'continue' statements target the inner for-loop's i++
  advance clause, which is the intended behaviour (skip this
  interface, try the next).  The outer 'while (!ret)' loop
  increments 'index' at the bottom of its body, which is
  unaffected by the inner continue.

* task_steam.c (1 fix):

  - task_push_steam_core_dlc_install: both task_init
    and steam_core_dlc_install_state_t calloc were unchecked
    before the state->app_id / ->name / ->has_downloaded and
    task->handler / ->state / ->title / ->progress / ->callback
    writes that NULL-deref.  Joint NULL-check frees whichever
    succeeded and returns; caller is menu Steam-DLC action
    with no task-return channel, so return-silently matches
    the pre-patch failure mode (task would have crashed or
    silently not installed) without the crash.

  (This is separate from the two other steam/steam.c bugs
  that are blocked on an external mist.h enum value.)

All fixes follow the same pattern: NULL-check immediately after
the alloc, clean up partial state on failure, and propagate the
error via either task_set_error, a bool/enum return, or the
next-task-iteration advance (continue).  Free-on-NULL paths
exploit free(NULL) being a no-op to minimise conditional
branches.

Thread-safety: these are all on-thread modifications within the
task worker or task-dispatch thread context - task_queue.c
serialises completion callbacks on the main thread before the
task_data memory is read, so the NULL-toleration added in
completion callbacks is safe against the earlier-dispatched
worker writing NULL into task_data.

Scope: all fixes are local to individual task handlers/callbacks;
no API changes, no header changes, no cross-subsystem impact.
The task_queue.c callback dispatch contract is unchanged -
callbacks receive task_data which may be NULL if the handler
was unable to allocate it, and callbacks are now consistently
NULL-tolerant in the cases touched here.

Reachability: every fix is reachable under OOM.  The
more likely user-facing cases are save_state_cb /
content_load_state_cb / content_load_and_save_state_cb
(triggered on every save-state / load-state action), and the
blissbox enumeration (triggered on every USB joypad hotplug if
blissbox support is built in).
2026-04-24 06:47:53 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 7f53f79e2a * less stdstring dependencies
* replace string_is_equal with memcmp
2026-04-02 17:35:07 +02:00
libretroadmin 546388a5bd Reduce some gotos in tasks 2025-08-04 23:34:53 +02:00
libretroadmin f45fd77d68 Fix errors and warnings pointed out by static code analysis (Clang) 2025-07-17 08:49:53 +02:00
libretroadmin c6d72062e2 remove dead code 2025-07-17 08:02:06 +02:00
libretroadmin cc826c4ca6 Cleanup some variable names and some other cleanups 2025-07-17 05:11:00 +02:00
sonninnos b2ca569521 Logging unification cleanups 2025-07-10 05:59:06 +03:00
LibretroAdmin d2d0e7a17d Style nits 2025-02-12 10:35:04 +01:00
LibretroAdmin 7a7c4df2a1 Settings cleanups 2025-02-10 17:12:02 +01:00
LibretroAdmin 6be18bfee9 Standardize naming of local len variables 2024-12-30 14:27:24 +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 36bcbefc96 Cleanup some char variables - title variables will always be 128
in size
2024-09-10 00:15:23 +02:00
libretroadmin afc9cb509a CXX_BUILDFIX buildfixes 2024-07-20 19:42:45 +02:00
libretroadmin 3e85a17d7a iFix warnings picked up by -fanalyzer 2024-05-23 23:50:23 +02:00
libretroadmin 71edae5955 Fix unused function warning 2024-01-25 16:04:11 +01:00
Jesse Talavera 17c9227a9c Fix the build when XDelta is enabled on certain platforms (#15968)
* Rename the `MIN_MATCH` defined by xdelta3 to `XD3_MIN_MATCH`

- zlib defines its own macro by that name, but with a different value

* Don't redefine `SIZEOF_ARRAY` in xdelta3 if it already exists

* Don't define ssize_t in xdelta3, rely on libretro's definition instead

* Enable xdelta3 support in MSVC 2015-2019

* Fix some invalid MSBuild condition syntax

* Always build xdelta with XD3_USE_LARGESIZET as 1

* Fix an `#if` in task_patch.c

* Enable `HAVE_XDELTA` in the UWP build

* First crack at fixing Xdelta support for Android
2023-12-05 08:32:16 -08:00
Jesse Talavera-Greenberg cbf49a0b77 XDelta patch support (Take 2) (#15915)
* Add xdelta in deps

* Include <assert.h> in xdelta3.h

- Otherwise the static_assert calls can fail

* Build xdelta3 in Makefile.common

* Add xdelta support to the softpatching infrastructure

- The patching itself isn't fully implemented yet

* Adjust how xdelta3.h checks the sizes of some types

- Now checks max values instead of relying on autotools

* Add some enums that were excluded by the cherry-pick

* Remove stray whitespace

* Adjust SIZE macros in xdelta3.h

- Move them outside the XD3_USE_LARGEFILE64 block
- Add more SIZE declarations
- Make SIZEOF_UNSIGNED_LONG_LONG contingent on the presence of ULLONG_MAX

* Reintegrate xdelta support

* Enable support for xdelta's secondary compressors

- Necessary for some patches

* Fix some format specifiers

* Remove unnecessary files from xdelta

* Include xdelta3.h with a relative path

* Add xdelta3 headers to HEADERS variable

* Gate Xdelta support behind HAVE_XDELTA

- HAVE_XDELTA is on by default
- HAVE_PATCH is still required for HAVE_XDELTA to be meaningful
- Support is mostly contingent on the availability of LZMA
- Anything modern should be okay
- Legacy platforms (e.g. DOS) may need to have Xdelta support disabled
- At least until some other solution can be found

* Disable HAVE_XDELTA on platforms where the build recently failed

- These come from looking at the failed builds on GitHub
- These are guesses, and may turn out to be wrong

* Fix a potential memory leak

- Whoops, looks like I need to call two cleanup functions
- xd3_close_stream exists separately from xd3_free_stream

* Split the --help printout for --xdelta into its own strlcat call

- GCC was complaining about #ifdefs within macro arguments being non-portable

* Fix some incorrect printf format specifiers

* Modify Xdelta to adhere to C89

- It's mostly using RetroArch's INLINE macro instead of the inline keyword

* Slight cleanups

* Remove a stray comma that was hindering C89 builds

* Add XDelta support to CHANGES.md

* Change how the xdelta patch's name is computed

- To be in line with other recent refactoring

* Fix an incorrect merge

- Whoops, this part was from before I figured out how to get the size of a patched file

* Explain the song-and-dance behind computing a patched file's size

* Define some XDelta3-related constants to 0 on 32-bit platforms

* Adjust some Xdelta-related macro definitions

- Exclude the encoder, since we're not making patches
- Move some #defines to after inclusion of <stdint.h>, to fix undefined behavior
- Remove _WIN32_WINNT overrides, since they were for code that we're not using

* Fix Xdelta support

* Wrap an encoder-only function in `#if XD3_ENCODER`
2023-11-23 20:19:07 -08:00
LibretroAdmin f5133d8cc4 Revert "Add Xdelta support for softpatching (#14706)" (#14743)
This reverts commit aaad220836.
2022-12-19 03:29:46 +01:00
libretroadmin 7a4a860680 Revert "Don't rely on ENOSPC - relies on errno.h"
This reverts commit f6c2e4d292.
2022-12-19 03:22:07 +01:00
libretroadmin f6c2e4d292 Don't rely on ENOSPC - relies on errno.h 2022-12-19 03:17:09 +01:00
Jesse Talavera-Greenberg aaad220836 Add Xdelta support for softpatching (#14706)
* Add xdelta in deps

* Include <assert.h> in xdelta3.h

- Otherwise the static_assert calls can fail

* Build xdelta3 in Makefile.common

* Add xdelta support to the softpatching infrastructure

- The patching itself isn't fully implemented yet

* Adjust how xdelta3.h checks the sizes of some types

- Now checks max values instead of relying on autotools

* First crack at xdelta softpatching support

- There may be undiscovered edge cases or bugs

* Add xdelta in deps

* Include <assert.h> in xdelta3.h

- Otherwise the static_assert calls can fail

* Build xdelta3 in Makefile.common

* Add xdelta support to the softpatching infrastructure

- The patching itself isn't fully implemented yet

* Adjust how xdelta3.h checks the sizes of some types

- Now checks max values instead of relying on autotools

* First crack at xdelta softpatching support

- There may be undiscovered edge cases or bugs

* Remove trailing commas from the enums I modified

- C89 doesn't allow them

* Remove stray whitespace

* Adjust SIZE macros in xdelta3.h

- Move them outside the XD3_USE_LARGEFILE64 block
- Add more SIZE declarations
- Make SIZEOF_UNSIGNED_LONG_LONG contingent on the presence of ULLONG_MAX

* Add some RARCH_DBG calls for xdelta patching

* Enable support for xdelta's secondary compressors

- Necessary for some patches

* Fix some format specifiers

* Remove unnecessary files from xdelta

* Include xdelta3.h with a relative path

* Add xdelta3 headers to HEADERS variable

* Gate Xdelta support behind HAVE_XDELTA

- HAVE_XDELTA is on by default
- HAVE_PATCH is still required for HAVE_XDELTA to be meaningful
- Support is mostly contingent on the availability of LZMA
- Anything modern should be okay
- Legacy platforms (e.g. DOS) may need to have Xdelta support disabled
- At least until some other solution can be found

* Disable HAVE_XDELTA on platforms where the build recently failed

- These come from looking at the failed builds on GitHub
- These are guesses, and may turn out to be wrong

* Fix a potential memory leak

- Whoops, looks like I need to call two cleanup functions
- xd3_close_stream exists separately from xd3_free_stream

* Split the --help printout for --xdelta into its own strlcat call

- GCC was complaining about #ifdefs within macro arguments being non-portable

* Fix some incorrect printf format specifiers

* Modify Xdelta to adhere to C89

- It's mostly using RetroArch's INLINE macro instead of the inline keyword
2022-12-19 01:10:04 +01:00
libretroadmin 04f510d503 Cleanup header includes 2022-12-05 15:10:19 +01:00
LibretroAdmin 4c4bec11f7 NULL termination already happens in strlcpy 2022-08-10 02:45:27 +02:00
libretroadmin 3cf7e881ec Get rid of unnecessary log spam about non-required/non-essential files/directories 2022-07-21 03:48:11 +02:00
libretroadmin f7194e167f use path_basename_nocompression where it is safe to do so 2022-07-12 19:14:12 +02:00
Tony 09880e92d2 Logging cleanups (#13320) 2021-12-04 14:21:12 +01:00
eadmaster 019130298a added multi-softpatching support + OSD messages for patches (#9947)
fixed Travis error
2021-04-30 14:12:47 +02:00
twinaphex 68027c606e Silence some warnings 2021-02-09 16:43:40 +01:00
twinaphex 87c0fb6323 Struct reordering 2020-08-14 18:58:09 +02:00
twinaphex 9ae4031d13 Cleanups 2020-03-07 19:14:45 +01:00
twinaphex 64c515bac4 Turn while (true) into for (;;) for easier MSVC backwards compatibility 2020-02-01 04:15:22 +01:00
twinaphex 60faeffde0 (task_patch.c) Cleanups 2020-01-20 04:44:45 +01:00
twinaphex 481f31fe8f Turn task_patch.c into separately compiled file 2020-01-20 04:31:32 +01:00
brenodantas10 0ab26a1371 Soft-Patch any IPS size (put declarations at beginning) 2019-09-01 18:44:21 -03:00
brenodantas10 49032ae2f2 Soft-Patch any IPS size 2019-09-01 16:01:48 -03:00
brenodantas10 33c681c0c7 Fix IPS Patch, still without re-allocation 2019-08-28 01:52:26 -03:00
Breno Dantas Mendonça be493daf72 Update task_patch.c
Fix IPS Patch, still without reallocation
2019-08-28 01:39:15 -03:00
brenodantas10 a099812f6e (bps/ups)_apply_patch - Re-allocation target_data variable for target patch size (can now apply bigger patches without extra-bytes on memory) 2019-08-24 00:06:34 -03:00