Commit Graph
472 Commits
Author SHA1 Message Date
LibretroAdmin 31215d5838 scan: report a vanished folder on a database scan too
A folder of known kind is no longer stat'd when the scan is set up, so
the worker is where a missing folder is found.  A plain scan says so,
but a database scan ended with no message on screen, and a command line
scan blamed the configuration.  Give it the plain scan's message.

Refuse the other half of the same mismatch: a file that has become a
folder was walked as a folder while the scan kept treating it as a
file.

The task already holds the content kind in its config, so do not ask
for it again on the main thread.
2026-11-09 19:12:47 +01:00
Davey Hughes 0f72bd97d5 scan: reuse known path kinds for local content (#20029)
Reuse the caller's known content kind for every path. CLI scans and
playlist refreshes already read it on a worker; asking again while
building their configuration can stall the main thread.

Keep the stat fallback when no kind is available. Reject an expected
folder that is no longer a directory on the worker before playlist
overwrite or validation.
2026-11-09 19:16:12 +01:00
LibretroAdmin 8e367fbb41 scan: keep a refresh-all skip reason, and lend the down-share list
Refresh All decides on a playlist from its first load, so a skip from
that record printed "content folder not found" even when master knows
why an smb:// folder failed. The record now keeps the reason, and both
skips share one helper.

An empty folder now joins a group like a missing one: one line, and no
second load and folder open just to skip.

The chain runs one task at a time and changes its list of dead shares
only in that task's callback, so each load borrows the list instead of
copying it. Finding whether a playlist has a database compares names
in place rather than copying each one on the main thread.
2026-11-09 05:01:48 +01:00
davey d99a3e2edd scan: Refresh All waits for a dead SMB share once
A frozen or unreachable SMB server cost the client timeout for every
smb:// playlist in Refresh All, even when they all point at the same
server.

When a playlist's smb:// folder is not there in the loading pass, its
share root is checked. If the root answers, the folder is really
missing and the run goes on as before, with no more root checks. If
it fails too, the share is taken as down for the rest of the run:
later folders, --scan paths and refreshes on it fail with the same
message and no check. With a share set in the settings, the client
uses it for every URL, so every smb:// path is down. With none set,
each URL names its share, so only the failed shares are down, and a
root that answers later clears them, so a NAS waking from sleep
recovers in the same run.
2026-11-09 05:01:47 +01:00
davey 5e83dce622 scan: '??' names only files the scan leaves unmatched
A database scan printed "??" from the lookup, before it knew what
became of the file: a loose scan then added it, an expanded archive's
members still had to be checked, and an m3u's discs could still match.
The line is now printed where a scan counts a file unmatched, so the
"??" lines and the unmatched total agree for every kind of scan.

A .lutro, which matches by its extension, was counted unmatched
without a line by a refresh of another database and by a group scan
without a Lutro playlist; both now name it.
2026-11-09 05:01:47 +01:00
davey 0663a163c2 scan: Refresh All scans a shared folder once per group
Refresh All walked and checksummed a mixed folder once for every
playlist a Fully Automatic scan of it had filled. It now reads every
playlist's settings before it runs one, keeping only its name, folder
and settings, and loads each playlist again when it runs, so it still
holds one playlist at a time. The load turns the saved settings into
text, so grouping compares strings and stats no folder on the main
thread. Playlists named after an installed database, matched
strictly against it alone with no DAT file, saved with no other
database name and otherwise equal settings, overrides applied, share
one group scan. The group runs at its first playlist's place under
one line and task title naming the folder and the playlists, and the
summary still counts playlists. Any other playlist, and every
--scan-refresh, runs alone as before.
2026-11-09 05:01:47 +01:00
davey 8313950a30 scan: scan a folder once for a group of playlists
A Fully Automatic scan of a mixed folder fills one playlist per
database, yet refreshing those playlists walks and checksums the folder
once per playlist. A group scan does it once: it matches only the
databases of the playlists it is given and sends each match to its
database's playlist, filling one member at a time so each is sorted
once. Every member is treated as its own refresh would treat it:
cleared when overwriting, validated, given the scan settings whether or
not it gained an entry, and saved as "<name>.lpl". A result no member
takes counts as unmatched.

A group scan needs a strict database scan, so it exists only with
libretrodb. Its task title and --scan lines carry the label it is
given. While it runs, a scan of a member's playlist is refused, and
the reverse.

Nothing pushes a group scan yet; Refresh All will.
2026-11-09 05:01:47 +01:00
davey 5074821a24 scan: DAT and match-none scans print the --scan lines
A DAT scan and --scan-match=none run apart from the database lookup,
so --scan printed only their "++"/"==" lines and the totals. They now
print the start line, a numbered line per file and a "??" for each file
they count unmatched, an m3u included, as a database scan does.
2026-11-09 05:01:47 +01:00
LibretroAdmin 76fe96acb8 scan: do no path work for an entry the clean pass keeps
The clean pass copied, expanded and matched every entry path against
the content folder, and resolved that folder once, before it asked
whether the entry needed any of it. An entry that exists and passes the
extension filter, which is nearly all of them, now returns after the
existence check: no copy, and no realpath on a network folder unless
an entry calls for one.

The three scratch buffers become one allocation, and the refresh chain
expands the saved folder on the stack and only looks inside a
directory.
2026-11-09 04:55:06 +01:00
davey 65f0370650 scan: skip a refresh whose content folder is empty
A playlist whose saved folder is an empty mount point, its drive
unplugged, was refreshed and failed with "No valid content detected.",
which made --scan-refresh and --scan-refresh-all exit 1. The refresh
chain now skips it as it skips a folder that is gone, with a "skipped:
content folder empty" line; it counts as skipped, not failed, in
Refresh All Playlists' summary and in the exit status. A menu Refresh
Playlist on such a folder is unchanged: it fails and leaves the
playlist as it was.
2026-11-09 04:55:03 +01:00
davey 23af9fdedd scan: keep a missing entry whose folder is gone or empty
Validating a playlist dropped every entry whose file was missing, so a
refresh with a drive unplugged, or with a mount point left behind
empty, emptied the playlist of everything on it. A missing entry now
goes only when the folder it is judged by holds something: the content
folder for an entry inside it, else the folder holding the file or its
archive. The extension filter applies only inside the content folder;
entries outside it came from other scans.

Entries are saved with their symlinks resolved, so the content folder
is compared both as typed and resolved, ignoring case on Windows. The
test harness builds file_path.c with RARCH_INTERNAL, as RetroArch
does, so its symlink case can resolve; not on Windows, where that
turns the slashes its checks look for into backslashes.
2026-11-09 04:55:00 +01:00
LibretroAdmin 201082c1ae Scanner: log the scanned folder for every manual scan
The 'Scanning content: "<dir>"' log line (and its CLI printf)
only ran on database-matched scans, so a plain manual scan with no
database logged nothing. Move it below both branches so every scan
that starts logs the folder it is walking.
2026-11-07 23:01:54 +01: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 e9759423d6 scan: no set fingerprint while an archive hides a member
rar names no member it cannot unpack (solid, encrypted, an older
packer), so a fingerprint taken over the members it does name would
claim a set that may not be all there.  Such an archive now has none
and goes on to its other passes.

7z and rar also name no folder, which would look the same, so the
scan's directory walk asks them to name one as zip does, ending in
'/'.  Nothing else sets the flag.
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 0b7c12251d Scanner: Wii U discs, WUX images and Wii U archives
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.
2026-11-07 13:49:21 +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
LibretroAdmin d06c4b2ebd formats/zar: ZArchive reader; scan Xbox 360 games in .zar
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.
2026-11-07 12:23:29 +01:00
LibretroAdmin 37121e88e9 formats/xdvdfs: Xbox 360 titles; scan Xbox 360 games
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.
2026-11-07 06:23:32 +01:00
LibretroAdmin 5ca1dee585 formats/xdvdfs: Xbox disc file system; scan Xbox games
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.
2026-11-07 05:45:07 +01:00
LibretroAdmin cd1a16c44b formats/ciso: CISO reader; scan .ciso GameCube/Wii images
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.
2026-11-07 04:18:55 +01:00
LibretroAdmin e98e1da005 vfs smb, scan: read every smb:// URL from the configured server
The VFS reads the configured server whatever host a URL names, so a
scan or refresh no longer compares the host: a playlist saved under an
older server address refreshes after the SMB server setting changes,
and the check takes no name lookup. A share other than the configured
one is still refused.

vfs_test checks URLs of other hosts, unresolvable ones included, pass
on their share alone.
2026-11-06 05:15:15 +01:00
davey c4fb538a89 scan: don't wait on an SMB server on the main thread
From the menu, the main thread stat'd an smb:// content folder up to
three times before its scan task ran: for the playlist name, for
whether it is a file and for the scan's folder flag. Manual Scan, Scan
Directory, Scan File and a lone Refresh Playlist each did, and against
a server that does not answer each stat waits out a connect with the
menu frozen.

The manual scan settings now keep what the caller knows the content
folder to be. The menu's folder pick, Scan File and Scan Directory say
whether it is a folder or a file, a refresh says its saved folder is a
folder, and --scan and the chain's refreshes take it from the worker's
read of the path. For an smb:// path of known kind those three places
use the kind instead of a stat: the menu paths stat it none at all on
the main thread, and a --scan or refresh of a reachable share is not
stat'd again when its scan is pushed. The kind is kept with the
settings a scan chain saves and puts back. A local path, and an
smb:// one of unknown kind, stats as before.
2026-11-06 05:15:14 +01:00
davey 6ef3af70f8 scan: say why an smb:// folder failed; refuse another host or share
A scan or refresh of an smb:// folder that could not be read said
"not found" or "skipped: content folder not found", whatever the
cause, and logged nothing; in the menu, a scan scanned the folder path
as a single file. A URL naming another host or share than the SMB
settings was read from the configured server and share all the same.

The scan task, the --scan path task and the playlist load of a
refresh now check such a folder on the task worker before the scan
starts: no SMB server set, a URL host or share other than the
settings', or, when the folder cannot be read, the share's recorded
connect failure (name lookup, connect, login, share). A URL refused
for its host or share is never stat'd by them. The reason goes to the
menu notification, one log line and the --scan line or the refresh's
skip line. The item still fails, or the playlist is still skipped and
left untouched, as before. A folder the server reports missing keeps
the message it had.

The man page states the host and share rule.
2026-11-06 05:15:14 +01:00
Davey HughesandLibretroAdmin 08e5b72a88 Scan from the command line: exit status, Manual Scan options, playlist refresh (#19977)
* file_path: stop at the end of the path after '~'

fill_pathname_expand_special() skipped two characters after a leading
'~' or ':', so a bare "~" read past its NUL and "~x" lost the x. It
now skips the prefix and a slash after it, if there is one.

* scan: hand the callback user data and what the scan did

task_push_dbscan() and task_push_manual_content_scan() take user data
for their callback, and the callback's task_data is now a
task_dbscan_result_t: how many entries the scan added, how many its
playlists already held, and how many files matched nothing. A file is
counted by what became of it, so an archive that is expanded is not
counted as unmatched, and a loose scan's unmatched files count as
added. Callers pass NULL for now.

* scan: say in the result when a scan failed

A scan that ends before it runs (bad setup, no valid content, a DAT
that will not load) or ends with a task error now sets the result's
failed flag. A database folder that is missing or unset is treated as
an empty one, so it reports the same "no database" error instead of
finishing as if it had scanned.

* scan: count the files a scan could not read

A file whose scan fails (an unreadable file, a failed lookup) was in
no count. The result now carries an errors count for them. They do
not fail the scan.

* scan: print --scan errors on stderr and totals on stdout

A command-line scan now ends with a totals line on stdout, or with the
reason it failed on stderr. A file it could not read is listed on
stderr. The ++/==/?? marks are coloured only when their stream is a
terminal, so pipes and redirected output get plain text; on Windows
redirected output keeps its marks instead of losing them to
WriteConsole.

* scan: the manual scan finder skips a finished task

A finished scan stays in the task queue while its callback runs, and
the finder that refuses a second scan for the same playlist still
matched it, so a scan pushed from that callback was refused.

* retroarch: run every --scan, then exit with what the scans did

Each --scan is collected while the command line is parsed and run in
turn once it is done, so later options and further --scan flags are
no longer dropped. A path is expanded and made absolute first; one
that does not exist, or a scan that cannot start, is reported on
stderr and the next path still runs. --scan with --cloudsync or
--command is refused.

Without --menu the exit status is 1 if any scan failed, else 0 if any
added an entry, else 2, and a content path given with the scans is
ignored, with a line on stderr. With --menu each finished scan starts
the next, as a second scan is refused while one runs.

* manual_content_scan: clear the database name a refresh did not save

A playlist with no saved database name left the name buffer
uninitialised, and the refresh compared it against every installed
database, so whatever was on the stack could pick a database the
playlist never named.

* scan: Skip Database References names the scan's one playlist

The option was meant to put the playlist's name in each entry's
db_name, even for a database match (#18641), for users who build
their own thumbnail sets. When the scan picks the playlists, db_name
also picks the playlist an entry goes to, so with the option on every
match went to one playlist named after the content folder.

It now applies only when the scan writes one playlist, and gives
that playlist's name, a loose scan's unmatched entries included. With
the target on <Automatic>, or Fully Automatic with the option left on
from a Custom scan, matches go to their databases' playlists as with
it off; the entries of a custom playlist look their thumbnails up
under its name, not the folder's.

* scan: name the scanned folder in the start line

The "Scanning content" line, in the log and in --scan's output, has
named the database folder since the manual scan and the database scan
were merged (2fdf736d51); before, it named the path being scanned. It
names the content folder again.

* manual_content_scan: reset, scan overrides and their apply

The command line's scan options need each scan to start from the
defaults and to lay their values over them, or over a playlist's saved
settings. Add a reset, a record of those options and a function that
applies it through the existing setters: a core named by path, file
name or display name, a database, a playlist, the database check or a
DAT, extensions and the switches, stopping with a reason at the first
that does not resolve.

A core path is normalised before it is compared. A core's file name
matches in the case given first, then ignoring case, on every
platform; a display name matches exactly. Given another database, a
playlist named after its database keeps that name as a custom one, so
a refresh still writes the same playlist.

The core setter's copy step becomes its own function, so a core found
by path or file name can be set. Nothing calls the new functions yet.

* scan: run --scan items through one chain

The --scan paths ran through a loop in retroarch.c, and with --menu
through a second chain of their own. The scan options and playlist
refreshes to come need one runner for every item, from the command
line and from the menu.

task_push_dbscan_chain() runs a list of items one task at a time: a
prep task lists the databases, then each step is pushed from the last
task's callback on the main thread, so nothing waits and nothing
locks. An item that fails is reported and the run goes on; a
cancelled task ends it. retroarch.c builds the items in the first
argument pass and hands them to the chain; without --menu it waits
for the chain's end and exits as before.

Running out of memory prints "out of memory" on stderr: for an item's
path the item fails, and for the chain itself nothing runs, which
without --menu exits 1.

The chain also prints a scan's override errors, and the warnings for
an option that needs one playlist or does nothing for a single file,
which the scan options of the next commit can trigger.

* retroarch: Manual Scan options for --scan

--scan-playlist, --scan-database, --scan-match, --scan-dat, --scan-core,
--scan-exts and the five switches set the Manual Scan settings of the
--scan before them; a --scan without any stays Fully Automatic.

Values are checked in the first pass, so an option before any --scan,
an empty or bad value, or one too long for its setting ends the run
with its reason on stderr and status 1, before the config loads and
before anything is scanned. Cores, databases and DAT files are
resolved when their scan runs, and one that does not resolve fails
only that scan.

* scan: refresh playlists in the chain

A refresh item rescans one playlist with its saved scan settings, as
the menu's Refresh Playlist does, with the item's scan options laid
over them and written back by the scan. A refresh-all item does the
same for every playlist in the playlist folder that has saved
settings, in the order Manage Playlists lists them, histories and
favorites left out.

A refresh item names its playlist by name or by a path in the playlist
folder. A bare "name.lpl" is the playlist folder's file, and an
absolute path is normalised before it is checked against the folder.
The name is looked up in the folder's listing on every platform, the
exact name first, then ignoring case, since macOS and FAT/exFAT cards
ignore case; the refresh then takes the file's own name, so a
database's playlist stays one. Two or more playlists that match only
in other cases fail the item.

The playlist folder walk and each playlist load run in prep tasks: on
the worker with a threaded queue, under the shared I/O window without
one, each pushed from the previous step's callback. A playlist whose
saved content folder is gone is skipped rather than failed. A listing
that runs out of memory fails the refresh-all; a playlist folder that
is missing or cannot be read lists nothing, and the refresh-all ends
with "no playlists with saved scan settings". A refresh's start line
names its content folder; its totals and failure lines name the
playlist.

* retroarch: --scan-refresh and --scan-refresh-all

--scan-refresh=NAME|PATH rescans a playlist with its saved scan
settings, as the menu's Refresh Playlist does, and --scan-refresh-all
rescans every playlist that has them. Both are items of the same run
as --scan: the scan options after one are laid over the saved
settings and written back, and the exit status follows the same rule.

--scan-playlist after a refresh is refused, so a refresh always
updates its own playlist, and an empty --scan-refresh is refused as
the other empty values are. Like --scan, the refresh options cannot be
combined with --cloudsync or --command; the error names whichever of
the three comes first on the command line.

* menu: Refresh All Playlists

Manage Playlists gets Refresh All Playlists as its first entry when it
lists any playlist, so an empty list still says there are no entries.
It rescans every playlist that has saved scan settings, with those
settings, through the same chain as --scan-refresh-all, and ends with
one notification saying how many playlists were refreshed, skipped
(content folder gone) and failed.

While a content scan runs it is refused with a new message; a refused
scan had none. Other languages come through Crowdin.

While a scan chain runs (Refresh All, or a command-line scan with
--menu), Start Scan, a playlist's Refresh, Scan Directory and Scan
File are refused with the same message, as they would run with the
settings the chain last loaded. task_push_dbscan() returns false then
too, which covers the companion and the iOS caller.

* docs: --scan, refresh and the Manual Scan options in the man page

--help lists the options but not what a script needs: the order the
scans run in, the exit status and what the options set. The man page
now has them, next to --cloudsync, and CHANGES.md has the entry.

* scan chain: writes from workers reach the playlist cache by note

A playlist written by a task - the chain's prep parse, a scan, a
playlist-manager task, whatever thread it runs on - leaves a note on a
lock-free stack instead of reading the cached playlist; the main
thread applies the notes when it next decides whether the cache may
stand in, so no worker reads playlist_cached while the main thread
frees or installs it. Without threads or pointer atomics a write
applies at once.

The chain's prep tasks set their handlers by name, and
thread_read_audit.py fails on a handler set from a
retro_task_handler_t parameter, which would hide every handler passed
in. The chain puts the Manual Scan settings it found back when it
ends, and is no longer running when its done callback runs, so that
callback may start another. task_push_dbscan() says why it refuses,
so the menu and the companions show the same reason, and the
companions' status line takes it from companion_core. --scan and
--scan-refresh set the verbosity override, so a config with logging
off cannot detach the console the totals go to, and refuse a path too
long for the chain's buffers. The Refresh All notification passes the
length written, and fill_pathname_expand_special() stops at the end of
a buffer shorter than the home or application directory.

Lanes: playlist_parity_test writes the cached file from a worker,
once at the same size and then while the main thread reuses and frees
the cache; database_scan_test checks the refusal message, the restored
settings and a done callback that starts the next chain;
fill_pathname_test expands into a buffer shorter than the home
directory.

* playlist: header-only parse for the scan chain's prep

The prep task needs a playlist's saved scan settings and nothing else,
yet parsed every entry and, through autofix, could write the file back
from a worker. playlist_parse_begin_header() stops at "items", rebases
the scan record in memory when the base content directory moved, and
marks the playlist so playlist_write_file() refuses it.

Lane: playlist_parity_test header_only (entries skipped, scan dir
rebased, file bytes untouched, old format).

* scan chain: ask the file system nothing on the main thread

The chain's steps ran on the main thread between its tasks and stat'd
and realpath'd there: a --scan path's resolve and stat, a
--scan-refresh path's two realpaths, the content folder's stat, the
saved and override DATs' stat and size, an override core path's
realpath.  On a network share each of those can stall a frame.

- manual_content_scan_fs_read() reads them on any thread, touching
  nothing but its arguments; the _fs variants of the content-folder,
  playlist and override setters take its answers instead of asking.
  The plain setters pass NULL and behave as before, so the menu is
  unchanged.
- A --scan path gets its own prep task (dbscan_path_handler); a
  --scan-refresh resolves its path inside the load task, and the load
  reads the folder, the saved DAT and the overrides' paths once the
  header is parsed.  The worker gets copies of the item's strings.
- The prep's state is freed in one place.

Lane: database_scan_test "fs off main": six items that each stop
before their scan, on a threaded queue, with path_stat, path_is_valid,
path_is_directory, path_get_size and path_resolve_realpath wrapped:
no call on the main thread.

Not moved: the scan task's own push still stats the content folder
and the DAT (manual_content_scan_get_task_config), shared with the
menu.

* samples: the scan chain's lanes hold on Windows and without realpath

From a native Windows run of both tests:

- database_scan_test "fs off main" refreshed f_gone.lpl through
  "pl/../pl/", which only a realpath folds; the sample builds without
  RARCH_INTERNAL, where path_resolve_realpath() folds nothing, so the
  item was rightly not in the playlist folder.  It names the playlist
  by its plain path now, which the check still realpaths on the
  worker.
- "another case, a database's playlist" read the system name type
  after the chain ended, and the chain puts the Manual Scan settings
  back then.  The item callback records each scan's type instead.
- playlist_parity_test's header lane expected "/moved/snes"; autofix
  converts the suffix to the local form, "/moved\snes" on Windows.
- The worker lane's stress read required a core name of every read.
  Windows replaces the file with MoveFileExW, and an open that meets
  the replace fails: that read is an empty playlist, which has none.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-11-04 19:34:05 +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 9d38efa2d6 scan: let the parallel readers open smb:// files (#19939)
* vfs: close a private SMB connection when an open, stat or opendir fails

When every pool slot is held, smb_take() connects privately for the
caller. If the open, stat or opendir then fails, smb_heal() returns
NULL when the connection is alive (a missing path, the usual case) or
cannot be replaced, and the caller stored that NULL over its context
and gave back nothing, so the connection and its socket were never
freed.

Keep the caller's context when smb_heal() returns NULL, so smb_give()
closes it. A pooled slot is given back as before.

vfs_test holds both pool slots with open files and then stats, opens
and lists a missing path; LSan reported the three connections before.

* vfs: release an SMB stream's connection when close follows a failed mend

When a stream's connection cannot be mended (the server is gone and
the reconnect is refused), or its file cannot be opened again, the
mend clears the stream's handle. Close returned early on the missing
handle, so a private stream leaked its connection, a pooled stream
kept its slot busy for the pool's life (smb_shutdown then left the
pool unfreed), and the reopen record leaked either way.

Close now checks for the connection rather than the handle and closes
the handle only when there is one. After a failed mend a private
connection is freed without a goodbye, since the server may be gone.

smb_idle_test gains a mode in which the server is stopped for good
during the pause, and local_samba_test.sh runs it, so the sanitizer
lane's LSan reports these leaks.

* cloud sync: make and drop SMB contexts under the VFS's list lock

libsmb2 keeps every context on one process-wide list with no lock of
its own, so the SMB VFS makes and drops its contexts under a lock
(4e6885d5a3). The SMB cloud sync driver called smb2_init_context() and
smb2_destroy_context() directly. A sync that began or ended while the
VFS connected or disconnected on another thread, as during a scan,
could lose a list entry, after which a live connection reads as dead,
or break the list.

The VFS exports its two wrappers and cloud sync uses them. The
built-in client has no such list; there they call straight through.

cloud_sync_test runs cloud sync's connect and disconnect beside private
VFS connections; the libsmb2 TSan lane reported the race before.

* scan: readers take smb:// paths when an SMB client is built

The scan's parallel readers were kept off every "://" path. smb://
paths go through the SMB VFS, whose connection pool serves several
streams at once, and the commits before this one fix the connection
leaks and the libsmb2 list race that readers would otherwise hit. So
readers now take smb:// paths in builds with an SMB client, built-in
or libsmb2; other schemes stay with the scan.

database_scan_test adds smb://, nfs:// and ftp:// archives to a
threaded scan's list and counts the readers' reads of each. Its TSan
build gets a stub SMB backend, so CI runs both halves.

* vfs: keep an SMB pool per share, never freed under its users

Pools live in a static table, one per connection key. Each pool's state
and user count share one atomic word: a lookup or a held slot is a use,
only an idle pool is evicted, and a retired pool closes its connections
when its last user leaves. Readers on two shares each keep their pool's
connections, and no thread touches a freed pool.

A failed reconnect after a dead transport frees the connection without
the round trips of a logoff; a pooled slot reconnects on its next take.

vfs_threads_test runs threads alternating between two shares of one
directory with no share configured.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-10-29 18:17:24 +01:00
Davey HughesandLibretroAdmin 40a5f4e6ae scan: look archives up by their first member's CRC first (#19937)
* scan: look archives up by their first member's CRC first

A zip, 7z, apk, rar, zst or bz2 was hashed whole before its first
member's CRC was fetched.  Cartridge databases key on ROM CRCs, so a
one-ROM-per-zip set always matches by the member: the whole read, the
main cost of scanning zips on a slow share, was wasted.

The databases are now walked first for the member's CRC alone.  Where
it is stored (zip, 7z, RAR with CRC32) that costs one directory read;
a zst, bz2 or BLAKE2 RAR member is decoded for it, as before.  Only
when that misses is the archive read whole, or a reader's whole result
taken, and the databases walked again for its own CRC, which the
arcade databases key on.  The archive is expanded only after both
miss.  Each walk's size check uses its own size: the member's, then
the archive's.

By default the core gate looks in a database only when a core claims
the file's extension.  Stock cartridge cores do not list zip, so a
cartridge zip was read whole and matched only once expanded.  The
first walk now also takes the databases claimed for the first member's
extension.  A hit there is held while the walk finishes the databases
claimed for the archive's name: a match in one of those is written for
the archive; otherwise the archive is expanded without the whole
read.  With "Scan Inside Archives" off nothing expands, so the first
walk keeps to the archive's name.

The parallel readers likewise start an archive with its first member's
CRC, size and extension, and hand them to the scan.  They hash
archives whole only as far as the scan grants: a member-CRC miss
grants one whole read ahead, each further miss in a row twice the
last, up to 16 at a time, and a member-CRC match takes back what is
left.  A lone unknown cartridge then costs one wasted read, while an
arcade folder soon has the readers 16 ahead.  While the scan first
walks a database's index in a member pass mid streak, the readers may
keep 16 ahead, so the walk does not leave them idle.  A grant goes
first to the nearest archive ahead that has only its member CRC.
Without a reader's whole result the scan hashes an archive it needs
whole itself, in steps, like a file over the cutoff.

An archive with no CRC for its first entry, such as a zip or 7z with
a directory first, skipped every database, so its own CRC was never
compared.  It now goes straight to the whole walk, and readers always
hash it whole.  In first-match mode the walk's early exit leads to the
whole walk too, while that has not run.

The CRCs, sizes and walk are cleared at each file's start.  A file
that errored left them to the next, and an archive after it was
looked up by the stale CRC.  The serial is cleared with them: an
archive matched after a file that errored in its serial lookup was
written under that file's serial.

Every database's member CRC is now checked before any whole CRC;
each database used to check the whole CRC first.  That differs only
when a zip's first member matches a cartridge record and the whole
zip an arcade record.  The cartridge record now wins, written for the
zip itself where the core gate lets the zip's name into the cartridge
database, otherwise through the expansion.  With "Scan Inside
Archives" off nothing expands, so in that second case the arcade
record still wins.

* samples/tasks/database: write an rdb count over 127 as a uint

A record count from 128 up is written as a msgpack uint32.  The
read-ahead lanes size their sets from the reader window, 64 files per
reader, so they write 131 to 259 records; a fixint byte past 127
decodes as a map or a bool and the database is rejected on two- and
three-core hosts.

* scan: keep a refused crc index build refused

A database whose crc index build is refused is flagged, and neither
the size probe nor the CRC lookup starts another build for it.  The
index budget only shrinks, so a retry could only walk the database
again to the same refusal, once per content file.

The database scan test gains a cap on index builds and a lane that
scans plain files with every build refused: one query walk each.

* scan: look archives of several members up by either CRC

An archive whose header lists more than one entry, an arcade set as a
rule, is read whole first, and each database takes its own CRC or its
first member's.  A set whose first member is a cartridge ROM is
written for its arcade record rather than expanded into the cartridge
playlist, and an arcade folder walks no database claimed only for a
member's extension.  Readers read such an archive whole without a
grant.  The member pass stays for one-member archives, where a
cartridge zip needs no whole read.

file_archive_get_file_crc32_size_and_ext() reports the entry count
the backends already take from the archive's header.  A database
claimed only for the member's extension joins the member pass only
while it has or may get a crc index; unindexed, the lookup is a full
walk the expansion repeats.  A reader's member CRC survives a whole
read that fails or is over the cutoff, so the scan reads only the
archive itself.

Lanes: an arcade set with a cartridge ROM first, an arcade folder
beside a cartridge database, sets whose reader reads fail, and
cartridge zips against an unindexed database.

* archive: read a mapped zip's directory in place

When the archive is mapped, zip_parse_file_init() finds the end of
central directory record, reads the ZIP64 records and walks the
central directory where they lie; only the context is allocated.
Unmapped archives read them through the stream.  The scan's member
pass opens every zip for its directory, so this is its hot path.

archive_zip64_test counts reads through the stream and checks that,
mapped, a plain zip with a comment and a ZIP64 one give their first
member's CRC without any.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-10-28 23:36:20 +01:00
LibretroAdmin cf60e94e40 scan: RAR archives and .bz2 files matched through their members
The scanner treats .rar as an archive, and .bz2 is a compressed file
the way .zst is, so a .bz2 is opened even when no core lists it; ".7Z"
is an archive as ".7z" is.

database_scan_test scans a 7z, a RAR, a RAR 5 with BLAKE2, a .zst, a
.bz2 and a zip with a Zstandard member, each matched through its
member, on both queues.
2026-10-27 18:29:38 +01:00
LibretroAdmin 2ddc97ff80 archive_file: bzip2 zip members and .bz2 files
Zip members stored with method 12 are decoded with rbzip2, whole, from
the mapping, from what the stream lends or else read, as Zstandard
members are. A .bz2 file stands for the file named as it is without the
extension: a stream does not say how long it decodes to, so the member
is decoded when it is listed, its size and CRC then known, and kept for
the extraction that follows. "#" after ".bz2" names its member.

HAVE_RBZIP2, on unless configured off, builds both and the decoder;
RVZ's bzip2 groups take the decoder alone where it is off.
file_archive_whole() is the whole-file read the .zst and .bz2 backends
share.

archive_bz2_test lists, reads and extracts bzip2 zip members and a .bz2
file, and refuses members whose CRC is wrong.
2026-10-27 09:08:39 +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 04d8870275 apple: the PowerPC build links again, and builds without warnings
retro_atomic.h's C11, C++11 and GCC __atomic backends set
RETRO_ATOMIC_HAS_64 on every target, but where a target has no 8-byte
atomic instructions (32-bit PowerPC, MIPS32 - the compiler reports
8-byte atomics as not always lock-free) each 64-bit operation compiles
to a libatomic call, which Darwin does not have: cocoa_common.m's
vblank timestamp left the PowerPC link with __atomic_load_8 undefined.
There the 64-bit operations are now left out, as on 32-bit __sync
targets, and their callers take the fallback they already have.

rcheevos' millisecond clock divided by CLOCKS_PER_SEC / 1000, which is
zero below a 10.5 deployment target, where Darwin's CLOCKS_PER_SEC is
CLK_TCK (100); and clock() is CPU time in any case.  Darwin builds
below macOS 10.12 / iOS 10, which have no clock_gettime, count with
mach_absolute_time() instead.

GCC 14's other warnings on that build, none a change in behaviour:

- rmp3: the short-block scalefactor loop is bounded as i + 2 <
  n_short_sfb (the same iterations, n_short_sfb being a multiple of
  3) under a test that n_long_sfb + n_short_sfb fits iscf, which
  every block the side info can describe does.  Decoded output is
  bit-identical on MPEG-1 and MPEG-2 streams with short blocks.
- vp9: the d135 predictor says its block is at most 32 wide.
- The pointer frame's read_as index is tested against MAX_USERS as
  well as against the count it is clamped to.
- The scanner's serial query is copied together from pieces of known
  length rather than through a snprintf the compiler cannot bound.
- The companion spells 'fldr' as its value and reads the name
  column's font through an NSCell.
2026-10-07 09:54:48 +02:00
LibretroAdmin bd35ea5496 task_database: task_push_dbscan takes the path and the callback only
The scan reads its playlist and database directories and the
hidden-files setting from the settings, and treats the path the same
whether it names a directory or a file, so task_push_dbscan() takes
only the path and the callback. companion_core_request_scan() takes
only the core and the path, and companion_core_pref_show_hidden_files()
is gone with its last callers.
2026-10-02 09:46:53 +02:00
LibretroAdmin 902c7f9a57 task_database: pass over every refused database in one scanner step
The core-claim gate now advances past every database it refuses in a
single step, so a file costs a handler call per database it can match
plus a fixed few, rather than one per database in the directory. On
the regular task queue the handler runs once per check, which is once
a frame.

database_scan_test scans four unmatched files over one claimed and 48
unclaimed databases on the regular queue and bounds the checks the
scan takes by the file count.
2026-10-02 09:12:39 +02:00
LibretroAdmin 8acbe4ab8c core_info: resolve database claims once per scan
Which cores claim a database does not depend on the file being
scanned, so the scanner now asks core info once per database when it
sizes its per-database state: core_info_database_claim() returns the
merged extensions of the claiming cores and whether any of them
matches archive members. The per-file test is a single extension
lookup in that list, with no core info lock taken, and the claims
move with their database when a match promotes it to the front.

database_scan_test gains a second core claiming its own database with
its own extension, so claims differ per database: a claim left behind
by the promotion, or a claim that ignores the database, fails it.
2026-10-02 08:56:56 +02:00
LibretroAdmin 1ef03e7980 scanner: keep the M3U's own name when its discs have no real title
Since 8618e55115 the scanner collapses a multi-disc game's disc
entries into its M3U, labelling the M3U entry with the first disc's
label minus its disc indicator - and the playlist flush then
deliberately replaces the entry the M3U got under its own name.

That only helps when the disc label is a database or DAT title. When
the disc matched nothing (hacks, undubs, a plain manual scan), its
label is just its file name, so

  Game Name (Undub).m3u
  Game Name (USA) [Hack by Person v2] (Undub) (Disc 1).chd

came out as 'Game Name (USA) [Hack by Person v2] (Undub)' instead of
the 'Game Name (Undub)' that 1.22.2 gave, breaking thumbnail setups
and anything else keyed to the M3U's name.

When the first disc's label is its own file name, label the M3U entry
with the M3U's file name. A real title is still collapsed as before.

Fixes #19376.
2026-09-18 08:42:19 +02:00
LibretroAdmin 940c37ba03 comments: explain the code moving forward
CODING-GUIDELINES line 275: explain how the code works moving
forward, not how it worked historically - and the rule applies to
code comments. A sweep of this engagement's comments for
diff-narration - 'used to', 'old code', 'is gone', 'moved out of',
'has been removed' - rewritten as what each site must do and what
breaks otherwise, with the measurements and failure modes kept:
the invariant is the point, the archaeology is not. Touches
video_driver, retroarch, runloop, the save/database/updater/backup/
image tasks, the companion latch, the widgets producer, gl1's
swizzle staging and the audit allowlist. Lifecycle wording that
happens to read as history ('the driver itself is gone', 'no
longer valid') describes present teardown states and stands.
Comments only; the build, the fifty-entry audit zero and every
touched file's syntax check all hold.
2026-09-16 04:12:55 +02:00
LibretroAdmin d7d75f4000 windows: the audit crosses the mingw build, and finds its blind spot full
The first run of tools/thread_read_audit.py against a Windows
binary - a mingw cross build, which host objdump reads natively -
found 52 worker entries and 27 findings where the Linux build shows
42 and zero. Twenty-five shared one reader: on Windows RARCH_LOG
routes through the desktop companion, and
ui_companion_driver_log_active read desktop_menu_enable through
config_get_ptr on whatever thread logged - every worker that logs a
line was a worker-thread singleton read, invisible on Linux where
logging never touches the companion.

desktop_menu_enable is now latched into the companion state as an
atomic, stored on the main thread at init_first and toggle - both
already receive the live value from their callers' settings read -
and the log sink, the message push and the refresh notification
read the latch with relaxed loads. Staleness across a toggle costs
at most one log line. The manual scan's completion notify moves
from the handler to the task callback, at retrieval on the main
thread, alongside the read it carried. The WASAPI pump captures its
two MMCSS bools into the driver at init and takes them as
parameters. And the mmdevice watcher thread, which raised exactly
one flag through audio_state_get_ptr, is handed a pointer to that
flag at spawn instead - its previously unused thread argument.

Windows: 52 entries, 0 findings. Linux: 42 entries, 0 findings,
unchanged budgets, the 74-lane matrix, C89 on the shared files and
the database suite all pass. The 33-entry --list-unaudited blind
spot is now ten entries smaller in the one build that can see
them.
2026-09-15 18:14:58 +02:00
LibretroAdmin 1ecfd83536 tasks: every worker reads captured state, and the audit reads zero
The last eight findings, and with them the campaign: the audit that
opened at thirty-nine findings closes at none, with two allowlisted
pairs carrying their justification in the list and one reviewed
boundary. Every task handler that ran settings or override reads on
the threaded task queue's worker now reads a capture its push made
on the main thread.

The per-entry thumbnail task captures the five thumbnail settings
into its handle and resolves paths through a _cfg variant of
gfx_thumbnail_update_path that reads nothing live; the enable check
splits the same way, into a values-parameterized core the live
wrapper feeds. The manual scan's task config carries the CLI-scan
flag and the serial/CRC toggle from the moment the config is built.
The core updater list task captures its three paths at push - and
because the update-installed-cores handler pushes that task from
the worker, the push itself splits into a captured-only core and a
live wrapper, with the worker passing captures made at its own
push. The core updater and core backup handlers stop clearing and
setting menu flags from the worker - a read-modify-write racing
every writer on the main thread - and move that work into task
callbacks, which run at retrieval on the main thread. The disc dump
task captures the core assets directory. The load handler's single
frame-count poll is allowlisted with its justification: a benign
monotonic read, documented at the site, holding the load until the
core has rendered.

Audit: 42 entries, 0 findings. All five atomic backends and C89
hold on every touched file; the task suites, the 74-lane matrix,
and the hot-function budgets pass.
2026-09-15 17:13:07 +02:00
Davey HughesandLibretroAdmin 5e4b8889af task_database: fix memory errors in database scans (#19544)
* task_database: fix memory errors in database scans

DATABASE_SCAN_ITERATE_NEXT handed an exhausted index to
MANUAL_SCAN_ITERATE_CONTENT, which read one entry past the end of the
content list.  Since 914f0e26f1 stopped zeroing a grown list's spare
capacity that entry is stale, so a scan could crash on it.  Go straight
to the M3U or end state instead.

A folder with no scannable files read entry 0 of the empty list and
ended without reaching MANUAL_SCAN_END.  Reject it once the walk
finishes, as the non-database scan already does.

A cue or gdi sheet that names itself freed its own list entry while
pruning its tracks, and the scan then read that path for its serial.
Skip the sheet's own path.

The scan test covers each case under AddressSanitizer, and includes
file/file_path.h for path_mkdir, which GCC 14 rejects as implicit.

* ci: run database_scan_test in the samples/tasks lane

The scan test only builds under 'make check', which no workflow
invokes, so its coverage never runs. Give it its own ASan + UBSan step
next to scan_begin_budget_test: the full-content-list, empty-folder
and self-naming-sheet cases are bounds and lifetime properties a plain
build walks past, and LeakSanitizer takes the scan teardown with them.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-09-14 09:05:17 +02:00
LibretroAdmin 60cb421bc0 playlist: pack an entry's slot, runtime status and thumbnail flags
The three ride in one word: the slot index is a subsystem content
slot, the runtime status has three values, and the thumbnail flags
are five bits. struct playlist_entry goes from 120 bytes to 112, so
a large playlist sheds another eighty kilobytes on top of what the
timestamps returned.

The JSON reader gains one more name for the slot, since a packed
field has no address to hand it.
2026-09-12 11:07:32 +02:00
LibretroAdmin 5599a3176b playlist: pack an entry's runtime and last-played values
The nine values ride in three words instead of nine: hours get 20
bits, which is 119 years of play, and the rest are what a calendar
and a clock allow. struct playlist_entry goes from 152 bytes to 120,
and a playlist holds one per item, so a large one sheds hundreds of
kilobytes.

The JSON reader named these fields by taking their address, which a
packed field does not have, so it now names which one it is filling
and goes through the setters.
2026-09-12 10:59:36 +02:00
LibretroAdmin fbe3d2b246 task_database: ask the core-info gate before walking the database
task_database_iterate_crc_lookup() consulted the size gate before the
core-info gate.  The size gate is not free: the first time a database
is consulted, task_database_fill_db_min_max() walks the whole .rdb to
build its crc index and derive the size range.  The core-info gate is
an in-memory string comparison.  Doing them in that order meant every
database in the directory was read end to end once per scan, whether
or not any installed core claims it - 201 MB of .rdb reads to scan a
71 MB Master System set against the shipped 147-file database
directory, most of it the 47 MB J2ME database that can never match a
.zip of SMS ROMs.

Run the cheap gate first.  Databases no core claims are now skipped
without being opened.

Measured, --scan of the reporter's sets against all 147 rdbs, release
build, same machine:

              before    after
  SMS  (620)  6.76 s    0.19 s
  PCE  (412)  6.70 s    0.16 s
  Lynx  (95)  1.28 s    0.05 s

Playlist output is byte-identical to the pre-change build.  The gain
scales with how many databases the installed cores do not claim; a
setup with every core installed still walks each claimed database
once, as before.  ASan+UBSan+LSan clean.
2026-09-10 22:28:56 +02:00
LibretroAdmin 9fed6a244b Scanner: don't hang on a legacy .rdb, and never spin on a database that can't answer
Reported by Tatsuya79: the automatic directory scan stopped on the
first or second file of every set since early August, while the same
folder scanned to the end from the CLI on another machine and via
Manual Scan.  His log shows the loop:

  [Scanner] Type 6, ".../20 em 1 (Brazil).zip" against ".../FB Alpha - Arcade Games.rdb".
  [Scanner] Size: min -1 actual 262144 max -1.
  [Scanner] Scan verdict is 0 for .../20 em 1 (Brazil).zip

repeating every tick, forever.

Two defects combine:

1. libretrodb_open() rejects the 2015-2016 era .rdb files.  Those
   writers never rewrote the header, so metadata_offset is 0.  The
   old rmsgpack_dom_read_into() silently returned 0 when the value
   at offset 0 (the header's own bytes) was not a map, leaving
   md.count uninitialised but the open "successful"; the hardened
   reader correctly returns -1, so the open now fails.  Users whose
   database directory predates upstream renames still have such
   files (the online updater never deletes removed ones; "FB Alpha -
   Arcade Games.rdb" was renamed to FBNeo in 2019), and their
   records are perfectly readable - the cursor walks from the header
   to the RDT_NULL sentinel and never uses the count.  Accept a zero
   metadata_offset as "no metadata, no indexes" instead of failing.

2. task_database_iterate_crc_lookup() and the serial lookup ran the
   query at entry_index == 0 and then, with a NULL info, fell through
   to entry_index++ and SCAN_VERDICT_CONTINUE without ever touching
   list_index.  The next tick re-entered with entry_index != 0,
   skipped the query, and returned CONTINUE again.  Any database the
   scanner cannot open or query therefore hung the scan on the first
   content file that reached it - and only if a core claimed that
   database, which is why one machine hung and another did not.
   Treat an unanswerable database as one with no match and advance.
   The dispatcher's SCAN_VERDICT_ERROR case had the same shape
   (log, then re-run the identical step next tick); it now moves to
   the next content file.

Also guard the DEBUG-only size log in task_database_iterate(): it
read min_sizes[list_index] on the "against (null)" tick where
list_index == list->size, one past the arrays.

Verified on the reporter's three no-intro sets (Lynx 95, PCE 412,
SMS 620 members) with the 2016 FB Alpha rdb in the database list and
a core claiming it: reproduced the spin on master (3M ticks in 30 s
on the first file), and with this change the scan completes with the
same playlist output as the last-good build, from --scan and from
the menu, with the task queue threaded and unthreaded, under
ASan+UBSan+LSan.
2026-09-10 22:07:25 +02:00
LibretroAdmin b9be38fd55 strl: copy string literals without scanning them at runtime
strlcpy() begins with strlen() of its source. It lives in another
translation unit, so with no LTO that scan happens at runtime even when
the source is a literal whose length the compiler already measured, and
the call itself cannot be folded away either.

strlcpy_lit() passes the length over as sizeof(). When the destination
size is also a constant -- sizeof(buf), the usual case -- nothing is
left but the stores memcpy() compiles to:

  strlcpy      "core_options"  sizeof(buf)   7.01 ns
  strlcpy_lit  "core_options"  sizeof(buf)   0.42 ns
  strlcpy      41-char literal sizeof(buf)   7.74 ns
  strlcpy_lit  41-char literal sizeof(buf)   0.71 ns
  strlcpy      "core_options"  runtime len   7.11 ns
  strlcpy_lit  "core_options"  runtime len   0.70 ns

The destination bound is kept. When the literal does not fit it defers
to strlcpy(), so the copy truncates as before rather than overrunning;
a form that took only the literal would have turned every one of these
sites into an overflow waiting for a small buffer. The literal is
concatenated with "" so a non-literal source is a compile error rather
than a sizeof() that silently measures a pointer.

818 sites across 104 files were converted by parsing arguments rather
than by pattern-matching text: only a three-argument call whose second
argument is a bare string literal is rewritten, so a macro that happens
to expand to a literal is left alone. Line endings are preserved, so
the CRLF files carry only their own changed lines.

test/compat/test_strl.c compares the two against each other over every
destination size from 0 past the literal's length, for literals that
are empty, single-character, path-shaped, adjacently concatenated and
escape-bearing, checking the return, the terminator and the whole
buffer so an overrun past the terminator is caught. ASan+UBSan+LSan and
TSan both 4/4. The full menu_displaylist_build_list walk over every
displaylist type is byte-identical to before the change
(md5 a2a081bcac09cdc8d72d67efd14ac40e).
2026-08-30 02:10:20 +02:00
LibretroAdmin 82915a59f4 Drop dead locals and narrow guards on conditional helpers
The unused declarations in command_event's CMD_EVENT_CORE_DEINIT
block, in task_overlay_deferred_loading and in
ozone_compute_entries_position are gone, and hw_render_context_type
tests its driver names with string_is_equal so it carries no length
of its own. The 'settings' scope in
menu_displaylist_parse_core_manager_list, the index budget helper in
task_database.c and the cpu_proc_rank helpers in features_cpu.c each
sit under the conditions their only readers do, so a build without
those features declares nothing it cannot reach.

Verified on a Linux target configured with OpenGL, Vulkan and the
D3D backends off, with -Wall -Wextra and no -Wno-unused-variable,
both with HAVE_LIBRETRODB, HAVE_IMAGEVIEWER and HAVE_AUDIOMIXER on
and with all three off.
2026-08-29 22:07:48 +02:00
LibretroAdmin b4eb9622df rm3u: move file I/O out of the codec, and do less of it
Same contract as rjson and rxml before it: a format in
libretro-common/formats imposes no file I/O through its interface.
rm3u was the most entangled of the three - rm3u_init read the file
from inside the constructor, rm3u_save opened and wrote from inside
the codec, and rm3u_is_m3u answered "is this an m3u" with two
filesystem stats.  The codec now performs no I/O at all:
rm3u_init creates an empty handle, rm3u_parse consumes a
caller-supplied buffer, rm3u_dump renders the file contents as a
single caller-owned string, and rm3u_is_m3u is a pure extension
check.  formats/rm3u_stream.h is the opt-in filestream wiring,
reproducing the old load / save / is-m3u behaviour for the two
task callers; cheevos' include turned out to reference nothing and
is dropped.

Decoupling exposed where the I/O was wasteful, so the adapters do
less of it - which matters most through network VFS backends,
where every operation is a round trip:

- rm3u_is_m3u_filestream answers extension + exists + non-empty
  with ONE stat where the old check used two: a missing file has
  no size, so path_get_size() alone settles both questions.  The
  scan and playlist-cleanup tasks call this per candidate path.
- Saving now renders everything and writes ONCE where the old
  writer issued one or two filestream_printf calls - each an
  unbuffered write - per entry.
- The parse itself became a single bounded cursor pass: the old
  loader split the file into a string_list (one allocation and
  copy per line) before copying each line again into stack
  buffers.  The rewrite walks the buffer in place with
  length-bounded copies, drops the codec's string_list dependency,
  and preserves the old truncation and whitespace-trim semantics
  exactly.

A new oracle (libretro-common/samples/formats/m3u) pins the
rewrite: a parse lane covering every construct the old loader
understood (#LABEL:, #EXTINF:, path|label, plain paths, comments,
CRLF endings, surrounding whitespace, empty lines, dangling
labels) with relative-path resolution asserted; a dump lane
asserting the rendered bytes equal the old per-line writer's
output literally, for all four label types; round-trips; and an
adapter lane against real files (wrong extension rejects, missing
file loads empty, empty file is not an m3u, save/load is
lossless, bytes on disk equal rm3u_dump).  The codec and adapters
have no threads, so the sweep is ASan+UBSan+LSan; a TSan run
would exercise nothing.

Verified: rm3u.c and the adapter header pass the strict C89 gate
standalone; strict gates clean on both migrated task TUs; full
Linux build links with HAVE_QT=1; oracle passes plain and under
ASan+UBSan+LSan with zero reports.
2026-08-15 06:03:37 +02:00
LibretroAdmin da0852e867 m3u: rename m3u_file to rm3u
Aligns the M3U codec with the naming convention every other format
in libretro-common/formats follows (rjson, rxml, rbmp, rpng, ...):
the translation unit becomes formats/m3u/rm3u.c, the header
formats/rm3u.h, and the full API surface renames with it -
rm3u_t / rm3u_entry_t, enum rm3u_label_type with RM3U_LABEL_*,
RM3U_EXT, and rm3u_init / _free / _get_path / _get_size /
_get_entry / _add_entry / _clear / _save / _qsort / _is_m3u.  The
internal struct tag becomes rm3u, which also retires the comment
apologising for the old workaround tag.

Purely mechanical: no behavioural change anywhere.  The three
in-tree consumers (task_database, task_playlist_manager, and
cheevos' include - which uses nothing from the header) migrate,
along with Makefile.common, griffin, and the two Apple project
files that list the header.  Local variables in the task callers
tidy from m3u_file to m3u so the rename reads complete rather than
half-done.

Verified: rm3u.c passes the strict C89 gate standalone; strict
gates clean on both migrated task TUs; full Linux build links with
HAVE_QT=1 after invalidating the four stale dependency files that
still named the old header; zero references to any old identifier
remain in the tree.
2026-08-15 06:03:35 +02:00
LibretroAdminandLibretroAdmin 545ab4e9a2 Manual scan follow-ups: O(1) playlist dedup, incremental DAT parse (#19408)
* playlist: extract playlist_path_ids_match from the entry matcher

playlist_path_matches_entry() interleaves two concerns: lazily
building the entry's cached path ID, and comparing two path IDs
under the playlist's matching rules (exact real-path equality with
the case-insensitive OS variant, then the fuzzy bare-archive vs
inside-archive equivalence on the parent archive path).  The
comparison now stands alone as playlist_path_ids_match(), symmetric
in its arguments and operating on const IDs; the entry matcher
keeps the lazy cache initialisation and delegates.

No behaviour change; this is preparation for a dedup index that
must verify hash-bucket candidates with exactly these rules against
path IDs it owns itself rather than against live entries.

Verified: strict C89 syntax pass; full Linux build links; the
scanner oracle's plain run passes (its playlist parity lane goes
through this matcher for every fixture entry).

* playlist: split playlist_push; add playlist_push_unchecked

playlist_push() bundles three separable stages: the validation
preamble (core path check, path-ID construction, real core path
resolution, core name derivation), the linear scan for an existing
matching entry (update-in-place / bump-to-top semantics), and the
append tail (capacity policy, front insertion, field duplication).
The preamble and the append tail now live in playlist_push_prepare()
and playlist_push_new_entry(); playlist_push() keeps the scan and
delegates around it, with identical error messages, path-ID
ownership transfer and modification flagging.

The new public playlist_push_unchecked() composes the two helpers
without the scan, for callers that have already proven the content
path absent.  The manual scan's END flush probes every result with
playlist_entry_exists() before pushing, then pays playlist_push()'s
own linear scan a second time for the same answer; with a dedup
index answering the first probe, the second scan is pure O(n) waste
per added entry, and this entry point removes it.

One latent hazard fixed in passing: playlist_push() read
entry->core_name in an initialiser before its NULL check of @entry;
the shared preamble guards the dereference.

Verified: strict C89 syntax pass; full Linux build links; scanner
oracle plain run passes (parity lane exercises playlist_push for
all 5000 fixture entries, m3u overwrite path included).

* playlist: add playlist_dedup, an O(1) content path existence index

The manual content scan's END flush answers "is this path already
in the playlist?" once per scan result via playlist_entry_exists(),
whose linear matcher scan makes the flush quadratic in playlist
size - 48% of total scan wall time under gprof for a 5000-entry
scan, and growing with the square of collection size.

playlist_dedup_t is an open-addressing hash index over content path
IDs.  Correctness rests on a superset property of the matching
rules: any two IDs accepted by playlist_path_ids_match() share at
least one hash value between their {real, archive} pairs, because
an exact match implies equal real-path hashes and the fuzzy
bare-archive vs inside-archive match implies equal parent-archive
hashes (a bare archive's archive hash equals its real hash).
Storing every ID under both of its hashes and probing under both of
the query's hashes therefore yields a candidate superset, and every
candidate is verified with playlist_path_ids_match() itself - the
index can change only the cost of a query, never its answer.

The index owns all stored IDs, re-deriving them from entry path
strings during seeding instead of borrowing the entries' lazy
caches, so entry deletion (the scanner's m3u overwrite path calls
playlist_delete_by_path() mid-flush) cannot dangle it, and teardown
order relative to the playlist is free.  Seeding is resumable with
a caller-supplied budget callback and a one-entry-per-call progress
floor, matching the budgeted iteration idiom of the scan's
directory walk.  Any allocation failure permanently degrades the
index: queries fall back to the linear playlist_entry_exists() scan
and remain correct.

No callers yet; the scanner flush is wired in the next commit.

Verified: strict C89 syntax pass; full Linux build links; the
scanner oracle's differential lane (added two commits ahead)
asserts index answers equal linear-scan answers over a synthetic
corpus of plain, bare-archive, inside-archive and case-variant
paths with fuzzy matching both enabled and disabled.

* task_database: dedup the END flush with playlist_dedup

The flush paid two linear matcher scans per added result: the
playlist_entry_exists() probe, then playlist_push()'s own duplicate
scan reaching the same conclusion.  Together they were 48% of scan
wall time under gprof and quadratic in collection size.

Each playlist the flush opens (or borrows, in single-playlist mode)
now gets a playlist_dedup_t.  Pre-existing entries are indexed by
budgeted seeding on the shared per-frame window, resuming across
gathers exactly like the directory walk - flush_pos does not
advance while seeding, so a resumed gather re-enters the same
group.  Existence is then answered by playlist_dedup_check_add()
with will_add, which records the path as present precisely when the
result is pushed: an absent path is always pushed, and the m3u
overwrite path (delete + re-push of the same path) keeps it
present.  The push becomes playlist_push_unchecked(), absence
having been proven by the check.  Index allocation failure at any
point falls back to the original linear probe and checked push.

The index is freed at group close, at flush completion, and in the
mid-flight teardown a cancelled task takes; it owns all of its
state, so ordering against the playlist frees is immaterial.

Scanner oracle, plain build: total 73-84ms for the 5000-file
fixture against ~230ms before this commit and a ~266ms blocking
reference - the scan is now ~3x faster than before the index and
~0.3x of blocking, with max gather CPU 7.6-11.7ms inside the 16ms
budget, first feedback 0.02ms, and the parity, threaded and
14-point cancellation lanes passing.

Sanitizer sweeps (ASan+UBSan+LSan, and TSan separately, both via
"./scan_begin_budget_test sanitize"): PASS with zero reports across
all lanes, covering group switches, cancellation mid-flush and full
teardown.  Without the sanitize argument the wall-clock pacing
assertion trips under instrumentation on this tree and on pristine
master alike - the still-single-gather DAT parse inflates ~3.5x
under ASan past the 16ms budget - which is the documented rxml
residual addressed later in this series, at which point even
uninstrumented-style pacing should hold under sanitizers.

* samples/tasks/database: dedup lanes; tighten the throughput factor

Two lanes pin the playlist dedup index:

The differential lane builds a playlist of plain, bare-archive,
inside-archive and case-variant paths (path IDs are syntactic, so
none needs to exist) and asserts playlist_dedup_check_add() answers
exactly like the linear playlist_entry_exists() scan over a probe
corpus covering exact hits, misses, both fuzzy archive
equivalences, a case variant whose answer is OS-dependent - exactly
why the lane is differential - and the empty-path guard, with fuzzy
matching both off and on.  An absolute anchor keeps the
differential from rotting into vacuity by asserting the fuzzy
equivalences themselves; it is build-aware, since the sample
compiles without RARCH_INTERNAL, where the matcher's config gate is
compiled out and fuzzy matching is unconditionally on.  The lane
also pins the will_add contract: a recorded path is immediately
visible to the index, and playlist_push_unchecked() then brings the
playlist into agreement.

The no-overwrite rescan lane runs the full scan a second time into
the playlist the first pass wrote: all 5000 results must hit the
index against the pre-existing entries - driving the budgeted
seeding path at scale - and the playlist must still hold exactly
5000 entries afterwards.

THROUGHPUT_FACTOR drops from 1.60 to 0.80: with the index the
measured ratio against the blocking reference is ~0.35-0.41, and
0.80 keeps double headroom for runner noise while rejecting the
pre-index quadratic flush, which lands at ~1.1.

Verified with the CI step's literal command sequence: plain build
PASS (total 77.2ms, max gather CPU 8.1ms, all lanes), ASan+UBSan
+LSan sanitize-mode PASS with zero reports, TSan sanitize-mode PASS
with zero reports.

* rxml: incremental owned-buffer parsing

The manual content scanner reads its DAT file in budgeted chunks
but then parses the completed buffer with one
rxml_load_document_owned() call: a multi-hundred-MB MAME list still
parses inside a single task gather on a non-threaded queue,
freezing the frame for the duration.  The scanner needs to buy the
parse a slice at a time.

The parser was already shaped for it: rxml_parse_document() is
fully iterative, with the cursor, accumulator, frame stack and open-
name budget all in struct rxml_parser, and exactly one program
point where no function-local state is live - the between-
constructs point at the head of the content loop, reached each time
an element opens or a child closes.  That point now honours a stop
cursor: past it the parser records the suspension and returns a new
code, and the next invocation jumps straight back in.  The one-shot
path sets the stop past the end of input, where the check can never
fire (the cursor never moves beyond the terminating NUL), so its
code path is one always-false comparison per construct.

rxml_parse_begin_owned() / rxml_parse_step() / rxml_parse_end() /
rxml_parse_abort() expose this: begin takes the buffer under the
same ownership contract as rxml_load_document_owned(), each step
consumes roughly max_bytes of input (bounded by max_bytes plus one
construct), and the terminal verdict applies the same
RXML_OPT_STRICT_EOF and RXML_OPT_LINES rules as the one-shot
wrapper, including the tolerated-EOF partial tree.

Verified: strict C89 syntax pass (including the resume jump under
-pedantic); differential harness compares stepped trees against
one-shot trees over documents covering nested elements, attributes,
entity and character references, comments, PIs, CDATA, deep
nesting, truncation at two points, an invalid close and a trivial
document, at step sizes 1, 2, 3, 7, 64, 4096 and run-to-verdict -
byte-identical dumps and verdict parity throughout - plus a 64-
point mid-parse abort sweep and an end-before-verdict discard, all
under ASan+UBSan+LSan with zero reports.

* logiqx_dat: incremental initialisation; hash-based name index

Two single-gather spikes remained in the scanner's DAT handling:
the one-shot rxml parse of the completed buffer, and the search
index built inside the first logiqx_dat_search() - two full child
walks plus a qsort, tens of milliseconds for MAME-sized lists,
whichever gather happens to issue the first search.

The index becomes an open-addressing hash keyed on the game name,
power-of-two capacity at a load factor of at most 1/2, with first
occurrence winning on insert so duplicate names keep the leftmost-
match answer of the linear scan.  Exact lookup is all
logiqx_dat_search() ever asked of the sorted array, and unlike the
sorted array the build is a chunkable O(n) fill with no qsort
spike.  The count, allocation and fill stages are extracted as
cursor-advancing chunk helpers; the lazy build on first search
composes them unbudgeted, and the allocation-failure fallback to
the authoritative linear walk is preserved.

logiqx_dat_parse_begin_owned() / _step() / _end() / _abort() layer
incremental initialisation over rxml's new incremental parser: the
XML phase forwards the byte budget to rxml_parse_step(), the count
and fill phases translate it into node visits (with a progress
floor), and the verdict applies exactly the validation
logiqx_dat_init_owned() performs, under the same buffer ownership
contract.  A DAT built incrementally marks the index attempt
complete, so a later search neither rebuilds nor bypasses it.

Verified: strict C89 syntax pass; differential harness compares a
2000-game DAT (with every tenth name duplicated, an anonymous game
node and a non-game node) built incrementally at step budgets 1,
300, 4096, 65536 and unbudgeted against logiqx_dat_init_owned() -
2100 search queries answer identically at every budget, duplicates
resolve to first occurrence, the iteration API sees all 2001 game
nodes, and four invalid/truncated documents reach the same verdict
- plus a 40-point abort sweep and an end-before-done discard, all
under ASan+UBSan+LSan with zero reports.  Scanner oracle plain run
passes unchanged through the reworked lazy index.

* task_database: budget the DAT parse and index build across gathers

MANUAL_SCAN_BEGIN_DAT_LOAD read the DAT in budgeted chunks and then
handed the completed buffer to logiqx_dat_init_owned() in one call:
the whole rxml parse in a single gather, with the search index
following in whichever later gather issued the first search.  A
multi-hundred-MB MAME list froze the frame for the duration of each
on a non-threaded queue - the last single-gather work proportional
to input size anywhere in the scan.

The completed buffer now goes to logiqx_dat_parse_begin_owned(),
and the tick steps the parse and index build 256 KiB at a time
under the shared window - one step per gather as the floor, more
while the window lasts - resuming across gathers until the verdict.
The invalid-document error path and user-facing message are
unchanged, and a cancelled task aborts the in-flight parse in the
teardown alongside the stream and buffer it already released.

Scanner oracle, plain build (three runs): total 79.1-82.4ms, max
gather CPU 7.7-8.4ms (the DAT parse gather no longer contributes a
spike), all lanes passing.  ASan+UBSan+LSan and TSan sweeps
(sanitize mode): PASS, zero reports, the 14-point cancellation
sweep covering the new mid-parse abort path.

For the record, instrumented builds still exceed the 16ms pacing
budget without the sanitize-mode skip, at ~29ms max gather: a
temporary probe attributes 16.8ms CPU of that gather to the final
playlist sort + write alone under ASan (~5ms plain), which is the
deliberately retained one-blocking-write-per-group parity noted in
the original split.  The budget is a production-build contract; the
sanitize-mode treatment of it is unchanged.

* samples/tasks/database: big-DAT pacing lane

The 5000-game fixture parses in a couple of budgeted steps, which
cannot distinguish an incremental DAT parse from a single-gather
one.  The new lane scans 50 files against a generated 300000-game
DAT (~40MB of XML, one streamed write to build) and asserts the
same 16ms pacing budget over that scan: before the incremental
parse this lane's whole document parse - and the search-index build
after it - each sat inside one gather, and any return to that fails
the assertion by an order of magnitude.

Correctness in every mode: exactly 50 playlist entries, with the
content files sampling every 6000th game so the labels span the
whole list - the final sample's label can only come from an index
that covered all 300k entries, so a build that silently stopped at
a prefix mislabels the tail and fails.  Three additional cancel
points (32, 128, 512 gathers) land inside the budgeted read and
parse of the large document, phases the small fixture's sweep
passes through in single digits; the mid-parse abort path they
exercise is the one the task teardown gained with the incremental
parse.  Under sanitizers the lane runs for memory coverage with the
wall-clock assertion skipped, like every other pacing check.

Lane cost: ~2s plain, ~3s ASan, ~7s TSan on a development machine,
well inside the CI step's timeouts.

Verified with the CI step's literal command sequence: plain PASS
(big-DAT pacing held), ASan+UBSan+LSan sanitize-mode PASS with zero
reports, TSan sanitize-mode PASS with zero reports.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-08-15 01:13:43 +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