mirror of
https://github.com/libretro/RetroArch.git
synced 2026-11-22 10:50:15 -10:00
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.