Commit Graph
203 Commits
Author SHA1 Message Date
Rob Loach 43b783a351 Database: Multiples with " / ", explore tags, fix duplicates (#20071) 2026-11-14 19:35:40 -05:00
LibretroAdmin d186c05fe1 scan: index a set fingerprint once when set_fpm1 equals set_fp1
A set with no clones has the same merged and split fingerprint.  Both
keys indexed the record twice, so the lookup returned it twice; with
its size equal to the archive's that read as two sized records and the
set fell through to a whole read.  The second key is now skipped when
it equals the first, which also keeps the index smaller.

The fingerprint's CRC list sits on the stack for sets of up to 64
members, so most archives no longer allocate for it.
2026-11-07 22:49:22 +01:00
davey 4d320c445f scan: match arcade sets by a fingerprint of their member CRCs
The arcade databases key each set on the CRC of the whole
TorrentZipped archive, so the same ROMs packed any other way - zstd
or 7z, other names or order, a merged parent - never match.

An optional set_fp1 key holds the CRC-32 of the set's ROM CRCs,
de-duplicated, sorted and taken as big-endian bytes; set_fpm1 holds
the same for a merged parent.  The archive's one directory walk gives
its fingerprint, leaving out folders, empty members and cue or gdi
sheets; a member that stores no CRC leaves it without one.  Each
database whose cores open the archive's type and that carries the
keys is looked up through an index built like the crc one.  A hit
writes the record's entry, as a match on the archive's own CRC does,
and no archive is read whole for it.

An archive of several members is looked up by its fingerprint before
its size is.  An archive of one member is looked up by it only after
its member's CRC missed, so a first-member hit held for a cartridge
database still wins.

Where several records of a database share the fingerprint, as a set's
split and non-merged packings can, the one whose size is the archive's
is taken; where several have that size the archive's own CRC decides,
and where none does, the one named like the archive, else the first.

The readers read a TorrentZip set whole with no grant only while no
database that opens zip carries fingerprints, so the fingerprint
indexes of those databases are built before the readers start.  One
that cannot be built counts as carrying none: that database can match
the set only by its own CRC.  A database without the keys costs one
walk per scan; older versions skip the keys.
2026-11-07 22:49:22 +01:00
LibretroAdmin 1acc68146f Scanner: pick an Xbox release by the regions its executable names
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.
2026-11-07 13:10:24 +01:00
Davey Hughesandlibretroadmin 770391e8d5 scan: read an archive whole only when a database may hold its size (#19944)
* scan: read an archive's directory once for all its passes

The scan fetched an archive's first member's CRC, size and extension
through a helper that stops at the first entry and reports how many
the header counts, and its readers did the same.  One walk now reads
the whole directory, in the readers as in the scan: every member's
stored CRC, size and name, kept for each of the archive's passes.
Its transfer state is on the heap, out of the readers' frames.  The
walk replaces the helper in the archive passes; the helper stays for
its other users.

The walk decodes the first member for a CRC where the archive stores
none, a zstd stream or a RAR 5 member hashed with BLAKE2, so it is
looked up as before.  Later members are not decoded and keep a CRC of
0.  A .bz2 is decoded to be listed at all.

Folders are not members: an archive of a folder and one file has one
member, that file, and is looked up by its CRC first.

* zip: report a TorrentZip end comment

A zip whose end-of-central-directory comment is TORRENTZIPPED- and
eight hex digits was written by TorrentZip, as arcade sets are.  The
zip reader already reads that record to find the directory, so it now
says so in the transfer state, for a caller that wants the hint.  The
CRC in the comment is not checked: nothing depends on it.

* database_info, libretro-db: archive record sizes beside the crc index

The crc index build walks each database once, off the main thread.
In the same walk it now also collects the size of every record whose
rom_name ends in an archive extension (zip, 7z, apk, rar, zst), kept
in one sorted array keyed by size and type, so a caller can ask
whether a database may hold an archive of a given type and size.  A
record of that type with no size, or an index built without the
sizes, answers yes.  The sizes count against the index budget.

The stepped database scan reports one string field for this:
libretrodb_scan_begin() and its callback gain a name field.  A
record's rom_name can also be extracted on request.

* scan: look every archive member up from the directory

An archive whose first member missed was read whole and, when that
missed too, expanded: each member went through the databases again,
by the stored CRC the directory already held.  An archive of several
members was read whole before any lookup, even where no database
could hold it, so disc zips and console sets were read whole again.

One member: its stored CRC is looked up first, as before.  A hit in a
database claimed only for the member's type is held, and every
member's CRC is looked up next.  On a miss the archive is read whole
only when a database whose cores open its type may hold it by its
exact size; its own CRC is then looked up there, and where that is
not asked or misses, every member's.

Several members: the same size question comes first.  Each database
whose cores open the type is then asked for the first member's CRC,
and for the archive's own CRC only when the size let it be read
whole, so an arcade record still wins and no database claimed only
for a member's type is walked before it.  Where neither matches,
every member's stored CRC is looked up.

A database may hold the archive when it has a record whose rom_name
is of the archive's type and size, one of that type with no size, or
no sizes at all.  Every member is looked up with the gates and size
checks the expansion uses.  A hit names the archive itself only when
it is the one record hit, that record is named for this archive and
its database's cores open the type; other hits are written as the
expansion wrote them, archive#member.  The expansion stays for scans
that keep unmatched files, for archives whose directory cannot be
read, and where nothing hit and a member stores no CRC, which only
the expansion unpacks for one.

Readers read an archive whole ahead only after a whole match, twice
as many after each such match up to the cap; any other verdict takes
the rest back.  A TorrentZip set of several members is still read
whole by a reader with no grant while some database opens zip.  An
archive over the readers' cutoff is handed back before a grant is
spent on it.

This narrows "several members are read whole first" to "read whole
when a database may hold it by its size".  A record whose crc is an
archive's own CRC but whose rom_name is not of the archive's type, or
whose size is not the file's, is no longer matched; each of FBNeo's
596 sets carries its zip's size.  A zip of a folder and one ROM takes
the one-member order.

* database_scan_test: rar archives through every pass

A RAR 4 archive of stored entries, written by hand as the zips are,
takes the passes zip and 7z take: a first member's hit where a core
opens rar names the archive, a later member's elsewhere is held as
archive#member, and the archive is read whole only while a database
whose cores open rar holds a rar record of its size.

* database_scan_test: define the fixture byte writers once

* archive_file: clear the TorrentZip flag for every archive

The flag was cleared only by the zip reader, so a transfer reused for
a 7z, a rar or an archive with no backend kept what the last zip said.
It is now cleared before any backend opens the archive.

* scan: readers read TorrentZip sets whole while the scan asks for that

Readers read every TorrentZip set of several members whole while some
database opens zip, but where no database may hold a set by its size
the scan drops that CRC, so a folder of sets no database holds was
read whole for nothing.  Each TorrentZip set the scan rules on now
says whether its own CRC was asked, and the readers read the next ones
whole only while it was.

---------

Co-authored-by: libretroadmin <[email protected]>
2026-10-30 04:08:09 +01:00
Davey HughesandLibretroAdmin ad2e9e05d8 scan: parallel readers, 3DS product codes, CRCs and index builds over steps (#19920)
* 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]>
2026-10-26 13:28:42 +01:00
LibretroAdmin cf1caee167 database_info: read index hits through one stream per database
Every hit answered from the crc or serial index opened the database
twice: libretrodb_open() to read the header, then libretrodb_read_at()
opened a second, buffered stream with a 64 KB window to fetch the one
record at the known offset, and both were closed again.  On the
Master System set that was 1214 opens and 36 MB of reads against a
300 KB database for 607 matches.

Keep one buffered stream (16 KB window - the records read back are a
few hundred bytes) on the index, opened on the first hit and closed
with the index.  Opening lazily means only databases that actually
match content hold a file handle; a scan can index every claimed
database and console fd tables are small.  The lookups now take a
non-const index for that reason.

Measured on the Master System set against all 147 rdbs: opens of the
SMS database 1216 -> 3, read() calls 10559 -> 7687, playlist output
byte-identical.  The wall time was already dominated elsewhere after
fbe3d2b246, so this is fewer syscalls rather than a visible speedup.
database_index_test (14 checks), database_scan_test (10) and
scan_begin_budget_test pass; ASan+UBSan+LSan clean.
2026-09-10 22:54:21 +02:00
LibretroAdminandLibretroAdmin ac05d2f6cd Make the manual content scan non-blocking: budgeted BEGIN/END states, resumable dir walk, I/O-free DAT parser (#19407)
* rxml: add rxml_load_document_owned

A public owned-buffer entry point next to the copying string one:
the caller hands over a NUL-terminated heap buffer and the document
keeps it for its lifetime (the tree points into it), freeing it in
rxml_free_document - or immediately on a failed parse.  This is
exactly the contract rxml_load_document's tail already had with its
own file read; exposing it lets a caller that read the document
bytes itself (e.g. a task handler filling a buffer under a time
budget across gathers) parse without doubling peak memory the way
rxml_load_document_string's mandatory copy does.  DAT files reach
hundreds of megabytes, so the copy is not a rounding error there.

First consumer is logiqx_dat, which is losing its file I/O in a
following commit.

Verified: strict C89 syntax pass (-std=c89 -ansi -pedantic
-Werror=declaration-after-statement); full Linux build links; the
rxml sample parses; series tip swept under ASan+UBSan+LSan and TSan
separately via samples/tasks/database/scan_begin_budget_test
(threaded lane and a 14-point cancellation sweep included), clean.

* lists/dir_list: add a resumable directory iterator

dir_list_new() is a blocking recursive walk: whoever calls it pays
for the whole tree in that call, which is why the manual content
scanner freezes the frame that starts a scan of a large library
when Threaded Tasks is off.  dir_list_iter_new()/_step()/_free()
is the same walk with the recursion made explicit - one frame per
open directory on a growable stack - so it can stop between any
two entries and resume on the next gather under a caller-supplied
budget callback, with a floor of one entry per step so a spent
budget still makes progress.  Entries land in the caller's list as
they are read: it is the only walk, nothing is enumerated twice.

The enumeration is a transliteration of dir_list_read_ctx(), and
two behaviours of the recursion that read like accidents are
contract and preserved deliberately: the recursive call's return
value is ignored, so an unreadable subdirectory is skipped silently
while its owed post-order append still happens; and a directory
itself is appended (under include_dirs) after its contents, because
the append sits after the recursive call.  The platform special
cases (System Volume Information, the IOS/OSX .framework-as-file
rule) are carried over verbatim.  Equivalence with dir_list_new()
on the same tree - same entries, same order, pre-sort - is pinned
by samples/tasks/database/scan_begin_budget_test, whose playlist
parity lane fails on any drift.

Verified: strict C89 syntax pass; full Linux build links; series
tip swept under ASan+UBSan+LSan and TSan separately (iterator
lifecycle covered mid-walk by the harness's cancellation sweep,
which frees iterators at every phase), clean.

* tasks: extract the shared I/O window into task_nbio_slice.c

The per-frame window that bounds file-transfer work per gather -
at most 4 ms of budgeted work per 16.6 ms of wall time, shared by
every participating task rather than handed to each one, with a
floor of one work item per open so a spent window still makes
progress - moves from file-local statics in task_file_transfer.c
into a translation unit of its own, and its type plus the three
entry points (task_nbio_slice_open/close/within_budget) are
exported through tasks_internal.h.

Two reasons.  The manual content scanner's BEGIN and END states
are about to become budgeted, and per the window's own design
rationale they must share this window, not invent a parallel
per-task budget that multiplies with the task count.  And a TU
whose only dependencies are the clock and the task queue lets test
harnesses link the real window instead of a reimplementation -
samples/tasks/file_transfer already compiles the shipping transfer
TU and now links this one with it; the scanner oracle does the
same.

Behaviour is unchanged: same constants, same threaded-queue
opt-out (each task gets a whole slice on the worker thread, where
there is no frame to protect and a shared static would be a race),
same floor-then-deadline accounting.  task_file_transfer_test
passes unmodified against the extracted TU, including its
budget-exhaustion and concurrency lanes.

Verified: strict C89 syntax pass on both TUs; full Linux build
links (Makefile.common + griffin wiring included); series tip
swept under ASan+UBSan+LSan and TSan separately, clean.

* task_database: fix empty-path strdup leak on scan handle teardown

content_database_path and playlist_directory are strdup'd
unconditionally when a manual content scan task is pushed, but the
teardown freed each only when it was non-empty - and strdup("") is
a real allocation.  Any scan pushed while the content database
path setting is empty (every scan in a bare configuration, and
every scan in the new oracle's fixture) leaked both, 16 bytes per
push under glibc.

Found by LeakSanitizer under the cancellation sweep of
samples/tasks/database/scan_begin_budget_test, which pushes 16
scans per run: 16 identical 16-byte leaks, all from
task_push_manual_content_scan.  The leak predates the scanner
rework this series performs; it lands first so the sweeps behind
the rest of the series run clean on their own merits.

Verified: strict C89 syntax pass; full Linux build links; series
tip swept under ASan+UBSan+LSan (leak detection on) and TSan
separately, clean - the sweep that found this reports zero leaks
with it applied.

* logiqx_dat: make the parser I/O-free

logiqx_dat.c performed two kinds of file I/O: logiqx_dat_path_is_valid()
stat'd the path for existence and size, and logiqx_dat_init(path)
read the whole document off disk (blocking, via rxml_load_document)
before parsing it.  The second is why the manual content scanner's
BEGIN state could stall a frame for the duration of a DAT read -
DAT files reach hundreds of megabytes - with no way for the task
layer to budget it: the read was buried inside the parser.

The module now performs no I/O of any kind.  Its API is:

  logiqx_dat_extension_is_valid()  - the extension whitelist (.dat /
      .xml, case-insensitive), a pure string check.  The whitelist is
      logiqx domain knowledge, so it stays here; existence and size
      checks belong to whoever owns the path.
  logiqx_dat_init_owned(buf, len)  - parses a document the caller
      read, taking ownership of the buffer (heap, len + 1 bytes,
      NUL-terminated) via rxml_load_document_owned: kept for the
      document's lifetime on success, freed here on failure, and no
      copy either way.

Call sites move accordingly.  manual_content_scan.c gets a static
content_scan_dat_path_is_valid() with exactly the old validation
semantics (extension, path_is_valid, path_get_size > 0, optional
size out-param for the free-memory check).  task_database.c
validates then reads the file itself and hands the buffer over -
still one blocking read in this commit, kept deliberately so this
change is purely a custody move; a following commit spreads that
read across gathers under the shared I/O window, which is the point
of the custody move.

Verified: strict C89 syntax pass on all four touched TUs; full
Linux build links (no other callers of the removed entry points
exist, griffin included); series tip swept under ASan+UBSan+LSan
and TSan separately - the DAT ownership transfer, including the
parse-failure path that frees the handed-over buffer, is exercised
by the scanner oracle's cancellation sweep - clean.

* logiqx_dat: index game names for logiqx_dat_search

logiqx_dat_search() walked every child of the root per call.  The
manual content scanner calls it once per content file to resolve
the playlist label, so a DAT-backed scan was O(files x games):
gprof put logiqx_dat_is_game_node at 29% of a 5000-file scan's
wall time, and the product is quadratic into MAME-sized lists.

The search now builds, lazily on first use, an index of every game
node keyed by its 'name' attribute - pointers into the document's
own storage, so the index owns no strings - sorted by (name,
document position) and answered by a leftmost-equal binary search.
Sorting by position second means duplicate names resolve to the
first occurrence, which is the answer the linear scan gave; nodes
without a non-empty name are exactly the nodes the linear matcher
could never match, so omitting them changes no answer either.  On
any allocation failure the index is marked failed and the linear
walk remains authoritative, and logiqx_dat_get_next()/reset()
iteration is untouched.

Cost: 24 bytes per game (~120 KB for the 5000-game fixture, a few
MB for a full MAME list), and the build-plus-qsort runs once inside
whichever gather issues the first search - milliseconds at fixture
scale; on a very large DAT under a non-threaded queue it is a
single one-off hitch far below the per-file scan it replaces, noted
in the scanner oracle alongside the parse-tick residual.

Measured on the oracle's fixture (5000 files, 5000-game DAT,
regular queue, release build): total scan 364.9 ms -> 183.6 ms,
which is 0.87x the blocking dir_list_new walk + whole-file DAT
parse reference - the incremental scanner is now faster end to end
than the code it replaced, not merely smoother.

Verified: strict C89 syntax pass; full Linux build links; oracle
passes all lanes including playlist parity; series tip swept under
ASan+UBSan+LSan and TSan separately, clean.

* database_info: add database_info_dir_init_from_list

database_info_dir_init() owns three things: the blocking recursive
dir_list_new() walk, the cue/gdi-prioritising sort, and the handle
construction.  The scanner's BEGIN split needs the walk performed
incrementally by the task under a time budget, but the sort and the
handle belong with the database layer - the comparator
(dir_entry_compare) is static here for a reason.

database_info_dir_init_from_list() is the second and third pieces
over a content list the caller already built: same sort, same
handle fields, borrows the list without taking ownership, NULL only
on allocation failure.  The directory variant remains for callers
that want the one-call blocking form.

Verified: strict C89 syntax pass; full Linux build links; series
tip swept under ASan+UBSan+LSan and TSan separately, clean.

* task_database: split MANUAL_SCAN_BEGIN into budgeted sub-states

MANUAL_SCAN_BEGIN performed the entire recursive directory walk
(dir_list_new via database_info_dir_init or the blocking content
list getter), the whole DAT file load and the playlist setup in a
single handler invocation.  Under the regular task queue that
invocation runs on the frame thread, so starting a scan of a large
library froze the frame for the duration - hundreds of
milliseconds at 5000 files, unbounded above - and the freeze is
exactly what Threaded Tasks off is supposed to avoid paying.

BEGIN is now a sequence: BEGIN (setup and branch selection) ->
BEGIN_DIR_LIST (the walk, via the resumable dir_list iterator) ->
BEGIN_DAT_LOAD (a chunked 256 KiB-per-read fill of a single
buffer, then one owned-buffer parse) -> BEGIN_PLAYLIST (playlist
open, parameter recording, and the final status selection, moved
verbatim).  Every sub-state runs under the shared per-frame I/O
window (task_nbio_slice_*, the same window the file-transfer spine
uses - deliberately shared rather than a parallel per-task budget,
which would multiply with the task count), each with a floor of
one work item so a spent window still progresses.  Completed
sub-states collapse into one invocation while the window lasts, so
a small library finishes the whole BEGIN sequence in a single tick
- the latency it had before the split.  The task's public identity
(handler, state) is unchanged, so duplicate-scan suppression via
task_queue_find() is unaffected.

The same total work is performed: the walk is incremental rather
than done twice, the DAT is read into one buffer whose ownership
passes to logiqx_dat_init_owned, and the DB branch's rdb-list
setup moves verbatim into the setup sub-state.  The non-DB
branch's content list creation moves to
manual_content_scan_content_list_iter_new(), which shares its
extension/compressed-inclusion policy with the blocking getter
through one helper so the two cannot drift; the caller owes the
completed list the same empty-reject and dir_list_sort the getter
applied.  Error semantics match the old code path for path: same
messages, same terminal exits, including dir walk allocation
failure mirroring dir_list_new() returning NULL.

Cancellation mid-walk or mid-read is now possible, so the handle
teardown releases the in-flight resources: the directory iterator
(which closes any open directory handles), the DAT stream, and the
read buffer when its ownership has not yet transferred.

Residual, documented in the oracle: the rxml parse of a completed
DAT buffer and the (following commit's) search-index build remain
one operation inside a single gather - budgeting the read bounds
the dominant I/O latency, but a pathological multi-hundred-MB DAT
still parses in one tick on a non-threaded queue.  rxml is not
resumable today; the sub-state structure leaves the seam for it.

Measured on the scanner oracle's fixture (5000 files across 50
dirs, 5000-game DAT, regular queue, release build): worst gather
attributable to the scanner's begin path drops from the full
walk+load+setup cost to inside the 4 ms window plus slack; first
task feedback 0.01 ms after push; playlist parity exact.

Verified: strict C89 syntax pass (HAVE_LIBRETRODB both ways); full
Linux build links; database_scan_test links and passes against
this commit standalone; series tip swept under ASan+UBSan+LSan and
TSan separately, including a 14-point cancellation sweep landing
in setup, mid-walk, mid-DAT-read, iteration and flush, clean.

* task_database: make the MANUAL_SCAN_END flush resumable

With BEGIN split, the largest single freeze left in a scan was the
gather that reached MANUAL_SCAN_END: it added every accumulated
scan result to the playlist - each add a linear
playlist_entry_exists() probe over the growing entry array, so the
batch is quadratic - then sorted and wrote the file, all in one
handler invocation.  Measured at 166 ms for the 5000-file fixture
on a release build; gprof attributes 48% of the whole scan's wall
time to playlist_path_matches_entry alone.

scan_results_batch_update_playlists() becomes
manual_scan_end_flush_tick(): the same loop with its locals -
position, the open playlist for the group being written, the group
key, the added counter, the path scratch buffer - promoted to the
scan handle, yielding on the shared per-frame window between any
two results with a floor of one result per gather.  The
MANUAL_SCAN_END case drives it until completion before running its
terminal message block.  Group-close writes for multi-playlist
scans and the final sort+write remain single blocking operations:
a playlist file write is atomic by design, and a partial write
would corrupt the playlist on a cancelled scan.

One behavioural fix rides along, forced by the loop conversion:
the old for loop's continue on a playlist that failed to open
advanced the index implicitly; the while loop must advance the
position itself, or the same unopenable playlist would be retried
every gather forever.

Cancellation mid-flush is now possible, so the handle teardown
closes the flush's open playlist - before manual_scan->playlist is
released, because in single-playlist mode flush_playlist borrows
that handle and the identity comparison preventing a double free
needs the pointer still live to say so - and frees the scratch.

Measured on the oracle's fixture (regular queue, release build):
worst gather over the whole scan 166 ms -> 5.6 ms, inside the 4 ms
window plus bounded slack; total scan time unchanged by this
commit (the quadratic probe cost still runs, spread out - its
removal is the playlist-side dedup index left as follow-up, with
the gprof profile attached to the oracle).

Verified: strict C89 syntax pass; full Linux build links; series
tip swept under ASan+UBSan+LSan and TSan separately, with
mid-flush cancellation covered by the sweep's tail points, clean.

* samples/tasks/database: add scan_begin_budget_test

Pacing + throughput oracle for the manual content scanner's
BEGIN/END split, compiled from the tree so it exercises the
shipping translation units.  It builds its own fixture - 5000
content files across 50 subdirectories plus a Logiqx DAT naming
each - so it needs nothing but a writable directory (honours
TMPDIR).

Three wall-clock assertions guard the plain build, because any one
alone can be satisfied by a scanner that is worse: pacing (no
task_queue_check() attributable to the scanner over the shared
4 ms window times a 4x slack multiplier - the pre-split tree fails
this at >160 ms), first feedback within two frames of the push,
and total scan time within 1.60x of the blocking walk + DAT parse
+ 40 us/entry floor it replaced, so a scanner that no longer
freezes but takes twice as long fails.  Playlist parity - every
fixture file present exactly once - is asserted in every mode, and
is also the equivalence pin for the dir_list iterator against
dir_list_new().  Measured at the series tip (release, regular
queue): total 183.6 ms = 0.87x reference, max gather 5.6 ms, first
feedback 0.01 ms.

A 'sanitize' mode runs every lane but skips the wall-clock
assertions a sanitized build cannot honestly meet; the sanitizers
are the assertion there.  Its lanes are where the split's
in-flight resources are made to die at every phase: a threaded
lane runs the same scan under the threaded queue (the TSan target
- the shared window deliberately opts threaded queues out of its
static state, and a mistake in that opt-out surfaces here), and a
14-point cancellation sweep lands a cancel in setup, mid-walk,
mid-DAT-read, content iteration and mid-flush, with LeakSanitizer
deciding whether teardown released everything.  The sweep already
paid for itself: it found the pre-existing empty-path strdup leak
fixed earlier in this series.

A 'bench' mode prints the metrics and skips assertions, for
regression-guard sampling.

The CI workflow gains the corresponding step (plain assertions,
then ASan+UBSan and TSan in sanitize mode) and its C89
syntax-check list gains the translation units this series touched.

Known residuals, deliberate and documented in the source: the rxml
parse of a completed DAT buffer and the logiqx index build each
run inside a single gather; playlist-side entry dedup remains
quadratic (48% of scan wall time per gprof) with the flush now
spreading rather than removing it - the fix is a path-hash dedup
index in playlist.c verifying candidates with the existing fuzzy
matcher, left as follow-up.

* samples/tasks/image_decode_slice: link task_nbio_slice

The window extraction moved task_nbio_slice_open/close/
within_budget out of task_file_transfer.c into their own
translation unit, and updated the two sample Makefiles built
during that work - file_transfer and database.  This oracle also
compiles the transfer spine (for the fill path its decode window
budgets), so it now fails to link on the three slice symbols,
which is exactly how CI reported it.

Add the slice TU to its source list.  No flag or include changes
are needed: the slice TU's includes are a subset of the transfer
TU's, and its external calls resolve against what the sample
already links - task_queue_is_threaded from task_queue.o, and
cpu_features_get_time_usec from the sample's own fake clock.  The
latter is not an accident to paper over but the point: the
oracle's budgets are deterministic because the clock is the test's
instrument, and the extracted window now runs against that same
instrument, as the in-tree window did before the extraction.

A repo-wide sweep confirms these were the only three sample
Makefiles compiling the transfer TU, so no further consumer is
left to fail one CI job at a time.

Verified: image_decode_slice_test builds and passes in both its CI
lanes against this Makefile - plain and ASan+UBSan (leak detection
and stack-use-after-return on).

* logiqx_dat: make the parser fully path-agnostic

logiqx_dat_extension_is_valid() performed no I/O - it was a pure
string check - but it was still the module reasoning about file
paths, and it forced logiqx_dat.c to keep including file/file_path.h
for path_get_extension().  With the file system checks already moved
to the callers, the .dat/.xml whitelist was the last piece of path
knowledge left in a parser whose contract is bytes in, structs out.

The whitelist moves into manual_content_scan.c, folded into the
validator introduced when the parser lost its I/O, which is now
exported as manual_content_scan_dat_path_is_valid(): extension,
existence, size > 0, optional size out-param.  Both menu-side call
sites use it, and task_database.c's budgeted DAT loader validates
through it instead of composing the three checks itself - so the
task can no longer drift from the acceptance rules the menu applied
when the path was chosen, which is a small correctness win on top
of the layering one.  logiqx_dat.c drops the function and the
file_path.h include; its remaining includes serve the parse alone.

Verified: strict C89 syntax pass (-std=c89 -ansi -pedantic
-Werror=declaration-after-statement) on all three touched TUs; full
Linux build links; scan_begin_budget_test passes all lanes
(playlist parity, threaded, 14-point cancellation sweep) and was
swept under ASan+UBSan+LSan and TSan separately, clean; repo-wide
grep confirms no caller of the removed entry point remains.

* samples/tasks/database: build the budget oracle from all; pace on CPU time

The new CI step follows the workflow's house pattern - `make clean
all`, then probe for the binary, then run it - but `all` in this
Makefile only built database_task, so the step's silent
`test -x scan_begin_budget_test` failed under set -eu right after
a successful database_task link, which is exactly the shape of the
CI log: link echo, no error text, exit 1.  It passed locally only
because a stale binary from an earlier explicit
`make scan_begin_budget_test` was still sitting in the directory.
The oracle joins the all target, so every build invocation in the
step - plain and both sanitizer configs - produces it, and plain
`make` in this directory builds everything runnable.

While correcting the step, the pacing lane switches its per-gather
measurement from wall time to thread CPU time
(CLOCK_THREAD_CPUTIME_ID, falling back to the wall clock where
unavailable).  The property under test is how much work the
scanner chooses to do in one gather; on a shared CI runner a cheap
gather can be preempted mid-flight and charged tens of wall-clock
milliseconds it never spent, failing the lane spuriously, while
the regression the lane exists for - the pre-split tree doing the
whole walk, DAT load and flush in one invocation - burns its
>160 ms as CPU and is caught by either clock.  Wall time remains
the clock for the total/throughput and first-feedback lanes, where
elapsed time is the property.

Verified with the step's literal command sequence in all three
build configurations: plain (`make clean all`, test -x, full
assertion run - PASS, max gather 8.2 ms CPU), ASan+UBSan+LSan
sanitize mode, and TSan sanitize mode, all clean.

* comments: describe the code as it is, not as it was

Review feedback on the scanner series: comments narrating how the
code previously behaved add nothing to reading it now - that story
lives in the commit messages.  Rewrite the affected comments in
present tense (the BEGIN-family and flush headers, the enum and
handle-field notes, the logiqx index rationale, the DAT-path
validator, the shared-window deadline note), keeping only what
states a live contract: the parity targets against the still-
present blocking entry points, the atomic-playlist-write floor,
the teardown ordering constraint, and the advance-before-continue
invariant in the flush loop.  The leak-fix guards lose their
comments entirely - a NULL-checked free needs no explanation - and
the database sample Makefile's comments go with them.

The regression oracle and the CI workflow keep their historical
descriptions: there, the previous behaviour is the documented
subject.

Comment-only change apart from the Makefile whitespace; verified
no object-code effect is possible, strict C89 pass on all touched
TUs, and the oracle's full plain run passes.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-08-14 23:52:31 +02:00
libretroadmin a2a71fe984 libretro-db, encodings: narrow size ranges, and one CRC-16
Two unrelated defects and a consolidation, all found reading the
scanner's database path outward.
2026-07-28 19:28:05 +02:00
LibretroAdmin 93ccb92418 Audit and harden the content scanner database stack (#19279)
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.
2026-07-28 16:47:56 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 78c52ab36e libretro-common/string: add strlcpy_append helper and apply to database_info_build_query_enum
Add strlcpy_append, a bound-checked replacement for the unsafe
idiom that's widespread in this codebase:

   _len += strlcpy(s + _len, src, len - _len);

That looks like a self-bounding chain but isn't.  strlcpy
returns strlen(source) regardless of how much was actually
written, so on truncation _len overshoots len and the next
(len - _len) underflows to a huge size_t, driving the next
strlcpy into an OOB-write or memcpy of attacker-influenced
size.  This is the same primitive that drove the shader-
wildcard fix (commit bac6894).

strlcpy_append takes (s, len, *pos, src), checks the
truncation condition correctly, and on overflow:
  - leaves s NUL-terminated at len - 1 (strlcpy's contract)
  - clamps *pos to len - 1 so subsequent calls in a chain
    short-circuit (also returning -1)
  - returns -1 to the caller

The clamp is what makes chained use safe with a single check
at the end of the chain.

Apply to database_info_build_query_enum (database_info.c).
That function builds DB query strings of the shape

   {'KEY':"PATH"}      (or numeric variants without the quotes,
                        or {'developer':glob('*PATH*')})

via 22 switch cases, each of which was a hand-unrolled chain
of s[++_len] = '...' character writes followed by a path
strlcpy and another short s[++_len] = '...' chain to close
the brace.  None of those writes was bounded against len.
A caller passing a buffer smaller than the prefix length
got OOB-writes from the prefix; a caller whose buffer was
just barely enough for prefix + path got the trailing
s[_len]='"';s[++_len]='}' writes off the end (up to 3 bytes
OOB).  All callers in tree pass query[4096] from the menu
displaylist, so practical buffers are large -- but the
pattern is wrong and the path component is attacker-
influenced when scanning content metadata.

Side fix in DATABASE_QUERY_ENTRY_BBFC_RATING: pre-rewrite
the case wrote s[++_len] = '"' after the path strlcpy
instead of s[_len] = '"', leaving the strlcpy's NUL
terminator embedded in the query.  BBFC rating searches
have been silently returning nothing since this code was
written.  Fixed while rewriting.

Adds libretro-common/samples/string/strlcpy_append/
strlcpy_append_test as a regression test, registered in
.github/workflows/Linux-libretro-common-samples.yml's
RUN_TARGETS allowlist (which builds with ASan + UBSan
default since the cdfs/chd commit).  Eight cases covering
the contract: basic append, chained append, exact-fit
boundary, wide-margin truncation, chain short-circuiting
after truncation, empty source, NULL/zero-length args, and
*pos already at or past len.

Test follows the existing libretro-common/samples pattern
(heap-allocated destinations sized to exactly the legal
capacity so any reintroduction of the unbounded chain is
flagged by ASan).  Verified to fire under ASan when the
helper is replaced with the unsafe naive idiom: heap-
buffer-overflow WRITE of size 2 at offset 26 of an 8-byte
allocation in test_chain_short_circuits_after_truncation.
With the safe helper all 8 cases pass clean.

Verified database_info_build_query_enum produces identical
output for all 21 enum values at len=4096 (the production
caller's buffer size); also verified that at len=8 the
function returns -1 with no OOB write, which is the
behaviour the unsafe naive replacement would have failed at.
2026-04-28 06:44:59 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 5ee27095b6 (database_info) filtered queries and scanning should both be faster
Here's what was added in this round — 3 new pieces across 3 files:
database_info.h — Added DB_EXTRACT_* field mask flags and database_info_list_new_filtered declaration. The flags let callers specify exactly which fields to extract: DB_EXTRACT_NAME, DB_EXTRACT_CRC, DB_EXTRACT_SERIAL, DB_EXTRACT_SIZE, DB_EXTRACT_MD5, DB_EXTRACT_SHA1. The DB_EXTRACT_SCAN_FIELDS preset combines the 4 fields the scanner actually uses.
database_info.c — Added database_cursor_iterate_filtered which contains a stripped-down version of the field extraction switch. When a field mask is active, it only enters the case branches for requested fields and falls through on everything else — no strdup, no string_split, no bin_to_hex_alloc for unrequested fields. database_info_list_new now delegates to database_info_list_new_filtered(path, query, 0) for backward compatibility. Callers that know what fields they need call _filtered directly.
task_database.c — Changed database_info_list_iterate_new to call database_info_list_new_filtered with DB_EXTRACT_SCAN_FIELDS. This is the scanner's entry point for CRC, serial, and min/max queries. The scanner only reads .crc32, .name, .serial, and .size from the results, so the other ~30 fields are now never extracted.
The filtered query test (Test 2) shows a 15% additional speedup on top of all previous optimizations. This comes entirely from eliminating ~30 unnecessary strdup + free pairs per matching record in the scanner path. For the min/max queries that do full table scans, the savings are largest: 50,000 records × 30 skipped fields = 1.5 million fewer heap allocations per scan.
2026-04-14 05:38:29 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 1294d47ea9 (database_info) Database Manager should be massively faster now
Geometric realloc — replaced realloc(ptr, (k+1) * sizeof(...)) with doubling growth from an initial capacity of 64 (for filtered queries) or 256 (for name-only). The original did 50,000 realloc calls for MAME, each potentially copying the entire array. Geometric growth does ~16 reallocs total, eliminating the O(n²) copy amplification. This alone accounts for most of the improvement on the filtered query path (Test 2: 7% speedup).
Name-only fast path — database_info_list_new_names_only() replaces the full database_cursor_iterate path when query is NULL (the Database Manager browse case). Instead of extracting all 15+ fields per record via strdup into a database_info_t, it does a standard DOM read and scans only for the "name" key, strdups just that one string, and skips everything else. For 50,000 records this eliminates ~700,000 unnecessary strdup + free pairs.
Combined result on the Database Manager browse path:

         Original     Modified     Change
Best     0.367s       0.153s       58% faster
Average  0.385s       0.189s       51% faster

For MAME.rdb (51,914 entries), this would cut the UI freeze from several seconds down to under a second on typical hardware — a directly user-visible improvement for the exact scenario in the screenshot.
2026-04-14 05:21:40 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 6603fe2369 Replace string_is_empty 2026-04-07 03:35:23 +02:00
Eric Warmenhoven f580b3954b fix serial db scan 2026-04-06 17:52:34 -04:00
zoltanvb 2fdf736d51 Merge of manual and autoscan
Scanning options are unified for a single operation, which can be
customized to cover previous autoscan, manual scan, DAT scan, and
a lot of combinations in-between.

More details in the pull request.
2026-04-06 19:11:06 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 80347ceb96 database_info: no more stdstring dependency 2026-04-02 22:50:32 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 227b712b2d Apparently some targets don't like this 2026-04-01 08:35:21 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre a30c9b31ee Fix 2026-04-01 08:32:01 +02:00
zoltanvb acd3fa1172 Change size to 64-bit (#18410)
Several rom sizes could exceed 32-bit. Database uses uint64_t, so let's align.
2025-11-16 20:59:18 +01:00
zoltanvb 8c10eaa250 Prevent uninitialized memory. (#18320) 2025-10-20 13:20:18 +02:00
libretroadmin 9b6ddfb727 Turn iteration variables from unsigned to size_t or int 2025-08-06 08:04:11 +02:00
libretroadmin 8181583298 Try to reserve 'error' keyword for goto labels, use 'err' for
variables and arguments instead
2025-08-05 21:02:49 +02:00
zoltanvb 85aa59dc4f Enable database filter for genre and region (#18122) 2025-07-28 10:48:06 +02:00
zoltanvb 4d8283a460 Minor improvements for db / playlist handling (#16060)
Do not load rom_name as nothing is using it (but it does occupy memory)
Add two more media index options for label sanitization
2023-12-30 11:45:36 -08:00
Joe Osborn 679083a08b Graceful fallback to readonly mode if RDB can't be opened readwrite (#15569)
* Graceful fallback to readonly mode if RDB can't be opened readwrite
* let RA open db readonly
2023-08-10 11:04:47 -07:00
libretroadmin 458fe7a761 * Remove more strlcat calls
* Safer manual char assignment in database_info.c
2023-06-20 17:43:33 +02:00
libretroadmin b04a926170 (libretro-db) Further cleanups 2023-02-17 17:49:36 +01:00
libretroadmin de717a50d3 Style nits 2023-01-22 16:12:27 +01:00
LibretroAdmin 28f55845b6 * database_info cleanups:
- database_cursor_close's return value was never used, and doesn't
necessitate a function either
- some other misc. cleanups
2022-10-06 19:43:44 +02:00
LibretroAdmin 94ed25be56 Cleanups (#14296)
- (database_info.c) Optimizations for database_info_build_query_enum() -
 it would call strlcat at the very least 3 times, normally more than that.
 Every strlcat call is at least one or more strlens. Reduce it all down
 to manual string concatenation and one strlcat
- (database_info_build_query_enum) - always NULL terminates string so no need for NULL termination done by callee
* (menu_displaylist) use smaller strings for basename paths, remove one unnecessary string
in menu_displaylist.c function
- (disk_index_file.c) Avoid another trivial string concatenation by doing
it manually after fill_pathname_join_special
- (fill_pathname_join_delim) since fill_pathname_join_delim() now has a return value, use it for 
string concatenation
- (platform_unix) - Use BUFSIZ as size for a buffer in system_property_get
- some other trivial strlcat usage replacements
2022-08-06 18:04:40 +02:00
TheRetroPirate 6f90b24f72 added more categories to the explore menu 2022-03-15 05:51:20 +01:00
twinaphex 460f5e745d Silence some MSVC 2019 code analysis warnings 2022-03-05 14:39:56 +01:00
jdgleaver b2a4620f3b (Database) Fix heap-buffer-overflow when fetching CRC values 2021-08-11 17:32:45 +01:00
twinaphex 9910dfbee2 Replace strcpy_literal usage of trivial string setting 2021-04-06 11:21:28 +02:00
twinaphex 1296fc4745 use strlcpy_literal for string literal copies 2020-09-19 23:28:01 +02:00
Bernhard Schelling 0ddb073784 First set of cleanups to archive handling
- Don't read the entire archive file into memory on systems without HAVE_MMAP
- Support ZIP files between 2GB ~ 4GB on 32bit architectures
- Remove zip exclusive members from `file_archive_transfer`
- Add `zip_context_t` for zip like the already existing `sevenzip_context_t`
- Unify cleanups of zip and 7z in `file_archive_file_backend::archive_parse_file_free`
- Handle some sizes and offsets as int64_t (preparation for future Zip64 support)
- Handle compression methods in `zlib_stream_decompress_data_to_file_init` not in `file_archive_perform_mode`
- Return progress of 7z iterating with `file_archive_parse_file_progress`
2020-07-12 00:51:35 +09:00
twinaphex ef51ef1fb1 database_info_list_new - md5 and sha1 need to be freed 2020-06-29 19:27:50 +02:00
twinaphex 6dcc7d5441 Use malloc where possible 2020-06-28 16:11:17 +02:00
twinaphex de36ff20fb Create string_ends_with_size 2020-06-25 14:38:06 +02:00
twinaphex 091b1c88c2 Optimize database_cursor_iterate 2020-06-08 15:27:08 +02:00
twinaphex e54e12876b Header cleanups 2020-01-25 17:51:07 +01:00
twinaphex 6dd46e6971 Fix database query regression 2019-09-26 13:37:58 +02:00
twinaphex b94b9e2adb Go back to plain strlcpy/strlcat - probably best to look at
opportunities to reduce these calls vs. replacing them with
unsafe macros
2019-09-23 00:19:01 +02:00
twinaphex 3b057d9605 Start using STRLCAT_CONST_INCR and STRLCPY_CONST 2019-09-20 23:33:17 +02:00
twinaphex 4c3e0d44b8 Revert "Start using string_is_equal_memcmp and"
This reverts commit 26d6aee1eb.
2019-04-29 04:04:33 +02:00
twinaphex 26d6aee1eb Start using string_is_equal_memcmp and
string_is_equal_memcmp_fast
2019-04-28 17:23:11 +02:00
Brad Parker c606e8893c null check 2019-02-28 16:56:41 -05:00
Brad Parker 4f0d61a2ac update copyright 2019-02-22 19:13:36 -05:00
orbea bfc366decc Squeeze extra blank lines with cat(1).
Example:

find . -type f -iname '*.c' | while read -r i; do
  cat -s "$i" > "$i.new"
  mv "$i.new" "$i"
done
2019-01-08 11:04:58 -08:00