Commit Graph
11 Commits
Author SHA1 Message Date
LibretroAdmin 22ba917922 libretro-common: word_wrap_offset(), with a test
menu_wrap_offset(), which finds where a byte of a string landed in its
word_wrap() or word_wrap_wideglyph() wrap, moves to stdstring.c beside
them as word_wrap_offset(), and MaterialUI and XMB call it from there.

It gave a glyph the wide-glyph wrap had put a line end before the
offset of that line end, so the input dialog's caret sat at the end
of the line above; it now gives the glyph's own.

word_wrap_offset_test wraps plain, wide-glyph and mixed text at every
width from 1 to 39, with line ends left or made NUL as the drivers
make them, and checks that every character lands on itself or on the
line end its space or newline became, in order, that the end lands
on the end, that no wrap more than doubles its text, and that the
caret before a word moved to the next line is on that line. It found
the wrong offset and the wide-glyph wrap's runaway at narrow widths.
2026-11-16 11:49:11 +01:00
LibretroAdmin 21635dd171 samples: build with -g1 instead of -g
The sample and test builds used full debug info. -g1 keeps what
sanitizer reports and backtraces need - function names, files and line
numbers - and drops the variable and type information nobody reads in
CI. Objects get about 30% smaller (rh265.o under ASan+UBSan: 5.1MB to
3.7MB), so the ccache caches hold more of each job's build and are
quicker to restore and save.
2026-10-13 11:50:11 +02:00
Codex 14c3fb1126 encoding: bound UTF-8 copy scans by destination capacity
Stop scanning once the output buffer is full instead of walking the rest of a long source. Preserve whole-glyph truncation and add boundary coverage for mixed UTF-8 text.
2026-10-12 00:34:45 +02:00
Codex a810576b97 string: carry wide wrapping widths across space breaks
Keep the measured word tail after a space break instead of copying and decoding it again. Preserve the rewind paths for stale spaces and short remaining input. Add a scan-count regression for accented word tails.
2026-10-12 00:30:45 +02:00
Codex ed4af44226 string: skip UTF-8 decoding for ASCII wrapping
Advance directly over ASCII bytes in both wrapping paths. Keep multibyte decoding unchanged and verify that ASCII wrapping produces the expected text without calling utf8skip.
2026-10-12 00:25:31 +02:00
Codex fe04a9a7bc string: avoid replaying wide glyphs at line breaks
Emit a break before the current wide glyph and carry its measured width forward when the glyph fits on the next line. Keep the existing fallback for earlier break positions and constrained buffers. Add a regression check that these breaks scan each glyph at most once.
2026-10-12 00:22:45 +02:00
Codex 0a6d081ea2 string: avoid rescanning wrapped word tails
Keep the glyph count after the chosen space instead of rewinding and decoding that span again. Retain the existing embedded-newline fallback and early-return decisions so wrapping output and line limits stay unchanged.

Count glyph scans in the regression harness to verify ordinary word-boundary wrapping visits each glyph at most once.
2026-10-12 00:15:18 +02:00
Codex cae9ec0154 string: wrap text with one input copy
Copy the input once and only replace the spaces chosen as line breaks. Advance over UTF-8 spans without writing them again when the wrapping loop rewinds. Preserve wrapping decisions, line limits, return lengths and short-buffer rejection.

Add regression cases for word boundaries, multibyte text, existing newlines, leading spaces and bounded destinations.
2026-10-12 00:07:20 +02:00
libretroadmin afbad7a104 samples: shared sources build into each sample's own obj/
Samples compiled shared tree sources in place, so whichever sample ran
next linked those objects with the flags they were built with, as
unity_identity did with mic_handshake's ASan objects. Every sample that
builds a source from outside its directory now includes
sample_objdir.mk and maps those objects under its own obj/; its own
objects stay where they were. The rule for the mapped objects has a
slash in its target, so make 3.81 does not strip the directory.

tools/sample_objdir_check.py dry-runs every sample Makefile and fails
on an object written outside the sample; the Samples-Objdir-Check
workflow runs it.
2026-10-10 19:43:34 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 0e648390c9 libretro-common: clamp word_wrap_wideglyph return to bytes-written + CI
word_wrap_wideglyph violated its implicit contract that the returned
length always fits inside the destination buffer.  Three return paths
forwarded strlcpy()'s return value, which is strlen(src) per spec --
not bytes-actually-written -- so on truncation the function returned
a value larger than the destination it had written into.

