Commit Graph
10 Commits
Author SHA1 Message Date
LibretroAdmin 10bf3808bc (libretro-common) compat_strl: bound the destination scan in strlcat
strlcat() located the end of the destination with an unbounded strlen(),
which is only correct when the destination happens to be NUL-terminated
inside 'len'. The contract does not require that: a buffer filled by a
raw read(), a fixed-width record, or a zero-length destination all read
past the end. ASan on an exactly-sized 16-byte heap buffer with no
terminator reports a heap-buffer-overflow READ of size 17.

Scan with memchr(s, 0, len) instead, which stops at the first NUL and
never examines more than 'len' bytes.

This also settles the return value in that case. The previous code
returned strlen(s) + strlen(source); OpenBSD, Darwin and glibc all
return len + strlen(source), and Apple's __strlcat_chk() reimplements
the same contract independently. Every libc RetroArch links against
agreed with one another and not with us, so the NOTE documenting the
divergence goes away rather than being reworded. Truncation detection
(return >= len) is unaffected either way.

Note that neither the old nor the new code is compiled on Darwin, where
strl.h forces HAVE_STRL and the system implementation is used. This was
therefore a behavioural split between macOS builds and everything else,
which is exactly the kind of divergence that does not show up in CI.

memchr() rather than a bounded byte loop: the loop costs 18x more than
strlen() on a 768-byte destination and crosses over above ~16 bytes,
while memchr() keeps the vectorised scan. Measured (Xeon 2.1GHz, gcc
13.3 -O2, len = PATH_MAX_LENGTH, median of 11 runs x 2M reps, ns/call):

  dst_len   strlen    memchr   byte-loop
        8    11.30     11.68        6.37
       48    12.83     13.01       24.65
      192    11.55     12.07       66.50
      768    14.03     14.76      254.49

+1.4% to +6.1% against the old code, ~0.2-0.8ns/call. There are 18
strlcat() call sites in the tree, all of them cold - configuration
init, platform bring-up, NAT-PMP, cloud-sync, connmanctl, netplay
nickname. The fill_pathname_* family uses the returned-offset strlcpy()
pattern and does not call strlcat() at all.

Verified by differential sweep against Apple's _platform_strlcat()
(libplatform/src/string/generic/strlcat.c) over every combination of
capacity 0-24 x destination length 0-26 x source length 0-26, checking
the return value and the full buffer including guard bytes, in three
classes: strlcpy, strlcat with a terminated destination, and strlcat
with the terminator outside the buffer. 0 mismatches in all three; the
old code produced 125 in the third. Also 0 mismatches against native
glibc 2.39 strlcpy/strlcat.

Sanitizer sweep: ASan+UBSan+LSan clean, TSan clean (run separately),
both over the full sweep above. gcc -std=c89 -pedantic -Wall -Wextra
clean on x86_64 and aarch64.

