intfstream_read_at reads at an offset and leaves the stream's position
where it was: files and memory streams without touching the stream, so
from several threads at once, CHD tracks by seeking there and back. The
buffered stream reads from the file and keeps its window, and its own
refills and wide reads go to the file at the offset. memstream_read_at
backs memory streams. The CUE/ISO serial detectors read their probes
this way.
The zip reader takes its end records, directory, local headers and
member chunks with one read at the offset each, where the file has
them; the reads the stream lends from stay as they are.
The Windows second handle is opened relative to the stream's own with
an empty name through ntdll's NtCreateFile on every NT. From Vista on
that is what ReOpenFile does; before it the handle is kept only when
its volume and file index match the stream's, else the path reopen
follows.
Lanes: intfstream_read_at_test (file, buffered, memory; four threads),
vfs_positional_ntverify_test (the check, on any version); archive_zip64
counts reads at offsets as reads through the stream.
Follow-up to "Scanner: Match Jaguar CD discs by CRC".
When a sheet had no data track, the fallback parsed the whole sheet
a second time with that track forced to data. That re-reads the cue
and reopens every track file - a Redump Jaguar CD has one file per
track, so ~20+ extra opens per disc during a scan.
Note the first track of session 2 (while no data track has been seen)
during the one parse instead: its start index, its end (next track's
index in the same file, or the file's end), its path and its open
stream, which the CRC pass then hashes without a fresh open, as a
data candidate's is. The force_track parameter goes away.
Same answers as before on 13 sheets (one file per track, single bin,
shared files, Enhanced CD, data before/after session 2, missing file,
CD-i, REM comments), ASan/UBSan clean. On a 24-track Redump-style
sheet: 48 -> 24 track opens, ~100 -> ~47 us per sheet.
A lookup finds directories as well as files, the root at the empty
path, and searches each directory's sorted entries by bisection instead
of scanning them. A listing's entries carry their place: a file's
offset and size, a directory's first entry and count. zar_index_offset()
tells a caller where the index begins, so it can keep that part of the
file in memory and answer lookups and listings without I/O.
zar_write.c builds an archive front to back through a write callback,
compressing blocks with rzstd where HAVE_RZSTD is defined and finishing
with the footer's SHA-256, so an emulator can make .zar/.wua files
without the reference ZArchive library. Its output reads back with the
reference reader, and the reference writer's output with this one.
Wii U content did not scan. It now takes the serial lookup by its
product code:
- a WUD, or a Wii U disc by another name (.iso, probed only once the
other detectors find nothing, so other discs read nothing more), by
the "WUP-P-XXXX" its header starts with;
- a WUX, through the new formats/wux, the same octets of the disc it
stands for;
- a Wii U archive (.wua), by the product and company codes of its base
title's meta/meta.xml, read through formats/zar.
formats/wux reads WUX, the Wii U image format that keeps each distinct
sector once, as the WUD it stands for. Like the other readers it does
no file I/O: it asks for each range it needs. Opening reads the
32-octet header alone; the sector index is read a window at a time,
only where a read needs it; a read's data lands in its own destination,
one request per run of sectors the file keeps in order.
formats/zar gains a directory listing, zar_dir_begin() and
zar_dir_step(), each name read whole, the listing's end ZAR_END.
A Wii U release's serial in the database is the product code and the
maker's two characters, or the code alone for a title sold as a
download; a disc does not say its maker. The code is therefore looked
up as a stem, in the Wii U database alone - glob() in a libretrodb
query now matches binary fields, as a serial is kept - and the release
picked is the one of the maker an archive names, else a download for
an archive and a disc release for a disc. The playlist names the
release found.
wux_test is new, zar_test lists directories, and the scan test gains a
Wii U lane: a WUD, a WUX, a disc named .iso, two archives whose update
is listed before the game, and another database holding the codes.
Redump gives one serial to every release of an Xbox or Xbox 360 title,
and to the extras discs that came with them, so a serial lookup found
the first record - "Halo Movies (Japan)" for a North American Halo.
formats/xdvdfs now reads the regions a title is for: the game region of
an XBE's certificate, and the region of an XEX's security info, each
only where the executable is long enough to hold it. The scanner reads
the region field of the records a serial matches when it has regions to
go by, and takes the first record whose regions overlap them; when none
does, the first record stands in, as before.
The duplicate DB_EXTRACT_* definitions in database_info.c go: the
header carries them, with DB_EXTRACT_REGION added.
formats/zar looks files up in a ZArchive and reads them, with no file
I/O of its own. A lookup asks for a directory's entries a run at a
time and for each name only as far as it can match; a read asks for a
block kept as it is straight into its destination, decodes a
compressed block (HAVE_RZSTD) into the destination when the read
wants all of it, and otherwise into one block kept for the reads that
follow.
The scanner takes a .zar by the title of the default.xex it holds.
The title read takes the executable an Xbox 360 disc boots,
default.xex, ahead of an Xbox one's default.xbe, and reads one on its
own as well: an XEX's execution info, an XBE's certificate or an STFS
package's header, each only as far as the title needs, after a 24-octet
head that tells them apart. The game partition is also looked for where
development images keep it, and a padded root reads as empty.
The scanner takes .xex and .xcp files by their title, and Xbox 360
discs too; a disc of a set gets its place in it ("FO-2046-1"). A .xex
that is no Xbox executable, as an Atari 8-bit one, goes on to the CRC
lookup.
formats/xdvdfs finds an Xbox disc's game partition, at the start of a
trimmed XISO or where XGD1, XGD2 and XGD3 images keep it, looks files
up in its directory trees and reads the title of its default.xbe, with
no file I/O of its own. A lookup asks for one entry at a time, only as
much of each name as decides the search.
The scanner takes .xiso files, and .iso and .chd files no other
detector finds a serial for, through the serial lookup by the XBE's
title ("MS-004"), without the ISO size hint, which would rule out
trimmed images. Other discs read nothing more for it.
formats/ciso reads a CISO file as the disc image it stands for, with
no file I/O of its own: like formats/rvz, it describes each range of
the file it needs as a request and the caller supplies it. A read asks
for one range per run of stored blocks, straight into the read's own
destination, and blocks left out are zeroed in place; the head lands
in the block map's own storage and the map is built over it. Heads
that are not CISO, PSP CSO included, are refused.
The scanner takes .ciso files through the serial lookup, reading the
disc header through the reader on a descriptor-path stream.
ciso_test covers the reader and the database scan test a GameCube and
a Wii image, and one whose disc starts with a block left out.
* samples/database: include compat/strl.h in the scan test
The test calls strlcpy(), which mingw-w64 does not declare, so it did
not build for Windows.
* PS1 scan: PSX.EXE means no serial only as the BOOT target
A root directory can list a PSX.EXE ahead of the executable SYSTEM.CNF
boots: Tomb Raider (USA) lists one before SLUS_001.52. Stopping at the
first PSX.EXE in the probe window sent such discs to a whole-track CRC,
eight seconds for a CHD. Look for the BOOT target first, matched without
regard to case so cdrom:\psx.exe counts. A disc that boots PSX.EXE, or
has no SYSTEM.CNF so the BIOS boots PSX.EXE, has no serial and still
falls back to its CRC (#15241); any other disc is searched for its
serial with PSX.EXE directory records ignored.
* 3DS scan: identify .3ds, .cci and .cxi by the NCCH product code
These images took the default whole-file CRC, 0.5-4 GB a game. The
product code in the NCCH header (partition 0 of a cart image, or the
start of a bare NCCH) is the serial the 3DS database is keyed on, and
the header is plaintext in encrypted dumps too. A code held by one
record matches it outright. Revisions and regions that share a code fall
back to the file's CRC to choose, and to the first record when no CRC
matches; with scan_serial_and_crc on every match is confirmed by CRC, as
for PSP and Dreamcast, and a file none of whose records carry its CRC
goes on to the plain CRC lookup with the CRC already computed. A code no
record carries, or a header without valid magic such as a CIA, keeps the
CRC path, in first-match mode too. Like the CRC lookup, the serial pass
visits only databases an installed core claims the extension for, unless
Scan Without Core Match is on.
* scan: run ITERATE steps while the shared I/O window lasts
A file takes about twenty ITERATE steps, and the handler ran one per
call. On the regular task queue that is one step per frame: 1000 NES
zips took 335 s of pacing, 400 arcade sets 1639 s. The ITERATE states
now run in a loop under the same window the BEGIN states use, which
times the steps rather than counting them and grants every call at least
one. The scan test's unclaimed-database lane spends the window before
each check, so that it still counts steps.
* scan: hash file CRCs a quantum at a time across steps
A step that needed a CRC computed all of it in one handler call: a whole
CHD track with LZMA decode, or a multi-gigabyte 3DS image. On the
regular queue that froze a frame, and on the threaded queue it held the
worker for seconds. Each CRC site now opens its span and returns, and
later steps hash 256 KiB quanta while the shared I/O window lasts, at
least one per call. The lookup that wanted the CRC runs when it is in,
at the same entry. The one-shot CRC helpers, which nothing else called,
are gone.
* scan: walk each database once for its crc and serial indexes
The first file to reach the serial lookup built a crc index and then a
serial index for every database, a full walk each: 47 MB of Mobile -
J2ME twice in one handler call, the second for an index that came out
empty. The crc walk now reads serials as well. It notes whether a
database has any, so the serial lookup passes over one with none, and
for the serial lookup it builds the serial index in the same pass. Index
contents, matches and the split of the index budget are unchanged.
* scan: let a database's indexes be built a run of records at a time
A database's crc and serial indexes were built by one walk and a qsort
in a single call: 50-70 ms for Mobile - J2ME. libretrodb_scan_begin(),
_step() and _end() walk a run of records per call, and
database_info_index_job_*() builds both indexes over as many calls as it
takes, each walking a run of records or merging a run of entries in a
resumable merge sort. libretrodb_scan_field2() and
database_info_index_new() are built on them and answer as before.
* scan: build each database's indexes over steps
The first file to reach a database built its indexes in one handler
call: 52-68 ms on the regular queue for Mobile - J2ME, 13-17 frames'
worth of the 4 ms window. The build now runs over the steps that follow
the lookup that began it, a run of records walked or entries merged at a
time while the window lasts, and the lookup takes the indexes when they
are done. A database counts as size-checked only then. Cancelling frees
a build in flight. The one-shot builders, database_info_crc_index_new(),
database_info_serial_index_new(), database_info_index_new() and
libretrodb_scan_field() and _field2(), lose their last caller here and
go; the tests build through the job and the stepped scan.
* task_queue samples: build on macOS, run on GCD in a macOS job
No sample ran the GCD runner and nothing in CI built HAVE_GCD. Apple's
ld has no --wrap, so on Darwin the switch and init-failure tests
redirect the wrapped calls from task_queue.c by macro instead, and
libdispatch comes from libSystem there. The switch test gets a GCD=1
build, and a macOS job runs every task_queue sample plain, under
ASan+UBSan and TSan, threaded and, where it has a GCD=1 build, on GCD.
* task_queue: a switch waits out a wake from another thread
task_queue_wake() is documented as safe from any thread, but a switch
between the threaded and the unthreaded queue frees the threaded
runner's lock and condition variable while a waker on another thread can
still be inside it. Toggling Threaded Video makes that switch at the
next frame. Two seq_cst counters now keep them apart without a lock: a
switch that finds a waker inside is put off to the next
task_queue_check(), and a waker that finds a switch under way leaves its
task to it. A wake on the thread that drives the queue cannot meet a
switch and skips the counters.
A switch now ends every park, and the new runner takes wakes again
before it runs any task, so a parked task loses nothing to a wake
dropped during the switch. A wake dropped while a switch is put off and
then taken back, or for a task whose park a switch keeps because it
leaves a stuck handler behind, waits for that park's horizon.
The switch test holds a waker inside the queue across a switch, wakes
from four threads through 1000 switches, and holds the main thread where
the new runner first runs a task while that task's first pass wakes it.
GCD builds leave out the threaded runner's own code, which they never
used and which warned there. The switch test also checks that its
realloc() wrapper ran, since on macOS that wrap is a macro rather than a
link option.
* scan: a scan of one file only adds to its playlist
A Content Location that is a file is scanned as one file, which the Scan
button, --scan=FILE and iOS "open in" already rely on. Such a scan
cleared the playlist when Overwrite was on, and recorded the file, and
its core, as what the playlist refreshes with, so Refresh Playlist later
rescanned that file alone. Overwrite is now ignored for a file, and the
playlist's scan record and default core are left as they were. Validate
Existing Entries is skipped too: a file scan's extensions can differ
from its folder's, so validating with them could drop entries the folder
scan added. A later folder scan or Refresh still prunes. With no
database and an automatic target playlist, a file is filed under its
folder's name, as a scan of that folder files it, rather than in a
playlist named after the file. A Content Location that is missing, as on
a drive that is offline, counts as a file, so Overwrite no longer
empties its playlist while the drive is away.
* menu: Content Location takes a file or a folder
Content Scan's Content Location now opens one browser that lists folders
and files in every scan method: OK on a file picks it, <Use This
Directory> picks the folder. In Automatic it lists every file, as an
Automatic scan reads every file; Custom keeps listing the scan's
extensions. The Scan Single File toggle, which switched the browser to
files and was shown only in Custom with Search Recursively off, goes
with its setting and strings, and a scan of a file no longer turns
Search Recursively off behind the user's back. Import Content drops Scan
Directory and Scan File, as the Scan Directory list already had, leaving
Content Scan as the one way in; Scan File no longer started a scan. On
Apple, File > Open and the iOS document picker opened from Content
Location set the location as OK on a file does.
* task_queue: hold pushes from other threads for the main thread
task_queue_push() from another thread could meet a switch between the
threaded and the unthreaded queue, which frees the lock and condition
variable the push takes. On the unthreaded queue, with no switch at all,
it put the task on a list the main thread walks without a lock. Windows
pushes from the video thread under threaded video, and HID builds from
libusb's thread. Such a push now goes through the switch's gate: when
the gate is shut, or the unthreaded queue is up, the task goes onto a
lock-free list that the next gather pushes on the main thread, and the
push returns true. A push is also held while earlier ones still wait, so
a thread's pushes start in the order it made them. A BLOCKING task
refused there is cancelled, and its callback still runs. The switch test
pushes from four threads on the unthreaded queue and through 1000
switches, checks a held BLOCKING push, and holds the main thread inside
the gather that reopens the queue to show that a thread's next push does
not pass its held one.
* task_queue: cancel by ident and find safely from other threads
task_queue_cancel_task() and task_queue_find() from another thread met
the same switch and the same unlocked lists as a push did.
task_queue_cancel_ident() cancels by ident from any thread: a locked
walk when the threaded queue is up with nothing held, otherwise an ident
left for the next gather, which applies it after its pushes, to a held
push as well. A held push cancelled so retires cancelled without
running, and its callback runs. A find from another thread goes through
the switch's gate and reports false when it cannot walk the lists. The
queue's own workers and GCD threads skip the gate, and a find on the
main thread also sees held pushes. Each worker keeps its thread id in a
slot of its own and clears it before it reports that it left, so a
thread that reuses a joined worker's id is not taken for one. The switch
test cancels and finds from other threads on both queues and across a
put-off switch, and holds the main thread in the gather to show that a
thread's cancel of its own held push is not lost. Once extra workers
start, finds from handlers on the one worker and on an extra still skip
the gate, and a find with a joined extra worker's id from inside deinit
is refused.
* autoconfig: make connects reported on other threads on the main thread
libusb's hotplug thread and the Wii's HID poll thread report pads from
their own threads, where task_queue_find() can no longer answer exactly:
at a switch, or on the unthreaded queue, it reports false. Off the main
thread, input_autoconfigure_connect_ex() and
input_autoconfigure_disconnect() now copy the request into a main-thread
task and return true. Its callback makes the call on the main thread, in
the order the requests were made, so the duplicate check, the port's
sequence number and the settings it reads are the main thread's. A new
sample drives task_autodetect.c on the task queue with the rest stubbed,
reports pads from another thread, and checks that every find runs on the
main thread, that a pad reported twice queues one connect, that a
disconnect handed off is made and that a cancelled request is not.
* task_queue: wait, reset and deinit see pushes held for the main thread
On the unthreaded queue every push from another thread is held for the
next gather. A wait with nothing running returned without running it,
and a reset, the exit drain's included, left it to run normally
afterwards. Cancels held for the gather were never freed at deinit.
The unthreaded wait now drains held pushes first, and a reset drains
them into the runner before it cancels, so a held task meets a queued
one's fate. Deinit applies and frees held cancels; held pushes stay held
for the next runner's first gather, so no callback runs inside deinit.
* task_queue: make the Threaded Tasks flag atomic
Task handlers on the worker read it through task_queue_is_threaded(),
and the main thread writes it when the setting changes, so changing the
setting while a task ran was a data race. ThreadSanitizer shows it on a
database scan whose queue is switched under it.
* task_queue: a parallel task names the extra workers it needs
retro_task_t gains parallel_workers, which task_init() clears. A
parallel push starts the extra workers it finds missing, up to the
larger of task_queue_set_parallel_workers() and the task's number, at
most 8. They serve every parallel task and stay until deinit, as before,
so the pool only grows; 0 keeps the frontend's number. The started count
is atomic, so a push that finds enough takes no lock, and one that needs
more claims the next entries under running_lock.
The parallel test has a task asking for three, a later one asking for
fewer, one asking for more than eight, a plain task whose number is
ignored, the frontend's number holding for a task asking for fewer, and
a task that leaves the number alone.
* task_queue: let deinit leave extra workers behind in detachable handlers
A parallel task may now also be detachable, and then runs on the extra
workers like any other parallel task. Deinit gives every worker the one
bound it gave the one worker, the extra workers first. One still inside
a detachable handler past it is left behind to finish alone, as the one
worker was, and one inside any other handler is still waited for. The
primitives of an init are held by deinit and by each worker it leaves
behind, and the last of them to let go frees them, so the one worker and
several extras can be left behind together.
A worker left behind, the one or an extra, now runs the task's cleanup
once the handler returns, then frees the task, so a detachable task
releases what it holds however it ends. Its callback still never runs;
its cleanup, like its handler, may touch only what the task owns.
The parallel test runs a detachable parallel task on an extra worker,
leaves one stuck past the bound, waits for a slow one that is not
detachable, and leaves the one worker and two extras behind together
with a new queue running beside them. Each task left behind is cleaned
up once, by its own worker, after its handler returns, and one not left
behind at its retirement as before. The switch test switches to the
unthreaded queue and back with extra workers live.
* task_queue: on Emscripten, sleep after a pass on the one worker only
On Emscripten every worker sleeps 1 ms after each handler call, a
pthreads workaround from when the one worker ran every task. The extra
workers run parallel tasks, which work in many short passes, and the
sleep cost each of those passes 1 ms, more than the pass itself. The
extra workers no longer sleep; the one worker still does.
* emscripten: ask for at most 4 extra workers, and start 5 threads
In the browser a pthread the pool has not started is made on demand by
the main thread, and with the JS file system, where every thread's file
calls go through the main thread, 8 extra workers made each of those
calls about 40% dearer than 4 did. The frontend asked for cores - 3
extra workers, up to 8; on Emscripten it now asks for at most 4, and the
build starts 5 pthreads up front, enough for the one worker and those 4.
* scan: read small plain files on parallel reader tasks, in list order
A database scan on the threaded queue pushes min(4, cores) reader tasks,
none below 2, as parallel tasks that ask for that many extra workers, in
HAVE_THREADS builds with lock-free atomics, except on Wii U, whose C
library and FAT layer take no locks, and on Vita, where Vita3K's sceIo
tables take none. With Threaded Tasks off none starts and the scan
reads every file itself, stepped as before.
The scan hands the plain files and archives it would CRC whole to the
readers, up to 64 per reader ahead of it, each with its own copy of the
path. A reader claims them in list order, opens and sizes each, leaves
one over 128 MiB to the scan unread and CRCs the rest a quantum per
call. The scan takes each result at its own place in the content list,
so the databases see files in the same order as before, parks while the
next one is still being read, and reads itself whatever a reader could
not.
The scan never waits for its readers. At its end, on cancel and once
the queue is unthreaded, each reader leaves at its next call and hands
back the file in hand. Each reader drops its reference to what they
share in its cleanup, and the last reference frees it. A queue deinit
leaves a reader stuck in a read behind after its 1 s bound and never
calls it again; the worker left with it runs its cleanup once the read
returns, which hands back the file in hand and drops the reference.
The scan test covers list order, files over the cutoff, failed pushes,
cancels and quits with a reader stuck in a read, and queue switches
under a scan; CI runs it under TSan, without threads and with no
readers.
* scan: run the command-line scan with no menu on the threaded queue
A command-line scan with no menu waits for the task queue to run dry,
and only a scan on the threaded queue gets readers. In threaded builds
that run now uses the threaded queue whatever Threaded Tasks says; the
setting is not changed.
* menu: Import Content offers Scan Directory and Scan File
Both entries sit beside Content Scan when the database is built in.
OK on a file in Scan File's browser scans that file, as the Scan
action does. The load_content_filter harness checks that the
entries are listed and that OK on a file starts its scan.
* manual scan: Content Location holds a full file path
The location can now be a file, so it is kept in a PATH_MAX_LENGTH
buffer, as is the scan task's copy. A file whose path does not fit
is refused in the browser instead of being joined short. The
load_content_filter harness sets a location deeper than a folder
buffer and checks that it is kept whole.
---------
Co-authored-by: LibretroAdmin <[email protected]>
intfstream_file_get_crc_and_size() opened the file HINT_NONE and
hashed it through a 256 KB buffer; the bounded-span path (a CD data
track, hundreds of MB) had its own copy of that loop with its own
malloc. Open FREQUENT_ACCESS instead, so the VFS maps the file
where it can and intfstream_crc_step() folds the CRC straight out
of the mapping - no read, no copy - and route the bounded span
through crc_step() as well, which keeps one scratch buffer per
stream on hosts that cannot map. Where the hint cannot be honoured
(a URL scheme, a huge image on a 32-bit host) the read path is what
it was.
A short step inside the span fails the call, as a short read did.
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).
update_cand() derives a track's span from last_index - cand_index on
signed int64_t values, assuming the sheet lists indices in ascending
order. A malformed or truncated sheet can violate that: most simply,
a sheet missing its final newline makes the tokenizer discard the
trailing INDEX token, so the last track's index is never recorded and
last_index stays behind cand_index. The signed subtraction then goes
negative and, stored into the uint64_t largest and handed on as a
size_t size, becomes a near-SIZE_MAX value.
Downstream that value reaches the serial-probe staging malloc in
intfstream_file_get_serial_fd(). The span is clamped to
SERIAL_PROBE_SPAN only inside the bounded branch (offset != 0 ||
size < file_size); a whole-file candidate that skips the clamp
requests the full underflowed size. malloc() returns NULL and the
read is checked, so there is no overflow, but a crafted cue in a
scanned directory can still provoke a multi-exabyte allocation
request - needless work driven entirely by a garbage length.
Guard the subtraction: a candidate whose last_index is below its
cand_index has no valid span and is skipped, exactly as a zero-length
track would be. Well-formed sheets are unaffected.
Resolving a cue or GDI sheet's data track used to open the track
binary once per question asked of it: the parse opened it to learn
its size and closed it (intfstream_get_file_size), the CD-i
AUDIO-track check opened it again for twelve magic bytes, and the
serial or CRC probe then opened it a third time. On the library scan
path that is two to three opens per referenced binary per sheet, and
the serial-to-CRC fallback repeats the whole sequence.
Keep the handle instead of re-opening the file:
- cue_track_stream_open() replaces the open-for-size-and-close
helper: one open reports the size and stays open.
- cue_find_track_internal() / gdi_find_track_internal() carry the
current file's stream through the parse and, whenever the candidate
data track changes, move that stream into the candidate slot
(cue_cand_adopt_stream). On success the winning track's open
stream and its size are handed to the caller; non-winning streams
are closed as they are displaced. The existing public
cue_find_track()/gdi_find_track() signatures remain as wrappers
that decline the stream.
- The CD-i magic probe reads through the stream the FILE line just
opened instead of opening the track separately. Later consumers
seek before reading, so the position disturbance is harmless.
- intfstream_file_get_serial() / intfstream_file_get_crc_and_size()
are split into _fd cores that run on a caller-owned stream and
accept a pre-measured file size (skipping the seek-END round trip
the parse already paid for), with the by-path functions kept as
thin open-delegate-close wrappers for their existing callers in
task_database.c.
- task_database_{cue,gdi}_get_serial / _get_crc_and_size consume the
retained stream; if the parse could not open the winning track (so
no stream was retained) they fall back to the by-path probe, which
fails the same way it always has.
A cue with one data track now costs exactly one open of the binary
for the size + serial (or size + CRC) sequence, and the ~600 KiB
serial staging window plus the 256 KiB CRC fold both run over the
handle the parse already held. Serial and CRC results are unchanged;
only how the bytes are reached changed.
Every token in a cue or GDI sheet was assembled one character at a
time with intfstream_read(fd, c, 1): a full VFS round trip per byte
of every sheet touched by a library scan. The sheets are KB-scale
text, so the scan-side cost of parsing them was almost entirely
per-call overhead, multiplied across a disc-heavy collection.
Feed the tokenizer from a small refill window instead. The window
is 1 KiB on the caller's stack: a typical single-bin cue is consumed
in one bulk read and a large multi-track sheet in a handful, while
the parse itself allocates nothing and holds no more than the window
no matter how large the sheet is - deliberately not a whole-file
slurp. The token state machine is carried over unchanged, including
its historical quirks (leading whitespace skipped even inside quotes;
a final token with no trailing newline is discarded at EOF), so parse
results are byte-identical.
cue_next_file() and gdi_next_file() operate on a caller-owned stream,
are re-entered with the same handle, and gdi_next_file() keys its
header skip off intfstream_tell(). For those, cue_tok_detach()
rewinds whatever the window read ahead before returning, so the
caller-visible stream position is exactly what byte-at-a-time
tokenizing produced. cue_find_track() and gdi_find_track() own their
stream for the whole parse and need no repositioning.
The tokenizer's stored-length cap carries over the previous commit's
bound: at most len - 1 characters plus the terminating NUL.
task_database_cue_get_token() stores each character at *c and only
then checks the length cap:
_len++;
c++;
if (_len == (int64_t)len)
{
*c = '\0';
return _len;
}
When a token reaches len characters, c has advanced to s + len and
the terminating NUL is written one byte past the caller's buffer.
Every caller passes a 255-byte stack array (tmp_token[MAX_TOKEN_LEN]),
so any cue/gdi sheet containing a token of 255 or more characters -
a long quoted FILE path is enough - writes a NUL over whatever the
compiler placed after tmp_token. Cue sheets are downloaded alongside
romsets, so this is attacker-reachable input on the library scan path.
Stop storing at len - 1 characters so the NUL lands on the last byte
of the buffer. The longest representable token shrinks from 255 to
254 characters; delimiter-terminated tokens are unaffected (their NUL
overwrites the delimiter slot, which was always in bounds). Also
reject len < 2 outright rather than looping on a buffer that cannot
hold a character and a terminator.
Found while preparing the buffered-tokenizer conversion of this
parser.
Serial/system detectors resolve within the first 600000 bytes of a
data track (DISC_DATA_SIZE_PS2 is the largest probe, 0x9320 the
deepest magic-number offset), so intfstream_file_get_serial() stages
at most SERIAL_PROBE_SPAN of a bounded span rather than the whole
track. On a 650 MB single-bin rip this takes the probe from 4523 ms
and a 622 MiB peak allocation (cold cache) to 1.5 ms and 2.9 MiB per
scanned disc; detection is byte-identical, verified on Saturn and
Sega CD fixtures covering spans longer than the window, tracks
shorter than it, and data tracks at non-zero offsets.
Per-byte loops folded into span operations on paths a seek or a
content scan walks constantly, the DEFLATE match hash settled at run
time instead of behind a compile flag nothing sets, dead machinery
next to both, and three passthrough wrappers gone.
rvorbis: vorbis_find_page() folded a candidate page into its
checksum a byte at a time, through a wrapper handing the shared
function one byte per call. len is the sum of the segment table, so
up to 65025 bytes, each costing a bounds check, a pointer bump and a
call - and the bytes were already contiguous, since rvorbis reads
from a memory span only. crc32_stream() folds a span instead, in all
three loops: the 27-byte header, the segment table, the payload. A
short stream is folded exactly as the byte loop folded it: what is
there, then that many zeroes with eof set. Checked over 1536 page
shapes - every segment count 0-255 against six truncation points -
comparing checksum, accumulated length, eof and the final stream
pointer: no difference. The scan feeding those loops had the same
shape, one get8() per scanned byte hunting for the capture pattern;
one memchr replaces it. Both show up on seeking:
64 seeks over an 8 second file, best of 30
before 12.14 ms
checksum fold 8.36 ms
+ memchr scan 7.86 ms
compute_window()'s square() helper existed to narrow a multiply to
float; folding it in keeps the narrowing through float temporaries -
written as one expression the multiply could have stayed wide, which
is a different window. Bitwise identical for every block size at
-O0, -O2, -O3 -ffp-contract=fast and -O2 -march=native (12878
samples, 0 differ). The CRCscan struct and page_crc_tests field are
leftovers of stb_vorbis's push-mode search rvorbis does not carry;
nothing set the field past its -1 initialisation; both gone. The Q31
twin of inverse_db_table was built at first use behind a non-atomic
flag - a data race when two decoders enter s16 mode concurrently,
found by this patch's ThreadSanitizer sweep and present unchanged on
master. The 256 entries are rvq_coef_q31() over the float table,
baked as const data generated by that same converter; decode output
is bit-identical and four concurrent decoders now run clean.
task_database_cue: intfstream_file_get_crc_and_size() took a
buffering branch whenever an offset or bounded length was passed,
and the cue track path always passes one - a CD data track,
routinely hundreds of MB. The branch allocated the whole track, read
it in, wrapped it in a memory stream, and had intfstream_get_crc()
copy it back out 256 KB at a time: two passes and a track-sized
allocation, which on a console is the difference between scanning
and not. Seek once and fold in place instead:
track of 400 MB at offset 4096
before 285.6 ms peak buffer 400 MB
after 76.4 ms peak buffer 256 KB
Identical CRC; a short read fails the call as the single full-span
read used to, verified over an offset/length matrix including the
one-past-end case, 24 shapes, 0 mismatches. Whole-file callers never
entered the branch and are untouched.
encoding_deflate: the match finder's hardware CRC32 hash was gated
on __SSE4_2__ at compile time, and nothing in the build passes
-msse4.2, so a stock x86-64 build compiled the shift-xor fallback on
CPUs that have the instruction. Which hash runs matters more than
how fast it hashes - the CRC spreads 3-byte keys more evenly, so the
chains rd_longest_match walks are shorter. End to end on 24 MB
corpora, five runs, best of each, level 6:
binary (executable) 39.0 MB/s 32.1 MB/s +21.6%
text 33.5 MB/s 34.5 MB/s -2.9%
records 92.6 MB/s 94.9 MB/s -2.3%
incompressible 48.2 MB/s 48.4 MB/s -0.3%
The one that wins is the one that matters: savestates are
machine-code-and-pointer shaped and rzip compresses at level 6. The
choice is made per stream in rdeflate_new() from cpu_features_get()
& RETRO_SIMD_SSE42, with the same toolchain predicate as the
carry-less multiply path in encoding_crc32.c; the flag lives in
struct rdeflate so there is nothing shared to race on. The
dispatched build measures within 1-3% of a -msse4.2 build and
produces byte-identical output to it on every corpus and level;
builds already compiled with -msse4.2 or __ARM_FEATURE_CRC32 keep
their direct path unchanged. The symbol-lookup tables next to the
hash were built at first use behind a non-atomic flag - the pattern
removed from encoding_crc32.c by 19278, and a real ThreadSanitizer
report when two streams are constructed concurrently. They are 771
bytes derived mechanically from rd_len_base and rd_dist_base, so
they are baked as const data generated by the same builder loops,
byte-identical output to the runtime-built tables verified against a
build of the previous revision. On the inflate side,
rinf_window_commit() gains two explicit uint32_t casts on the ring
advance and wrap-around reset - n is clamped to 32768 and first <= n,
so both fit; this silences clang's -Wshorten-64-to-32 with no
behavioural change.
file_archive: all three backends carried an identical passthrough
for the stream_crc_calculate slot whose type is encoding_crc32's
exact signature; the function goes in the vtables and the wrappers
go away. Nothing in the tree reads the slot - extraction folds its
checksums through encoding_crc32 directly - but the struct is public
libretro-common API that vendored copies read through, so the slot
stays, pointing at the real function.
An 8 second Ogg decodes to the same 352800 frames with the same hash
over decode plus 32 seeks throughout; ASan, UBSan and LeakSanitizer
clean including 401 truncations; four concurrent compressors clean
under ThreadSanitizer; every deflate output round-trips through
rinflate; the archive suite (14 checks), scanner suite (10 checks),
rzip sample and audio mixer sample pass; C90 clean.
Audit and harden the content scanner database stack
An audit of the content scanner and everything it calls -
tasks/task_database.c, tasks/task_database_cue.c, database_info.c,
manual_content_scan.c and the six sources under libretro-db - with
fixes for what it turned up and tests that demonstrate them.
.rdb files are downloaded from the buildbot, so the reader has to
survive whatever is in one, and most of the parser findings are of
that shape: end-of-file taken for a fabricated record and looped on
forever, an output value freed before it was ever initialised,
container nesting with no depth cap, a binary search that read
before its own count test and recursed without shrinking, identifier
slices handed to strlcpy which strlen()s its source, and an integer
accumulator with nothing bounding it. Two file-scope statics in the
query compiler were shared across concurrent compiles.
In the scanner: a stack-buffer-overflow write building the serial
query, a walk one element past the end of the info list, a
256-database ceiling that wrote past the per-database arrays,
strlcpy's return value used as a length against a destination half
the size of its source, an over-long content directory accepted
truncated and so pointed at a different directory, a completion
callback dropped entirely in builds without menu support, and an
uninitialised flag written into the playlist and read back on the
next scan to decide whether to overwrite it.
Two archive fixes came out of testing against a real library and are
included here: an LZMA property limit that rejected the lc=4 streams
7-Zip routinely writes - and since 7z holds its own header as an
LZMA stream, such an archive could not be opened at all - and a
lookup for an absent archive member that spun at full CPU instead of
returning.
The scanner asked each database the same question once per content
file, and each was a full cursor walk. A crc index built in one pass
answers those in under a microsecond against 10.59 ms before. Serial
lookups got the same treatment and the per-database size range now
comes out of the same walk rather than two further queries. Indexes
cost 8 bytes per record, are capped at a share of free memory, and
anything the index cannot serve falls back to the query path.
Equivalence was checked rather than assumed, because the scanner
takes the first match and a sixth to a quarter of the crcs shipped
are duplicates: 1,225 lookups and 126 duplicate groups return the
same records in the same order through both paths.
The four sample directories now carry 64 checks between them, every
case verified to fail without its fix, and sweep.sh runs the lot
under ASan, UBSan, LeakSanitizer and TSan.
Three of the defects fixed here were introduced by this work and
found afterwards, all of them wrong answers with no error reported:
index caches keyed by a database's position but not moved when a
match promoted it, a teardown reading a list's size after freeing
it, and a type check that excluded the binary encoding every shipped
database uses for its serial field, which stopped disc-based systems
matching entirely. Each has a regression test that fails without its
fix.
Not covered: the index memory share is a judgement
rather than a measurement against a constrained working set.
PS1-Classic and PSP content is distributed as EBOOT.PBP, which the
folder scanner previously could not match: .pbp had no file-type
mapping, so it fell through to a CRC lookup that has no corresponding
entries in the databases, leaving PBP collections unscannable.
The disc image embedded in DATA.PSAR is encrypted (PGD/AMCTRL) on
official titles, so the raw linear serial scan used for CUE/CHD/ISO
cannot reach the on-disc license string or game ID. The plaintext
PARAM.SFO at the head of the PBP does carry the serial, however, in
its DISC_ID key (PS1-Classics) or TITLE_ID key (PSP).
Add detect_pbp_game(), which parses the PBP header offset table,
seeks to PARAM.SFO, walks the SFO key/data tables, and extracts
DISC_ID (falling back to TITLE_ID). The product code is stored
without a separator (e.g. "SCUS94900"); the hyphen is re-inserted
after the 4-letter prefix to produce the "SCUS-94900" form the RDB
is keyed on. Multi-disc sets receive the usual disc suffix.
Wire .pbp -> FILE_TYPE_PBP in the scanner, routing to a new
task_database_pbp_get_serial() with a CRC fallback for the
unencrypted/homebrew tail. FILE_TYPE_PBP is appended at the end of
the msg_file_type enum to preserve the existing ordering relied on
by menu_cbs_init_bind_get_string_representation_compare_type().
No libretro-database changes are required; PS1 and PSP serials are
already present in the respective .rdb files.
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).
- added region dependent extension of Dreamcast game serials
- updated extra CRC check to be valid for Dreamcast as well
- changed logic of multiple-hit queries (very rare case if ever)
- reverted #7349 as now database contains CRCs for the main track
CD-i discs have a unique quirk: they store data in tracks labeled as
AUDIO in both CUE and CHD formats. The scanner normally skips AUDIO
tracks when looking for data, causing CD-i games to never match the
database.
Also simplify this part; the point here is to start the copy later, but
otherwise the buffer size is the same, and it's still a string, so needs
no special handling.