1 // SPDX-License-Identifier: GPL-2.0
3 #define pr_fmt(fmt) "kcsan: " fmt
5 #include <linux/init.h>
6 #include <linux/kernel.h>
7 #include <linux/printk.h>
8 #include <linux/random.h>
9 #include <linux/types.h>
13 #define ITERS_PER_TEST 2000
15 /* Test requirements. */
16 static bool test_requires(void)
18 /* random should be initialized for the below tests */
19 return prandom_u32() + prandom_u32() != 0;
23 * Test watchpoint encode and decode: check that encoding some access's info,
24 * and then subsequent decode preserves the access's info.
26 static bool test_encode_decode(void)
30 for (i
= 0; i
< ITERS_PER_TEST
; ++i
) {
31 size_t size
= prandom_u32_max(MAX_ENCODABLE_SIZE
) + 1;
32 bool is_write
= !!prandom_u32_max(2);
35 prandom_bytes(&addr
, sizeof(addr
));
39 if (WARN_ON(!check_encodable(addr
, size
)))
42 /* Encode and decode */
44 const long encoded_watchpoint
=
45 encode_watchpoint(addr
, size
, is_write
);
46 unsigned long verif_masked_addr
;
50 /* Check special watchpoints */
51 if (WARN_ON(decode_watchpoint(
52 INVALID_WATCHPOINT
, &verif_masked_addr
,
53 &verif_size
, &verif_is_write
)))
55 if (WARN_ON(decode_watchpoint(
56 CONSUMED_WATCHPOINT
, &verif_masked_addr
,
57 &verif_size
, &verif_is_write
)))
60 /* Check decoding watchpoint returns same data */
61 if (WARN_ON(!decode_watchpoint(
62 encoded_watchpoint
, &verif_masked_addr
,
63 &verif_size
, &verif_is_write
)))
65 if (WARN_ON(verif_masked_addr
!=
66 (addr
& WATCHPOINT_ADDR_MASK
)))
68 if (WARN_ON(verif_size
!= size
))
70 if (WARN_ON(is_write
!= verif_is_write
))
75 pr_err("%s fail: %s %zu bytes @ %lx -> encoded: %lx -> %s %zu bytes @ %lx\n",
76 __func__
, is_write
? "write" : "read", size
,
77 addr
, encoded_watchpoint
,
78 verif_is_write
? "write" : "read", verif_size
,
87 /* Test access matching function. */
88 static bool test_matching_access(void)
90 if (WARN_ON(!matching_access(10, 1, 10, 1)))
92 if (WARN_ON(!matching_access(10, 2, 11, 1)))
94 if (WARN_ON(!matching_access(10, 1, 9, 2)))
96 if (WARN_ON(matching_access(10, 1, 11, 1)))
98 if (WARN_ON(matching_access(9, 1, 10, 1)))
102 * An access of size 0 could match another access, as demonstrated here.
103 * Rather than add more comparisons to 'matching_access()', which would
104 * end up in the fast-path for *all* checks, check_access() simply
105 * returns for all accesses of size 0.
107 if (WARN_ON(!matching_access(8, 8, 12, 0)))
113 static int __init
kcsan_selftest(void)
118 #define RUN_TEST(do_test) \
124 pr_err("selftest: " #do_test " failed"); \
127 RUN_TEST(test_requires
);
128 RUN_TEST(test_encode_decode
);
129 RUN_TEST(test_matching_access
);
131 pr_info("selftest: %d/%d tests passed\n", passed
, total
);
133 panic("selftests failed");
136 postcore_initcall(kcsan_selftest
);