Add a KUnit test for strlen() 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 <[email protected]>
Signed-off-by: Feng Jiang <[email protected]>
---
 lib/tests/string_kunit.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/lib/tests/string_kunit.c b/lib/tests/string_kunit.c
index f9a8e557ba77..335f2e6c2ed6 100644
--- a/lib/tests/string_kunit.c
+++ b/lib/tests/string_kunit.c
@@ -10,6 +10,7 @@
 #include <linux/printk.h>
 #include <linux/slab.h>
 #include <linux/string.h>
+#include <linux/vmalloc.h>
 
 #define STRCMP_LARGE_BUF_LEN 2048
 #define STRCMP_CHANGE_POINT 1337
@@ -17,6 +18,9 @@
 #define STRCMP_TEST_EXPECT_LOWER(test, fn, ...) KUNIT_EXPECT_LT(test, 
fn(__VA_ARGS__), 0)
 #define STRCMP_TEST_EXPECT_GREATER(test, fn, ...) KUNIT_EXPECT_GT(test, 
fn(__VA_ARGS__), 0)
 
+#define STRING_TEST_MAX_LEN    128
+#define STRING_TEST_MAX_OFFSET 16
+
 static void string_test_memset16(struct kunit *test)
 {
        unsigned i, j, k;
@@ -104,6 +108,30 @@ static void string_test_memset64(struct kunit *test)
        }
 }
 
+static void string_test_strlen(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_EQ_MSG(test, strlen(s), len,
+                               "offset:%zu len:%zu", offset, len);
+                       s[len] = 'A';
+               }
+       }
+
+       vfree(buf);
+}
+
 static void string_test_strchr(struct kunit *test)
 {
        const char *test_string = "abcdefghijkl";
@@ -618,6 +646,7 @@ static struct kunit_case string_test_cases[] = {
        KUNIT_CASE(string_test_memset16),
        KUNIT_CASE(string_test_memset32),
        KUNIT_CASE(string_test_memset64),
+       KUNIT_CASE(string_test_strlen),
        KUNIT_CASE(string_test_strchr),
        KUNIT_CASE(string_test_strnchr),
        KUNIT_CASE(string_test_strspn),
-- 
2.25.1


Reply via email to