The sister function word_wrap() has a `len < src_len + 1` guard up
front that bails to 0 when the buffer is too small, sidestepping
this entirely.  word_wrap_wideglyph has no such guard and tries to
fit what it can, which is correct behaviour, but the inflated return
breaks every caller that uses it as a length argument.

Concrete impact: three menu drivers (xmb, ozone, materialui) feed
this return value as the `n` argument to memchr() over the wrapped
destination buffer when laying out messageboxes
(xmb_render_messagebox_internal at xmb.c line ~1183;
ozone_draw_messagebox at ozone.c line ~7362;
materialui_render_messagebox at materialui.c line ~2825).  Pre-patch,
an inflated `n` walks memchr past the destination into adjacent stack
memory (the lines[] / line_lengths[] arrays the messagebox helpers
keep right next to the wrapped buffer).  A '\n' byte found there
yields a wild pointer used in pointer arithmetic and as a length
argument to font_driver_get_message_width(), causing stack info
disclosure or a crash.

The wideglyph path is selected by msg_hash_get_wideglyph_str(), so
the bug is reachable in CJK locales (Japanese, Korean, Chinese) via
any messagebox payload exceeding MENU_LABEL_MAX_LENGTH (256 bytes
default) -- error notifications, file paths, network handshake
text, search results.

Two issues fixed in stdstring.c:

* Return value: every truncating return path
  (`return strlcpy(...)` and `return (s - s_start) + strlcpy(...)`)
  now clamps strlcpy's return to the actual bytes written:

      copied = strlcpy(s, src, n);
      if (copied >= n) copied = (n > 0) ? n - 1 : 0;
      return [(s - s_start) +] copied;

  This avoids introducing a strnlen() dependency (not used anywhere
  else in libretro-common, portability concerns on old MSVC).

* `len` semantic drift: the loop body decremented `len` by char_len
  on every byte written, while the early-return paths computed
  `remaining = len - (s - s_start)`.  Both expressions track "bytes
  used", so the formula effectively double-subtracted, yielding a
  too-small `remaining` and forcing the strlcpys to truncate harder
  than necessary.  The lastspace/lastwideglyph rewinds at lines ~411
  and ~429 also moved `s` backward without a matching `len` adjustment,
  desyncing the two over time.  Drop the `len -= char_len`, compute
  `remaining = len - (s - s_start)` once at the top of each loop
  iteration (and reuse it for the buffer-overflow guard previously
  spelled `if (char_len >= len)`).  `len` now stays constant across
  the function body, matching word_wrap()'s convention.

Regression test: libretro-common/samples/string/word_wrap_overflow
_test/.  Five cases covering both truncating and non-truncating
inputs across the line-358 early-return path and the main-loop
late-return paths.  The discriminator is two-fold: the test asserts
return-value-vs-bytes-written directly, AND mimics the menu drivers'
call shape by feeding the returned value to memchr() over the
destination, so an ASan build catches pre-patch failures via
heap-buffer-overflow on the memchr.  Verified by running against
both pre-patch and post-patch stdstring.c:

    pre-patch:  short_input_tiny_dest fails
                (returned=47, dst_size=16) -> exit 1
    post-patch: all five cases pass -> exit 0

CI: word_wrap_overflow_test added to RUN_TARGETS in
.github/workflows/Linux-libretro-common-samples.yml.  Builds under
SANITIZER=address,undefined like the other overflow regression
tests in the same workflow (rpng_chunk_overflow_test,
vfs_read_overflow_test, cdrom_cuesheet_overflow_test,
chd_meta_overflow_test, cdfs_dir_record_test, rzip_chunk_size_test).

Note on libretro-common/test/string/test_stdstring.c (the
libcheck-based suite): I considered adding a unit-test entry there
too, but the file is already broken at HEAD on master --
test_string_replacesubstr calls string_replace_substring with the
old 3-arg signature, but the API was extended to 5 args some time
ago; the test fails to compile.  Wiring up Makefile.test in CI
would have caught that regression but is out of scope here.
The samples-based regression test is the working surface and
matches the established pattern for every other overflow test
in the tree.
2026-04-28 22:05:12 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 78c52ab36e libretro-common/string: add strlcpy_append helper and apply to database_info_build_query_enum
Add strlcpy_append, a bound-checked replacement for the unsafe
idiom that's widespread in this codebase:

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

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

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

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

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

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

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

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

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

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

Verified database_info_build_query_enum produces identical
output for all 21 enum values at len=4096 (the production
caller's buffer size); also verified that at len=8 the
function returns -1 with no OOB write, which is the
behaviour the unsafe naive replacement would have failed at.
2026-04-28 06:44:59 +02:00