From ddd22b2f533db9c0da0bb262fbafa51f67c8587e Mon Sep 17 00:00:00 2001 From: jvoisin Date: Fri, 1 May 2026 00:36:32 +0200 Subject: Fix strncat/wcsncat Previously, no checks were done when __n <= __b, but strncat _appends_ after existing content, making this a overly broad check check. For example, with an 8-byte buffer containing "12345\0", strncat(buf, "ABCD", 4) would have the check skipped, but the result "12345ABCD\0" is 10 bytes, resulting in an overflow. This commit fixes this oversight, and adds a bunch of tests. --- tests/test_wcsncat_safe.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 tests/test_wcsncat_safe.c (limited to 'tests/test_wcsncat_safe.c') diff --git a/tests/test_wcsncat_safe.c b/tests/test_wcsncat_safe.c new file mode 100644 index 0000000..00fc8e6 --- /dev/null +++ b/tests/test_wcsncat_safe.c @@ -0,0 +1,34 @@ +#include "common.h" + +#include + +int main(int argc, char** argv) { + wchar_t buffer[8] = {0}; + + /* Safe: empty buffer, append 7 wide chars → exactly fills buffer */ + wcsncat(buffer, L"ABCDEFG", 7); + printf("%ls\n", buffer); + + /* Safe: reset, append with n larger than source. + * src is L"AB" (len 2), n=100 → only 2 wchars copied */ + buffer[0] = L'\0'; + wcsncat(buffer, L"AB", 100); + printf("%ls\n", buffer); + + /* Safe: partially filled, append fits exactly. + * buffer = L"ABCD" (4 wchars), append L"EFG" n=3 → 4+3+1 = 8 = exact fit */ + buffer[0] = L'\0'; + wcsncat(buffer, L"ABCD", 4); + wcsncat(buffer, L"EFG", 3); + printf("%ls\n", buffer); + + /* Safe: n limits copy to fit. + * buffer = L"ABCDE" (5 wchars), src long, n=2 → 5+2+1 = 8 = exact fit */ + buffer[0] = L'\0'; + wcsncat(buffer, L"ABCDE", 5); + wcsncat(buffer, L"FGHIJKLM", 2); + printf("%ls\n", buffer); + + /* All safe operations passed without trapping */ + return 0; +} -- cgit v1.3