From: Feng Jiang Date: Sat, 4 Apr 2026 01:28:47 +0000 (-0600) Subject: lib/string_kunit: add correctness test for strrchr() X-Git-Tag: v7.1-rc1~27^2~11 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=27b2810a4a3dcd1545ec8bafc82f967eda591c47;p=thirdparty%2Fkernel%2Flinux.git lib/string_kunit: add correctness test for strrchr() Add a KUnit test for strrchr() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected. Suggested-by: Kees Cook Signed-off-by: Feng Jiang Reviewed-by: Kees Cook Link: https://patch.msgid.link/20260130025018.172925-4-jiangfeng@kylinos.cn Signed-off-by: Paul Walmsley --- diff --git a/lib/tests/string_kunit.c b/lib/tests/string_kunit.c index 1c2d57e05624..2bed641e1eae 100644 --- a/lib/tests/string_kunit.c +++ b/lib/tests/string_kunit.c @@ -190,6 +190,36 @@ static void string_test_strchr(struct kunit *test) KUNIT_ASSERT_NULL(test, result); } +static void string_test_strrchr(struct kunit *test) +{ + size_t buf_size; + char *buf, *s; + + buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1); + buf = vmalloc(buf_size); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); + + memset(buf, 'A', buf_size); + + for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) { + for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) { + s = buf + buf_size - 1 - offset - len; + s[len] = '\0'; + + KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'Z'), NULL); + + if (len > 0) + KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'A'), s + len - 1); + else + KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'A'), NULL); + + s[len] = 'A'; + } + } + + vfree(buf); +} + static void string_test_strnchr(struct kunit *test) { const char *test_string = "abcdefghijkl"; @@ -685,6 +715,7 @@ static struct kunit_case string_test_cases[] = { KUNIT_CASE(string_test_strnlen), KUNIT_CASE(string_test_strchr), KUNIT_CASE(string_test_strnchr), + KUNIT_CASE(string_test_strrchr), KUNIT_CASE(string_test_strspn), KUNIT_CASE(string_test_strcmp), KUNIT_CASE(string_test_strcmp_long_strings),