1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/init.h>
4 #include <linux/kernel.h>
5 #include <linux/printk.h>
6 #include <linux/random.h>
7 #include <linux/types.h>
11 #define ITERS_PER_TEST 2000
13 /* Test requirements. */
14 static bool test_requires(void)
16 /* random should be initialized for the below tests */
17 return prandom_u32() + prandom_u32() != 0;
21 * Test watchpoint encode and decode: check that encoding some access's info,
22 * and then subsequent decode preserves the access's info.
24 static bool test_encode_decode(void)
28 for (i = 0; i < ITERS_PER_TEST; ++i) {
29 size_t size = prandom_u32_max(MAX_ENCODABLE_SIZE) + 1;
30 bool is_write = !!prandom_u32_max(2);
33 prandom_bytes(&addr, sizeof(addr));
34 if (WARN_ON(!check_encodable(addr, size)))
37 /* Encode and decode */
39 const long encoded_watchpoint =
40 encode_watchpoint(addr, size, is_write);
41 unsigned long verif_masked_addr;
45 /* Check special watchpoints */
46 if (WARN_ON(decode_watchpoint(
47 INVALID_WATCHPOINT, &verif_masked_addr,
48 &verif_size, &verif_is_write)))
50 if (WARN_ON(decode_watchpoint(
51 CONSUMED_WATCHPOINT, &verif_masked_addr,
52 &verif_size, &verif_is_write)))
55 /* Check decoding watchpoint returns same data */
56 if (WARN_ON(!decode_watchpoint(
57 encoded_watchpoint, &verif_masked_addr,
58 &verif_size, &verif_is_write)))
60 if (WARN_ON(verif_masked_addr !=
61 (addr & WATCHPOINT_ADDR_MASK)))
63 if (WARN_ON(verif_size != size))
65 if (WARN_ON(is_write != verif_is_write))
70 pr_err("%s fail: %s %zu bytes @ %lx -> encoded: %lx -> %s %zu bytes @ %lx\n",
71 __func__, is_write ? "write" : "read", size,
72 addr, encoded_watchpoint,
73 verif_is_write ? "write" : "read", verif_size,
82 /* Test access matching function. */
83 static bool test_matching_access(void)
85 if (WARN_ON(!matching_access(10, 1, 10, 1)))
87 if (WARN_ON(!matching_access(10, 2, 11, 1)))
89 if (WARN_ON(!matching_access(10, 1, 9, 2)))
91 if (WARN_ON(matching_access(10, 1, 11, 1)))
93 if (WARN_ON(matching_access(9, 1, 10, 1)))
97 * An access of size 0 could match another access, as demonstrated here.
98 * Rather than add more comparisons to 'matching_access()', which would
99 * end up in the fast-path for *all* checks, check_access() simply
100 * returns for all accesses of size 0.
102 if (WARN_ON(!matching_access(8, 8, 12, 0)))
108 static int __init kcsan_selftest(void)
113 #define RUN_TEST(do_test) \
119 pr_err("KCSAN selftest: " #do_test " failed"); \
122 RUN_TEST(test_requires);
123 RUN_TEST(test_encode_decode);
124 RUN_TEST(test_matching_access);
126 pr_info("KCSAN selftest: %d/%d tests passed\n", passed, total);
128 panic("KCSAN selftests failed");
131 postcore_initcall(kcsan_selftest);