History

lib/string_kunit: add correctness test for strlen()

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.

Feng Jiang committed 7 months ago

Commit ae45f891 parent d7df0501 file · +30 −0Browse files

Unified · Split

lib/tests/string_kunit.c+30−0
@@ -6,10 +6,12 @@ · 5 unmodified lines
66 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
77
88 #include <kunit/test.h>
9+#include <linux/mm.h>
910 #include <linux/module.h>
1011 #include <linux/printk.h>
1112 #include <linux/slab.h>
1213 #include <linux/string.h>
14+#include <linux/vmalloc.h>
1315
1416 #define STRCMP_LARGE_BUF_LEN 2048
1517 #define STRCMP_CHANGE_POINT 1337
@@ -17,6 +19,9 @@ · 1 unmodified line
1719 #define STRCMP_TEST_EXPECT_LOWER(test, fn, ...) KUNIT_EXPECT_LT(test, fn(__VA_ARGS__), 0)
1820 #define STRCMP_TEST_EXPECT_GREATER(test, fn, ...) KUNIT_EXPECT_GT(test, fn(__VA_ARGS__), 0)
1921
22+#define STRING_TEST_MAX_LEN 128
23+#define STRING_TEST_MAX_OFFSET 16
24+
2025 static void string_test_memset16(struct kunit *test)
2126 {
2227 unsigned i, j, k;
@@ -104,6 +109,30 @@ static void string_test_memset64(struct kunit *test) · 81 unmodified lines
104109 }
105110 }
106111
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+
107136 static void string_test_strchr(struct kunit *test)
108137 {
109138 const char *test_string = "abcdefghijkl";
@@ -618,6 +647,7 @@ static struct kunit_case string_test_cases[] = { · 508 unmodified lines
618647 KUNIT_CASE(string_test_memset16),
619648 KUNIT_CASE(string_test_memset32),
620649 KUNIT_CASE(string_test_memset64),
650+ KUNIT_CASE(string_test_strlen),
621651 KUNIT_CASE(string_test_strchr),
622652 KUNIT_CASE(string_test_strnchr),
623653 KUNIT_CASE(string_test_strspn),

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t