Add a KUnit test for strnlen() 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
| @@ -133,6 +133,40 @@ static void string_test_strlen(struct kunit *test) · 132 unmodified lines | |||
| 133 | vfree(buf); | 133 | vfree(buf); |
| 134 | } | 134 | } |
| 135 | 135 | ||
| 136 | static void string_test_strnlen(struct kunit *test) | ||
| 137 | { | ||
| 138 | size_t buf_size; | ||
| 139 | char *buf, *s; | ||
| 140 | |||
| 141 | buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1); | ||
| 142 | buf = vmalloc(buf_size); | ||
| 143 | KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf); | ||
| 144 | |||
| 145 | memset(buf, 'A', buf_size); | ||
| 146 | |||
| 147 | for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) { | ||
| 148 | for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) { | ||
| 149 | s = buf + buf_size - 1 - offset - len; | ||
| 150 | s[len] = '\0'; | ||
| 151 | |||
| 152 | if (len > 0) | ||
| 153 | KUNIT_EXPECT_EQ(test, strnlen(s, len - 1), len - 1); | ||
| 154 | if (len > 1) | ||
| 155 | KUNIT_EXPECT_EQ(test, strnlen(s, len - 2), len - 2); | ||
| 156 | |||
| 157 | KUNIT_EXPECT_EQ(test, strnlen(s, len), len); | ||
| 158 | |||
| 159 | KUNIT_EXPECT_EQ(test, strnlen(s, len + 1), len); | ||
| 160 | KUNIT_EXPECT_EQ(test, strnlen(s, len + 2), len); | ||
| 161 | KUNIT_EXPECT_EQ(test, strnlen(s, len + 10), len); | ||
| 162 | |||
| 163 | s[len] = 'A'; | ||
| 164 | } | ||
| 165 | } | ||
| 166 | |||
| 167 | vfree(buf); | ||
| 168 | } | ||
| 169 | |||
| 136 | static void string_test_strchr(struct kunit *test) | 170 | static void string_test_strchr(struct kunit *test) |
| 137 | { | 171 | { |
| 138 | const char *test_string = "abcdefghijkl"; | 172 | const char *test_string = "abcdefghijkl"; |
| @@ -648,6 +682,7 @@ static struct kunit_case string_test_cases[] = { · 509 unmodified lines | |||
| 648 | KUNIT_CASE(string_test_memset32), | 682 | KUNIT_CASE(string_test_memset32), |
| 649 | KUNIT_CASE(string_test_memset64), | 683 | KUNIT_CASE(string_test_memset64), |
| 650 | KUNIT_CASE(string_test_strlen), | 684 | KUNIT_CASE(string_test_strlen), |
| 685 | KUNIT_CASE(string_test_strnlen), | ||
| 651 | KUNIT_CASE(string_test_strchr), | 686 | KUNIT_CASE(string_test_strchr), |
| 652 | KUNIT_CASE(string_test_strnchr), | 687 | KUNIT_CASE(string_test_strnchr), |
| 653 | KUNIT_CASE(string_test_strspn), | 688 | KUNIT_CASE(string_test_strspn), |