mirror of
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
synced 2026-05-16 03:11:11 -04:00
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. Suggested-by: Kees Cook <kees@kernel.org> Signed-off-by: Feng Jiang <jiangfeng@kylinos.cn> Reviewed-by: Kees Cook <kees@kernel.org> Link: https://patch.msgid.link/20260130025018.172925-2-jiangfeng@kylinos.cn Signed-off-by: Paul Walmsley <pjw@kernel.org>
This commit is contained in:
committed by
Paul Walmsley
parent
d7df050547
commit
ae45f896a4
@@ -6,10 +6,12 @@
|
||||
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
|
||||
|
||||
#include <kunit/test.h>
|
||||
#include <linux/mm.h>
|
||||
#include <linux/module.h>
|
||||
#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 +19,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 +109,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 +647,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),
|
||||
|
||||
Reference in New Issue
Block a user