mirror of
https://github.com/libretro/RetroArch.git
synced 2026-11-22 10:50:15 -10:00
codex/android-native-streaming
14
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f140e9592a |
Soft-patching: apply a streamed IPS patch to the loaded ROM where it lies
A streamed IPS patch built its target as the source arrived: a second buffer the size of the ROM, taken at open, every byte of the source copied into it, then the records laid over it, and the source freed. The target of an IPS patch is the source with the records on it, and the source is the content buffer the load already owns. patch_stream_finish_into() finishes a stream whose source the caller owns (malloc'd, given to patch_stream_set_source()): an IPS patch puts its records on that buffer in place, growing it with realloc() only when the target is longer, and any other format hands back its target in the buffer's place. On failure the buffer is still the unpatched source, as before. Fed in place, IPS copies nothing while the source arrives; a chunk fed from elsewhere copies what came before through to the target and carries on as before. The target is no longer taken at open but by the first copy-through, so the in-place path never takes one. The content load finishes its patch with finish_into(). A 16 MiB ROM with a 2000-record IPS patch, first touch: 6.7 ms -> 0.05 ms to apply, and 16 MiB less heap during the load. The patch_stream test finishes every in-place and fallback comparison with finish_into() on a buffer of its own, and checks a 4 MiB IPS source is patched where it lies without being moved or copied. Leaving the grown tail unzeroed, skipping the records in place or in the catch-up, copying nothing in the catch-up, or copying through while fed in place each fail it. |
||
|
|
69d936201c |
Soft-patching: read the source in place while streaming BPS, UPS, xdelta
The content load streams a soft patch alongside the read: each span the transfer fills is fed to the applier as it arrives. BPS and xdelta may copy from anywhere in the source, so both kept their own growing copy of every byte fed (BPS in src_buf, xdelta in own_src), and UPS kept the part it had not consumed yet in its carry. The transfer buffer already holds the whole source in one allocation that never moves, and stays alive, detached as the content, until the patch is finished - so that copy is a second ROM in memory, written once and read back. patch_stream_set_source() (and vcdiff_stream_set_source() under it) tells the stream where the source it is about to be fed lies. Chunks fed from there are read in place: no copy, no realloc as it grows, no memmove of the UPS carry. A chunk fed from anywhere else falls back to the old copy, starting with what came before it, so a caller that does not keep the source whole still gets the right answer. IPS keeps no source and is unchanged. content_file_pump_source() sets the transfer buffer as the source. A 32 MiB BPS hack patch: 32 MiB less heap during the load, and 143 -> 137 ms to apply. The patch_stream test feeds each comparison as a copy, in place, or in place then from another buffer (freed at once, so ASan catches a stream still reading it), and checks with glibc's heap counters that a 4 MiB BPS source and the xdelta source are no longer copied. Dropping the bytes the fallback copies, restarting the UPS carry at 0, reading the wrong byte in place, or ignoring the setter each fail it. |
||
|
|
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.
|
||
|
|
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. |
||
|
|
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.
|
||
|
|
9673ceb088 |
patch: do not hand NULL to memcpy/memset on a zero-length write
patch_stream_reserve() returns early for a request it already satisfies, so reserve(ps, 0) succeeds without allocating and leaves ps->out NULL. patch_stream_put() and patch_stream_fill() then form ps->out + at and call memcpy/memset with a null first argument. Both the null pointer arithmetic and the null argument are undefined even though the length is zero, and UBSan reports the memset every time an empty target is finished: patch_stream.c:143: runtime error: null pointer passed as argument 1, which is declared to never be null Skip the call when there is nothing to move. out_len still advances exactly as before. Predates the varint work; noticed while sweeping this file. With the guard in place a 60k-iteration randomised-input sweep over the IPS, UPS and BPS readers is clean under ASan and UBSan, where it previously reported this site on every run. |
||
|
|
41a8b1bed0 |
patch: bound the UPS skip walk so a valid varint cannot hang
The preceding commit stops a *truncated* varint from spinning the
decoder forever, but the UPS reader has a second, independent hang on
the same path that a well-formed varint still reaches.
patch_stream_ups_run() walks the skip run one byte at a time:
while (skip--)
{
if (ps->s_off < ps->src_len && !patch_stream_ups_src_ready(ps))
... roll back and wait for more source ...
patch_stream_ups_out(ps, patch_stream_ups_src(ps));
}
Once s_off reaches src_len the rollback arm is dead, so the loop runs
the full remaining count. skip is a uint64_t straight out of
patch_stream_decode() with no upper bound, and a correctly terminated
varint encodes up to 2^64-1 in nine bytes. A 27-byte UPS1 file whose
first command is a skip of 2^60 wedges content loading indefinitely:
"UPS1" | num(16) | num(16) | num(1<<60) | 12 zero bytes
Rejecting an oversized skip is not open to us - the whole-buffer
applier lets a run overshoot the declared target and this reader has
to reproduce it byte for byte - but the overshoot need not be walked.
Once s_off is past src_len and t_off is past tgt_len the loop body
reads nothing and writes nothing: patch_stream_ups_src() returns 0
without touching the carry, patch_stream_ups_out() drops the byte, and
neither cursor's exact value is observable afterwards. Both are
already past every bound that is tested downstream, so the remaining
iterations are dropped.
That bounds the walk by src_len + tgt_len, both of which are already
bounded by a successful allocation at open().
Verified against tasks/task_patch.c ups_apply_patch() as the oracle,
on bodies built specifically to overshoot the declared target (skip
magnitudes just past tgt_len, 4x tgt_len, and 0x7FFFFFFF), with the
trailer restamped from the whole-buffer result so both readers are
asked to verify the same patch: 1500/1500 pairs byte-identical, same
accept/reject verdict on every one. The same test against the parent
commit does not finish in 45 seconds. Valid-patch equivalence against
the parent is unchanged over 5000 randomised BPS and 5000 UPS patches
at random feed-chunk sizes, and 260k randomised-input iterations pass
clean under ASan and UBSan.
|
||
|
|
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. |
||
|
|
8274842330 |
tasks: validate the BPS checksums when streaming
The same omission the UPS applier had, found by asking the question that fix raised rather than waiting for it to bite: BPS carries a checksum for the source, the target and the patch, bps_apply_patch verifies all three, and the streaming applier verified none. It was hidden by how the earlier test happened to damage a patch. A flipped byte usually lands on an instruction or a length and trips the structural bounds, so the streaming applier refused and the behaviour looked right. The case that matters is not a damaged patch at all - it is a patch applied to the wrong revision of the content, which is the commonest way patching goes wrong and the exact thing the source checksum exists to catch. Applied to a ROM one byte away from the one it was built against, the streaming applier accepted it and produced content from the wrong base, silently, with no error anywhere. Check the footer as bps_apply_patch does, and in its order, so the error a rejected patch reports matches as well. The source checksum accumulates as chunks are fed - shared with UPS, which needs the same thing - and the target's is taken once the target is complete. Verified on a real ROM through a real build: applied to the ROM it was built against, a .bps still applies and reports the expected CRC; applied to a ROM one byte different, it is now refused by both appliers and the content runs unpatched. UPS behaves the same. All four formats still stream and apply correctly against the right content. The differential suite is unchanged at 300000 comparisons - it could not have caught this either, for the reason recorded when UPS was fixed: its generator emits correct checksums, so both sides agree on bytes while disagreeing on whether the patch should have been applied. |
||
|
|
ba610e33b6 |
tasks: validate the UPS checksums when streaming
build showed the streaming applier accepting it and handing the core silently corrupt content, where the whole-buffer applier refuses the same patch and the content runs unpatched. UPS carries a checksum for the patch, for the source and for the target, and ups_apply_patch checks all three - refusing on any mismatch, with an allowance for a patch applied in reverse, where the two content checksums swap. The streaming applier checked none of them. It decoded the diff stream, produced a target, and returned it. For a patch that is intact the result is identical, which is why nothing noticed; for a damaged one the caller's careful fallback - keep the unpatched buffer when a patch is rejected - never fires, and the corrupt target is adopted instead. Track the same three checksums and refuse exactly what the whole-buffer applier refuses. The source checksum accumulates as chunks are fed, the target's is taken once the target is complete, and the patch's is over the patch minus its own trailing four bytes. The differential suite could not have caught this. It compares output bytes for patches its generator builds with correct checksums, and its oracle deliberately omits the validation verdicts - so both sides agreed on the bytes while disagreeing on whether the patch should have been applied at all. That is the gap: a contract stated as "whatever the whole-buffer applier does, the streaming one does too" was only ever enforced for the output, never for the refusal. BPS was tested the same way and behaves correctly, but for a weaker reason than its checksums: damage to its instruction stream trips the structural bounds first. Worth knowing that its correct behaviour here is not evidence its checksums are being verified either. Verified: a valid .ups still applies to the real ROM with the expected CRC, a damaged one is now refused by both appliers and the content runs with the source ROM's own CRC and its internal checksum intact. The differential suite is unchanged at 300000 comparisons. |
||
|
|
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. |
||
|
|
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. |
||
|
|
27599fb98e |
tasks: never finish a patch whose source arrived only in part
A regression from streaming soft patches alongside the load. Both load paths open the patch stream before the transfer and feed it as spans arrive, but neither dropped the stream when the transfer itself failed part way. The load then fell back - to file_archive_compressed_read or filestream_read_file - and produced a complete buffer, after which patch_stream_finish ran on the stream that had seen only a prefix, and its result replaced the good buffer. The appliers cannot detect this on their own: a feed that stops early is indistinguishable from a source that is legitimately short, so they zero-fill the remainder and return a plausible-looking buffer. Measured on a 64 KiB ROM whose transfer died a quarter of the way in, three quarters of the resulting content was zeros - and nothing reported an error, because as far as every layer was concerned the patch applied cleanly. Reaching it needs a read failure (a corrupt archive, a vanished file, an I/O error) on content that also has a patch beside it, which is presumably why it survived review. Fix it at both levels. The load paths now drop the stream whenever the pump returns no buffer, so the fallback read is followed by the ordinary whole-buffer patch pass, which is what would have happened had streaming never been attempted. And patch_stream_finish now refuses outright when fewer bytes were fed than the source length declared at open, so the failure is explicit rather than depending on every caller to notice - this is the belt to the load paths' braces, and it is what stops the next caller from reintroducing it. UPS's feed had not been tracking the byte count that check needs; it does now. Verified: finish() rejects a partial feed and a stream never fed at all, accepts a complete feed and a zero-length source (whose complete feed is no feed). The differential suite is unaffected - it always feeds the whole source - and still reports 300000 comparisons with zero mismatches. patch_stream.c compiles under -std=c89 -pedantic -Wall -Wextra with no diagnostics; task_content.c compiles with and without each of HAVE_PATCH and HAVE_COMPRESSION. |
||
|
|
87d644652d |
tasks: add streaming patch appliers with a differential harness
Soft patching currently runs as a separate pass: content_file_load_into _memory reads (and, for compressed content, inflates) the whole ROM into a buffer, and only then does patch_content walk it end to end. The data_transfer spine already makes the load itself sliceable across task ticks - the comment on the entry-source path says as much - but a whole-buffer applier cannot participate, because it needs every byte before it can start. Add incremental counterparts to the three appliers in task_patch.c. They consume the source as consecutive chunks, so the patch advances on the same tick that produced the bytes, and load, decompression and patching interleave instead of running as serial passes over the same data. Output is byte-identical to the whole-buffer form and independent of where the chunk boundaries fall. Residency differs by format, because they differ in how they address the source. IPS reads it strictly sequentially and retains nothing; UPS consumes it in lockstep with the target and retains only a small rolling carry; BPS has to retain it in full, because SourceCopy seeks arbitrarily - there the gain is the overlap with the load, not memory. IPS and UPS run as straight state machines; BPS attempts each command and, when it would read source past the fed frontier, rolls the command back whole and retries on the next feed, which is what makes its output chunk-boundary-independent. Nothing calls this yet, so no build system is wired and no existing binary changes; the first consumer will add it. The harness in tasks/test holds the whole-buffer logic as an oracle and compares the two across random valid patches at chunk sizes from 1 byte to 1 MB, with a deliberately edge-heavy size distribution. Streaming appliers have failure modes the whole-buffer form cannot have, because the whole-buffer form always has everything: an empty source (feed() never called), a source ending short of its declared length, and chunk boundaries landing inside a patch command. The first of those caught a real bug during development - an empty source left the patch entirely uninterpreted - which is why the case is now generated explicitly. Verified: 300000 comparisons (280000 IPS/UPS, 20000 BPS) with zero mismatches, clean under ASan and UBSan; the module compiles under -std=c89 -pedantic -Wall -Wextra with no diagnostics. Separately exercised against the real data_transfer source-mode spine - a producer callback standing in for an inflating archive entry, iterate() driven with a per-tick byte budget - for 3200 loads with zero mismatches, confirming the intended integration shape works before any of it is wired up. |