Adds a test_strlcat case covering the unterminated destination.
2026-08-07 00:33:49 +02:00
LibretroAdminandLibretroAdmin 1a8ad63599 Vulkan hardening + libretro-common test suites in CI (#19292)
* file_list: tests for the actiondata destructor hook

file_list_t::actiondata_free is the optional destructor for
item_file::actiondata.  It exists because the menu's actiondata,
menu_file_list_cbs_t, owns a further allocation and so cannot be torn
down with a plain free(); seven call sites across menu_driver.c, xmb.c
and ozone.c can destroy a menu list, and routing them through one hook
is what keeps each of them from needing to know how to take a cbs
apart.

Two properties are worth pinning down before someone simplifies them
away.

A list that has not set the hook must behave exactly as before.  Every
file_list_t outside the menu depends on that, and they get NULL by
being calloc()ed, memset() to zero, or embedded in a zeroed handle
rather than by saying so anywhere -- so the default is invisible at the
call sites and easy to break from the other end.

And the hook must never be handed NULL.  A destructor written for a
real object is under no obligation to tolerate it, and the entries of
a freshly appended list all have actiondata == NULL.

Nine tests: dispatch through the hook, fallback to free() without one,
NULL actiondata skipped, NULL list tolerated, teardown of a whole list
routing through the hook, mixed lists where only some entries carry
actiondata, file_list_clear() deliberately *not* freeing actiondata
(the menu relies on that split, so it is stated rather than
discovered), the hook surviving capacity growth, and file_list_insert()
starting an entry with no actiondata rather than inheriting the slot's.

They use file_list_deinitialize() rather than file_list_free(), since
the latter also free()s the file_list_t and these live on the stack.
Both share file_list_deinitialize_internal(), which is the path under
test.

Reverting just the dispatch in file_list_free_actiondata() back to a
plain free() -- the likely regression, since the function reads as
needlessly complicated without the context above -- fails seven of the
nine.

Added to Makefile.test alongside the existing suites, with the same
flags including -Werror, ASan and UBSan.

(cherry picked from commit ff169e23b5)

* vulkan: run the real context setup under the validation layer

The other vulkan samples in this directory each pin down one known
defect.  This one asserts a property instead -- "gfx/common/
vulkan_common.c provokes no complaint from VK_LAYER_KHRONOS_validation"
-- so it catches regressions nobody has thought of yet.  Wrong queue
family indices, extensions used without being enabled, child objects
outliving their parent, semaphores destroyed while still pending: all
of that is invisible on a forgiving driver and all of it is a
validation error here.

No debug messenger of its own.  vulkan_common.c already has one: built
with -DVULKAN_DEBUG it enables the validation layer and
VK_EXT_debug_utils and installs vulkan_debug_cb(), which formats every
message through RARCH_LOG.  The test supplies that RARCH_LOG and counts
validation lines.  So the driver's own debug path is the
instrumentation, and if it ever stops reporting, this test stops
passing.

Headless, via VULKAN_WSI_NONE -- no window, surface or swapchain.  On
CI that means lavapipe:

    apt-get install mesa-vulkan-drivers vulkan-validationlayers
    export VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.json

With no Vulkan device at all it exits 77, the automake convention for
skipped, so it is safe to run unconditionally.

Three checks: one init/destroy round trip; three of them in a row,
since a leak visible only at vkDestroyInstance shows up on the first
pass while one that needs state carried over from a previous context --
a cached device, a stale queue index -- only shows up on a later one,
and RetroArch does exactly this on every driver reinit; and that every
memory type the device advertises is selectable through
vulkan_find_memory_type(), which is where a wrong answer turns into a
validation error at the first vkBindImageMemory rather than at the
point of the mistake.

The harness has teeth, verified by breaking the driver on purpose.
Removing the vkDestroyDebugUtilsMessengerEXT() call from
vulkan_context_destroy() makes the run fail with

  ERROR Validation: [ VUID-vkDestroyInstance-instance-00629 ]
  ... VkDebugUtilsMessengerEXT 0x10000000001[] has not been destroyed
  errors=1

rather than passing quietly.

Scope, since the request was for vulkan.c: gfx/drivers/vulkan.c itself
is out of reach here.  It has 169 undefined frontend symbols, so
linking it would mean stubbing most of the frontend, and its texture
and descriptor helpers are static besides.  What this covers is
vulkan_common.c -- instance creation, physical device and queue family
selection, logical device creation, the extension and layer
negotiation around all of it, and the teardown.  That is where the
validation-visible mistakes in this backend have historically been.

Passes plain and under SANITIZER=address,undefined.

One observation left in a comment rather than acted on: under
VULKAN_WSI_NONE, vk.context.gpu_properties reads back zeroed even
though vulkan_context_init_device() fills it two lines before it fills
memory_properties, which does come through. Worth a look separately.

(cherry picked from commit f1270e8788)

* vulkan: make the validation sample actually reach the device

The sample I added in f1270e8 brought the context up with
VULKAN_WSI_NONE and claimed to cover physical device selection, queue
family selection and logical device creation.  It covered none of them.

vulkan_context_init_device() is called from vulkan_surface_create(),
not from vulkan_context_init(), and vulkan_surface_create() answers
VULKAN_WSI_NONE with `return false`.  So init alone creates an instance
and stops: context.gpu stays NULL and memory_properties stays zeroed.
The "every advertised memory type is selectable" check was iterating
zero memory types and reporting a pass.  A test that goes green by
reaching nothing is worse than no test, and this one had my name on it.

Bring the context up over a real Xlib surface instead.  That runs the
whole path -- instance, surface, physical device, queue families,
logical device, swapchain -- and still runs headless, because Xvfb and
lavapipe are both packaged:

    apt-get install xvfb mesa-vulkan-drivers vulkan-validationlayers
    Xvfb :99 -screen 0 1280x720x24 &

Added the assertions that would have caught the original mistake:
context.gpu, context.device, a non-zero memory type count and a
non-zero swapchain image count are all now checked explicitly, and the
memory type loop fails if it had nothing to iterate.  On lavapipe the
run reports what it reached:

    device: llvmpipe (LLVM 20.1.2, 256 bits), 1 memory type(s),
            3 swapchain image(s)

Also fixed the log hook, which scored any line containing "WARNING" as
a warning.  vulkan_debug_cb() formats as "[Vulkan] <SEVERITY> <TYPE>:",
so it now keys on "ERROR Validation" and "WARNING Validation" as pairs
-- otherwise a VUID name like WARNING-cache-file-error, which arrives
at INFO severity, counted as a failure.  lavapipe emits exactly that
one on first run when its shader validation cache does not exist yet.

Negative control re-verified against the new shape: removing the
vkDestroyDebugUtilsMessengerEXT() call from vulkan_context_destroy()
fails with VUID-vkDestroyInstance-instance-00629 and a non-zero exit,
rather than passing.

(cherry picked from commit f230399cea)

* stdstring: get the test suite building again, and sweep the wrappers

The stdstring suite has not compiled for some time.  Three things had
rotted, each independent of the others:

  - string_replace_substring() gained explicit lengths for all three
    of its arguments; the one call in the suite still passed the old
    three-argument form, so the file did not compile.

  - strldup() moved to compat/compat_strldup.c, which is not in
    TEST_STDSTRING_SRC, so once it compiled it did not link.

  - test_string_filter and test_string_replace call
    string_remove_all_chars(NULL, ...) and
    string_replace_all_chars(NULL, ...).  Both are documented in
    stdstring.h as "must be non-NULL, otherwise UB" and are leaf
    functions with no guard, so once it linked, two of seventeen
    checks segfaulted.  The library is right and the tests were
    written against an older, defensive version; the NULL calls are
    gone rather than the functions re-guarded.

With those fixed the suite runs clean: 17 checks, 0 failures, under
-fsanitize=address -fsanitize=undefined, which is what
libretro-common/Makefile.test already asks for.

Added test_word_wrap_bounds while here.  The existing test_word_wrap
checks that a comfortable case produces the right output; this one
checks that uncomfortable ones stay inside the buffer.  Destinations
are malloc()ed at exactly the size passed in, so a single byte past
the end is an ASan report rather than a stomp on whatever followed,
and it sweeps ten inputs -- three-byte and four-byte UTF-8, a
truncated sequence, input with no break opportunity, embedded
newlines, empty -- across every destination size and line width in the
interesting range, through both word_wrap() and
word_wrap_wideglyph().

Both come back clean: 20055 of 28236 calls wrote something, no
overflow, no unterminated output.  A negative result, and worth
having as one: this is the same glyph-versus-byte arithmetic that
overran a caller's stack buffer in gfx_animation.c's ticker, and the
wrappers are reached from far more places.

The count of calls that actually wrote is asserted, not just observed.
Both wrappers return early when dst_size < src_len + 1, so a sweep
whose sizes never cleared that bar would exercise nothing and still
report a pass.

(cherry picked from commit 32e6582c84)

* libretro-common: make every test suite in Makefile.test build and run

Following the stdstring repair, I ran the rest.  Three of the seven
suites the recipe builds did not link, and three more test files were
not in the recipe at all.

Not linking:

  utils, hash   streams/file_stream.c calls path_is_directory() and
                path_mkdir(), which live in file/file_path_io.c.  That
                file is in neither source list.

  rpng          the deflate path calls compress2(); TEST_RPNG_LIBS was
                defined and left empty, so nothing supplied -lz.

Not in the recipe at all -- present under test/formats/, never built,
never run: test_rwav.c, test_rjpeg.c and test_rwebm_audio.c.  All
three work; rjpeg needed features/features_cpu.c adding, the other two
needed nothing but a rule.  test_rwebm_audio.c is not a libcheck suite
but a plain main() that prints its own verdict and returns non-zero on
failure, so it gets no lcov step.

All ten now build and pass under -fsanitize=address -fsanitize=undefined,
which is what TEST_UNIT_CFLAGS already asked for:

  stdstring       17 checks
  utils            3
  hash             3
  linked_list     89
  file_list        9
  generic_queue   16
  rpng             6
  rwav             4
  rjpeg            2
  rwebm_audio     (own harness, ALL TESTS PASS)

None of the failures were in the tests or the library: every one was a
missing source or library in the makefile.  Which is the awkward part
-- a suite that cannot be built reads exactly like a suite that passes,
right up until someone tries to run it, and by then it has been
silently absent for however long the source list has been stale.  Worth
wiring into CI now that it goes green.

(cherry picked from commit bd8d13b127)

* ci: run the libretro-common test suites

Nothing in .github/ referenced libretro-common/Makefile.test.  That is
how three of its suites came to reference sources that had moved and a
fourth a library it never linked -- a suite that cannot be built reads
exactly like a suite that passes, and there was nothing to say
otherwise.

Two things had to be fixed before it could go in CI at all.

TEST_UNIT_CFLAGS hardcoded -lcheck.  On Debian and Ubuntu libcheck
needs -lcheck_pic -lsubunit -lrt -lm -pthread, so the link failed for
every suite regardless of the source lists.  Ask pkg-config for both
halves and fall back to the bare flag only when it cannot answer, so
platforms without pkg-config are no worse off.  The libs go after the
sources rather than in CFLAGS, which is where they belonged anyway.

`clean` removed only *.gcda and *.gcno from the top directory, leaving
ten test binaries, eight coverage.info files and a generated
test/coverage/ tree behind in the working copy.  It now removes what
the recipe creates.

With those in place the recipe runs end to end, and the first run
found something: UBSan flagged

  formats/wav/rwav.c:794:51: runtime error: left shift of negative
  value -3

8-bit PCM is unsigned with a bias of 128, so the centred sample is
negative across the lower half of the range and shifting it left is
undefined.  Multiplying by 256 is defined everywhere and identical on
every representation.  That is one real defect from the first run of a
suite that had been sitting there unbuilt.

Adds .github/workflows/Linux-libretro-common-tests.yml to run it, and
five steps to Linux-samples-gfx.yml for the samples added since that
file was last touched: display_servers, display_servers_kms,
gfx_animation_sanitize, gfx_thumbnail_sanitize and
gfx_widgets_sanitize.  The first three carry regression cases for
fixed defects -- the XRandR NULL derefs and crtc mis-indexing, the KMS
connector deref and dead qsort count, and the ticker's
glyph-versus-byte overflow -- and each step says which, in the style
the existing steps use.  The last two pin no defect and say so; they
are tripwires.

display_servers needs the X11 and Xrandr headers and
display_servers_kms the libdrm ones, added to the job's apt line.
Neither links against those libraries: both stub them, because what is
under test is what happens when those queries fail.

Every command in every new step was run locally first.  All ten
libretro-common suites pass, and all five samples pass under
address,undefined, with the two sanitize samples also under thread.
The workflow files themselves are only YAML-validated -- I have no way
to run GitHub Actions from here.

(Split from the graphics-audit series: the samples/gfx workflow
steps this commit originally carried ride with the display-server
and widgets/animation/thumbnail PRs, whose sample directories they
reference.)

* vulkan_common: drop the 65 KB of dead stack in the instance wrapper

vulkan_context_create_instance_wrapper() declared

  uint32_t i, layer_count;
  VkLayerProperties properties[128];

filled the array with

  layer_count = ARRAY_SIZE(properties);
  vkEnumerateInstanceLayerProperties(&layer_count, properties);

and then read neither of them.  Nothing else in the function or the
file touches either name; the enumeration result is written and
discarded, presumably left behind when whatever consulted the layer
list was removed.

VkLayerProperties is 520 bytes, so the array is 66560 of them:

  vulkan_context_create_instance_wrapper  stack usage
    -O0   66784 -> 192
    -O3   66848 -> 288

GCC does not elide it -- it cannot prove the callee does not retain
the pointer -- so this was 65 KB of stack burned on every instance
creation, on every platform, to write a table nobody reads.  That is
comfortable on a desktop and less so on the console targets where the
whole thread stack is measured in tens of kilobytes.

The unchecked return is beside the point once the call goes, but worth
noting as the thing that made it easy to miss: a call whose result is
discarded reads like a call whose result does not matter.

Found while resuming the gfx/common audit that the display server
files started.  samples/gfx/vulkan_validation exercises this exact
path -- instance creation is the first thing it does -- and still
reports clean on lavapipe under VK_LAYER_KHRONOS_validation, three
setup/teardown cycles included.

(cherry picked from commit e8cbda15a1)

* vulkan_common: clamp the debug object name before appending to it

vulkan_debug_mark_object() composes a name as

  size_t _len = strlcpy(merged_name, name, sizeof(merged_name));
  snprintf(merged_name + _len, sizeof(merged_name) - _len, " (%u)", count);

strlcpy() returns the length of the SOURCE, not the number of bytes
copied.  A name at or over 1024 bytes therefore puts merged_name + _len
past the end of the buffer and underflows the remaining size to near
SIZE_MAX, and snprintf writes wherever that lands.

Not reachable today: all three callers -- vulkan_debug_mark_buffer,
_image and _memory -- pass short string literals, and the whole
function is behind a non-NULL vkSetDebugUtilsObjectNameEXT, which only
exists in a VULKAN_DEBUG build.  This is hardening, not a fix for
anything that can currently happen, and it is a one-line clamp rather
than anything worth restructuring.

Worth doing because it is the third instance in this audit of the same
mistake: a function's return value meaning one thing and being used as
another.  gfx_animation_ticker() passed a glyph count where a byte
count was wanted; word_wrap()'s callers were checked for it and were
clean; here it is a source length used as a copied length.

Verified with samples/gfx/vulkan_validation, still clean on lavapipe
under VK_LAYER_KHRONOS_validation.

(cherry picked from commit d9e4512eeb)

* vulkan: check the reallocs in the HW render callbacks

Two of the callbacks a libretro core drives through the Vulkan HW
render interface grow their arrays with realloc() and store the result
without testing it.

realloc() returns NULL on failure and leaves the original block
allocated, so each of these leaked the old array, replaced a valid
pointer with NULL, and then immediately wrote through it.

vulkan_set_signal_semaphores():

  VkPipelineStageFlags *stage_flags  = realloc(...);
  VkSemaphore          *new_semaphores = realloc(...);
  vk->hw.wait_dst_stages = stage_flags;
  vk->hw.semaphores      = new_semaphores;
  for (i = 0; i < vk->hw.num_semaphores; i++)
     vk->hw.wait_dst_stages[i] = ...;   /* NULL[i] = */

Whichever array did grow is now kept, and if either failed the count
is reported as zero and VK_FLAG_HW_VALID_SEMAPHORE cleared, so nothing
downstream walks a short array.

vulkan_set_command_buffers() is the same shape with a worse tail:

  vk->hw.cmd          = hw_cmd;          /* NULL on failure */
  vk->hw.capacity_cmd = required_capacity;
  ...
  memcpy(vk->hw.cmd, cmd, ...);          /* memcpy to NULL */

capacity_cmd was updated regardless, so the damage outlived the call:
the next invocation with a smaller count found the capacity sufficient,
skipped the grow entirely, and wrote through NULL again with no
allocation attempt to fail visibly.  It now returns early with
num_cmd = 0, which the guard at line 6826 already treats as "no
commands to submit", and leaves capacity_cmd describing the block that
is actually there.

Reachable from any core using the Vulkan HW render context negotiation
interface -- these are the entry points it calls -- under memory
pressure or with a large enough command buffer count.

Compiles clean under the flags the unix Makefile emits and under
-std=c89 -pedantic.  Not runtime tested: reaching it needs a core
driving the HW render interface with a failing allocator, which is not
something the validation sample can stage.

(cherry picked from commit 974f6b05bf)

* libretro-common: link features_cpu into the suites master's crc32 rework needs

The libretro-common tests job went red on the PR merge while passing
on the branch alone, which is the signature of a semantic conflict
with master rather than a defect in either side.  PR jobs build the
merge of the branch into master, and master's encoding rework --
encoding_crc32.c gaining PCLMUL/CRC32 runtime dispatch through
cpu_features_get(), the Ogg page checksum moving into
encoding_crc32_ogg(), and encoding_deflate.c picking up the same
cpu_features_get() dispatch -- added link dependencies to three
files that Makefile.test builds standalone.  Both sides are correct
in isolation; the textual merge is clean; the linked result is not:

  test_utils        encoding_crc32.c        -> cpu_features_get
  test_rpng         encoding_deflate.c      -> cpu_features_get
  test_rwebm_audio  rvorbis.c / rwebm_audio.c -> encoding_crc32_ogg

Add features/features_cpu.c to the first two, and encoding_crc32.c
plus features/features_cpu.c to the third.

Verified on a local merge of graphics-audit into current
libretro/master, running the job's exact recipe: all three link
errors reproduce before the change, and after it the run is rc=0
with all nine libcheck suites at 0 failures and the rwebm audio
decode checks passing, under the ASan+UBSan flags the recipe builds
with.  Also re-run on the branch alone, where the extra objects are
inert: rc=0, same nine suites clean, ALL TESTS PASS.

Note that upstream master's own copy of Makefile.test links
encoding_crc32.c and encoding_deflate.c without features_cpu.c too,
so its libretro-common tests workflow should be failing the same way
on pushes to master; this commit resolves it for the merge, and the
same two hunks apply there if it is.

(cherry picked from commit ca181ab327e174b4717ea20b4f22b17aa5d6fa02)

* vulkan_common: free the queue lock at context destroy

vulkan_context_init_device() creates queue_lock with slock_new() on
every bring-up and nothing ever freed it -- vulkan_context_destroy()
tears down the swapchain, surface, device and instance and leaves the
lock behind.  One slock (40 bytes plus a pthread mutex) leaks per
driver reinit: every resolution change, fullscreen toggle and HDR
mode switch.  The cached-context path leaks identically, because
restoring cached_device_vk happens inside init_device which then
falls through to slock_new() like any other init, so the lock's
lifetime is per-context-cycle regardless of device caching.

Found by running samples/gfx/vulkan_validation under LSan against
lavapipe: five context cycles, five leaked locks, all allocated at
vulkan_common.c:1040 via vulkan_surface_create().

Free it at the end of vulkan_context_destroy() and NULL the pointer.
Every taker of the lock (vulkan_present, the submission paths) is
done by then: vkDeviceWaitIdle() runs at the top of the function.

Also guard the two instance-wrapper memcpys against a NULL source: a
caller enabling no extensions or no layers legitimately passes NULL
with a zero count, and memcpy's second argument is declared non-NULL
even for n == 0.  UBSan flagged both lines on every context
bring-up under the validation layer.  These copies are new in this
series (the instance wrapper rework), so this is fixing our own
regression rather than an upstream defect.

Sweep after the fix, via the validation sample on lavapipe + Xvfb
under ASan+UBSan with LSan: zero reports across one init/destroy
round trip, three consecutive cycles, and the memory type walk;
all validation-layer checks pass.  The path is single-threaded in
this harness, so TSan has nothing to observe here; the lock free
sits after vkDeviceWaitIdle() by construction.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-07-29 07:50:22 +02:00
libretroadmin 28783c657a Remove if 0 2025-11-14 19:37:58 +01:00
libretroadmin 03dbcc53e7 Get rid of superfluous macros around memcmp and strcpy 2025-08-04 19:30:03 +02:00
libretroadmin 60e0dd839a iC comments 2024-07-20 17:54:44 +02:00
LibretroAdmin e769436876 (word wrap functions in stdstring.c) Avoid implicit strlens, caller
should pass the 'length' to the function instead
2022-08-23 17:06:01 +02:00
David Guillen Fandos 8b53aaf45f Fix string test that fails. 2022-05-23 18:47:29 +02:00
toshixm 4fab84ca9e improve message wrapping with CJK languages 2021-06-03 21:09:35 +09:00
David Guillen Fandos 32d6eeaf07 Moving more stuff from samples to tests
Reworked the test a bit to make it separate from RA's build system for
simplicity.
Reworked the testing a bit to ensure coverage is properly generated.
This needs more work since it's rather manual and verbose
2021-05-10 19:45:50 +02:00
David Guillen Fandos a0f0d7bed2 Add more tests and coverage generation 2021-05-06 18:43:56 +02:00