From 62b9ef504e7f89d6ae3e9ab704cc4befab1d37f0 Mon Sep 17 00:00:00 2001 From: Gabriela Bittencourt Date: Mon, 2 Dec 2024 15:55:42 +0800 Subject: [PATCH 01/16] unicode: kunit: refactor selftest to kunit tests Refactoring 'test' functions into kunit tests, to test utf-8 support in unicode subsystem. This allows the utf8 tests to be run alongside the KUnit test suite using kunit-tool, quickly compiling and running all desired tests as part of the KUnit test suite, instead of compiling the selftest module and loading it. The refactoring kept the original testing logic intact, while adopting a testing pattern across different kernel modules and leveraging KUnit's benefits. Co-developed-by: Pedro Orlando Signed-off-by: Pedro Orlando Co-developed-by: Danilo Pereira Signed-off-by: Danilo Pereira Signed-off-by: Gabriela Bittencourt Reviewed-by: David Gow Acked-by: Gabriel Krisman Bertazi Reviewed-by: Rae Moar Link: https://lore.kernel.org/r/20241202075545.3648096-6-davidgow@google.com Signed-off-by: Kees Cook --- fs/unicode/.kunitconfig | 3 + fs/unicode/Kconfig | 5 +- fs/unicode/Makefile | 2 +- fs/unicode/utf8-norm.c | 2 +- fs/unicode/utf8-selftest.c | 149 +++++++++++++++++-------------------- 5 files changed, 77 insertions(+), 84 deletions(-) create mode 100644 fs/unicode/.kunitconfig diff --git a/fs/unicode/.kunitconfig b/fs/unicode/.kunitconfig new file mode 100644 index 000000000000..62dd5c171f9c --- /dev/null +++ b/fs/unicode/.kunitconfig @@ -0,0 +1,3 @@ +CONFIG_KUNIT=y +CONFIG_UNICODE=y +CONFIG_UNICODE_NORMALIZATION_KUNIT_TEST=y diff --git a/fs/unicode/Kconfig b/fs/unicode/Kconfig index da786a687fdc..4ad2c36550f1 100644 --- a/fs/unicode/Kconfig +++ b/fs/unicode/Kconfig @@ -10,6 +10,7 @@ config UNICODE be a separate loadable module that gets requested only when a file system actually use it. -config UNICODE_NORMALIZATION_SELFTEST +config UNICODE_NORMALIZATION_KUNIT_TEST tristate "Test UTF-8 normalization support" - depends on UNICODE + depends on UNICODE && KUNIT + default KUNIT_ALL_TESTS diff --git a/fs/unicode/Makefile b/fs/unicode/Makefile index e309afe2b2bb..37bbcbc628a1 100644 --- a/fs/unicode/Makefile +++ b/fs/unicode/Makefile @@ -4,7 +4,7 @@ ifneq ($(CONFIG_UNICODE),) obj-y += unicode.o endif obj-$(CONFIG_UNICODE) += utf8data.o -obj-$(CONFIG_UNICODE_NORMALIZATION_SELFTEST) += utf8-selftest.o +obj-$(CONFIG_UNICODE_NORMALIZATION_KUNIT_TEST) += utf8-selftest.o unicode-y := utf8-norm.o utf8-core.o diff --git a/fs/unicode/utf8-norm.c b/fs/unicode/utf8-norm.c index 768f8ab448b8..7b998c99c88d 100644 --- a/fs/unicode/utf8-norm.c +++ b/fs/unicode/utf8-norm.c @@ -586,7 +586,7 @@ ccc_mismatch: } } -#ifdef CONFIG_UNICODE_NORMALIZATION_SELFTEST_MODULE +#if IS_MODULE(CONFIG_UNICODE_NORMALIZATION_KUNIT_TEST) EXPORT_SYMBOL_GPL(utf8version_is_supported); EXPORT_SYMBOL_GPL(utf8nlen); EXPORT_SYMBOL_GPL(utf8ncursor); diff --git a/fs/unicode/utf8-selftest.c b/fs/unicode/utf8-selftest.c index 5ddaf27b21a6..9476ab012baa 100644 --- a/fs/unicode/utf8-selftest.c +++ b/fs/unicode/utf8-selftest.c @@ -1,35 +1,15 @@ // SPDX-License-Identifier: GPL-2.0-only /* - * Kernel module for testing utf-8 support. + * KUnit tests for utf-8 support. * * Copyright 2017 Collabora Ltd. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt - -#include -#include #include -#include +#include #include "utf8n.h" -static unsigned int failed_tests; -static unsigned int total_tests; - -#define _test(cond, func, line, fmt, ...) do { \ - total_tests++; \ - if (!cond) { \ - failed_tests++; \ - pr_err("test %s:%d Failed: %s%s", \ - func, line, #cond, (fmt?":":".")); \ - if (fmt) \ - pr_err(fmt, ##__VA_ARGS__); \ - } \ - } while (0) -#define test_f(cond, fmt, ...) _test(cond, __func__, __LINE__, fmt, ##__VA_ARGS__) -#define test(cond) _test(cond, __func__, __LINE__, "") - static const struct { /* UTF-8 strings in this vector _must_ be NULL-terminated. */ unsigned char str[10]; @@ -167,69 +147,74 @@ static int utf8cursor(struct utf8cursor *u8c, const struct unicode_map *um, return utf8ncursor(u8c, um, n, s, (unsigned int)-1); } -static void check_utf8_nfdi(struct unicode_map *um) +static void check_utf8_nfdi(struct kunit *test) { int i; struct utf8cursor u8c; + struct unicode_map *um = test->priv; for (i = 0; i < ARRAY_SIZE(nfdi_test_data); i++) { int len = strlen(nfdi_test_data[i].str); int nlen = strlen(nfdi_test_data[i].dec); int j = 0; unsigned char c; + int ret; + + KUNIT_EXPECT_EQ(test, utf8len(um, UTF8_NFDI, nfdi_test_data[i].str), nlen); + KUNIT_EXPECT_EQ(test, utf8nlen(um, UTF8_NFDI, nfdi_test_data[i].str, len), + nlen); - test((utf8len(um, UTF8_NFDI, nfdi_test_data[i].str) == nlen)); - test((utf8nlen(um, UTF8_NFDI, nfdi_test_data[i].str, len) == - nlen)); - if (utf8cursor(&u8c, um, UTF8_NFDI, nfdi_test_data[i].str) < 0) - pr_err("can't create cursor\n"); + ret = utf8cursor(&u8c, um, UTF8_NFDI, nfdi_test_data[i].str); + KUNIT_EXPECT_TRUE_MSG(test, ret >= 0, "Can't create cursor\n"); while ((c = utf8byte(&u8c)) > 0) { - test_f((c == nfdi_test_data[i].dec[j]), - "Unexpected byte 0x%x should be 0x%x\n", - c, nfdi_test_data[i].dec[j]); + KUNIT_EXPECT_EQ_MSG(test, c, nfdi_test_data[i].dec[j], + "Unexpected byte 0x%x should be 0x%x\n", + c, nfdi_test_data[i].dec[j]); j++; } - test((j == nlen)); + KUNIT_EXPECT_EQ(test, j, nlen); } } -static void check_utf8_nfdicf(struct unicode_map *um) +static void check_utf8_nfdicf(struct kunit *test) { int i; struct utf8cursor u8c; + struct unicode_map *um = test->priv; for (i = 0; i < ARRAY_SIZE(nfdicf_test_data); i++) { int len = strlen(nfdicf_test_data[i].str); int nlen = strlen(nfdicf_test_data[i].ncf); int j = 0; + int ret; unsigned char c; - test((utf8len(um, UTF8_NFDICF, nfdicf_test_data[i].str) == - nlen)); - test((utf8nlen(um, UTF8_NFDICF, nfdicf_test_data[i].str, len) == - nlen)); + KUNIT_EXPECT_EQ(test, utf8len(um, UTF8_NFDICF, nfdicf_test_data[i].str), + nlen); + KUNIT_EXPECT_EQ(test, utf8nlen(um, UTF8_NFDICF, nfdicf_test_data[i].str, len), + nlen); - if (utf8cursor(&u8c, um, UTF8_NFDICF, - nfdicf_test_data[i].str) < 0) - pr_err("can't create cursor\n"); + ret = utf8cursor(&u8c, um, UTF8_NFDICF, nfdicf_test_data[i].str); + KUNIT_EXPECT_TRUE_MSG(test, ret >= 0, "Can't create cursor\n"); while ((c = utf8byte(&u8c)) > 0) { - test_f((c == nfdicf_test_data[i].ncf[j]), - "Unexpected byte 0x%x should be 0x%x\n", - c, nfdicf_test_data[i].ncf[j]); + KUNIT_EXPECT_EQ_MSG(test, c, nfdicf_test_data[i].ncf[j], + "Unexpected byte 0x%x should be 0x%x\n", + c, nfdicf_test_data[i].ncf[j]); j++; } - test((j == nlen)); + KUNIT_EXPECT_EQ(test, j, nlen); } } -static void check_utf8_comparisons(struct unicode_map *table) +static void check_utf8_comparisons(struct kunit *test) { int i; + struct unicode_map *um = test->priv; for (i = 0; i < ARRAY_SIZE(nfdi_test_data); i++) { const struct qstr s1 = {.name = nfdi_test_data[i].str, @@ -237,8 +222,9 @@ static void check_utf8_comparisons(struct unicode_map *table) const struct qstr s2 = {.name = nfdi_test_data[i].dec, .len = sizeof(nfdi_test_data[i].dec)}; - test_f(!utf8_strncmp(table, &s1, &s2), - "%s %s comparison mismatch\n", s1.name, s2.name); + /* strncmp returns 0 when strings are equal */ + KUNIT_EXPECT_TRUE_MSG(test, utf8_strncmp(um, &s1, &s2) == 0, + "%s %s comparison mismatch\n", s1.name, s2.name); } for (i = 0; i < ARRAY_SIZE(nfdicf_test_data); i++) { @@ -247,62 +233,65 @@ static void check_utf8_comparisons(struct unicode_map *table) const struct qstr s2 = {.name = nfdicf_test_data[i].ncf, .len = sizeof(nfdicf_test_data[i].ncf)}; - test_f(!utf8_strncasecmp(table, &s1, &s2), - "%s %s comparison mismatch\n", s1.name, s2.name); + /* strncasecmp returns 0 when strings are equal */ + KUNIT_EXPECT_TRUE_MSG(test, utf8_strncasecmp(um, &s1, &s2) == 0, + "%s %s comparison mismatch\n", s1.name, s2.name); } } -static void check_supported_versions(struct unicode_map *um) +static void check_supported_versions(struct kunit *test) { + struct unicode_map *um = test->priv; /* Unicode 7.0.0 should be supported. */ - test(utf8version_is_supported(um, UNICODE_AGE(7, 0, 0))); + KUNIT_EXPECT_TRUE(test, utf8version_is_supported(um, UNICODE_AGE(7, 0, 0))); /* Unicode 9.0.0 should be supported. */ - test(utf8version_is_supported(um, UNICODE_AGE(9, 0, 0))); + KUNIT_EXPECT_TRUE(test, utf8version_is_supported(um, UNICODE_AGE(9, 0, 0))); /* Unicode 1x.0.0 (the latest version) should be supported. */ - test(utf8version_is_supported(um, UTF8_LATEST)); + KUNIT_EXPECT_TRUE(test, utf8version_is_supported(um, UTF8_LATEST)); /* Next versions don't exist. */ - test(!utf8version_is_supported(um, UNICODE_AGE(13, 0, 0))); - test(!utf8version_is_supported(um, UNICODE_AGE(0, 0, 0))); - test(!utf8version_is_supported(um, UNICODE_AGE(-1, -1, -1))); + KUNIT_EXPECT_FALSE(test, utf8version_is_supported(um, UNICODE_AGE(13, 0, 0))); + KUNIT_EXPECT_FALSE(test, utf8version_is_supported(um, UNICODE_AGE(0, 0, 0))); + KUNIT_EXPECT_FALSE(test, utf8version_is_supported(um, UNICODE_AGE(-1, -1, -1))); } -static int __init init_test_ucd(void) +static struct kunit_case unicode_normalization_test_cases[] = { + KUNIT_CASE(check_supported_versions), + KUNIT_CASE(check_utf8_comparisons), + KUNIT_CASE(check_utf8_nfdicf), + KUNIT_CASE(check_utf8_nfdi), + {} +}; + +static int init_test_ucd(struct kunit *test) { - struct unicode_map *um; + struct unicode_map *um = utf8_load(UTF8_LATEST); - failed_tests = 0; - total_tests = 0; + test->priv = um; - um = utf8_load(UTF8_LATEST); - if (IS_ERR(um)) { - pr_err("%s: Unable to load utf8 table.\n", __func__); - return PTR_ERR(um); - } + KUNIT_EXPECT_EQ_MSG(test, IS_ERR(um), 0, + "%s: Unable to load utf8 table.\n", __func__); - check_supported_versions(um); - check_utf8_nfdi(um); - check_utf8_nfdicf(um); - check_utf8_comparisons(um); - - if (!failed_tests) - pr_info("All %u tests passed\n", total_tests); - else - pr_err("%u out of %u tests failed\n", failed_tests, - total_tests); - utf8_unload(um); return 0; } -static void __exit exit_test_ucd(void) +static void exit_test_ucd(struct kunit *test) { + utf8_unload(test->priv); } -module_init(init_test_ucd); -module_exit(exit_test_ucd); +static struct kunit_suite unicode_normalization_test_suite = { + .name = "unicode_normalization", + .test_cases = unicode_normalization_test_cases, + .init = init_test_ucd, + .exit = exit_test_ucd, +}; + +kunit_test_suite(unicode_normalization_test_suite); + MODULE_AUTHOR("Gabriel Krisman Bertazi "); -MODULE_DESCRIPTION("Kernel module for testing utf-8 support"); +MODULE_DESCRIPTION("KUnit tests for utf-8 support."); MODULE_LICENSE("GPL"); -- 2.51.0 From 2be6ce9d9bd040780dda8d456fe8696a48d805be Mon Sep 17 00:00:00 2001 From: Gabriela Bittencourt Date: Mon, 2 Dec 2024 15:55:43 +0800 Subject: [PATCH 02/16] unicode: kunit: change tests filename and path Change utf8 kunit test filename and path to follow the style convention on Documentation/dev-tools/kunit/style.rst Co-developed-by: Pedro Orlando Signed-off-by: Pedro Orlando Co-developed-by: Danilo Pereira Signed-off-by: Danilo Pereira Signed-off-by: Gabriela Bittencourt Reviewed-by: David Gow Acked-by: Gabriel Krisman Bertazi Reviewed-by: Shuah Khan Reviewed-by: Rae Moar Link: https://lore.kernel.org/r/20241202075545.3648096-7-davidgow@google.com Signed-off-by: Kees Cook --- fs/unicode/Makefile | 2 +- fs/unicode/{ => tests}/.kunitconfig | 0 fs/unicode/{utf8-selftest.c => tests/utf8_kunit.c} | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename fs/unicode/{ => tests}/.kunitconfig (100%) rename fs/unicode/{utf8-selftest.c => tests/utf8_kunit.c} (99%) diff --git a/fs/unicode/Makefile b/fs/unicode/Makefile index 37bbcbc628a1..d95be7fb9f6b 100644 --- a/fs/unicode/Makefile +++ b/fs/unicode/Makefile @@ -4,7 +4,7 @@ ifneq ($(CONFIG_UNICODE),) obj-y += unicode.o endif obj-$(CONFIG_UNICODE) += utf8data.o -obj-$(CONFIG_UNICODE_NORMALIZATION_KUNIT_TEST) += utf8-selftest.o +obj-$(CONFIG_UNICODE_NORMALIZATION_KUNIT_TEST) += tests/utf8_kunit.o unicode-y := utf8-norm.o utf8-core.o diff --git a/fs/unicode/.kunitconfig b/fs/unicode/tests/.kunitconfig similarity index 100% rename from fs/unicode/.kunitconfig rename to fs/unicode/tests/.kunitconfig diff --git a/fs/unicode/utf8-selftest.c b/fs/unicode/tests/utf8_kunit.c similarity index 99% rename from fs/unicode/utf8-selftest.c rename to fs/unicode/tests/utf8_kunit.c index 9476ab012baa..5063e8138aec 100644 --- a/fs/unicode/utf8-selftest.c +++ b/fs/unicode/tests/utf8_kunit.c @@ -8,7 +8,7 @@ #include #include -#include "utf8n.h" +#include "../utf8n.h" static const struct { /* UTF-8 strings in this vector _must_ be NULL-terminated. */ -- 2.51.0 From 9ab61886ac683e8ff1b261a1738d5e68cd645604 Mon Sep 17 00:00:00 2001 From: Yu-Chun Lin Date: Mon, 3 Feb 2025 15:54:00 +0800 Subject: [PATCH 03/16] lib/math: Add Kunit test suite for gcd() Add a KUnit test suite for the gcd() function. This test suite verifies the correctness of gcd() across various scenarios, including edge cases. Signed-off-by: Yu-Chun Lin Reviewed-by: Kuan-Wei Chiu Link: https://lore.kernel.org/r/20250203075400.3431330-1-eleanor15x@gmail.com Signed-off-by: Kees Cook --- lib/Kconfig.debug | 13 +++++++++ lib/math/tests/Makefile | 1 + lib/math/tests/gcd_kunit.c | 56 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 lib/math/tests/gcd_kunit.c diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index 86ddf568cbca..ad1725465870 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -3222,6 +3222,19 @@ config INT_LOG_KUNIT_TEST If unsure, say N +config GCD_KUNIT_TEST + tristate "Greatest common divisor test" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + This option enables the KUnit test suite for the gcd() function, + which computes the greatest common divisor of two numbers. + + This test suite verifies the correctness of gcd() across various + scenarios, including edge cases. + + If unsure, say N + endif # RUNTIME_TESTING_MENU config ARCH_USE_MEMTEST diff --git a/lib/math/tests/Makefile b/lib/math/tests/Makefile index 14a245778394..1d2dd6424df8 100644 --- a/lib/math/tests/Makefile +++ b/lib/math/tests/Makefile @@ -1,5 +1,6 @@ # SPDX-License-Identifier: GPL-2.0-only +obj-$(CONFIG_GCD_KUNIT_TEST) += gcd_kunit.o obj-$(CONFIG_INT_LOG_KUNIT_TEST) += int_log_kunit.o obj-$(CONFIG_INT_POW_KUNIT_TEST) += int_pow_kunit.o obj-$(CONFIG_INT_SQRT_KUNIT_TEST) += int_sqrt_kunit.o diff --git a/lib/math/tests/gcd_kunit.c b/lib/math/tests/gcd_kunit.c new file mode 100644 index 000000000000..ede1883583b1 --- /dev/null +++ b/lib/math/tests/gcd_kunit.c @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0-only + +#include +#include +#include + +struct test_case_params { + unsigned long val1; + unsigned long val2; + unsigned long expected_result; + const char *name; +}; + +static const struct test_case_params params[] = { + { 48, 18, 6, "GCD of 48 and 18" }, + { 18, 48, 6, "GCD of 18 and 48" }, + { 56, 98, 14, "GCD of 56 and 98" }, + { 17, 13, 1, "Coprime numbers" }, + { 101, 103, 1, "Coprime numbers" }, + { 270, 192, 6, "GCD of 270 and 192" }, + { 0, 5, 5, "GCD with zero" }, + { 7, 0, 7, "GCD with zero reversed" }, + { 36, 36, 36, "GCD of identical numbers" }, + { ULONG_MAX, 1, 1, "GCD of max ulong and 1" }, + { ULONG_MAX, ULONG_MAX, ULONG_MAX, "GCD of max ulong values" }, +}; + +static void get_desc(const struct test_case_params *tc, char *desc) +{ + strscpy(desc, tc->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(gcd, params, get_desc); + +static void gcd_test(struct kunit *test) +{ + const struct test_case_params *tc = (const struct test_case_params *)test->param_value; + + KUNIT_EXPECT_EQ(test, tc->expected_result, gcd(tc->val1, tc->val2)); +} + +static struct kunit_case math_gcd_test_cases[] = { + KUNIT_CASE_PARAM(gcd_test, gcd_gen_params), + {} +}; + +static struct kunit_suite gcd_test_suite = { + .name = "math-gcd", + .test_cases = math_gcd_test_cases, +}; + +kunit_test_suite(gcd_test_suite); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("math.gcd KUnit test suite"); +MODULE_AUTHOR("Yu-Chun Lin "); -- 2.51.0 From 313b38a6ecb46db4002925af91b64df4f2b76d1f Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sat, 8 Feb 2025 21:44:39 -0500 Subject: [PATCH 04/16] lib/prime_numbers: convert self-test to KUnit Extract a private header and convert the prime_numbers self-test to a KUnit test. I considered parameterizing the test using `KUNIT_CASE_PARAM` but didn't see how it was possible since the test logic is entangled with the test parameter generation logic. Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20250208-prime_numbers-kunit-convert-v5-2-b0cb82ae7c7d@gmail.com Signed-off-by: Kees Cook --- lib/Kconfig.debug | 14 +++ lib/math/prime_numbers.c | 91 ++++---------------- lib/math/prime_numbers_private.h | 16 ++++ lib/math/tests/Makefile | 1 + lib/math/tests/prime_numbers_kunit.c | 59 +++++++++++++ tools/testing/selftests/lib/config | 1 - tools/testing/selftests/lib/prime_numbers.sh | 4 - 7 files changed, 109 insertions(+), 77 deletions(-) create mode 100644 lib/math/prime_numbers_private.h create mode 100644 lib/math/tests/prime_numbers_kunit.c delete mode 100755 tools/testing/selftests/lib/prime_numbers.sh diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index ad1725465870..7e548b9e36b7 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -3235,6 +3235,20 @@ config GCD_KUNIT_TEST If unsure, say N +config PRIME_NUMBERS_KUNIT_TEST + tristate "Prime number generator test" if !KUNIT_ALL_TESTS + depends on KUNIT + select PRIME_NUMBERS + default KUNIT_ALL_TESTS + help + This option enables the KUnit test suite for the {is,next}_prime_number + functions. + + Enabling this option will include tests that compare the prime number + generator functions against a brute force implementation. + + If unsure, say N + endif # RUNTIME_TESTING_MENU config ARCH_USE_MEMTEST diff --git a/lib/math/prime_numbers.c b/lib/math/prime_numbers.c index 9a17ee9af93a..95a6f7960db9 100644 --- a/lib/math/prime_numbers.c +++ b/lib/math/prime_numbers.c @@ -1,16 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only -#define pr_fmt(fmt) "prime numbers: " fmt #include #include #include #include -struct primes { - struct rcu_head rcu; - unsigned long last, sz; - unsigned long primes[]; -}; +#include "prime_numbers_private.h" #if BITS_PER_LONG == 64 static const struct primes small_primes = { @@ -62,9 +57,25 @@ static const struct primes small_primes = { static DEFINE_MUTEX(lock); static const struct primes __rcu *primes = RCU_INITIALIZER(&small_primes); -static unsigned long selftest_max; +#if IS_ENABLED(CONFIG_PRIME_NUMBERS_KUNIT_TEST) +/* + * Calls the callback under RCU lock. The callback must not retain + * the primes pointer. + */ +void with_primes(void *ctx, primes_fn fn) +{ + rcu_read_lock(); + fn(ctx, rcu_dereference(primes)); + rcu_read_unlock(); +} +EXPORT_SYMBOL(with_primes); + +EXPORT_SYMBOL(slow_is_prime_number); -static bool slow_is_prime_number(unsigned long x) +#else +static +#endif +bool slow_is_prime_number(unsigned long x) { unsigned long y = int_sqrt(x); @@ -239,77 +250,13 @@ bool is_prime_number(unsigned long x) } EXPORT_SYMBOL(is_prime_number); -static void dump_primes(void) -{ - const struct primes *p; - char *buf; - - buf = kmalloc(PAGE_SIZE, GFP_KERNEL); - - rcu_read_lock(); - p = rcu_dereference(primes); - - if (buf) - bitmap_print_to_pagebuf(true, buf, p->primes, p->sz); - pr_info("primes.{last=%lu, .sz=%lu, .primes[]=...x%lx} = %s\n", - p->last, p->sz, p->primes[BITS_TO_LONGS(p->sz) - 1], buf); - - rcu_read_unlock(); - - kfree(buf); -} - -static int selftest(unsigned long max) -{ - unsigned long x, last; - - if (!max) - return 0; - - for (last = 0, x = 2; x < max; x++) { - bool slow = slow_is_prime_number(x); - bool fast = is_prime_number(x); - - if (slow != fast) { - pr_err("inconsistent result for is-prime(%lu): slow=%s, fast=%s!\n", - x, slow ? "yes" : "no", fast ? "yes" : "no"); - goto err; - } - - if (!slow) - continue; - - if (next_prime_number(last) != x) { - pr_err("incorrect result for next-prime(%lu): expected %lu, got %lu\n", - last, x, next_prime_number(last)); - goto err; - } - last = x; - } - - pr_info("%s(%lu) passed, last prime was %lu\n", __func__, x, last); - return 0; - -err: - dump_primes(); - return -EINVAL; -} - -static int __init primes_init(void) -{ - return selftest(selftest_max); -} - static void __exit primes_exit(void) { free_primes(); } -module_init(primes_init); module_exit(primes_exit); -module_param_named(selftest, selftest_max, ulong, 0400); - MODULE_AUTHOR("Intel Corporation"); MODULE_DESCRIPTION("Prime number library"); MODULE_LICENSE("GPL"); diff --git a/lib/math/prime_numbers_private.h b/lib/math/prime_numbers_private.h new file mode 100644 index 000000000000..f3ebf5386e6b --- /dev/null +++ b/lib/math/prime_numbers_private.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +#include + +struct primes { + struct rcu_head rcu; + unsigned long last, sz; + unsigned long primes[]; +}; + +#if IS_ENABLED(CONFIG_PRIME_NUMBERS_KUNIT_TEST) +typedef void (*primes_fn)(void *, const struct primes *); + +void with_primes(void *ctx, primes_fn fn); +bool slow_is_prime_number(unsigned long x); +#endif diff --git a/lib/math/tests/Makefile b/lib/math/tests/Makefile index 1d2dd6424df8..13dc96e48408 100644 --- a/lib/math/tests/Makefile +++ b/lib/math/tests/Makefile @@ -4,4 +4,5 @@ obj-$(CONFIG_GCD_KUNIT_TEST) += gcd_kunit.o obj-$(CONFIG_INT_LOG_KUNIT_TEST) += int_log_kunit.o obj-$(CONFIG_INT_POW_KUNIT_TEST) += int_pow_kunit.o obj-$(CONFIG_INT_SQRT_KUNIT_TEST) += int_sqrt_kunit.o +obj-$(CONFIG_PRIME_NUMBERS_KUNIT_TEST) += prime_numbers_kunit.o obj-$(CONFIG_RATIONAL_KUNIT_TEST) += rational_kunit.o diff --git a/lib/math/tests/prime_numbers_kunit.c b/lib/math/tests/prime_numbers_kunit.c new file mode 100644 index 000000000000..2f1643208c66 --- /dev/null +++ b/lib/math/tests/prime_numbers_kunit.c @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-only + +#include +#include +#include + +#include "../prime_numbers_private.h" + +static void dump_primes(void *ctx, const struct primes *p) +{ + static char buf[PAGE_SIZE]; + struct kunit_suite *suite = ctx; + + bitmap_print_to_pagebuf(true, buf, p->primes, p->sz); + kunit_info(suite, "primes.{last=%lu, .sz=%lu, .primes[]=...x%lx} = %s", + p->last, p->sz, p->primes[BITS_TO_LONGS(p->sz) - 1], buf); +} + +static void prime_numbers_test(struct kunit *test) +{ + const unsigned long max = 65536; + unsigned long x, last, next; + + for (last = 0, x = 2; x < max; x++) { + const bool slow = slow_is_prime_number(x); + const bool fast = is_prime_number(x); + + KUNIT_ASSERT_EQ_MSG(test, slow, fast, "is-prime(%lu)", x); + + if (!slow) + continue; + + next = next_prime_number(last); + KUNIT_ASSERT_EQ_MSG(test, next, x, "next-prime(%lu)", last); + last = next; + } +} + +static void kunit_suite_exit(struct kunit_suite *suite) +{ + with_primes(suite, dump_primes); +} + +static struct kunit_case prime_numbers_cases[] = { + KUNIT_CASE(prime_numbers_test), + {}, +}; + +static struct kunit_suite prime_numbers_suite = { + .name = "math-prime_numbers", + .suite_exit = kunit_suite_exit, + .test_cases = prime_numbers_cases, +}; + +kunit_test_suite(prime_numbers_suite); + +MODULE_AUTHOR("Intel Corporation"); +MODULE_DESCRIPTION("Prime number library"); +MODULE_LICENSE("GPL"); diff --git a/tools/testing/selftests/lib/config b/tools/testing/selftests/lib/config index dc15aba8d0a3..306a3d4dca98 100644 --- a/tools/testing/selftests/lib/config +++ b/tools/testing/selftests/lib/config @@ -1,5 +1,4 @@ CONFIG_TEST_PRINTF=m CONFIG_TEST_SCANF=m CONFIG_TEST_BITMAP=m -CONFIG_PRIME_NUMBERS=m CONFIG_TEST_BITOPS=m diff --git a/tools/testing/selftests/lib/prime_numbers.sh b/tools/testing/selftests/lib/prime_numbers.sh deleted file mode 100755 index 370b79a9cb2e..000000000000 --- a/tools/testing/selftests/lib/prime_numbers.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -# SPDX-License-Identifier: GPL-2.0 -# Checks fast/slow prime_number generation for inconsistencies -$(dirname $0)/../kselftest/module.sh "prime numbers" prime_numbers selftest=65536 -- 2.51.0 From ee0445d6b6e9ec9149aa2d1b5b89991d0829883e Mon Sep 17 00:00:00 2001 From: Lukas Bulwahn Date: Mon, 17 Feb 2025 11:06:43 +0100 Subject: [PATCH 05/16] MAINTAINERS: adjust entries in FORTIFY_SOURCE and KERNEL HARDENING Commit db6fe4d61ece ("lib: Move KUnit tests into tests/ subdirectory") adds a file entry to the non-existing file scripts/test_fortify.sh. Probably, this entry intends to refer to ./lib/test_fortify/test_fortify.sh, though. As that file is already covered by the entry lib/test_fortify/*, there is no need for a separate file entry. So, drop the unnecessary file entry to the test_fortify script. Further, this commit misses to adjust the entry referring to lib/usercopy_kunit.c, which is moved to lib/tests. So, also adjust that file entry. Fixes: db6fe4d61ece ("lib: Move KUnit tests into tests/ subdirectory") Signed-off-by: Lukas Bulwahn Link: https://lore.kernel.org/r/20250217100643.20182-1-lukas.bulwahn@redhat.com Signed-off-by: Kees Cook --- MAINTAINERS | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 78be36fb1a74..8f37e238bf55 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -9068,7 +9068,6 @@ F: include/linux/fortify-string.h F: lib/test_fortify/* F: lib/tests/fortify_kunit.c F: lib/tests/memcpy_kunit.c -F: scripts/test_fortify.sh K: \bunsafe_memcpy\b K: \b__NO_FORTIFY\b @@ -12588,7 +12587,7 @@ F: arch/*/configs/hardening.config F: include/linux/overflow.h F: include/linux/randomize_kstack.h F: kernel/configs/hardening.config -F: lib/usercopy_kunit.c +F: lib/tests/usercopy_kunit.c F: mm/usercopy.c F: security/Kconfig.hardening K: \b(add|choose)_random_kstack_offset\b -- 2.51.0 From ba6be7ba2d3fe146aae2e7ff1b28d111beaa7e31 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Mon, 17 Feb 2025 08:30:44 -0500 Subject: [PATCH 06/16] selftests: remove reference to prime_numbers.sh Remove a leftover shell script reference from commit 313b38a6ecb4 ("lib/prime_numbers: convert self-test to KUnit"). Reported-by: kernel test robot Closes: https://lore.kernel.org/oe-lkp/202502171110.708d965a-lkp@intel.com Fixes: 313b38a6ecb4 ("lib/prime_numbers: convert self-test to KUnit") Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20250217-fix-prime-numbers-v1-1-eb0ca7235e60@gmail.com Signed-off-by: Kees Cook --- tools/testing/selftests/lib/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/testing/selftests/lib/Makefile b/tools/testing/selftests/lib/Makefile index c52fe3ad8e98..66dcbe2e39fa 100644 --- a/tools/testing/selftests/lib/Makefile +++ b/tools/testing/selftests/lib/Makefile @@ -4,5 +4,5 @@ # No binaries, but make sure arg-less "make" doesn't trigger "run_tests" all: -TEST_PROGS := printf.sh bitmap.sh prime_numbers.sh scanf.sh +TEST_PROGS := printf.sh bitmap.sh scanf.sh include ../lib.mk -- 2.51.0 From 04e403e6627d8513d14f3236e52068837eabd2a5 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Tue, 4 Mar 2025 09:28:48 -0800 Subject: [PATCH 07/16] kunit/overflow: Fix DEFINE_FLEX tests for counted_by MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Unfortunately, __builtin_dynamic_object_size() does not take into account flexible array sizes, even when they are sized by __counted_by. As a result, the size tests for the flexible arrays need to be separated to get an accurate check of the compiler's behavior. While at it, fully test sizeof, __struct_size (bdos(..., 0)), and __member_size (bdos(..., 1)). I still think this is a compiler design issue, but there's not much to be done about it currently beyond adjusting these tests. GCC and Clang agree on this behavior at least. :) Reported-by: "Thomas Weißschuh" Closes: https://lore.kernel.org/lkml/e1a1531d-6968-4ae8-a3b5-5ea0547ec4b3@t-8ch.de/ Fixes: 9dd5134c6158 ("kunit/overflow: Adjust for __counted_by with DEFINE_RAW_FLEX()") Signed-off-by: Kees Cook --- lib/tests/overflow_kunit.c | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/lib/tests/overflow_kunit.c b/lib/tests/overflow_kunit.c index 5222c6393f11..894691b4411a 100644 --- a/lib/tests/overflow_kunit.c +++ b/lib/tests/overflow_kunit.c @@ -1185,22 +1185,40 @@ struct bar { static void DEFINE_FLEX_test(struct kunit *test) { - /* Using _RAW_ on a __counted_by struct will initialize "counter" to zero */ - DEFINE_RAW_FLEX(struct foo, two_but_zero, array, 2); -#ifdef CONFIG_CC_HAS_COUNTED_BY - int expected_raw_size = sizeof(struct foo); -#else - int expected_raw_size = sizeof(struct foo) + 2 * sizeof(s16); -#endif - /* Without annotation, it will always be on-stack size. */ DEFINE_RAW_FLEX(struct bar, two, array, 2); DEFINE_FLEX(struct foo, eight, array, counter, 8); DEFINE_FLEX(struct foo, empty, array, counter, 0); + /* Using _RAW_ on a __counted_by struct will initialize "counter" to zero */ + DEFINE_RAW_FLEX(struct foo, two_but_zero, array, 2); + int array_size_override = 0; - KUNIT_EXPECT_EQ(test, __struct_size(two_but_zero), expected_raw_size); + KUNIT_EXPECT_EQ(test, sizeof(*two), sizeof(struct bar)); KUNIT_EXPECT_EQ(test, __struct_size(two), sizeof(struct bar) + 2 * sizeof(s16)); - KUNIT_EXPECT_EQ(test, __struct_size(eight), 24); + KUNIT_EXPECT_EQ(test, __member_size(two), sizeof(struct bar) + 2 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __struct_size(two->array), 2 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __member_size(two->array), 2 * sizeof(s16)); + + KUNIT_EXPECT_EQ(test, sizeof(*eight), sizeof(struct foo)); + KUNIT_EXPECT_EQ(test, __struct_size(eight), sizeof(struct foo) + 8 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __member_size(eight), sizeof(struct foo) + 8 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __struct_size(eight->array), 8 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __member_size(eight->array), 8 * sizeof(s16)); + + KUNIT_EXPECT_EQ(test, sizeof(*empty), sizeof(struct foo)); KUNIT_EXPECT_EQ(test, __struct_size(empty), sizeof(struct foo)); + KUNIT_EXPECT_EQ(test, __member_size(empty), sizeof(struct foo)); + KUNIT_EXPECT_EQ(test, __struct_size(empty->array), 0); + KUNIT_EXPECT_EQ(test, __member_size(empty->array), 0); + + /* If __counted_by is not being used, array size will have the on-stack size. */ + if (!IS_ENABLED(CONFIG_CC_HAS_COUNTED_BY)) + array_size_override = 2 * sizeof(s16); + + KUNIT_EXPECT_EQ(test, sizeof(*two_but_zero), sizeof(struct foo)); + KUNIT_EXPECT_EQ(test, __struct_size(two_but_zero), sizeof(struct foo) + 2 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __member_size(two_but_zero), sizeof(struct foo) + 2 * sizeof(s16)); + KUNIT_EXPECT_EQ(test, __struct_size(two_but_zero->array), array_size_override); + KUNIT_EXPECT_EQ(test, __member_size(two_but_zero->array), array_size_override); } static struct kunit_case overflow_test_cases[] = { -- 2.51.0 From d985e4399adffb58e10b38dbb5479ef29d53cde6 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Tue, 4 Mar 2025 14:56:11 -0800 Subject: [PATCH 08/16] kunit/stackinit: Use fill byte different from Clang i386 pattern The byte initialization values used with -ftrivial-auto-var-init=pattern (CONFIG_INIT_STACK_ALL_PATTERN=y) depends on the compiler, architecture, and byte position relative to struct member types. On i386 with Clang, this includes the 0xFF value, which means it looks like nothing changes between the leaf byte filling pass and the expected "stack wiping" pass of the stackinit test. Use the byte fill value of 0x99 instead, fixing the test for i386 Clang builds. Reported-by: ernsteiswuerfel Closes: https://github.com/ClangBuiltLinux/linux/issues/2071 Fixes: 8c30d32b1a32 ("lib/test_stackinit: Handle Clang auto-initialization pattern") Tested-by: Nathan Chancellor Link: https://lore.kernel.org/r/20250304225606.work.030-kees@kernel.org Signed-off-by: Kees Cook --- lib/tests/stackinit_kunit.c | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/lib/tests/stackinit_kunit.c b/lib/tests/stackinit_kunit.c index 135322592faf..63aa78e6f5c1 100644 --- a/lib/tests/stackinit_kunit.c +++ b/lib/tests/stackinit_kunit.c @@ -184,6 +184,15 @@ static bool stackinit_range_contains(char *haystack_start, size_t haystack_size, #define INIT_UNION_assigned_copy(var_type) \ INIT_STRUCT_assigned_copy(var_type) +/* + * The "did we actually fill the stack?" check value needs + * to be neither 0 nor any of the "pattern" bytes. The + * pattern bytes are compiler, architecture, and type based, + * so we have to pick a value that never appears for those + * combinations. Use 0x99 which is not 0xFF, 0xFE, nor 0xAA. + */ +#define FILL_BYTE 0x99 + /* * @name: unique string name for the test * @var_type: type to be tested for zeroing initialization @@ -206,12 +215,12 @@ static noinline void test_ ## name (struct kunit *test) \ ZERO_CLONE_ ## which(zero); \ /* Clear entire check buffer for 0xFF overlap test. */ \ memset(check_buf, 0x00, sizeof(check_buf)); \ - /* Fill stack with 0xFF. */ \ + /* Fill stack with FILL_BYTE. */ \ ignored = leaf_ ##name((unsigned long)&ignored, 1, \ FETCH_ARG_ ## which(zero)); \ - /* Verify all bytes overwritten with 0xFF. */ \ + /* Verify all bytes overwritten with FILL_BYTE. */ \ for (sum = 0, i = 0; i < target_size; i++) \ - sum += (check_buf[i] != 0xFF); \ + sum += (check_buf[i] != FILL_BYTE); \ /* Clear entire check buffer for later bit tests. */ \ memset(check_buf, 0x00, sizeof(check_buf)); \ /* Extract stack-defined variable contents. */ \ @@ -222,7 +231,8 @@ static noinline void test_ ## name (struct kunit *test) \ * possible between the two leaf function calls. \ */ \ KUNIT_ASSERT_EQ_MSG(test, sum, 0, \ - "leaf fill was not 0xFF!?\n"); \ + "leaf fill was not 0x%02X!?\n", \ + FILL_BYTE); \ \ /* Validate that compiler lined up fill and target. */ \ KUNIT_ASSERT_TRUE_MSG(test, \ @@ -234,9 +244,9 @@ static noinline void test_ ## name (struct kunit *test) \ (int)((ssize_t)(uintptr_t)fill_start - \ (ssize_t)(uintptr_t)target_start)); \ \ - /* Look for any bytes still 0xFF in check region. */ \ + /* Validate check region has no FILL_BYTE bytes. */ \ for (sum = 0, i = 0; i < target_size; i++) \ - sum += (check_buf[i] == 0xFF); \ + sum += (check_buf[i] == FILL_BYTE); \ \ if (sum != 0 && xfail) \ kunit_skip(test, \ @@ -271,12 +281,12 @@ static noinline int leaf_ ## name(unsigned long sp, bool fill, \ * stack frame of SOME kind... \ */ \ memset(buf, (char)(sp & 0xff), sizeof(buf)); \ - /* Fill variable with 0xFF. */ \ + /* Fill variable with FILL_BYTE. */ \ if (fill) { \ fill_start = &var; \ fill_size = sizeof(var); \ memset(fill_start, \ - (char)((sp & 0xff) | forced_mask), \ + FILL_BYTE & forced_mask, \ fill_size); \ } \ \ @@ -469,7 +479,7 @@ static int noinline __leaf_switch_none(int path, bool fill) fill_start = &var; fill_size = sizeof(var); - memset(fill_start, forced_mask | 0x55, fill_size); + memset(fill_start, (forced_mask | 0x55) & FILL_BYTE, fill_size); } memcpy(check_buf, target_start, target_size); break; @@ -480,7 +490,7 @@ static int noinline __leaf_switch_none(int path, bool fill) fill_start = &var; fill_size = sizeof(var); - memset(fill_start, forced_mask | 0xaa, fill_size); + memset(fill_start, (forced_mask | 0xaa) & FILL_BYTE, fill_size); } memcpy(check_buf, target_start, target_size); break; -- 2.51.0 From 416cf1f4d91bf52305cd160a382273ccef980b7f Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Tue, 11 Mar 2025 17:03:56 -0700 Subject: [PATCH 09/16] kunit/fortify: Expand testing of __compiletime_strlen() It seems that Clang thinks __builtin_constant_p() of undefined variables should return true[1]. This is being fixed separately[2], but in the meantime, expand the fortify tests to help track this kind of thing down faster in the future. Link: https://github.com/ClangBuiltLinux/linux/issues/2073 [1] Link: https://github.com/llvm/llvm-project/pull/130713 [2] Link: https://lore.kernel.org/r/20250312000349.work.786-kees@kernel.org Signed-off-by: Kees Cook --- lib/tests/fortify_kunit.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/tests/fortify_kunit.c b/lib/tests/fortify_kunit.c index ecb638d4cde1..18dcdedf777f 100644 --- a/lib/tests/fortify_kunit.c +++ b/lib/tests/fortify_kunit.c @@ -60,6 +60,7 @@ static int fortify_write_overflows; static const char array_of_10[] = "this is 10"; static const char *ptr_of_11 = "this is 11!"; +static const char * const unchanging_12 = "this is 12!!"; static char array_unknown[] = "compiler thinks I might change"; void fortify_add_kunit_error(int write) @@ -83,12 +84,28 @@ void fortify_add_kunit_error(int write) static void fortify_test_known_sizes(struct kunit *test) { + char stack[80] = "Test!"; + + KUNIT_EXPECT_FALSE(test, __is_constexpr(__builtin_strlen(stack))); + KUNIT_EXPECT_EQ(test, __compiletime_strlen(stack), 5); + + KUNIT_EXPECT_TRUE(test, __is_constexpr(__builtin_strlen("88888888"))); KUNIT_EXPECT_EQ(test, __compiletime_strlen("88888888"), 8); + + KUNIT_EXPECT_TRUE(test, __is_constexpr(__builtin_strlen(array_of_10))); KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_of_10), 10); + + KUNIT_EXPECT_FALSE(test, __is_constexpr(__builtin_strlen(ptr_of_11))); KUNIT_EXPECT_EQ(test, __compiletime_strlen(ptr_of_11), 11); + KUNIT_EXPECT_TRUE(test, __is_constexpr(__builtin_strlen(unchanging_12))); + KUNIT_EXPECT_EQ(test, __compiletime_strlen(unchanging_12), 12); + + KUNIT_EXPECT_FALSE(test, __is_constexpr(__builtin_strlen(array_unknown))); KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_unknown), SIZE_MAX); + /* Externally defined and dynamically sized string pointer: */ + KUNIT_EXPECT_FALSE(test, __is_constexpr(__builtin_strlen(test->name))); KUNIT_EXPECT_EQ(test, __compiletime_strlen(test->name), SIZE_MAX); } -- 2.51.0 From 6ee149f61bcce39692f0335a01e99355d4cec8da Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Tue, 11 Mar 2025 17:04:40 -0700 Subject: [PATCH 10/16] kunit/fortify: Replace "volatile" with OPTIMIZER_HIDE_VAR() It does seem that using "volatile" isn't going to be sane compared to using OPTIMIZER_HIDE_VAR() going forward. Some strange interactions[1] with the sanitizers have been observed in the self-test code, so replace the logic. Reported-by: Nathan Chancellor Closes: https://github.com/ClangBuiltLinux/linux/issues/2075 [1] Link: https://lore.kernel.org/r/20250312000439.work.112-kees@kernel.org Signed-off-by: Kees Cook --- lib/tests/fortify_kunit.c | 139 +++++++++++++++++++++----------------- 1 file changed, 77 insertions(+), 62 deletions(-) diff --git a/lib/tests/fortify_kunit.c b/lib/tests/fortify_kunit.c index 18dcdedf777f..29ffc62a71e3 100644 --- a/lib/tests/fortify_kunit.c +++ b/lib/tests/fortify_kunit.c @@ -411,8 +411,6 @@ struct fortify_padding { char buf[32]; unsigned long bytes_after; }; -/* Force compiler into not being able to resolve size at compile-time. */ -static volatile int unconst; static void fortify_test_strlen(struct kunit *test) { @@ -537,57 +535,56 @@ static void fortify_test_strncpy(struct kunit *test) { struct fortify_padding pad = { }; char src[] = "Copy me fully into a small buffer and I will overflow!"; + size_t sizeof_buf = sizeof(pad.buf); + + OPTIMIZER_HIDE_VAR(sizeof_buf); /* Destination is %NUL-filled to start with. */ KUNIT_EXPECT_EQ(test, pad.bytes_before, 0); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 3], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 3], '\0'); KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); /* Legitimate strncpy() 1 less than of max size. */ - KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, - sizeof(pad.buf) + unconst - 1) + KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, sizeof_buf - 1) == pad.buf); KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); /* Only last byte should be %NUL */ - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 3], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 3], '\0'); /* Legitimate (though unterminated) max-size strncpy. */ - KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, - sizeof(pad.buf) + unconst) + KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, sizeof_buf) == pad.buf); KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); /* No trailing %NUL -- thanks strncpy API. */ - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* But we will not have gone beyond. */ KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); /* Now verify that FORTIFY is working... */ - KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, - sizeof(pad.buf) + unconst + 1) + KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, sizeof_buf + 1) == pad.buf); /* Should catch the overflow. */ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 1); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* And we will not have gone beyond. */ KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); /* And further... */ - KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, - sizeof(pad.buf) + unconst + 2) + KUNIT_ASSERT_TRUE(test, strncpy(pad.buf, src, sizeof_buf + 2) == pad.buf); /* Should catch the overflow. */ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 2); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* And we will not have gone beyond. */ KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); } @@ -596,55 +593,56 @@ static void fortify_test_strscpy(struct kunit *test) { struct fortify_padding pad = { }; char src[] = "Copy me fully into a small buffer and I will overflow!"; + size_t sizeof_buf = sizeof(pad.buf); + size_t sizeof_src = sizeof(src); + + OPTIMIZER_HIDE_VAR(sizeof_buf); + OPTIMIZER_HIDE_VAR(sizeof_src); /* Destination is %NUL-filled to start with. */ KUNIT_EXPECT_EQ(test, pad.bytes_before, 0); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 3], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 3], '\0'); KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); /* Legitimate strscpy() 1 less than of max size. */ - KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, - sizeof(pad.buf) + unconst - 1), + KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, sizeof_buf - 1), -E2BIG); KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); /* Keeping space for %NUL, last two bytes should be %NUL */ - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 3], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 3], '\0'); /* Legitimate max-size strscpy. */ - KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, - sizeof(pad.buf) + unconst), + KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, sizeof_buf), -E2BIG); KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); /* A trailing %NUL will exist. */ - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* Now verify that FORTIFY is working... */ - KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, - sizeof(pad.buf) + unconst + 1), + KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, sizeof_buf + 1), -E2BIG); /* Should catch the overflow. */ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 1); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* And we will not have gone beyond. */ KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); /* And much further... */ - KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, - sizeof(src) * 2 + unconst), + KUNIT_ASSERT_EQ(test, strscpy(pad.buf, src, sizeof_src * 2), -E2BIG); /* Should catch the overflow. */ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 2); - KUNIT_EXPECT_EQ(test, pad.buf[sizeof(pad.buf) - 1], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); - KUNIT_EXPECT_NE(test, pad.buf[sizeof(pad.buf) - 2], '\0'); + KUNIT_EXPECT_EQ(test, pad.buf[sizeof_buf - 1], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); + KUNIT_EXPECT_NE(test, pad.buf[sizeof_buf - 2], '\0'); /* And we will not have gone beyond. */ KUNIT_EXPECT_EQ(test, pad.bytes_after, 0); } @@ -784,7 +782,9 @@ static void fortify_test_strlcat(struct kunit *test) struct fortify_padding pad = { }; char src[sizeof(pad.buf)] = { }; int i, partial; - int len = sizeof(pad.buf) + unconst; + int len = sizeof(pad.buf); + + OPTIMIZER_HIDE_VAR(len); /* Fill 15 bytes with valid characters. */ partial = sizeof(src) / 2 - 1; @@ -874,28 +874,32 @@ struct fortify_zero_sized { #define __fortify_test(memfunc) \ static void fortify_test_##memfunc(struct kunit *test) \ { \ - struct fortify_zero_sized zero = { }; \ + struct fortify_zero_sized empty = { }; \ struct fortify_padding pad = { }; \ char srcA[sizeof(pad.buf) + 2]; \ char srcB[sizeof(pad.buf) + 2]; \ - size_t len = sizeof(pad.buf) + unconst; \ + size_t len = sizeof(pad.buf); \ + size_t zero = 0; \ + \ + OPTIMIZER_HIDE_VAR(len); \ + OPTIMIZER_HIDE_VAR(zero); \ \ memset(srcA, 'A', sizeof(srcA)); \ KUNIT_ASSERT_EQ(test, srcA[0], 'A'); \ memset(srcB, 'B', sizeof(srcB)); \ KUNIT_ASSERT_EQ(test, srcB[0], 'B'); \ \ - memfunc(pad.buf, srcA, 0 + unconst); \ + memfunc(pad.buf, srcA, zero); \ KUNIT_EXPECT_EQ(test, pad.buf[0], '\0'); \ KUNIT_EXPECT_EQ(test, fortify_read_overflows, 0); \ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); \ - memfunc(pad.buf + 1, srcB, 1 + unconst); \ + memfunc(pad.buf + 1, srcB, zero + 1); \ KUNIT_EXPECT_EQ(test, pad.buf[0], '\0'); \ KUNIT_EXPECT_EQ(test, pad.buf[1], 'B'); \ KUNIT_EXPECT_EQ(test, pad.buf[2], '\0'); \ KUNIT_EXPECT_EQ(test, fortify_read_overflows, 0); \ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); \ - memfunc(pad.buf, srcA, 1 + unconst); \ + memfunc(pad.buf, srcA, zero + 1); \ KUNIT_EXPECT_EQ(test, pad.buf[0], 'A'); \ KUNIT_EXPECT_EQ(test, pad.buf[1], 'B'); \ KUNIT_EXPECT_EQ(test, fortify_read_overflows, 0); \ @@ -921,10 +925,10 @@ static void fortify_test_##memfunc(struct kunit *test) \ /* Reset error counter. */ \ fortify_write_overflows = 0; \ /* Copy nothing into nothing: no errors. */ \ - memfunc(zero.buf, srcB, 0 + unconst); \ + memfunc(empty.buf, srcB, zero); \ KUNIT_EXPECT_EQ(test, fortify_read_overflows, 0); \ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 0); \ - memfunc(zero.buf, srcB, 1 + unconst); \ + memfunc(empty.buf, srcB, zero + 1); \ KUNIT_EXPECT_EQ(test, fortify_read_overflows, 0); \ KUNIT_EXPECT_EQ(test, fortify_write_overflows, 1); \ } @@ -936,7 +940,9 @@ static void fortify_test_memscan(struct kunit *test) char haystack[] = "Where oh where is my memory range?"; char *mem = haystack + strlen("Where oh where is "); char needle = 'm'; - size_t len = sizeof(haystack) + unconst; + size_t len = sizeof(haystack); + + OPTIMIZER_HIDE_VAR(len); KUNIT_ASSERT_PTR_EQ(test, memscan(haystack, needle, len), mem); @@ -955,7 +961,9 @@ static void fortify_test_memchr(struct kunit *test) char haystack[] = "Where oh where is my memory range?"; char *mem = haystack + strlen("Where oh where is "); char needle = 'm'; - size_t len = sizeof(haystack) + unconst; + size_t len = sizeof(haystack); + + OPTIMIZER_HIDE_VAR(len); KUNIT_ASSERT_PTR_EQ(test, memchr(haystack, needle, len), mem); @@ -974,7 +982,9 @@ static void fortify_test_memchr_inv(struct kunit *test) char haystack[] = "Where oh where is my memory range?"; char *mem = haystack + 1; char needle = 'W'; - size_t len = sizeof(haystack) + unconst; + size_t len = sizeof(haystack); + + OPTIMIZER_HIDE_VAR(len); /* Normal search is okay. */ KUNIT_ASSERT_PTR_EQ(test, memchr_inv(haystack, needle, len), @@ -993,8 +1003,11 @@ static void fortify_test_memcmp(struct kunit *test) { char one[] = "My mind is going ..."; char two[] = "My mind is going ... I can feel it."; - size_t one_len = sizeof(one) + unconst - 1; - size_t two_len = sizeof(two) + unconst - 1; + size_t one_len = sizeof(one) - 1; + size_t two_len = sizeof(two) - 1; + + OPTIMIZER_HIDE_VAR(one_len); + OPTIMIZER_HIDE_VAR(two_len); /* We match the first string (ignoring the %NUL). */ KUNIT_ASSERT_EQ(test, memcmp(one, two, one_len), 0); @@ -1015,7 +1028,9 @@ static void fortify_test_kmemdup(struct kunit *test) { char src[] = "I got Doom running on it!"; char *copy; - size_t len = sizeof(src) + unconst; + size_t len = sizeof(src); + + OPTIMIZER_HIDE_VAR(len); /* Copy is within bounds. */ copy = kmemdup(src, len, GFP_KERNEL); -- 2.51.0 From 7a79e7daa84e230266184a2018507551086c2317 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 17:08:56 -0500 Subject: [PATCH 11/16] printf: convert self-test to KUnit Convert the printf() self-test to a KUnit test. In the interest of keeping the patch reasonably-sized this doesn't refactor the tests into proper parameterized tests - it's all one big test case. Signed-off-by: Tamir Duberstein Reviewed-by: Petr Mladek Tested-by: Petr Mladek Link: https://lore.kernel.org/r/20250307-printf-kunit-convert-v6-1-4d85c361c241@gmail.com Signed-off-by: Kees Cook --- Documentation/core-api/printk-formats.rst | 4 +- Documentation/dev-tools/kselftest.rst | 2 +- MAINTAINERS | 2 +- lib/Kconfig.debug | 12 +- lib/Makefile | 1 - lib/tests/Makefile | 1 + lib/{test_printf.c => tests/printf_kunit.c} | 207 +++++++++++--------- tools/testing/selftests/kselftest/module.sh | 2 +- tools/testing/selftests/lib/Makefile | 2 +- tools/testing/selftests/lib/config | 1 - tools/testing/selftests/lib/printf.sh | 4 - 11 files changed, 132 insertions(+), 106 deletions(-) rename lib/{test_printf.c => tests/printf_kunit.c} (85%) delete mode 100755 tools/testing/selftests/lib/printf.sh diff --git a/Documentation/core-api/printk-formats.rst b/Documentation/core-api/printk-formats.rst index ecccc0473da9..4bdc394e86af 100644 --- a/Documentation/core-api/printk-formats.rst +++ b/Documentation/core-api/printk-formats.rst @@ -661,7 +661,7 @@ Do *not* use it from C. Thanks ====== -If you add other %p extensions, please extend with -one or more test cases, if at all feasible. +If you add other %p extensions, please extend +with one or more test cases, if at all feasible. Thank you for your cooperation and attention. diff --git a/Documentation/dev-tools/kselftest.rst b/Documentation/dev-tools/kselftest.rst index fdb1df86783a..18c2da67fae4 100644 --- a/Documentation/dev-tools/kselftest.rst +++ b/Documentation/dev-tools/kselftest.rst @@ -347,7 +347,7 @@ kselftest. We use kselftests for lib/ as an example. 1. Create the test module 2. Create the test script that will run (load/unload) the module - e.g. ``tools/testing/selftests/lib/printf.sh`` + e.g. ``tools/testing/selftests/lib/bitmap.sh`` 3. Add line to config file e.g. ``tools/testing/selftests/lib/config`` diff --git a/MAINTAINERS b/MAINTAINERS index 8f37e238bf55..2a476c2a6ab9 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -25411,8 +25411,8 @@ R: Sergey Senozhatsky S: Maintained T: git git://git.kernel.org/pub/scm/linux/kernel/git/printk/linux.git F: Documentation/core-api/printk-formats.rst -F: lib/test_printf.c F: lib/test_scanf.c +F: lib/tests/printf_kunit.c F: lib/vsprintf.c VT1211 HARDWARE MONITOR DRIVER diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index 7e548b9e36b7..443036c36351 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -2427,6 +2427,15 @@ config ASYNC_RAID6_TEST config TEST_HEXDUMP tristate "Test functions located in the hexdump module at runtime" +config PRINTF_KUNIT_TEST + tristate "KUnit test printf() family of functions at runtime" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Enable this option to test the printf functions at runtime. + + If unsure, say N. + config STRING_KUNIT_TEST tristate "KUnit test string functions at runtime" if !KUNIT_ALL_TESTS depends on KUNIT @@ -2440,9 +2449,6 @@ config STRING_HELPERS_KUNIT_TEST config TEST_KSTRTOX tristate "Test kstrto*() family of functions at runtime" -config TEST_PRINTF - tristate "Test printf() family of functions at runtime" - config TEST_SCANF tristate "Test scanf() family of functions at runtime" diff --git a/lib/Makefile b/lib/Makefile index 1e886482a6a3..b618d9d913bc 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -77,7 +77,6 @@ obj-$(CONFIG_TEST_RHASHTABLE) += test_rhashtable.o obj-$(CONFIG_TEST_STATIC_KEYS) += test_static_keys.o obj-$(CONFIG_TEST_STATIC_KEYS) += test_static_key_base.o obj-$(CONFIG_TEST_DYNAMIC_DEBUG) += test_dynamic_debug.o -obj-$(CONFIG_TEST_PRINTF) += test_printf.o obj-$(CONFIG_TEST_SCANF) += test_scanf.o obj-$(CONFIG_TEST_BITMAP) += test_bitmap.o diff --git a/lib/tests/Makefile b/lib/tests/Makefile index 8696d778d92f..33e02744ec62 100644 --- a/lib/tests/Makefile +++ b/lib/tests/Makefile @@ -29,6 +29,7 @@ obj-$(CONFIG_LINEAR_RANGES_TEST) += test_linear_ranges.o obj-$(CONFIG_MEMCPY_KUNIT_TEST) += memcpy_kunit.o CFLAGS_overflow_kunit.o = $(call cc-disable-warning, tautological-constant-out-of-range-compare) obj-$(CONFIG_OVERFLOW_KUNIT_TEST) += overflow_kunit.o +obj-$(CONFIG_PRINTF_KUNIT_TEST) += printf_kunit.o obj-$(CONFIG_SIPHASH_KUNIT_TEST) += siphash_kunit.o obj-$(CONFIG_SLUB_KUNIT_TEST) += slub_kunit.o obj-$(CONFIG_TEST_SORT) += test_sort.o diff --git a/lib/test_printf.c b/lib/tests/printf_kunit.c similarity index 85% rename from lib/test_printf.c rename to lib/tests/printf_kunit.c index 59dbe4f9a4cb..1f4096b015c6 100644 --- a/lib/test_printf.c +++ b/lib/tests/printf_kunit.c @@ -3,9 +3,7 @@ * Test cases for printf facility. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt - -#include +#include #include #include #include @@ -25,8 +23,6 @@ #include -#include "../tools/testing/selftests/kselftest_module.h" - #define BUF_SIZE 256 #define PAD_SIZE 16 #define FILL_CHAR '$' @@ -37,12 +33,14 @@ block \ __diag_pop(); -KSTM_MODULE_GLOBALS(); +static unsigned int total_tests; -static char *test_buffer __initdata; -static char *alloced_buffer __initdata; +static char *test_buffer; +static char *alloced_buffer; -static int __printf(4, 0) __init +static struct kunit *kunittest; + +static void __printf(4, 0) do_test(int bufsize, const char *expect, int elen, const char *fmt, va_list ap) { @@ -57,52 +55,54 @@ do_test(int bufsize, const char *expect, int elen, va_end(aq); if (ret != elen) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) returned %d, expected %d\n", - bufsize, fmt, ret, elen); - return 1; + KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) returned %d, expected %d\n", + bufsize, fmt, ret, elen); + return; } if (memchr_inv(alloced_buffer, FILL_CHAR, PAD_SIZE)) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) wrote before buffer\n", bufsize, fmt); - return 1; + KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) wrote before buffer\n", + bufsize, fmt); + return; } if (!bufsize) { if (memchr_inv(test_buffer, FILL_CHAR, BUF_SIZE + PAD_SIZE)) { - pr_warn("vsnprintf(buf, 0, \"%s\", ...) wrote to buffer\n", - fmt); - return 1; + KUNIT_FAIL(kunittest, "vsnprintf(buf, 0, \"%s\", ...) wrote to buffer\n", fmt); } - return 0; + return; } written = min(bufsize-1, elen); if (test_buffer[written]) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) did not nul-terminate buffer\n", - bufsize, fmt); - return 1; + KUNIT_FAIL(kunittest, + "vsnprintf(buf, %d, \"%s\", ...) did not nul-terminate buffer\n", + bufsize, fmt); + return; } if (memchr_inv(test_buffer + written + 1, FILL_CHAR, bufsize - (written + 1))) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) wrote beyond the nul-terminator\n", - bufsize, fmt); - return 1; + KUNIT_FAIL(kunittest, + "vsnprintf(buf, %d, \"%s\", ...) wrote beyond the nul-terminator\n", + bufsize, fmt); + return; } if (memchr_inv(test_buffer + bufsize, FILL_CHAR, BUF_SIZE + PAD_SIZE - bufsize)) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) wrote beyond buffer\n", bufsize, fmt); - return 1; + KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) wrote beyond buffer\n", + bufsize, fmt); + return; } if (memcmp(test_buffer, expect, written)) { - pr_warn("vsnprintf(buf, %d, \"%s\", ...) wrote '%s', expected '%.*s'\n", - bufsize, fmt, test_buffer, written, expect); - return 1; + KUNIT_FAIL(kunittest, + "vsnprintf(buf, %d, \"%s\", ...) wrote '%s', expected '%.*s'\n", + bufsize, fmt, test_buffer, written, expect); + return; } - return 0; } -static void __printf(3, 4) __init +static void __printf(3, 4) __test(const char *expect, int elen, const char *fmt, ...) { va_list ap; @@ -110,9 +110,9 @@ __test(const char *expect, int elen, const char *fmt, ...) char *p; if (elen >= BUF_SIZE) { - pr_err("error in test suite: expected output length %d too long. Format was '%s'.\n", - elen, fmt); - failed_tests++; + KUNIT_FAIL(kunittest, + "error in test suite: expected length (%d) >= BUF_SIZE (%d). fmt=\"%s\"\n", + elen, BUF_SIZE, fmt); return; } @@ -124,19 +124,19 @@ __test(const char *expect, int elen, const char *fmt, ...) * enough and 0), and then we also test that kvasprintf would * be able to print it as expected. */ - failed_tests += do_test(BUF_SIZE, expect, elen, fmt, ap); + do_test(BUF_SIZE, expect, elen, fmt, ap); rand = get_random_u32_inclusive(1, elen + 1); /* Since elen < BUF_SIZE, we have 1 <= rand <= BUF_SIZE. */ - failed_tests += do_test(rand, expect, elen, fmt, ap); - failed_tests += do_test(0, expect, elen, fmt, ap); + do_test(rand, expect, elen, fmt, ap); + do_test(0, expect, elen, fmt, ap); p = kvasprintf(GFP_KERNEL, fmt, ap); if (p) { total_tests++; if (memcmp(p, expect, elen+1)) { - pr_warn("kvasprintf(..., \"%s\", ...) returned '%s', expected '%s'\n", - fmt, p, expect); - failed_tests++; + KUNIT_FAIL(kunittest, + "kvasprintf(..., \"%s\", ...) returned '%s', expected '%s'\n", + fmt, p, expect); } kfree(p); } @@ -146,7 +146,7 @@ __test(const char *expect, int elen, const char *fmt, ...) #define test(expect, fmt, ...) \ __test(expect, strlen(expect), fmt, ##__VA_ARGS__) -static void __init +static void test_basic(void) { /* Work around annoying "warning: zero-length gnu_printf format string". */ @@ -158,7 +158,7 @@ test_basic(void) __test("xxx\0yyy", 7, "xxx%cyyy", '\0'); } -static void __init +static void test_number(void) { test("0x1234abcd ", "%#-12x", 0x1234abcd); @@ -180,7 +180,7 @@ test_number(void) test("00|0|0|0|0", "%.2d|%.1d|%.0d|%.*d|%1.0d", 0, 0, 0, 0, 0, 0); } -static void __init +static void test_string(void) { test("", "%s%.0s", "", "123"); @@ -218,7 +218,7 @@ test_string(void) #define ZEROS "00000000" /* hex 32 zero bits */ #define ONES "ffffffff" /* hex 32 one bits */ -static int __init +static int plain_format(void) { char buf[PLAIN_BUF_SIZE]; @@ -230,8 +230,9 @@ plain_format(void) return -1; if (strncmp(buf, PTR_VAL_NO_CRNG, PTR_WIDTH) == 0) { - pr_warn("crng possibly not yet initialized. plain 'p' buffer contains \"%s\"", - PTR_VAL_NO_CRNG); + kunit_warn(kunittest, + "crng possibly not yet initialized. plain 'p' buffer contains \"%s\"\n", + PTR_VAL_NO_CRNG); return 0; } @@ -250,7 +251,7 @@ plain_format(void) #define ZEROS "" #define ONES "" -static int __init +static int plain_format(void) { /* Format is implicitly tested for 32 bit machines by plain_hash() */ @@ -259,7 +260,7 @@ plain_format(void) #endif /* BITS_PER_LONG == 64 */ -static int __init +static int plain_hash_to_buffer(const void *p, char *buf, size_t len) { int nchars; @@ -270,15 +271,16 @@ plain_hash_to_buffer(const void *p, char *buf, size_t len) return -1; if (strncmp(buf, PTR_VAL_NO_CRNG, PTR_WIDTH) == 0) { - pr_warn("crng possibly not yet initialized. plain 'p' buffer contains \"%s\"", - PTR_VAL_NO_CRNG); + kunit_warn(kunittest, + "crng possibly not yet initialized. plain 'p' buffer contains \"%s\"\n", + PTR_VAL_NO_CRNG); return 0; } return 0; } -static int __init +static int plain_hash(void) { char buf[PLAIN_BUF_SIZE]; @@ -298,32 +300,29 @@ plain_hash(void) * We can't use test() to test %p because we don't know what output to expect * after an address is hashed. */ -static void __init +static void plain(void) { int err; if (no_hash_pointers) { - pr_warn("skipping plain 'p' tests"); - skipped_tests += 2; + kunit_warn(kunittest, "skipping plain 'p' tests"); return; } err = plain_hash(); if (err) { - pr_warn("plain 'p' does not appear to be hashed\n"); - failed_tests++; + KUNIT_FAIL(kunittest, "plain 'p' does not appear to be hashed\n"); return; } err = plain_format(); if (err) { - pr_warn("hashing plain 'p' has unexpected format\n"); - failed_tests++; + KUNIT_FAIL(kunittest, "hashing plain 'p' has unexpected format\n"); } } -static void __init +static void test_hashed(const char *fmt, const void *p) { char buf[PLAIN_BUF_SIZE]; @@ -343,7 +342,7 @@ test_hashed(const char *fmt, const void *p) /* * NULL pointers aren't hashed. */ -static void __init +static void null_pointer(void) { test(ZEROS "00000000", "%p", NULL); @@ -354,7 +353,7 @@ null_pointer(void) /* * Error pointers aren't hashed. */ -static void __init +static void error_pointer(void) { test(ONES "fffffff5", "%p", ERR_PTR(-11)); @@ -364,7 +363,7 @@ error_pointer(void) #define PTR_INVALID ((void *)0x000000ab) -static void __init +static void invalid_pointer(void) { test_hashed("%p", PTR_INVALID); @@ -372,18 +371,18 @@ invalid_pointer(void) test("(efault)", "%pE", PTR_INVALID); } -static void __init +static void symbol_ptr(void) { } -static void __init +static void kernel_ptr(void) { /* We can't test this without access to kptr_restrict. */ } -static void __init +static void struct_resource(void) { struct resource test_resource = { @@ -432,7 +431,7 @@ struct_resource(void) "%pR", &test_resource); } -static void __init +static void struct_range(void) { struct range test_range = DEFINE_RANGE(0xc0ffee00ba5eba11, @@ -448,17 +447,17 @@ struct_range(void) "%pra", &test_range); } -static void __init +static void addr(void) { } -static void __init +static void escaped_str(void) { } -static void __init +static void hex_string(void) { const char buf[3] = {0xc0, 0xff, 0xee}; @@ -469,7 +468,7 @@ hex_string(void) "%*ph|%*phC|%*phD|%*phN", 3, buf, 3, buf, 3, buf, 3, buf); } -static void __init +static void mac(void) { const u8 addr[6] = {0x2d, 0x48, 0xd6, 0xfc, 0x7a, 0x05}; @@ -481,7 +480,7 @@ mac(void) test("057afcd6482d", "%pmR", addr); } -static void __init +static void ip4(void) { struct sockaddr_in sa; @@ -496,19 +495,19 @@ ip4(void) test("001.002.003.004:12345|1.2.3.4:12345", "%piSp|%pISp", &sa, &sa); } -static void __init +static void ip6(void) { } -static void __init +static void ip(void) { ip4(); ip6(); } -static void __init +static void uuid(void) { const char uuid[16] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, @@ -520,7 +519,7 @@ uuid(void) test("03020100-0504-0706-0809-0A0B0C0D0E0F", "%pUL", uuid); } -static struct dentry test_dentry[4] __initdata = { +static struct dentry test_dentry[4] = { { .d_parent = &test_dentry[0], .d_name = QSTR_INIT(test_dentry[0].d_iname, 3), .d_iname = "foo" }, @@ -535,7 +534,7 @@ static struct dentry test_dentry[4] __initdata = { .d_iname = "romeo" }, }; -static void __init +static void dentry(void) { test("foo", "%pd", &test_dentry[0]); @@ -556,12 +555,12 @@ dentry(void) test(" bravo/alfa| bravo/alfa", "%12pd2|%*pd2", &test_dentry[2], 12, &test_dentry[2]); } -static void __init +static void struct_va_format(void) { } -static void __init +static void time_and_date(void) { /* 1543210543 */ @@ -595,12 +594,12 @@ time_and_date(void) test("15:32:23|0119-00-04", "%ptTtrs|%ptTdrs", &t, &t); } -static void __init +static void struct_clk(void) { } -static void __init +static void large_bitmap(void) { const int nbits = 1 << 16; @@ -614,7 +613,7 @@ large_bitmap(void) bitmap_free(bits); } -static void __init +static void bitmap(void) { DECLARE_BITMAP(bits, 20); @@ -637,7 +636,7 @@ bitmap(void) large_bitmap(); } -static void __init +static void netdev_features(void) { } @@ -663,7 +662,7 @@ static const struct page_flags_test pft[] = { "%#x", "kasantag"}, }; -static void __init +static void page_flags_test(int section, int node, int zone, int last_cpupid, int kasan_tag, unsigned long flags, const char *name, char *cmp_buf) @@ -701,7 +700,7 @@ page_flags_test(int section, int node, int zone, int last_cpupid, test(cmp_buf, "%pGp", &flags); } -static void __init +static void flags(void) { unsigned long flags; @@ -749,7 +748,7 @@ flags(void) kfree(cmp_buffer); } -static void __init fwnode_pointer(void) +static void fwnode_pointer(void) { const struct software_node first = { .name = "first" }; const struct software_node second = { .name = "second", .parent = &first }; @@ -763,7 +762,7 @@ static void __init fwnode_pointer(void) rval = software_node_register_node_group(group); if (rval) { - pr_warn("cannot register softnodes; rval %d\n", rval); + kunit_warn(kunittest, "cannot register softnodes; rval %d\n", rval); return; } @@ -776,7 +775,7 @@ static void __init fwnode_pointer(void) software_node_unregister_node_group(group); } -static void __init fourcc_pointer(void) +static void fourcc_pointer(void) { struct { u32 code; @@ -793,7 +792,7 @@ static void __init fourcc_pointer(void) test(try[i].str, "%p4cc", &try[i].code); } -static void __init +static void errptr(void) { test("-1234", "%pe", ERR_PTR(-1234)); @@ -813,7 +812,7 @@ errptr(void) #endif } -static void __init +static void test_pointer(void) { plain(); @@ -842,13 +841,15 @@ test_pointer(void) fourcc_pointer(); } -static void __init selftest(void) +static void printf_test(struct kunit *test) { alloced_buffer = kmalloc(BUF_SIZE + 2*PAD_SIZE, GFP_KERNEL); if (!alloced_buffer) return; test_buffer = alloced_buffer + PAD_SIZE; + kunittest = test; + test_basic(); test_number(); test_string(); @@ -857,7 +858,31 @@ static void __init selftest(void) kfree(alloced_buffer); } -KSTM_MODULE_LOADERS(test_printf); +static int printf_suite_init(struct kunit_suite *suite) +{ + total_tests = 0; + return 0; +} + +static void printf_suite_exit(struct kunit_suite *suite) +{ + kunit_info(suite, "ran %u tests\n", total_tests); +} + +static struct kunit_case printf_test_cases[] = { + KUNIT_CASE(printf_test), + {} +}; + +static struct kunit_suite printf_test_suite = { + .name = "printf", + .suite_init = printf_suite_init, + .suite_exit = printf_suite_exit, + .test_cases = printf_test_cases, +}; + +kunit_test_suite(printf_test_suite); + MODULE_AUTHOR("Rasmus Villemoes "); MODULE_DESCRIPTION("Test cases for printf facility"); MODULE_LICENSE("GPL"); diff --git a/tools/testing/selftests/kselftest/module.sh b/tools/testing/selftests/kselftest/module.sh index fb4733faff12..51fb65159932 100755 --- a/tools/testing/selftests/kselftest/module.sh +++ b/tools/testing/selftests/kselftest/module.sh @@ -11,7 +11,7 @@ # SPDX-License-Identifier: GPL-2.0+ # $(dirname $0)/../kselftest/module.sh "description" module_name # -# Example: tools/testing/selftests/lib/printf.sh +# Example: tools/testing/selftests/lib/bitmap.sh desc="" # Output prefix. module="" # Filename (without the .ko). diff --git a/tools/testing/selftests/lib/Makefile b/tools/testing/selftests/lib/Makefile index 66dcbe2e39fa..befc4ab2c671 100644 --- a/tools/testing/selftests/lib/Makefile +++ b/tools/testing/selftests/lib/Makefile @@ -4,5 +4,5 @@ # No binaries, but make sure arg-less "make" doesn't trigger "run_tests" all: -TEST_PROGS := printf.sh bitmap.sh scanf.sh +TEST_PROGS := bitmap.sh scanf.sh include ../lib.mk diff --git a/tools/testing/selftests/lib/config b/tools/testing/selftests/lib/config index 306a3d4dca98..f4b4b8822241 100644 --- a/tools/testing/selftests/lib/config +++ b/tools/testing/selftests/lib/config @@ -1,4 +1,3 @@ -CONFIG_TEST_PRINTF=m CONFIG_TEST_SCANF=m CONFIG_TEST_BITMAP=m CONFIG_TEST_BITOPS=m diff --git a/tools/testing/selftests/lib/printf.sh b/tools/testing/selftests/lib/printf.sh deleted file mode 100755 index 05f4544e87f9..000000000000 --- a/tools/testing/selftests/lib/printf.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -# SPDX-License-Identifier: GPL-2.0 -# Tests the printf infrastructure using test_printf kernel module. -$(dirname $0)/../kselftest/module.sh "printf" test_printf -- 2.51.0 From 81a03aa9b88c5db19a6008a3dc43280637e45d84 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 17:08:57 -0500 Subject: [PATCH 12/16] printf: break kunit into test cases Move all tests into `printf_test_cases`. This gives us nicer output in the event of a failure. Combine `plain_format` and `plain_hash` into `hash_pointer` since they're testing the same scenario. Signed-off-by: Tamir Duberstein Reviewed-by: Petr Mladek Tested-by: Petr Mladek Link: https://lore.kernel.org/r/20250307-printf-kunit-convert-v6-2-4d85c361c241@gmail.com Signed-off-by: Kees Cook --- lib/tests/printf_kunit.c | 295 ++++++++++++++------------------------- 1 file changed, 102 insertions(+), 193 deletions(-) diff --git a/lib/tests/printf_kunit.c b/lib/tests/printf_kunit.c index 1f4096b015c6..dd373cb9036a 100644 --- a/lib/tests/printf_kunit.c +++ b/lib/tests/printf_kunit.c @@ -38,10 +38,8 @@ static unsigned int total_tests; static char *test_buffer; static char *alloced_buffer; -static struct kunit *kunittest; - -static void __printf(4, 0) -do_test(int bufsize, const char *expect, int elen, +static void __printf(5, 0) +do_test(struct kunit *kunittest, int bufsize, const char *expect, int elen, const char *fmt, va_list ap) { va_list aq; @@ -102,8 +100,8 @@ do_test(int bufsize, const char *expect, int elen, } } -static void __printf(3, 4) -__test(const char *expect, int elen, const char *fmt, ...) +static void __printf(4, 5) +__test(struct kunit *kunittest, const char *expect, int elen, const char *fmt, ...) { va_list ap; int rand; @@ -124,11 +122,11 @@ __test(const char *expect, int elen, const char *fmt, ...) * enough and 0), and then we also test that kvasprintf would * be able to print it as expected. */ - do_test(BUF_SIZE, expect, elen, fmt, ap); + do_test(kunittest, BUF_SIZE, expect, elen, fmt, ap); rand = get_random_u32_inclusive(1, elen + 1); /* Since elen < BUF_SIZE, we have 1 <= rand <= BUF_SIZE. */ - do_test(rand, expect, elen, fmt, ap); - do_test(0, expect, elen, fmt, ap); + do_test(kunittest, rand, expect, elen, fmt, ap); + do_test(kunittest, 0, expect, elen, fmt, ap); p = kvasprintf(GFP_KERNEL, fmt, ap); if (p) { @@ -144,10 +142,10 @@ __test(const char *expect, int elen, const char *fmt, ...) } #define test(expect, fmt, ...) \ - __test(expect, strlen(expect), fmt, ##__VA_ARGS__) + __test(kunittest, expect, strlen(expect), fmt, ##__VA_ARGS__) static void -test_basic(void) +test_basic(struct kunit *kunittest) { /* Work around annoying "warning: zero-length gnu_printf format string". */ char nul = '\0'; @@ -155,11 +153,11 @@ test_basic(void) test("", &nul); test("100%", "100%%"); test("xxx%yyy", "xxx%cyyy", '%'); - __test("xxx\0yyy", 7, "xxx%cyyy", '\0'); + __test(kunittest, "xxx\0yyy", 7, "xxx%cyyy", '\0'); } static void -test_number(void) +test_number(struct kunit *kunittest) { test("0x1234abcd ", "%#-12x", 0x1234abcd); test(" 0x1234abcd", "%#12x", 0x1234abcd); @@ -181,7 +179,7 @@ test_number(void) } static void -test_string(void) +test_string(struct kunit *kunittest) { test("", "%s%.0s", "", "123"); test("ABCD|abc|123", "%s|%.3s|%.*s", "ABCD", "abcdef", 3, "123456"); @@ -218,30 +216,6 @@ test_string(void) #define ZEROS "00000000" /* hex 32 zero bits */ #define ONES "ffffffff" /* hex 32 one bits */ -static int -plain_format(void) -{ - char buf[PLAIN_BUF_SIZE]; - int nchars; - - nchars = snprintf(buf, PLAIN_BUF_SIZE, "%p", PTR); - - if (nchars != PTR_WIDTH) - return -1; - - if (strncmp(buf, PTR_VAL_NO_CRNG, PTR_WIDTH) == 0) { - kunit_warn(kunittest, - "crng possibly not yet initialized. plain 'p' buffer contains \"%s\"\n", - PTR_VAL_NO_CRNG); - return 0; - } - - if (strncmp(buf, ZEROS, strlen(ZEROS)) != 0) - return -1; - - return 0; -} - #else #define PTR_WIDTH 8 @@ -251,90 +225,47 @@ plain_format(void) #define ZEROS "" #define ONES "" -static int -plain_format(void) -{ - /* Format is implicitly tested for 32 bit machines by plain_hash() */ - return 0; -} - #endif /* BITS_PER_LONG == 64 */ -static int -plain_hash_to_buffer(const void *p, char *buf, size_t len) +static void +plain_hash_to_buffer(struct kunit *kunittest, const void *p, char *buf, size_t len) { - int nchars; - - nchars = snprintf(buf, len, "%p", p); - - if (nchars != PTR_WIDTH) - return -1; + KUNIT_ASSERT_EQ(kunittest, snprintf(buf, len, "%p", p), PTR_WIDTH); if (strncmp(buf, PTR_VAL_NO_CRNG, PTR_WIDTH) == 0) { - kunit_warn(kunittest, + kunit_skip(kunittest, "crng possibly not yet initialized. plain 'p' buffer contains \"%s\"\n", PTR_VAL_NO_CRNG); - return 0; } - - return 0; } -static int -plain_hash(void) -{ - char buf[PLAIN_BUF_SIZE]; - int ret; - - ret = plain_hash_to_buffer(PTR, buf, PLAIN_BUF_SIZE); - if (ret) - return ret; - - if (strncmp(buf, PTR_STR, PTR_WIDTH) == 0) - return -1; - - return 0; -} - -/* - * We can't use test() to test %p because we don't know what output to expect - * after an address is hashed. - */ static void -plain(void) +hash_pointer(struct kunit *kunittest) { - int err; + if (no_hash_pointers) + kunit_skip(kunittest, "hash pointers disabled"); - if (no_hash_pointers) { - kunit_warn(kunittest, "skipping plain 'p' tests"); - return; - } + char buf[PLAIN_BUF_SIZE]; - err = plain_hash(); - if (err) { - KUNIT_FAIL(kunittest, "plain 'p' does not appear to be hashed\n"); - return; - } + plain_hash_to_buffer(kunittest, PTR, buf, PLAIN_BUF_SIZE); - err = plain_format(); - if (err) { - KUNIT_FAIL(kunittest, "hashing plain 'p' has unexpected format\n"); - } + /* + * The hash of %p is unpredictable, therefore test() cannot be used. + * + * Instead verify that the first 32 bits are zeros on a 64-bit system + * and that the non-hashed value is not printed. + */ + + KUNIT_EXPECT_MEMEQ(kunittest, buf, ZEROS, strlen(ZEROS)); + KUNIT_EXPECT_MEMNEQ(kunittest, buf, PTR_STR, PTR_WIDTH); } static void -test_hashed(const char *fmt, const void *p) +test_hashed(struct kunit *kunittest, const char *fmt, const void *p) { char buf[PLAIN_BUF_SIZE]; - int ret; - /* - * No need to increase failed test counter since this is assumed - * to be called after plain(). - */ - ret = plain_hash_to_buffer(p, buf, PLAIN_BUF_SIZE); - if (ret) - return; + plain_hash_to_buffer(kunittest, p, buf, PLAIN_BUF_SIZE); test(buf, fmt, p); } @@ -343,7 +274,7 @@ test_hashed(const char *fmt, const void *p) * NULL pointers aren't hashed. */ static void -null_pointer(void) +null_pointer(struct kunit *kunittest) { test(ZEROS "00000000", "%p", NULL); test(ZEROS "00000000", "%px", NULL); @@ -354,7 +285,7 @@ null_pointer(void) * Error pointers aren't hashed. */ static void -error_pointer(void) +error_pointer(struct kunit *kunittest) { test(ONES "fffffff5", "%p", ERR_PTR(-11)); test(ONES "fffffff5", "%px", ERR_PTR(-11)); @@ -364,26 +295,26 @@ error_pointer(void) #define PTR_INVALID ((void *)0x000000ab) static void -invalid_pointer(void) +invalid_pointer(struct kunit *kunittest) { - test_hashed("%p", PTR_INVALID); + test_hashed(kunittest, "%p", PTR_INVALID); test(ZEROS "000000ab", "%px", PTR_INVALID); test("(efault)", "%pE", PTR_INVALID); } static void -symbol_ptr(void) +symbol_ptr(struct kunit *kunittest) { } static void -kernel_ptr(void) +kernel_ptr(struct kunit *kunittest) { /* We can't test this without access to kptr_restrict. */ } static void -struct_resource(void) +struct_resource(struct kunit *kunittest) { struct resource test_resource = { .start = 0xc0ffee00, @@ -432,7 +363,7 @@ struct_resource(void) } static void -struct_range(void) +struct_range(struct kunit *kunittest) { struct range test_range = DEFINE_RANGE(0xc0ffee00ba5eba11, 0xc0ffee00ba5eba11); @@ -448,17 +379,17 @@ struct_range(void) } static void -addr(void) +addr(struct kunit *kunittest) { } static void -escaped_str(void) +escaped_str(struct kunit *kunittest) { } static void -hex_string(void) +hex_string(struct kunit *kunittest) { const char buf[3] = {0xc0, 0xff, 0xee}; @@ -469,7 +400,7 @@ hex_string(void) } static void -mac(void) +mac(struct kunit *kunittest) { const u8 addr[6] = {0x2d, 0x48, 0xd6, 0xfc, 0x7a, 0x05}; @@ -481,7 +412,7 @@ mac(void) } static void -ip4(void) +ip4(struct kunit *kunittest) { struct sockaddr_in sa; @@ -496,19 +427,12 @@ ip4(void) } static void -ip6(void) -{ -} - -static void -ip(void) +ip6(struct kunit *kunittest) { - ip4(); - ip6(); } static void -uuid(void) +uuid(struct kunit *kunittest) { const char uuid[16] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}; @@ -535,7 +459,7 @@ static struct dentry test_dentry[4] = { }; static void -dentry(void) +dentry(struct kunit *kunittest) { test("foo", "%pd", &test_dentry[0]); test("foo", "%pd2", &test_dentry[0]); @@ -556,12 +480,12 @@ dentry(void) } static void -struct_va_format(void) +struct_va_format(struct kunit *kunittest) { } static void -time_and_date(void) +time_and_date(struct kunit *kunittest) { /* 1543210543 */ const struct rtc_time tm = { @@ -595,12 +519,12 @@ time_and_date(void) } static void -struct_clk(void) +struct_clk(struct kunit *kunittest) { } static void -large_bitmap(void) +large_bitmap(struct kunit *kunittest) { const int nbits = 1 << 16; unsigned long *bits = bitmap_zalloc(nbits, GFP_KERNEL); @@ -614,7 +538,7 @@ large_bitmap(void) } static void -bitmap(void) +bitmap(struct kunit *kunittest) { DECLARE_BITMAP(bits, 20); const int primes[] = {2,3,5,7,11,13,17,19}; @@ -633,11 +557,11 @@ bitmap(void) test("fffff|fffff", "%20pb|%*pb", bits, 20, bits); test("0-19|0-19", "%20pbl|%*pbl", bits, 20, bits); - large_bitmap(); + large_bitmap(kunittest); } static void -netdev_features(void) +netdev_features(struct kunit *kunittest) { } @@ -663,8 +587,8 @@ static const struct page_flags_test pft[] = { }; static void -page_flags_test(int section, int node, int zone, int last_cpupid, - int kasan_tag, unsigned long flags, const char *name, +page_flags_test(struct kunit *kunittest, int section, int node, int zone, + int last_cpupid, int kasan_tag, unsigned long flags, const char *name, char *cmp_buf) { unsigned long values[] = {section, node, zone, last_cpupid, kasan_tag}; @@ -701,25 +625,24 @@ page_flags_test(int section, int node, int zone, int last_cpupid, } static void -flags(void) +flags(struct kunit *kunittest) { unsigned long flags; char *cmp_buffer; gfp_t gfp; - cmp_buffer = kmalloc(BUF_SIZE, GFP_KERNEL); - if (!cmp_buffer) - return; + cmp_buffer = kunit_kmalloc(kunittest, BUF_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(kunittest, cmp_buffer); flags = 0; - page_flags_test(0, 0, 0, 0, 0, flags, "", cmp_buffer); + page_flags_test(kunittest, 0, 0, 0, 0, 0, flags, "", cmp_buffer); flags = 1UL << NR_PAGEFLAGS; - page_flags_test(0, 0, 0, 0, 0, flags, "", cmp_buffer); + page_flags_test(kunittest, 0, 0, 0, 0, 0, flags, "", cmp_buffer); flags |= 1UL << PG_uptodate | 1UL << PG_dirty | 1UL << PG_lru | 1UL << PG_active | 1UL << PG_swapbacked; - page_flags_test(1, 1, 1, 0x1fffff, 1, flags, + page_flags_test(kunittest, 1, 1, 1, 0x1fffff, 1, flags, "uptodate|dirty|lru|active|swapbacked", cmp_buffer); @@ -744,11 +667,9 @@ flags(void) (unsigned long) gfp); gfp |= __GFP_HIGH; test(cmp_buffer, "%pGg", &gfp); - - kfree(cmp_buffer); } -static void fwnode_pointer(void) +static void fwnode_pointer(struct kunit *kunittest) { const struct software_node first = { .name = "first" }; const struct software_node second = { .name = "second", .parent = &first }; @@ -762,8 +683,7 @@ static void fwnode_pointer(void) rval = software_node_register_node_group(group); if (rval) { - kunit_warn(kunittest, "cannot register softnodes; rval %d\n", rval); - return; + kunit_skip(kunittest, "cannot register softnodes; rval %d\n", rval); } test(full_name_second, "%pfw", software_node_fwnode(&second)); @@ -775,7 +695,7 @@ static void fwnode_pointer(void) software_node_unregister_node_group(group); } -static void fourcc_pointer(void) +static void fourcc_pointer(struct kunit *kunittest) { struct { u32 code; @@ -793,13 +713,13 @@ static void fourcc_pointer(void) } static void -errptr(void) +errptr(struct kunit *kunittest) { test("-1234", "%pe", ERR_PTR(-1234)); /* Check that %pe with a non-ERR_PTR gets treated as ordinary %p. */ BUILD_BUG_ON(IS_ERR(PTR)); - test_hashed("%pe", PTR); + test_hashed(kunittest, "%pe", PTR); #ifdef CONFIG_SYMBOLIC_ERRNAME test("(-ENOTSOCK)", "(%pe)", ERR_PTR(-ENOTSOCK)); @@ -812,65 +732,54 @@ errptr(void) #endif } -static void -test_pointer(void) -{ - plain(); - null_pointer(); - error_pointer(); - invalid_pointer(); - symbol_ptr(); - kernel_ptr(); - struct_resource(); - struct_range(); - addr(); - escaped_str(); - hex_string(); - mac(); - ip(); - uuid(); - dentry(); - struct_va_format(); - time_and_date(); - struct_clk(); - bitmap(); - netdev_features(); - flags(); - errptr(); - fwnode_pointer(); - fourcc_pointer(); -} - -static void printf_test(struct kunit *test) +static int printf_suite_init(struct kunit_suite *suite) { + total_tests = 0; + alloced_buffer = kmalloc(BUF_SIZE + 2*PAD_SIZE, GFP_KERNEL); if (!alloced_buffer) - return; + return -ENOMEM; test_buffer = alloced_buffer + PAD_SIZE; - kunittest = test; - - test_basic(); - test_number(); - test_string(); - test_pointer(); - - kfree(alloced_buffer); -} - -static int printf_suite_init(struct kunit_suite *suite) -{ - total_tests = 0; return 0; } static void printf_suite_exit(struct kunit_suite *suite) { + kfree(alloced_buffer); + kunit_info(suite, "ran %u tests\n", total_tests); } static struct kunit_case printf_test_cases[] = { - KUNIT_CASE(printf_test), + KUNIT_CASE(test_basic), + KUNIT_CASE(test_number), + KUNIT_CASE(test_string), + KUNIT_CASE(hash_pointer), + KUNIT_CASE(null_pointer), + KUNIT_CASE(error_pointer), + KUNIT_CASE(invalid_pointer), + KUNIT_CASE(symbol_ptr), + KUNIT_CASE(kernel_ptr), + KUNIT_CASE(struct_resource), + KUNIT_CASE(struct_range), + KUNIT_CASE(addr), + KUNIT_CASE(escaped_str), + KUNIT_CASE(hex_string), + KUNIT_CASE(mac), + KUNIT_CASE(ip4), + KUNIT_CASE(ip6), + KUNIT_CASE(uuid), + KUNIT_CASE(dentry), + KUNIT_CASE(struct_va_format), + KUNIT_CASE(time_and_date), + KUNIT_CASE(struct_clk), + KUNIT_CASE(bitmap), + KUNIT_CASE(netdev_features), + KUNIT_CASE(flags), + KUNIT_CASE(errptr), + KUNIT_CASE(fwnode_pointer), + KUNIT_CASE(fourcc_pointer), {} }; -- 2.51.0 From 034bee685fd48101aff31591273258be0377b1ef Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 17:08:58 -0500 Subject: [PATCH 13/16] printf: implicate test line in failure messages This improves the failure output by pointing to the failing line at the top level of the test, e.g.: # test_number: EXPECTATION FAILED at lib/printf_kunit.c:103 lib/printf_kunit.c:167: vsnprintf(buf, 256, "%#-12x", ...) wrote '0x1234abcd ', expected '0x1234abce ' # test_number: EXPECTATION FAILED at lib/printf_kunit.c:142 lib/printf_kunit.c:167: kvasprintf(..., "%#-12x", ...) returned '0x1234abcd ', expected '0x1234abce ' Signed-off-by: Tamir Duberstein Reviewed-by: Petr Mladek Tested-by: Petr Mladek Link: https://lore.kernel.org/r/20250307-printf-kunit-convert-v6-3-4d85c361c241@gmail.com Signed-off-by: Kees Cook --- lib/tests/printf_kunit.c | 60 ++++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/lib/tests/printf_kunit.c b/lib/tests/printf_kunit.c index dd373cb9036a..2c9f6170bacd 100644 --- a/lib/tests/printf_kunit.c +++ b/lib/tests/printf_kunit.c @@ -38,9 +38,9 @@ static unsigned int total_tests; static char *test_buffer; static char *alloced_buffer; -static void __printf(5, 0) -do_test(struct kunit *kunittest, int bufsize, const char *expect, int elen, - const char *fmt, va_list ap) +static void __printf(7, 0) +do_test(struct kunit *kunittest, const char *file, const int line, int bufsize, const char *expect, + int elen, const char *fmt, va_list ap) { va_list aq; int ret, written; @@ -53,20 +53,24 @@ do_test(struct kunit *kunittest, int bufsize, const char *expect, int elen, va_end(aq); if (ret != elen) { - KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) returned %d, expected %d\n", - bufsize, fmt, ret, elen); + KUNIT_FAIL(kunittest, + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) returned %d, expected %d\n", + file, line, bufsize, fmt, ret, elen); return; } if (memchr_inv(alloced_buffer, FILL_CHAR, PAD_SIZE)) { - KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) wrote before buffer\n", - bufsize, fmt); + KUNIT_FAIL(kunittest, + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) wrote before buffer\n", + file, line, bufsize, fmt); return; } if (!bufsize) { if (memchr_inv(test_buffer, FILL_CHAR, BUF_SIZE + PAD_SIZE)) { - KUNIT_FAIL(kunittest, "vsnprintf(buf, 0, \"%s\", ...) wrote to buffer\n", fmt); + KUNIT_FAIL(kunittest, + "%s:%d: vsnprintf(buf, 0, \"%s\", ...) wrote to buffer\n", + file, line, fmt); } return; } @@ -74,34 +78,36 @@ do_test(struct kunit *kunittest, int bufsize, const char *expect, int elen, written = min(bufsize-1, elen); if (test_buffer[written]) { KUNIT_FAIL(kunittest, - "vsnprintf(buf, %d, \"%s\", ...) did not nul-terminate buffer\n", - bufsize, fmt); + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) did not nul-terminate buffer\n", + file, line, bufsize, fmt); return; } if (memchr_inv(test_buffer + written + 1, FILL_CHAR, bufsize - (written + 1))) { KUNIT_FAIL(kunittest, - "vsnprintf(buf, %d, \"%s\", ...) wrote beyond the nul-terminator\n", - bufsize, fmt); + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) wrote beyond the nul-terminator\n", + file, line, bufsize, fmt); return; } if (memchr_inv(test_buffer + bufsize, FILL_CHAR, BUF_SIZE + PAD_SIZE - bufsize)) { - KUNIT_FAIL(kunittest, "vsnprintf(buf, %d, \"%s\", ...) wrote beyond buffer\n", - bufsize, fmt); + KUNIT_FAIL(kunittest, + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) wrote beyond buffer\n", + file, line, bufsize, fmt); return; } if (memcmp(test_buffer, expect, written)) { KUNIT_FAIL(kunittest, - "vsnprintf(buf, %d, \"%s\", ...) wrote '%s', expected '%.*s'\n", - bufsize, fmt, test_buffer, written, expect); + "%s:%d: vsnprintf(buf, %d, \"%s\", ...) wrote '%s', expected '%.*s'\n", + file, line, bufsize, fmt, test_buffer, written, expect); return; } } -static void __printf(4, 5) -__test(struct kunit *kunittest, const char *expect, int elen, const char *fmt, ...) +static void __printf(6, 7) +__test(struct kunit *kunittest, const char *file, const int line, const char *expect, int elen, + const char *fmt, ...) { va_list ap; int rand; @@ -109,8 +115,8 @@ __test(struct kunit *kunittest, const char *expect, int elen, const char *fmt, . if (elen >= BUF_SIZE) { KUNIT_FAIL(kunittest, - "error in test suite: expected length (%d) >= BUF_SIZE (%d). fmt=\"%s\"\n", - elen, BUF_SIZE, fmt); + "%s:%d: error in test suite: expected length (%d) >= BUF_SIZE (%d). fmt=\"%s\"\n", + file, line, elen, BUF_SIZE, fmt); return; } @@ -122,19 +128,19 @@ __test(struct kunit *kunittest, const char *expect, int elen, const char *fmt, . * enough and 0), and then we also test that kvasprintf would * be able to print it as expected. */ - do_test(kunittest, BUF_SIZE, expect, elen, fmt, ap); + do_test(kunittest, file, line, BUF_SIZE, expect, elen, fmt, ap); rand = get_random_u32_inclusive(1, elen + 1); /* Since elen < BUF_SIZE, we have 1 <= rand <= BUF_SIZE. */ - do_test(kunittest, rand, expect, elen, fmt, ap); - do_test(kunittest, 0, expect, elen, fmt, ap); + do_test(kunittest, file, line, rand, expect, elen, fmt, ap); + do_test(kunittest, file, line, 0, expect, elen, fmt, ap); p = kvasprintf(GFP_KERNEL, fmt, ap); if (p) { total_tests++; if (memcmp(p, expect, elen+1)) { KUNIT_FAIL(kunittest, - "kvasprintf(..., \"%s\", ...) returned '%s', expected '%s'\n", - fmt, p, expect); + "%s:%d: kvasprintf(..., \"%s\", ...) returned '%s', expected '%s'\n", + file, line, fmt, p, expect); } kfree(p); } @@ -142,7 +148,7 @@ __test(struct kunit *kunittest, const char *expect, int elen, const char *fmt, . } #define test(expect, fmt, ...) \ - __test(kunittest, expect, strlen(expect), fmt, ##__VA_ARGS__) + __test(kunittest, __FILE__, __LINE__, expect, strlen(expect), fmt, ##__VA_ARGS__) static void test_basic(struct kunit *kunittest) @@ -153,7 +159,7 @@ test_basic(struct kunit *kunittest) test("", &nul); test("100%", "100%%"); test("xxx%yyy", "xxx%cyyy", '%'); - __test(kunittest, "xxx\0yyy", 7, "xxx%cyyy", '\0'); + __test(kunittest, __FILE__, __LINE__, "xxx\0yyy", 7, "xxx%cyyy", '\0'); } static void -- 2.51.0 From 5866730da7232dca5dc3b91645c964f3ec195c9d Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 06:27:34 -0500 Subject: [PATCH 14/16] scanf: implicate test line in failure messages This improves the failure output by pointing to the failing line at the top level of the test. Reviewed-by: Petr Mladek Tested-by: Petr Mladek Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20250307-scanf-kunit-convert-v9-1-b98820fa39ff@gmail.com Signed-off-by: Kees Cook --- lib/test_scanf.c | 66 ++++++++++++++++++++++++------------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/lib/test_scanf.c b/lib/test_scanf.c index 44f8508c9d88..e65b10c3dc11 100644 --- a/lib/test_scanf.c +++ b/lib/test_scanf.c @@ -24,12 +24,12 @@ static char *test_buffer __initdata; static char *fmt_buffer __initdata; static struct rnd_state rnd_state __initdata; -typedef int (*check_fn)(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap); +typedef int (*check_fn)(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap); -static void __scanf(4, 6) __init -_test(check_fn fn, const void *check_data, const char *string, const char *fmt, - int n_args, ...) +static void __scanf(6, 8) __init +_test(const char *file, const int line, check_fn fn, const void *check_data, const char *string, + const char *fmt, int n_args, ...) { va_list ap, ap_copy; int ret; @@ -42,12 +42,12 @@ _test(check_fn fn, const void *check_data, const char *string, const char *fmt, va_end(ap_copy); if (ret != n_args) { - pr_warn("vsscanf(\"%s\", \"%s\", ...) returned %d expected %d\n", - string, fmt, ret, n_args); + pr_warn("%s:%d: vsscanf(\"%s\", \"%s\", ...) returned %d expected %d\n", + file, line, string, fmt, ret, n_args); goto fail; } - ret = (*fn)(check_data, string, fmt, n_args, ap); + ret = (*fn)(file, line, check_data, string, fmt, n_args, ap); if (ret) goto fail; @@ -67,88 +67,88 @@ do { \ typeof(*expect) got = *va_arg(ap, typeof(expect)); \ pr_debug("\t" arg_fmt "\n", got); \ if (got != *expect) { \ - pr_warn("vsscanf(\"%s\", \"%s\", ...) expected " arg_fmt " got " arg_fmt "\n", \ - str, fmt, *expect, got); \ + pr_warn("%s:%d, vsscanf(\"%s\", \"%s\", ...) expected " arg_fmt " got " arg_fmt "\n", \ + file, line, str, fmt, *expect, got); \ return 1; \ } \ } \ return 0; \ } while (0) -static int __init check_ull(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_ull(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned long long *pval = check_data; _check_numbers_template("%llu", pval, string, fmt, n_args, ap); } -static int __init check_ll(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_ll(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const long long *pval = check_data; _check_numbers_template("%lld", pval, string, fmt, n_args, ap); } -static int __init check_ulong(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_ulong(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned long *pval = check_data; _check_numbers_template("%lu", pval, string, fmt, n_args, ap); } -static int __init check_long(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_long(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const long *pval = check_data; _check_numbers_template("%ld", pval, string, fmt, n_args, ap); } -static int __init check_uint(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_uint(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned int *pval = check_data; _check_numbers_template("%u", pval, string, fmt, n_args, ap); } -static int __init check_int(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_int(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const int *pval = check_data; _check_numbers_template("%d", pval, string, fmt, n_args, ap); } -static int __init check_ushort(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_ushort(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned short *pval = check_data; _check_numbers_template("%hu", pval, string, fmt, n_args, ap); } -static int __init check_short(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_short(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const short *pval = check_data; _check_numbers_template("%hd", pval, string, fmt, n_args, ap); } -static int __init check_uchar(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_uchar(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned char *pval = check_data; _check_numbers_template("%hhu", pval, string, fmt, n_args, ap); } -static int __init check_char(const void *check_data, const char *string, - const char *fmt, int n_args, va_list ap) +static int __init check_char(const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const signed char *pval = check_data; @@ -196,7 +196,7 @@ do { \ T result = ~expect_val; /* should be overwritten */ \ \ snprintf(test_buffer, BUF_SIZE, gen_fmt, expect_val); \ - _test(fn, &expect_val, test_buffer, "%" scan_fmt, 1, &result); \ + _test(__FILE__, __LINE__, fn, &expect_val, test_buffer, "%" scan_fmt, 1, &result); \ } while (0) #define simple_numbers_loop(T, gen_fmt, scan_fmt, fn) \ @@ -344,7 +344,7 @@ static void __init append_delim(char *str_buf, int *str_buf_pos, int str_buf_len #define test_array_8(fn, check_data, string, fmt, arr) \ do { \ BUILD_BUG_ON(ARRAY_SIZE(arr) != 8); \ - _test(fn, check_data, string, fmt, 8, \ + _test(__FILE__, __LINE__, fn, check_data, string, fmt, 8, \ &(arr)[0], &(arr)[1], &(arr)[2], &(arr)[3], \ &(arr)[4], &(arr)[5], &(arr)[6], &(arr)[7]); \ } while (0) @@ -608,7 +608,7 @@ do { \ const T expect[2] = { expect0, expect1 }; \ T result[2] = { (T)~expect[0], (T)~expect[1] }; \ \ - _test(fn, &expect, str, scan_fmt, n_args, &result[0], &result[1]); \ + _test(__FILE__, __LINE__, fn, &expect, str, scan_fmt, n_args, &result[0], &result[1]); \ } while (0) /* -- 2.51.0 From 6340d61b9005de1fab86963ff38c9cfd66e68483 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 06:27:35 -0500 Subject: [PATCH 15/16] scanf: remove redundant debug logs Remove `pr_debug` calls which emit information already contained in `pr_warn` calls that occur on test failure. This reduces unhelpful test verbosity. Note that a `pr_debug` removed from `_check_numbers_template` appears to have been the only guard against silent false positives, but in fact this condition is handled in `_test`; it is only possible for `n_args` to be `0` in `_check_numbers_template` if the test explicitly expects it *and* `vsscanf` returns `0`, matching the expectation. Reviewed-by: Petr Mladek Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20250307-scanf-kunit-convert-v9-2-b98820fa39ff@gmail.com Signed-off-by: Kees Cook --- lib/test_scanf.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/test_scanf.c b/lib/test_scanf.c index e65b10c3dc11..cb0b57dc7383 100644 --- a/lib/test_scanf.c +++ b/lib/test_scanf.c @@ -62,10 +62,8 @@ fail: #define _check_numbers_template(arg_fmt, expect, str, fmt, n_args, ap) \ do { \ - pr_debug("\"%s\", \"%s\" ->\n", str, fmt); \ for (; n_args > 0; n_args--, expect++) { \ typeof(*expect) got = *va_arg(ap, typeof(expect)); \ - pr_debug("\t" arg_fmt "\n", got); \ if (got != *expect) { \ pr_warn("%s:%d, vsscanf(\"%s\", \"%s\", ...) expected " arg_fmt " got " arg_fmt "\n", \ file, line, str, fmt, *expect, got); \ @@ -689,7 +687,6 @@ do { \ total_tests++; \ len = snprintf(test_buffer, BUF_SIZE, gen_fmt, expect); \ got = (fn)(test_buffer, &endp, base); \ - pr_debug(#fn "(\"%s\", %d) -> " gen_fmt "\n", test_buffer, base, got); \ if (got != (expect)) { \ fail = true; \ pr_warn(#fn "(\"%s\", %d): got " gen_fmt " expected " gen_fmt "\n", \ -- 2.51.0 From 97c1f302f2bc318ed88aa4a49641a3b60b33f7a5 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Mar 2025 06:27:36 -0500 Subject: [PATCH 16/16] scanf: convert self-test to KUnit Convert the scanf() self-test to a KUnit test. In the interest of keeping the patch reasonably-sized this doesn't refactor the tests into proper parameterized tests - it's all one big test case. Reviewed-by: David Gow Reviewed-by: Petr Mladek Tested-by: Petr Mladek Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20250307-scanf-kunit-convert-v9-3-b98820fa39ff@gmail.com Signed-off-by: Kees Cook --- MAINTAINERS | 2 +- lib/Kconfig.debug | 12 +- lib/Makefile | 1 - lib/tests/Makefile | 1 + lib/{test_scanf.c => tests/scanf_kunit.c} | 252 +++++++++++----------- tools/testing/selftests/lib/Makefile | 2 +- tools/testing/selftests/lib/config | 1 - tools/testing/selftests/lib/scanf.sh | 4 - 8 files changed, 134 insertions(+), 141 deletions(-) rename lib/{test_scanf.c => tests/scanf_kunit.c} (78%) delete mode 100755 tools/testing/selftests/lib/scanf.sh diff --git a/MAINTAINERS b/MAINTAINERS index 2a476c2a6ab9..2e7baadf3ef4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -25411,8 +25411,8 @@ R: Sergey Senozhatsky S: Maintained T: git git://git.kernel.org/pub/scm/linux/kernel/git/printk/linux.git F: Documentation/core-api/printk-formats.rst -F: lib/test_scanf.c F: lib/tests/printf_kunit.c +F: lib/tests/scanf_kunit.c F: lib/vsprintf.c VT1211 HARDWARE MONITOR DRIVER diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index 443036c36351..2601e4fb403c 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -2436,6 +2436,15 @@ config PRINTF_KUNIT_TEST If unsure, say N. +config SCANF_KUNIT_TEST + tristate "KUnit test scanf() family of functions at runtime" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Enable this option to test the scanf functions at runtime. + + If unsure, say N. + config STRING_KUNIT_TEST tristate "KUnit test string functions at runtime" if !KUNIT_ALL_TESTS depends on KUNIT @@ -2449,9 +2458,6 @@ config STRING_HELPERS_KUNIT_TEST config TEST_KSTRTOX tristate "Test kstrto*() family of functions at runtime" -config TEST_SCANF - tristate "Test scanf() family of functions at runtime" - config TEST_BITMAP tristate "Test bitmap_*() family of functions at runtime" help diff --git a/lib/Makefile b/lib/Makefile index b618d9d913bc..89b8a4bce108 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -77,7 +77,6 @@ obj-$(CONFIG_TEST_RHASHTABLE) += test_rhashtable.o obj-$(CONFIG_TEST_STATIC_KEYS) += test_static_keys.o obj-$(CONFIG_TEST_STATIC_KEYS) += test_static_key_base.o obj-$(CONFIG_TEST_DYNAMIC_DEBUG) += test_dynamic_debug.o -obj-$(CONFIG_TEST_SCANF) += test_scanf.o obj-$(CONFIG_TEST_BITMAP) += test_bitmap.o ifeq ($(CONFIG_CC_IS_CLANG)$(CONFIG_KASAN),yy) diff --git a/lib/tests/Makefile b/lib/tests/Makefile index 33e02744ec62..498915255860 100644 --- a/lib/tests/Makefile +++ b/lib/tests/Makefile @@ -30,6 +30,7 @@ obj-$(CONFIG_MEMCPY_KUNIT_TEST) += memcpy_kunit.o CFLAGS_overflow_kunit.o = $(call cc-disable-warning, tautological-constant-out-of-range-compare) obj-$(CONFIG_OVERFLOW_KUNIT_TEST) += overflow_kunit.o obj-$(CONFIG_PRINTF_KUNIT_TEST) += printf_kunit.o +obj-$(CONFIG_SCANF_KUNIT_TEST) += scanf_kunit.o obj-$(CONFIG_SIPHASH_KUNIT_TEST) += siphash_kunit.o obj-$(CONFIG_SLUB_KUNIT_TEST) += slub_kunit.o obj-$(CONFIG_TEST_SORT) += test_sort.o diff --git a/lib/test_scanf.c b/lib/tests/scanf_kunit.c similarity index 78% rename from lib/test_scanf.c rename to lib/tests/scanf_kunit.c index cb0b57dc7383..94eb5ec80fdb 100644 --- a/lib/test_scanf.c +++ b/lib/tests/scanf_kunit.c @@ -3,60 +3,44 @@ * Test cases for sscanf facility. */ -#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt - +#include #include -#include #include #include #include -#include #include #include #include -#include "../tools/testing/selftests/kselftest_module.h" - #define BUF_SIZE 1024 -KSTM_MODULE_GLOBALS(); -static char *test_buffer __initdata; -static char *fmt_buffer __initdata; -static struct rnd_state rnd_state __initdata; +static char *test_buffer; +static char *fmt_buffer; +static struct rnd_state rnd_state; -typedef int (*check_fn)(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap); +typedef void (*check_fn)(struct kunit *test, const char *file, const int line, + const void *check_data, const char *string, const char *fmt, int n_args, + va_list ap); -static void __scanf(6, 8) __init -_test(const char *file, const int line, check_fn fn, const void *check_data, const char *string, - const char *fmt, int n_args, ...) +static void __scanf(7, 9) +_test(struct kunit *test, const char *file, const int line, check_fn fn, const void *check_data, + const char *string, const char *fmt, int n_args, ...) { va_list ap, ap_copy; int ret; - total_tests++; - va_start(ap, n_args); va_copy(ap_copy, ap); ret = vsscanf(string, fmt, ap_copy); va_end(ap_copy); if (ret != n_args) { - pr_warn("%s:%d: vsscanf(\"%s\", \"%s\", ...) returned %d expected %d\n", - file, line, string, fmt, ret, n_args); - goto fail; + KUNIT_FAIL(test, "%s:%d: vsscanf(\"%s\", \"%s\", ...) returned %d expected %d", + file, line, string, fmt, ret, n_args); + } else { + (*fn)(test, file, line, check_data, string, fmt, n_args, ap); } - ret = (*fn)(file, line, check_data, string, fmt, n_args, ap); - if (ret) - goto fail; - - va_end(ap); - - return; - -fail: - failed_tests++; va_end(ap); } @@ -65,88 +49,92 @@ do { \ for (; n_args > 0; n_args--, expect++) { \ typeof(*expect) got = *va_arg(ap, typeof(expect)); \ if (got != *expect) { \ - pr_warn("%s:%d, vsscanf(\"%s\", \"%s\", ...) expected " arg_fmt " got " arg_fmt "\n", \ - file, line, str, fmt, *expect, got); \ - return 1; \ + KUNIT_FAIL(test, \ + "%s:%d: vsscanf(\"%s\", \"%s\", ...) expected " arg_fmt " got " arg_fmt, \ + file, line, str, fmt, *expect, got); \ + return; \ } \ } \ - return 0; \ } while (0) -static int __init check_ull(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_ull(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned long long *pval = check_data; _check_numbers_template("%llu", pval, string, fmt, n_args, ap); } -static int __init check_ll(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_ll(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const long long *pval = check_data; _check_numbers_template("%lld", pval, string, fmt, n_args, ap); } -static int __init check_ulong(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_ulong(struct kunit *test, const char *file, const int line, + const void *check_data, const char *string, const char *fmt, int n_args, + va_list ap) { const unsigned long *pval = check_data; _check_numbers_template("%lu", pval, string, fmt, n_args, ap); } -static int __init check_long(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_long(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const long *pval = check_data; _check_numbers_template("%ld", pval, string, fmt, n_args, ap); } -static int __init check_uint(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_uint(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const unsigned int *pval = check_data; _check_numbers_template("%u", pval, string, fmt, n_args, ap); } -static int __init check_int(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_int(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const int *pval = check_data; _check_numbers_template("%d", pval, string, fmt, n_args, ap); } -static int __init check_ushort(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_ushort(struct kunit *test, const char *file, const int line, + const void *check_data, const char *string, const char *fmt, int n_args, + va_list ap) { const unsigned short *pval = check_data; _check_numbers_template("%hu", pval, string, fmt, n_args, ap); } -static int __init check_short(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_short(struct kunit *test, const char *file, const int line, + const void *check_data, const char *string, const char *fmt, int n_args, + va_list ap) { const short *pval = check_data; _check_numbers_template("%hd", pval, string, fmt, n_args, ap); } -static int __init check_uchar(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_uchar(struct kunit *test, const char *file, const int line, + const void *check_data, const char *string, const char *fmt, int n_args, + va_list ap) { const unsigned char *pval = check_data; _check_numbers_template("%hhu", pval, string, fmt, n_args, ap); } -static int __init check_char(const char *file, const int line, const void *check_data, - const char *string, const char *fmt, int n_args, va_list ap) +static void check_char(struct kunit *test, const char *file, const int line, const void *check_data, + const char *string, const char *fmt, int n_args, va_list ap) { const signed char *pval = check_data; @@ -154,7 +142,7 @@ static int __init check_char(const char *file, const int line, const void *check } /* Selection of interesting numbers to test, copied from test-kstrtox.c */ -static const unsigned long long numbers[] __initconst = { +static const unsigned long long numbers[] = { 0x0ULL, 0x1ULL, 0x7fULL, @@ -194,7 +182,7 @@ do { \ T result = ~expect_val; /* should be overwritten */ \ \ snprintf(test_buffer, BUF_SIZE, gen_fmt, expect_val); \ - _test(__FILE__, __LINE__, fn, &expect_val, test_buffer, "%" scan_fmt, 1, &result); \ + _test(test, __FILE__, __LINE__, fn, &expect_val, test_buffer, "%" scan_fmt, 1, &result);\ } while (0) #define simple_numbers_loop(T, gen_fmt, scan_fmt, fn) \ @@ -212,7 +200,7 @@ do { \ } \ } while (0) -static void __init numbers_simple(void) +static void numbers_simple(struct kunit *test) { simple_numbers_loop(unsigned long long, "%llu", "llu", check_ull); simple_numbers_loop(long long, "%lld", "lld", check_ll); @@ -265,14 +253,14 @@ static void __init numbers_simple(void) * the raw prandom*() functions (Not mathematically rigorous!!). * Variabilty of length and value is more important than perfect randomness. */ -static u32 __init next_test_random(u32 max_bits) +static u32 next_test_random(u32 max_bits) { u32 n_bits = hweight32(prandom_u32_state(&rnd_state)) % (max_bits + 1); return prandom_u32_state(&rnd_state) & GENMASK(n_bits, 0); } -static unsigned long long __init next_test_random_ull(void) +static unsigned long long next_test_random_ull(void) { u32 rand1 = prandom_u32_state(&rnd_state); u32 n_bits = (hweight32(rand1) * 3) % 64; @@ -309,7 +297,7 @@ do { \ * updating buf_pos and returning the number of characters appended. * On error buf_pos is not changed and return value is 0. */ -static int __init __printf(4, 5) +static int __printf(4, 5) append_fmt(char *buf, int *buf_pos, int buf_len, const char *val_fmt, ...) { va_list ap; @@ -331,7 +319,7 @@ append_fmt(char *buf, int *buf_pos, int buf_len, const char *val_fmt, ...) * Convenience function to append the field delimiter string * to both the value string and format string buffers. */ -static void __init append_delim(char *str_buf, int *str_buf_pos, int str_buf_len, +static void append_delim(char *str_buf, int *str_buf_pos, int str_buf_len, char *fmt_buf, int *fmt_buf_pos, int fmt_buf_len, const char *delim_str) { @@ -342,7 +330,7 @@ static void __init append_delim(char *str_buf, int *str_buf_pos, int str_buf_len #define test_array_8(fn, check_data, string, fmt, arr) \ do { \ BUILD_BUG_ON(ARRAY_SIZE(arr) != 8); \ - _test(__FILE__, __LINE__, fn, check_data, string, fmt, 8, \ + _test(test, __FILE__, __LINE__, fn, check_data, string, fmt, 8, \ &(arr)[0], &(arr)[1], &(arr)[2], &(arr)[3], \ &(arr)[4], &(arr)[5], &(arr)[6], &(arr)[7]); \ } while (0) @@ -396,7 +384,7 @@ do { \ test_array_8(fn, expect, test_buffer, fmt_buffer, result); \ } while (0) -static void __init numbers_list_ll(const char *delim) +static void numbers_list_ll(struct kunit *test, const char *delim) { numbers_list_8(unsigned long long, "%llu", delim, "llu", check_ull); numbers_list_8(long long, "%lld", delim, "lld", check_ll); @@ -406,7 +394,7 @@ static void __init numbers_list_ll(const char *delim) numbers_list_8(long long, "0x%llx", delim, "lli", check_ll); } -static void __init numbers_list_l(const char *delim) +static void numbers_list_l(struct kunit *test, const char *delim) { numbers_list_8(unsigned long, "%lu", delim, "lu", check_ulong); numbers_list_8(long, "%ld", delim, "ld", check_long); @@ -416,7 +404,7 @@ static void __init numbers_list_l(const char *delim) numbers_list_8(long, "0x%lx", delim, "li", check_long); } -static void __init numbers_list_d(const char *delim) +static void numbers_list_d(struct kunit *test, const char *delim) { numbers_list_8(unsigned int, "%u", delim, "u", check_uint); numbers_list_8(int, "%d", delim, "d", check_int); @@ -426,7 +414,7 @@ static void __init numbers_list_d(const char *delim) numbers_list_8(int, "0x%x", delim, "i", check_int); } -static void __init numbers_list_h(const char *delim) +static void numbers_list_h(struct kunit *test, const char *delim) { numbers_list_8(unsigned short, "%hu", delim, "hu", check_ushort); numbers_list_8(short, "%hd", delim, "hd", check_short); @@ -436,7 +424,7 @@ static void __init numbers_list_h(const char *delim) numbers_list_8(short, "0x%hx", delim, "hi", check_short); } -static void __init numbers_list_hh(const char *delim) +static void numbers_list_hh(struct kunit *test, const char *delim) { numbers_list_8(unsigned char, "%hhu", delim, "hhu", check_uchar); numbers_list_8(signed char, "%hhd", delim, "hhd", check_char); @@ -446,16 +434,16 @@ static void __init numbers_list_hh(const char *delim) numbers_list_8(signed char, "0x%hhx", delim, "hhi", check_char); } -static void __init numbers_list(const char *delim) +static void numbers_list(struct kunit *test, const char *delim) { - numbers_list_ll(delim); - numbers_list_l(delim); - numbers_list_d(delim); - numbers_list_h(delim); - numbers_list_hh(delim); + numbers_list_ll(test, delim); + numbers_list_l(test, delim); + numbers_list_d(test, delim); + numbers_list_h(test, delim); + numbers_list_hh(test, delim); } -static void __init numbers_list_field_width_ll(const char *delim) +static void numbers_list_field_width_ll(struct kunit *test, const char *delim) { numbers_list_fix_width(unsigned long long, "%llu", delim, 20, "llu", check_ull); numbers_list_fix_width(long long, "%lld", delim, 20, "lld", check_ll); @@ -465,7 +453,7 @@ static void __init numbers_list_field_width_ll(const char *delim) numbers_list_fix_width(long long, "0x%llx", delim, 18, "lli", check_ll); } -static void __init numbers_list_field_width_l(const char *delim) +static void numbers_list_field_width_l(struct kunit *test, const char *delim) { #if BITS_PER_LONG == 64 numbers_list_fix_width(unsigned long, "%lu", delim, 20, "lu", check_ulong); @@ -484,7 +472,7 @@ static void __init numbers_list_field_width_l(const char *delim) #endif } -static void __init numbers_list_field_width_d(const char *delim) +static void numbers_list_field_width_d(struct kunit *test, const char *delim) { numbers_list_fix_width(unsigned int, "%u", delim, 10, "u", check_uint); numbers_list_fix_width(int, "%d", delim, 11, "d", check_int); @@ -494,7 +482,7 @@ static void __init numbers_list_field_width_d(const char *delim) numbers_list_fix_width(int, "0x%x", delim, 10, "i", check_int); } -static void __init numbers_list_field_width_h(const char *delim) +static void numbers_list_field_width_h(struct kunit *test, const char *delim) { numbers_list_fix_width(unsigned short, "%hu", delim, 5, "hu", check_ushort); numbers_list_fix_width(short, "%hd", delim, 6, "hd", check_short); @@ -504,7 +492,7 @@ static void __init numbers_list_field_width_h(const char *delim) numbers_list_fix_width(short, "0x%hx", delim, 6, "hi", check_short); } -static void __init numbers_list_field_width_hh(const char *delim) +static void numbers_list_field_width_hh(struct kunit *test, const char *delim) { numbers_list_fix_width(unsigned char, "%hhu", delim, 3, "hhu", check_uchar); numbers_list_fix_width(signed char, "%hhd", delim, 4, "hhd", check_char); @@ -518,16 +506,16 @@ static void __init numbers_list_field_width_hh(const char *delim) * List of numbers separated by delim. Each field width specifier is the * maximum possible digits for the given type and base. */ -static void __init numbers_list_field_width_typemax(const char *delim) +static void numbers_list_field_width_typemax(struct kunit *test, const char *delim) { - numbers_list_field_width_ll(delim); - numbers_list_field_width_l(delim); - numbers_list_field_width_d(delim); - numbers_list_field_width_h(delim); - numbers_list_field_width_hh(delim); + numbers_list_field_width_ll(test, delim); + numbers_list_field_width_l(test, delim); + numbers_list_field_width_d(test, delim); + numbers_list_field_width_h(test, delim); + numbers_list_field_width_hh(test, delim); } -static void __init numbers_list_field_width_val_ll(const char *delim) +static void numbers_list_field_width_val_ll(struct kunit *test, const char *delim) { numbers_list_val_width(unsigned long long, "%llu", delim, "llu", check_ull); numbers_list_val_width(long long, "%lld", delim, "lld", check_ll); @@ -537,7 +525,7 @@ static void __init numbers_list_field_width_val_ll(const char *delim) numbers_list_val_width(long long, "0x%llx", delim, "lli", check_ll); } -static void __init numbers_list_field_width_val_l(const char *delim) +static void numbers_list_field_width_val_l(struct kunit *test, const char *delim) { numbers_list_val_width(unsigned long, "%lu", delim, "lu", check_ulong); numbers_list_val_width(long, "%ld", delim, "ld", check_long); @@ -547,7 +535,7 @@ static void __init numbers_list_field_width_val_l(const char *delim) numbers_list_val_width(long, "0x%lx", delim, "li", check_long); } -static void __init numbers_list_field_width_val_d(const char *delim) +static void numbers_list_field_width_val_d(struct kunit *test, const char *delim) { numbers_list_val_width(unsigned int, "%u", delim, "u", check_uint); numbers_list_val_width(int, "%d", delim, "d", check_int); @@ -557,7 +545,7 @@ static void __init numbers_list_field_width_val_d(const char *delim) numbers_list_val_width(int, "0x%x", delim, "i", check_int); } -static void __init numbers_list_field_width_val_h(const char *delim) +static void numbers_list_field_width_val_h(struct kunit *test, const char *delim) { numbers_list_val_width(unsigned short, "%hu", delim, "hu", check_ushort); numbers_list_val_width(short, "%hd", delim, "hd", check_short); @@ -567,7 +555,7 @@ static void __init numbers_list_field_width_val_h(const char *delim) numbers_list_val_width(short, "0x%hx", delim, "hi", check_short); } -static void __init numbers_list_field_width_val_hh(const char *delim) +static void numbers_list_field_width_val_hh(struct kunit *test, const char *delim) { numbers_list_val_width(unsigned char, "%hhu", delim, "hhu", check_uchar); numbers_list_val_width(signed char, "%hhd", delim, "hhd", check_char); @@ -581,13 +569,13 @@ static void __init numbers_list_field_width_val_hh(const char *delim) * List of numbers separated by delim. Each field width specifier is the * exact length of the corresponding value digits in the string being scanned. */ -static void __init numbers_list_field_width_val_width(const char *delim) +static void numbers_list_field_width_val_width(struct kunit *test, const char *delim) { - numbers_list_field_width_val_ll(delim); - numbers_list_field_width_val_l(delim); - numbers_list_field_width_val_d(delim); - numbers_list_field_width_val_h(delim); - numbers_list_field_width_val_hh(delim); + numbers_list_field_width_val_ll(test, delim); + numbers_list_field_width_val_l(test, delim); + numbers_list_field_width_val_d(test, delim); + numbers_list_field_width_val_h(test, delim); + numbers_list_field_width_val_hh(test, delim); } /* @@ -596,9 +584,9 @@ static void __init numbers_list_field_width_val_width(const char *delim) * of digits. For example the hex values c0,3,bf01,303 would have a * string representation of "c03bf01303" and extracted with "%2x%1x%4x%3x". */ -static void __init numbers_slice(void) +static void numbers_slice(struct kunit *test) { - numbers_list_field_width_val_width(""); + numbers_list_field_width_val_width(test, ""); } #define test_number_prefix(T, str, scan_fmt, expect0, expect1, n_args, fn) \ @@ -606,14 +594,14 @@ do { \ const T expect[2] = { expect0, expect1 }; \ T result[2] = { (T)~expect[0], (T)~expect[1] }; \ \ - _test(__FILE__, __LINE__, fn, &expect, str, scan_fmt, n_args, &result[0], &result[1]); \ + _test(test, __FILE__, __LINE__, fn, &expect, str, scan_fmt, n_args, &result[0], &result[1]);\ } while (0) /* * Number prefix is >= field width. * Expected behaviour is derived from testing userland sscanf. */ -static void __init numbers_prefix_overflow(void) +static void numbers_prefix_overflow(struct kunit *test) { /* * Negative decimal with a field of width 1, should quit scanning @@ -682,24 +670,17 @@ do { \ T got; \ char *endp; \ int len; \ - bool fail = false; \ \ - total_tests++; \ len = snprintf(test_buffer, BUF_SIZE, gen_fmt, expect); \ got = (fn)(test_buffer, &endp, base); \ if (got != (expect)) { \ - fail = true; \ - pr_warn(#fn "(\"%s\", %d): got " gen_fmt " expected " gen_fmt "\n", \ - test_buffer, base, got, expect); \ + KUNIT_FAIL(test, #fn "(\"%s\", %d): got " gen_fmt " expected " gen_fmt, \ + test_buffer, base, got, expect); \ } else if (endp != test_buffer + len) { \ - fail = true; \ - pr_warn(#fn "(\"%s\", %d) startp=0x%px got endp=0x%px expected 0x%px\n", \ - test_buffer, base, test_buffer, \ - test_buffer + len, endp); \ + KUNIT_FAIL(test, #fn "(\"%s\", %d) startp=0x%px got endp=0x%px expected 0x%px", \ + test_buffer, base, test_buffer, \ + test_buffer + len, endp); \ } \ - \ - if (fail) \ - failed_tests++; \ } while (0) #define test_simple_strtoxx(T, fn, gen_fmt, base) \ @@ -715,7 +696,7 @@ do { \ } \ } while (0) -static void __init test_simple_strtoull(void) +static void test_simple_strtoull(struct kunit *test) { test_simple_strtoxx(unsigned long long, simple_strtoull, "%llu", 10); test_simple_strtoxx(unsigned long long, simple_strtoull, "%llu", 0); @@ -724,7 +705,7 @@ static void __init test_simple_strtoull(void) test_simple_strtoxx(unsigned long long, simple_strtoull, "0x%llx", 0); } -static void __init test_simple_strtoll(void) +static void test_simple_strtoll(struct kunit *test) { test_simple_strtoxx(long long, simple_strtoll, "%lld", 10); test_simple_strtoxx(long long, simple_strtoll, "%lld", 0); @@ -733,7 +714,7 @@ static void __init test_simple_strtoll(void) test_simple_strtoxx(long long, simple_strtoll, "0x%llx", 0); } -static void __init test_simple_strtoul(void) +static void test_simple_strtoul(struct kunit *test) { test_simple_strtoxx(unsigned long, simple_strtoul, "%lu", 10); test_simple_strtoxx(unsigned long, simple_strtoul, "%lu", 0); @@ -742,7 +723,7 @@ static void __init test_simple_strtoul(void) test_simple_strtoxx(unsigned long, simple_strtoul, "0x%lx", 0); } -static void __init test_simple_strtol(void) +static void test_simple_strtol(struct kunit *test) { test_simple_strtoxx(long, simple_strtol, "%ld", 10); test_simple_strtoxx(long, simple_strtol, "%ld", 0); @@ -752,35 +733,35 @@ static void __init test_simple_strtol(void) } /* Selection of common delimiters/separators between numbers in a string. */ -static const char * const number_delimiters[] __initconst = { +static const char * const number_delimiters[] = { " ", ":", ",", "-", "/", }; -static void __init test_numbers(void) +static void test_numbers(struct kunit *test) { int i; /* String containing only one number. */ - numbers_simple(); + numbers_simple(test); /* String with multiple numbers separated by delimiter. */ for (i = 0; i < ARRAY_SIZE(number_delimiters); i++) { - numbers_list(number_delimiters[i]); + numbers_list(test, number_delimiters[i]); /* Field width may be longer than actual field digits. */ - numbers_list_field_width_typemax(number_delimiters[i]); + numbers_list_field_width_typemax(test, number_delimiters[i]); /* Each field width exactly length of actual field digits. */ - numbers_list_field_width_val_width(number_delimiters[i]); + numbers_list_field_width_val_width(test, number_delimiters[i]); } /* Slice continuous sequence of digits using field widths. */ - numbers_slice(); + numbers_slice(test); - numbers_prefix_overflow(); + numbers_prefix_overflow(test); } -static void __init selftest(void) +static void scanf_test(struct kunit *test) { test_buffer = kmalloc(BUF_SIZE, GFP_KERNEL); if (!test_buffer) @@ -794,18 +775,29 @@ static void __init selftest(void) prandom_seed_state(&rnd_state, 3141592653589793238ULL); - test_numbers(); + test_numbers(test); - test_simple_strtoull(); - test_simple_strtoll(); - test_simple_strtoul(); - test_simple_strtol(); + test_simple_strtoull(test); + test_simple_strtoll(test); + test_simple_strtoul(test); + test_simple_strtol(test); kfree(fmt_buffer); kfree(test_buffer); } -KSTM_MODULE_LOADERS(test_scanf); +static struct kunit_case scanf_test_cases[] = { + KUNIT_CASE(scanf_test), + {} +}; + +static struct kunit_suite scanf_test_suite = { + .name = "scanf", + .test_cases = scanf_test_cases, +}; + +kunit_test_suite(scanf_test_suite); + MODULE_AUTHOR("Richard Fitzgerald "); MODULE_DESCRIPTION("Test cases for sscanf facility"); MODULE_LICENSE("GPL v2"); diff --git a/tools/testing/selftests/lib/Makefile b/tools/testing/selftests/lib/Makefile index befc4ab2c671..f876bf4744e1 100644 --- a/tools/testing/selftests/lib/Makefile +++ b/tools/testing/selftests/lib/Makefile @@ -4,5 +4,5 @@ # No binaries, but make sure arg-less "make" doesn't trigger "run_tests" all: -TEST_PROGS := bitmap.sh scanf.sh +TEST_PROGS := bitmap.sh include ../lib.mk diff --git a/tools/testing/selftests/lib/config b/tools/testing/selftests/lib/config index f4b4b8822241..81a1f64a22e8 100644 --- a/tools/testing/selftests/lib/config +++ b/tools/testing/selftests/lib/config @@ -1,3 +1,2 @@ -CONFIG_TEST_SCANF=m CONFIG_TEST_BITMAP=m CONFIG_TEST_BITOPS=m diff --git a/tools/testing/selftests/lib/scanf.sh b/tools/testing/selftests/lib/scanf.sh deleted file mode 100755 index b59b8ba561c3..000000000000 --- a/tools/testing/selftests/lib/scanf.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -# SPDX-License-Identifier: GPL-2.0 -# Tests the scanf infrastructure using test_scanf kernel module. -$(dirname $0)/../kselftest/module.sh "scanf" test_scanf -- 2.51.0