1 // SPDX-License-Identifier: GPL-2.0
3 * Test cases for KMSAN.
4 * For each test case checks the presence (or absence) of generated reports.
5 * Relies on 'console' tracepoint to capture reports as they appear in the
8 * Copyright (C) 2021-2022, Google LLC.
9 * Author: Alexander Potapenko <glider@google.com>
13 #include <kunit/test.h>
16 #include <linux/jiffies.h>
17 #include <linux/kernel.h>
18 #include <linux/kmsan.h>
20 #include <linux/random.h>
21 #include <linux/slab.h>
22 #include <linux/spinlock.h>
23 #include <linux/string.h>
24 #include <linux/tracepoint.h>
25 #include <linux/vmalloc.h>
26 #include <trace/events/printk.h>
28 static DEFINE_PER_CPU(int, per_cpu_var);
30 /* Report as observed from console. */
34 bool ignore; /* Stop console output collection. */
37 .lock = __SPIN_LOCK_UNLOCKED(observed.lock),
40 /* Probe for console output: obtains observed lines of interest. */
41 static void probe_console(void *ignore, const char *buf, size_t len)
47 spin_lock_irqsave(&observed.lock, flags);
49 if (strnstr(buf, "BUG: KMSAN: ", len)) {
51 * KMSAN report and related to the test.
53 * The provided @buf is not NUL-terminated; copy no more than
54 * @len bytes and let strscpy() add the missing NUL-terminator.
56 strscpy(observed.header, buf,
57 min(len + 1, sizeof(observed.header)));
58 WRITE_ONCE(observed.available, true);
59 observed.ignore = true;
61 spin_unlock_irqrestore(&observed.lock, flags);
64 /* Check if a report related to the test exists. */
65 static bool report_available(void)
67 return READ_ONCE(observed.available);
70 /* Information we expect in a report. */
71 struct expect_report {
72 const char *error_type; /* Error type. */
74 * Kernel symbol from the error header, or NULL if no report is
80 /* Check observed report matches information in @r. */
81 static bool report_matches(const struct expect_report *r)
83 typeof(observed.header) expected_header;
89 /* Doubled-checked locking. */
90 if (!report_available() || !r->symbol)
91 return (!report_available() && !r->symbol);
93 /* Generate expected report contents. */
96 cur = expected_header;
97 end = &expected_header[sizeof(expected_header) - 1];
99 cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
101 scnprintf(cur, end - cur, " in %s", r->symbol);
102 /* The exact offset won't match, remove it; also strip module name. */
103 cur = strchr(expected_header, '+');
107 spin_lock_irqsave(&observed.lock, flags);
108 if (!report_available())
109 goto out; /* A new report is being captured. */
111 /* Finally match expected output to what we actually observed. */
112 ret = strstr(observed.header, expected_header);
114 spin_unlock_irqrestore(&observed.lock, flags);
119 /* ===== Test cases ===== */
121 /* Prevent replacing branch with select in LLVM. */
122 static noinline void check_true(char *arg)
124 pr_info("%s is true\n", arg);
127 static noinline void check_false(char *arg)
129 pr_info("%s is false\n", arg);
140 #define EXPECTATION_ETYPE_FN(e, reason, fn) \
141 struct expect_report e = { \
142 .error_type = reason, \
146 #define EXPECTATION_NO_REPORT(e) EXPECTATION_ETYPE_FN(e, NULL, NULL)
147 #define EXPECTATION_UNINIT_VALUE_FN(e, fn) \
148 EXPECTATION_ETYPE_FN(e, "uninit-value", fn)
149 #define EXPECTATION_UNINIT_VALUE(e) EXPECTATION_UNINIT_VALUE_FN(e, __func__)
150 #define EXPECTATION_USE_AFTER_FREE(e) \
151 EXPECTATION_ETYPE_FN(e, "use-after-free", __func__)
153 /* Test case: ensure that kmalloc() returns uninitialized memory. */
154 static void test_uninit_kmalloc(struct kunit *test)
156 EXPECTATION_UNINIT_VALUE(expect);
159 kunit_info(test, "uninitialized kmalloc test (UMR report)\n");
160 ptr = kmalloc(sizeof(*ptr), GFP_KERNEL);
162 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
166 * Test case: ensure that kmalloc'ed memory becomes initialized after memset().
168 static void test_init_kmalloc(struct kunit *test)
170 EXPECTATION_NO_REPORT(expect);
173 kunit_info(test, "initialized kmalloc test (no reports)\n");
174 ptr = kmalloc(sizeof(*ptr), GFP_KERNEL);
175 memset(ptr, 0, sizeof(*ptr));
177 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
180 /* Test case: ensure that kzalloc() returns initialized memory. */
181 static void test_init_kzalloc(struct kunit *test)
183 EXPECTATION_NO_REPORT(expect);
186 kunit_info(test, "initialized kzalloc test (no reports)\n");
187 ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
189 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
192 /* Test case: ensure that local variables are uninitialized by default. */
193 static void test_uninit_stack_var(struct kunit *test)
195 EXPECTATION_UNINIT_VALUE(expect);
198 kunit_info(test, "uninitialized stack variable (UMR report)\n");
200 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
203 /* Test case: ensure that local variables with initializers are initialized. */
204 static void test_init_stack_var(struct kunit *test)
206 EXPECTATION_NO_REPORT(expect);
207 volatile int cond = 1;
209 kunit_info(test, "initialized stack variable (no reports)\n");
211 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
214 static noinline void two_param_fn_2(int arg1, int arg2)
220 static noinline void one_param_fn(int arg)
222 two_param_fn_2(arg, arg);
226 static noinline void two_param_fn(int arg1, int arg2)
235 static void test_params(struct kunit *test)
237 #ifdef CONFIG_KMSAN_CHECK_PARAM_RETVAL
239 * With eager param/retval checking enabled, KMSAN will report an error
240 * before the call to two_param_fn().
242 EXPECTATION_UNINIT_VALUE_FN(expect, "test_params");
244 EXPECTATION_UNINIT_VALUE_FN(expect, "two_param_fn");
246 volatile int uninit, init = 1;
249 "uninit passed through a function parameter (UMR report)\n");
250 two_param_fn(uninit, init);
251 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
254 static int signed_sum3(int a, int b, int c)
260 * Test case: ensure that uninitialized values are tracked through function
263 static void test_uninit_multiple_params(struct kunit *test)
265 EXPECTATION_UNINIT_VALUE(expect);
266 volatile char b = 3, c;
269 kunit_info(test, "uninitialized local passed to fn (UMR report)\n");
270 USE(signed_sum3(a, b, c));
271 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
274 /* Helper function to make an array uninitialized. */
275 static noinline void do_uninit_local_array(char *array, int start, int stop)
277 volatile char uninit;
279 for (int i = start; i < stop; i++)
284 * Test case: ensure kmsan_check_memory() reports an error when checking
285 * uninitialized memory.
287 static void test_uninit_kmsan_check_memory(struct kunit *test)
289 EXPECTATION_UNINIT_VALUE_FN(expect, "test_uninit_kmsan_check_memory");
290 volatile char local_array[8];
294 "kmsan_check_memory() called on uninit local (UMR report)\n");
295 do_uninit_local_array((char *)local_array, 5, 7);
297 kmsan_check_memory((char *)local_array, 8);
298 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
302 * Test case: check that a virtual memory range created with vmap() from
303 * initialized pages is still considered as initialized.
305 static void test_init_kmsan_vmap_vunmap(struct kunit *test)
307 EXPECTATION_NO_REPORT(expect);
308 const int npages = 2;
312 kunit_info(test, "pages initialized via vmap (no reports)\n");
314 pages = kmalloc_array(npages, sizeof(*pages), GFP_KERNEL);
315 for (int i = 0; i < npages; i++)
316 pages[i] = alloc_page(GFP_KERNEL);
317 vbuf = vmap(pages, npages, VM_MAP, PAGE_KERNEL);
318 memset(vbuf, 0xfe, npages * PAGE_SIZE);
319 for (int i = 0; i < npages; i++)
320 kmsan_check_memory(page_address(pages[i]), PAGE_SIZE);
324 for (int i = 0; i < npages; i++) {
326 __free_page(pages[i]);
329 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
333 * Test case: ensure that memset() can initialize a buffer allocated via
336 static void test_init_vmalloc(struct kunit *test)
338 EXPECTATION_NO_REPORT(expect);
342 kunit_info(test, "vmalloc buffer can be initialized (no reports)\n");
343 buf = vmalloc(PAGE_SIZE * npages);
345 memset(buf, 0xfe, PAGE_SIZE * npages);
347 for (int i = 0; i < npages; i++)
348 kmsan_check_memory(&buf[PAGE_SIZE * i], PAGE_SIZE);
350 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
353 /* Test case: ensure that use-after-free reporting works. */
354 static void test_uaf(struct kunit *test)
356 EXPECTATION_USE_AFTER_FREE(expect);
360 kunit_info(test, "use-after-free in kmalloc-ed buffer (UMR report)\n");
361 var = kmalloc(80, GFP_KERNEL);
364 /* Copy the invalid value before checking it. */
367 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
371 * Test case: ensure that uninitialized values are propagated through per-CPU
374 static void test_percpu_propagate(struct kunit *test)
376 EXPECTATION_UNINIT_VALUE(expect);
377 volatile int uninit, check;
380 "uninit local stored to per_cpu memory (UMR report)\n");
382 this_cpu_write(per_cpu_var, uninit);
383 check = this_cpu_read(per_cpu_var);
385 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
389 * Test case: ensure that passing uninitialized values to printk() leads to an
392 static void test_printk(struct kunit *test)
394 #ifdef CONFIG_KMSAN_CHECK_PARAM_RETVAL
396 * With eager param/retval checking enabled, KMSAN will report an error
397 * before the call to pr_info().
399 EXPECTATION_UNINIT_VALUE_FN(expect, "test_printk");
401 EXPECTATION_UNINIT_VALUE_FN(expect, "number");
405 kunit_info(test, "uninit local passed to pr_info() (UMR report)\n");
406 pr_info("%px contains %d\n", &uninit, uninit);
407 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
411 * Test case: ensure that memcpy() correctly copies uninitialized values between
412 * aligned `src` and `dst`.
414 static void test_memcpy_aligned_to_aligned(struct kunit *test)
416 EXPECTATION_UNINIT_VALUE_FN(expect, "test_memcpy_aligned_to_aligned");
417 volatile int uninit_src;
418 volatile int dst = 0;
422 "memcpy()ing aligned uninit src to aligned dst (UMR report)\n");
423 OPTIMIZER_HIDE_VAR(uninit_src);
424 memcpy((void *)&dst, (void *)&uninit_src, sizeof(uninit_src));
425 kmsan_check_memory((void *)&dst, sizeof(dst));
426 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
430 * Test case: ensure that memcpy() correctly copies uninitialized values between
431 * aligned `src` and unaligned `dst`.
433 * Copying aligned 4-byte value to an unaligned one leads to touching two
434 * aligned 4-byte values. This test case checks that KMSAN correctly reports an
435 * error on the first of the two values.
437 static void test_memcpy_aligned_to_unaligned(struct kunit *test)
439 EXPECTATION_UNINIT_VALUE_FN(expect, "test_memcpy_aligned_to_unaligned");
440 volatile int uninit_src;
441 volatile char dst[8] = { 0 };
445 "memcpy()ing aligned uninit src to unaligned dst (UMR report)\n");
446 OPTIMIZER_HIDE_VAR(uninit_src);
447 memcpy((void *)&dst[1], (void *)&uninit_src, sizeof(uninit_src));
448 kmsan_check_memory((void *)dst, 4);
449 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
453 * Test case: ensure that memcpy() correctly copies uninitialized values between
454 * aligned `src` and unaligned `dst`.
456 * Copying aligned 4-byte value to an unaligned one leads to touching two
457 * aligned 4-byte values. This test case checks that KMSAN correctly reports an
458 * error on the second of the two values.
460 static void test_memcpy_aligned_to_unaligned2(struct kunit *test)
462 EXPECTATION_UNINIT_VALUE_FN(expect,
463 "test_memcpy_aligned_to_unaligned2");
464 volatile int uninit_src;
465 volatile char dst[8] = { 0 };
469 "memcpy()ing aligned uninit src to unaligned dst - part 2 (UMR report)\n");
470 OPTIMIZER_HIDE_VAR(uninit_src);
471 memcpy((void *)&dst[1], (void *)&uninit_src, sizeof(uninit_src));
472 kmsan_check_memory((void *)&dst[4], sizeof(uninit_src));
473 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
476 static noinline void fibonacci(int *array, int size, int start) {
477 if (start < 2 || (start == size))
479 array[start] = array[start - 1] + array[start - 2];
480 fibonacci(array, size, start + 1);
483 static void test_long_origin_chain(struct kunit *test)
485 EXPECTATION_UNINIT_VALUE_FN(expect,
486 "test_long_origin_chain");
487 /* (KMSAN_MAX_ORIGIN_DEPTH * 2) recursive calls to fibonacci(). */
488 volatile int accum[KMSAN_MAX_ORIGIN_DEPTH * 2 + 2];
489 int last = ARRAY_SIZE(accum) - 1;
493 "origin chain exceeding KMSAN_MAX_ORIGIN_DEPTH (UMR report)\n");
495 * We do not set accum[1] to 0, so the uninitializedness will be carried
496 * over to accum[2..last].
499 fibonacci((int *)accum, ARRAY_SIZE(accum), 2);
500 kmsan_check_memory((void *)&accum[last], sizeof(int));
501 KUNIT_EXPECT_TRUE(test, report_matches(&expect));
504 static struct kunit_case kmsan_test_cases[] = {
505 KUNIT_CASE(test_uninit_kmalloc),
506 KUNIT_CASE(test_init_kmalloc),
507 KUNIT_CASE(test_init_kzalloc),
508 KUNIT_CASE(test_uninit_stack_var),
509 KUNIT_CASE(test_init_stack_var),
510 KUNIT_CASE(test_params),
511 KUNIT_CASE(test_uninit_multiple_params),
512 KUNIT_CASE(test_uninit_kmsan_check_memory),
513 KUNIT_CASE(test_init_kmsan_vmap_vunmap),
514 KUNIT_CASE(test_init_vmalloc),
515 KUNIT_CASE(test_uaf),
516 KUNIT_CASE(test_percpu_propagate),
517 KUNIT_CASE(test_printk),
518 KUNIT_CASE(test_memcpy_aligned_to_aligned),
519 KUNIT_CASE(test_memcpy_aligned_to_unaligned),
520 KUNIT_CASE(test_memcpy_aligned_to_unaligned2),
521 KUNIT_CASE(test_long_origin_chain),
525 /* ===== End test cases ===== */
527 static int test_init(struct kunit *test)
531 spin_lock_irqsave(&observed.lock, flags);
532 observed.header[0] = '\0';
533 observed.ignore = false;
534 observed.available = false;
535 spin_unlock_irqrestore(&observed.lock, flags);
540 static void test_exit(struct kunit *test)
544 static void register_tracepoints(struct tracepoint *tp, void *ignore)
546 check_trace_callback_type_console(probe_console);
547 if (!strcmp(tp->name, "console"))
548 WARN_ON(tracepoint_probe_register(tp, probe_console, NULL));
551 static void unregister_tracepoints(struct tracepoint *tp, void *ignore)
553 if (!strcmp(tp->name, "console"))
554 tracepoint_probe_unregister(tp, probe_console, NULL);
557 static int kmsan_suite_init(struct kunit_suite *suite)
560 * Because we want to be able to build the test as a module, we need to
561 * iterate through all known tracepoints, since the static registration
564 for_each_kernel_tracepoint(register_tracepoints, NULL);
568 static void kmsan_suite_exit(struct kunit_suite *suite)
570 for_each_kernel_tracepoint(unregister_tracepoints, NULL);
571 tracepoint_synchronize_unregister();
574 static struct kunit_suite kmsan_test_suite = {
576 .test_cases = kmsan_test_cases,
579 .suite_init = kmsan_suite_init,
580 .suite_exit = kmsan_suite_exit,
582 kunit_test_suites(&kmsan_test_suite);
584 MODULE_LICENSE("GPL");
585 MODULE_AUTHOR("Alexander Potapenko <glider@google.com>");