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.
Unified · Split
| @@ -6,10 +6,12 @@ · 5 unmodified lines | ||
| 6 | 6 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt |
| 7 | 7 | |
| 8 | 8 | #include <kunit/test.h> |
| 9 | +#include <linux/mm.h> | |
| 9 | 10 | #include <linux/module.h> |
| 10 | 11 | #include <linux/printk.h> |
| 11 | 12 | #include <linux/slab.h> |
| 12 | 13 | #include <linux/string.h> |
| 14 | +#include <linux/vmalloc.h> | |
| 13 | 15 | |
| 14 | 16 | #define STRCMP_LARGE_BUF_LEN 2048 |
| 15 | 17 | #define STRCMP_CHANGE_POINT 1337 |
| @@ -17,6 +19,9 @@ · 1 unmodified line | ||
| 17 | 19 | #define STRCMP_TEST_EXPECT_LOWER(test, fn, ...) KUNIT_EXPECT_LT(test, fn(__VA_ARGS__), 0) |
| 18 | 20 | #define STRCMP_TEST_EXPECT_GREATER(test, fn, ...) KUNIT_EXPECT_GT(test, fn(__VA_ARGS__), 0) |
| 19 | 21 | |
| 22 | +#define STRING_TEST_MAX_LEN 128 | |
| 23 | +#define STRING_TEST_MAX_OFFSET 16 | |
| 24 | + | |
| 20 | 25 | static void string_test_memset16(struct kunit *test) |
| 21 | 26 | { |
| 22 | 27 | unsigned i, j, k; |
| @@ -104,6 +109,30 @@ static void string_test_memset64(struct kunit *test) · 81 unmodified lines | ||
| 104 | 109 | } |
| 105 | 110 | } |
| 106 | 111 | |
| 112 | +static void string_test_strlen(struct kunit *test) | |
| 113 | +{ | |
| 114 | + size_t buf_size; | |
| 115 | + char *buf, *s; | |
| 116 | + | |
| 117 | + buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1); | |
| 118 | + buf = vmalloc(buf_size); | |
| 119 | + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); | |
| 120 | + | |
| 121 | + memset(buf, 'A', buf_size); | |
| 122 | + | |
| 123 | + for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) { | |
| 124 | + for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) { | |
| 125 | + s = buf + buf_size - 1 - offset - len; | |
| 126 | + s[len] = '\0'; | |
| 127 | + KUNIT_EXPECT_EQ_MSG(test, strlen(s), len, | |
| 128 | + "offset:%zu len:%zu", offset, len); | |
| 129 | + s[len] = 'A'; | |
| 130 | + } | |
| 131 | + } | |
| 132 | + | |
| 133 | + vfree(buf); | |
| 134 | +} | |
| 135 | + | |
| 107 | 136 | static void string_test_strchr(struct kunit *test) |
| 108 | 137 | { |
| 109 | 138 | const char *test_string = "abcdefghijkl"; |
| @@ -618,6 +647,7 @@ static struct kunit_case string_test_cases[] = { · 508 unmodified lines | ||
| 618 | 647 | KUNIT_CASE(string_test_memset16), |
| 619 | 648 | KUNIT_CASE(string_test_memset32), |
| 620 | 649 | KUNIT_CASE(string_test_memset64), |
| 650 | + KUNIT_CASE(string_test_strlen), | |
| 621 | 651 | KUNIT_CASE(string_test_strchr), |
| 622 | 652 | KUNIT_CASE(string_test_strnchr), |
| 623 | 653 | KUNIT_CASE(string_test_strspn), |