xref: /openbmc/linux/lib/fortify_kunit.c (revision ca637c0e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Runtime test cases for CONFIG_FORTIFY_SOURCE that aren't expected to
4  * Oops the kernel on success. (For those, see drivers/misc/lkdtm/fortify.c)
5  *
6  * For corner cases with UBSAN, try testing with:
7  *
8  * ./tools/testing/kunit/kunit.py run --arch=x86_64 \
9  *	--kconfig_add CONFIG_FORTIFY_SOURCE=y \
10  *	--kconfig_add CONFIG_UBSAN=y \
11  *	--kconfig_add CONFIG_UBSAN_TRAP=y \
12  *	--kconfig_add CONFIG_UBSAN_BOUNDS=y \
13  *	--kconfig_add CONFIG_UBSAN_LOCAL_BOUNDS=y \
14  *	--make_options LLVM=1 fortify
15  */
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 
18 #include <kunit/test.h>
19 #include <linux/string.h>
20 
21 static const char array_of_10[] = "this is 10";
22 static const char *ptr_of_11 = "this is 11!";
23 static char array_unknown[] = "compiler thinks I might change";
24 
25 static void known_sizes_test(struct kunit *test)
26 {
27 	KUNIT_EXPECT_EQ(test, __compiletime_strlen("88888888"), 8);
28 	KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_of_10), 10);
29 	KUNIT_EXPECT_EQ(test, __compiletime_strlen(ptr_of_11), 11);
30 
31 	KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_unknown), SIZE_MAX);
32 	/* Externally defined and dynamically sized string pointer: */
33 	KUNIT_EXPECT_EQ(test, __compiletime_strlen(test->name), SIZE_MAX);
34 }
35 
36 /* This is volatile so the optimizer can't perform DCE below. */
37 static volatile int pick;
38 
39 /* Not inline to keep optimizer from figuring out which string we want. */
40 static noinline size_t want_minus_one(int pick)
41 {
42 	const char *str;
43 
44 	switch (pick) {
45 	case 1:
46 		str = "4444";
47 		break;
48 	case 2:
49 		str = "333";
50 		break;
51 	default:
52 		str = "1";
53 		break;
54 	}
55 	return __compiletime_strlen(str);
56 }
57 
58 static void control_flow_split_test(struct kunit *test)
59 {
60 	KUNIT_EXPECT_EQ(test, want_minus_one(pick), SIZE_MAX);
61 }
62 
63 static struct kunit_case fortify_test_cases[] = {
64 	KUNIT_CASE(known_sizes_test),
65 	KUNIT_CASE(control_flow_split_test),
66 	{}
67 };
68 
69 static struct kunit_suite fortify_test_suite = {
70 	.name = "fortify",
71 	.test_cases = fortify_test_cases,
72 };
73 
74 kunit_test_suite(fortify_test_suite);
75 
76 MODULE_LICENSE("GPL");
77