kmsan_test.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  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
  6. * kernel log.
  7. *
  8. * Copyright (C) 2021-2022, Google LLC.
  9. * Author: Alexander Potapenko <[email protected]>
  10. *
  11. */
  12. #include <kunit/test.h>
  13. #include "kmsan.h"
  14. #include <linux/jiffies.h>
  15. #include <linux/kernel.h>
  16. #include <linux/kmsan.h>
  17. #include <linux/mm.h>
  18. #include <linux/random.h>
  19. #include <linux/slab.h>
  20. #include <linux/spinlock.h>
  21. #include <linux/string.h>
  22. #include <linux/tracepoint.h>
  23. #include <linux/vmalloc.h>
  24. #include <trace/events/printk.h>
  25. static DEFINE_PER_CPU(int, per_cpu_var);
  26. /* Report as observed from console. */
  27. static struct {
  28. spinlock_t lock;
  29. bool available;
  30. bool ignore; /* Stop console output collection. */
  31. char header[256];
  32. } observed = {
  33. .lock = __SPIN_LOCK_UNLOCKED(observed.lock),
  34. };
  35. /* Probe for console output: obtains observed lines of interest. */
  36. static void probe_console(void *ignore, const char *buf, size_t len)
  37. {
  38. unsigned long flags;
  39. if (observed.ignore)
  40. return;
  41. spin_lock_irqsave(&observed.lock, flags);
  42. if (strnstr(buf, "BUG: KMSAN: ", len)) {
  43. /*
  44. * KMSAN report and related to the test.
  45. *
  46. * The provided @buf is not NUL-terminated; copy no more than
  47. * @len bytes and let strscpy() add the missing NUL-terminator.
  48. */
  49. strscpy(observed.header, buf,
  50. min(len + 1, sizeof(observed.header)));
  51. WRITE_ONCE(observed.available, true);
  52. observed.ignore = true;
  53. }
  54. spin_unlock_irqrestore(&observed.lock, flags);
  55. }
  56. /* Check if a report related to the test exists. */
  57. static bool report_available(void)
  58. {
  59. return READ_ONCE(observed.available);
  60. }
  61. /* Information we expect in a report. */
  62. struct expect_report {
  63. const char *error_type; /* Error type. */
  64. /*
  65. * Kernel symbol from the error header, or NULL if no report is
  66. * expected.
  67. */
  68. const char *symbol;
  69. };
  70. /* Check observed report matches information in @r. */
  71. static bool report_matches(const struct expect_report *r)
  72. {
  73. typeof(observed.header) expected_header;
  74. unsigned long flags;
  75. bool ret = false;
  76. const char *end;
  77. char *cur;
  78. /* Doubled-checked locking. */
  79. if (!report_available() || !r->symbol)
  80. return (!report_available() && !r->symbol);
  81. /* Generate expected report contents. */
  82. /* Title */
  83. cur = expected_header;
  84. end = &expected_header[sizeof(expected_header) - 1];
  85. cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
  86. scnprintf(cur, end - cur, " in %s", r->symbol);
  87. /* The exact offset won't match, remove it; also strip module name. */
  88. cur = strchr(expected_header, '+');
  89. if (cur)
  90. *cur = '\0';
  91. spin_lock_irqsave(&observed.lock, flags);
  92. if (!report_available())
  93. goto out; /* A new report is being captured. */
  94. /* Finally match expected output to what we actually observed. */
  95. ret = strstr(observed.header, expected_header);
  96. out:
  97. spin_unlock_irqrestore(&observed.lock, flags);
  98. return ret;
  99. }
  100. /* ===== Test cases ===== */
  101. /* Prevent replacing branch with select in LLVM. */
  102. static noinline void check_true(char *arg)
  103. {
  104. pr_info("%s is true\n", arg);
  105. }
  106. static noinline void check_false(char *arg)
  107. {
  108. pr_info("%s is false\n", arg);
  109. }
  110. #define USE(x) \
  111. do { \
  112. if (x) \
  113. check_true(#x); \
  114. else \
  115. check_false(#x); \
  116. } while (0)
  117. #define EXPECTATION_ETYPE_FN(e, reason, fn) \
  118. struct expect_report e = { \
  119. .error_type = reason, \
  120. .symbol = fn, \
  121. }
  122. #define EXPECTATION_NO_REPORT(e) EXPECTATION_ETYPE_FN(e, NULL, NULL)
  123. #define EXPECTATION_UNINIT_VALUE_FN(e, fn) \
  124. EXPECTATION_ETYPE_FN(e, "uninit-value", fn)
  125. #define EXPECTATION_UNINIT_VALUE(e) EXPECTATION_UNINIT_VALUE_FN(e, __func__)
  126. #define EXPECTATION_USE_AFTER_FREE(e) \
  127. EXPECTATION_ETYPE_FN(e, "use-after-free", __func__)
  128. /* Test case: ensure that kmalloc() returns uninitialized memory. */
  129. static void test_uninit_kmalloc(struct kunit *test)
  130. {
  131. EXPECTATION_UNINIT_VALUE(expect);
  132. int *ptr;
  133. kunit_info(test, "uninitialized kmalloc test (UMR report)\n");
  134. ptr = kmalloc(sizeof(*ptr), GFP_KERNEL);
  135. USE(*ptr);
  136. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  137. }
  138. /*
  139. * Test case: ensure that kmalloc'ed memory becomes initialized after memset().
  140. */
  141. static void test_init_kmalloc(struct kunit *test)
  142. {
  143. EXPECTATION_NO_REPORT(expect);
  144. int *ptr;
  145. kunit_info(test, "initialized kmalloc test (no reports)\n");
  146. ptr = kmalloc(sizeof(*ptr), GFP_KERNEL);
  147. memset(ptr, 0, sizeof(*ptr));
  148. USE(*ptr);
  149. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  150. }
  151. /* Test case: ensure that kzalloc() returns initialized memory. */
  152. static void test_init_kzalloc(struct kunit *test)
  153. {
  154. EXPECTATION_NO_REPORT(expect);
  155. int *ptr;
  156. kunit_info(test, "initialized kzalloc test (no reports)\n");
  157. ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
  158. USE(*ptr);
  159. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  160. }
  161. /* Test case: ensure that local variables are uninitialized by default. */
  162. static void test_uninit_stack_var(struct kunit *test)
  163. {
  164. EXPECTATION_UNINIT_VALUE(expect);
  165. volatile int cond;
  166. kunit_info(test, "uninitialized stack variable (UMR report)\n");
  167. USE(cond);
  168. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  169. }
  170. /* Test case: ensure that local variables with initializers are initialized. */
  171. static void test_init_stack_var(struct kunit *test)
  172. {
  173. EXPECTATION_NO_REPORT(expect);
  174. volatile int cond = 1;
  175. kunit_info(test, "initialized stack variable (no reports)\n");
  176. USE(cond);
  177. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  178. }
  179. static noinline void two_param_fn_2(int arg1, int arg2)
  180. {
  181. USE(arg1);
  182. USE(arg2);
  183. }
  184. static noinline void one_param_fn(int arg)
  185. {
  186. two_param_fn_2(arg, arg);
  187. USE(arg);
  188. }
  189. static noinline void two_param_fn(int arg1, int arg2)
  190. {
  191. int init = 0;
  192. one_param_fn(init);
  193. USE(arg1);
  194. USE(arg2);
  195. }
  196. static void test_params(struct kunit *test)
  197. {
  198. #ifdef CONFIG_KMSAN_CHECK_PARAM_RETVAL
  199. /*
  200. * With eager param/retval checking enabled, KMSAN will report an error
  201. * before the call to two_param_fn().
  202. */
  203. EXPECTATION_UNINIT_VALUE_FN(expect, "test_params");
  204. #else
  205. EXPECTATION_UNINIT_VALUE_FN(expect, "two_param_fn");
  206. #endif
  207. volatile int uninit, init = 1;
  208. kunit_info(test,
  209. "uninit passed through a function parameter (UMR report)\n");
  210. two_param_fn(uninit, init);
  211. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  212. }
  213. static int signed_sum3(int a, int b, int c)
  214. {
  215. return a + b + c;
  216. }
  217. /*
  218. * Test case: ensure that uninitialized values are tracked through function
  219. * arguments.
  220. */
  221. static void test_uninit_multiple_params(struct kunit *test)
  222. {
  223. EXPECTATION_UNINIT_VALUE(expect);
  224. volatile char b = 3, c;
  225. volatile int a;
  226. kunit_info(test, "uninitialized local passed to fn (UMR report)\n");
  227. USE(signed_sum3(a, b, c));
  228. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  229. }
  230. /* Helper function to make an array uninitialized. */
  231. static noinline void do_uninit_local_array(char *array, int start, int stop)
  232. {
  233. volatile char uninit;
  234. for (int i = start; i < stop; i++)
  235. array[i] = uninit;
  236. }
  237. /*
  238. * Test case: ensure kmsan_check_memory() reports an error when checking
  239. * uninitialized memory.
  240. */
  241. static void test_uninit_kmsan_check_memory(struct kunit *test)
  242. {
  243. EXPECTATION_UNINIT_VALUE_FN(expect, "test_uninit_kmsan_check_memory");
  244. volatile char local_array[8];
  245. kunit_info(
  246. test,
  247. "kmsan_check_memory() called on uninit local (UMR report)\n");
  248. do_uninit_local_array((char *)local_array, 5, 7);
  249. kmsan_check_memory((char *)local_array, 8);
  250. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  251. }
  252. /*
  253. * Test case: check that a virtual memory range created with vmap() from
  254. * initialized pages is still considered as initialized.
  255. */
  256. static void test_init_kmsan_vmap_vunmap(struct kunit *test)
  257. {
  258. EXPECTATION_NO_REPORT(expect);
  259. const int npages = 2;
  260. struct page **pages;
  261. void *vbuf;
  262. kunit_info(test, "pages initialized via vmap (no reports)\n");
  263. pages = kmalloc_array(npages, sizeof(*pages), GFP_KERNEL);
  264. for (int i = 0; i < npages; i++)
  265. pages[i] = alloc_page(GFP_KERNEL);
  266. vbuf = vmap(pages, npages, VM_MAP, PAGE_KERNEL);
  267. memset(vbuf, 0xfe, npages * PAGE_SIZE);
  268. for (int i = 0; i < npages; i++)
  269. kmsan_check_memory(page_address(pages[i]), PAGE_SIZE);
  270. if (vbuf)
  271. vunmap(vbuf);
  272. for (int i = 0; i < npages; i++) {
  273. if (pages[i])
  274. __free_page(pages[i]);
  275. }
  276. kfree(pages);
  277. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  278. }
  279. /*
  280. * Test case: ensure that memset() can initialize a buffer allocated via
  281. * vmalloc().
  282. */
  283. static void test_init_vmalloc(struct kunit *test)
  284. {
  285. EXPECTATION_NO_REPORT(expect);
  286. int npages = 8;
  287. char *buf;
  288. kunit_info(test, "vmalloc buffer can be initialized (no reports)\n");
  289. buf = vmalloc(PAGE_SIZE * npages);
  290. buf[0] = 1;
  291. memset(buf, 0xfe, PAGE_SIZE * npages);
  292. USE(buf[0]);
  293. for (int i = 0; i < npages; i++)
  294. kmsan_check_memory(&buf[PAGE_SIZE * i], PAGE_SIZE);
  295. vfree(buf);
  296. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  297. }
  298. /* Test case: ensure that use-after-free reporting works. */
  299. static void test_uaf(struct kunit *test)
  300. {
  301. EXPECTATION_USE_AFTER_FREE(expect);
  302. volatile int value;
  303. volatile int *var;
  304. kunit_info(test, "use-after-free in kmalloc-ed buffer (UMR report)\n");
  305. var = kmalloc(80, GFP_KERNEL);
  306. var[3] = 0xfeedface;
  307. kfree((int *)var);
  308. /* Copy the invalid value before checking it. */
  309. value = var[3];
  310. USE(value);
  311. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  312. }
  313. /*
  314. * Test case: ensure that uninitialized values are propagated through per-CPU
  315. * memory.
  316. */
  317. static void test_percpu_propagate(struct kunit *test)
  318. {
  319. EXPECTATION_UNINIT_VALUE(expect);
  320. volatile int uninit, check;
  321. kunit_info(test,
  322. "uninit local stored to per_cpu memory (UMR report)\n");
  323. this_cpu_write(per_cpu_var, uninit);
  324. check = this_cpu_read(per_cpu_var);
  325. USE(check);
  326. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  327. }
  328. /*
  329. * Test case: ensure that passing uninitialized values to printk() leads to an
  330. * error report.
  331. */
  332. static void test_printk(struct kunit *test)
  333. {
  334. #ifdef CONFIG_KMSAN_CHECK_PARAM_RETVAL
  335. /*
  336. * With eager param/retval checking enabled, KMSAN will report an error
  337. * before the call to pr_info().
  338. */
  339. EXPECTATION_UNINIT_VALUE_FN(expect, "test_printk");
  340. #else
  341. EXPECTATION_UNINIT_VALUE_FN(expect, "number");
  342. #endif
  343. volatile int uninit;
  344. kunit_info(test, "uninit local passed to pr_info() (UMR report)\n");
  345. pr_info("%px contains %d\n", &uninit, uninit);
  346. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  347. }
  348. /*
  349. * Test case: ensure that memcpy() correctly copies uninitialized values between
  350. * aligned `src` and `dst`.
  351. */
  352. static void test_memcpy_aligned_to_aligned(struct kunit *test)
  353. {
  354. EXPECTATION_UNINIT_VALUE_FN(expect, "test_memcpy_aligned_to_aligned");
  355. volatile int uninit_src;
  356. volatile int dst = 0;
  357. kunit_info(
  358. test,
  359. "memcpy()ing aligned uninit src to aligned dst (UMR report)\n");
  360. memcpy((void *)&dst, (void *)&uninit_src, sizeof(uninit_src));
  361. kmsan_check_memory((void *)&dst, sizeof(dst));
  362. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  363. }
  364. /*
  365. * Test case: ensure that memcpy() correctly copies uninitialized values between
  366. * aligned `src` and unaligned `dst`.
  367. *
  368. * Copying aligned 4-byte value to an unaligned one leads to touching two
  369. * aligned 4-byte values. This test case checks that KMSAN correctly reports an
  370. * error on the first of the two values.
  371. */
  372. static void test_memcpy_aligned_to_unaligned(struct kunit *test)
  373. {
  374. EXPECTATION_UNINIT_VALUE_FN(expect, "test_memcpy_aligned_to_unaligned");
  375. volatile int uninit_src;
  376. volatile char dst[8] = { 0 };
  377. kunit_info(
  378. test,
  379. "memcpy()ing aligned uninit src to unaligned dst (UMR report)\n");
  380. memcpy((void *)&dst[1], (void *)&uninit_src, sizeof(uninit_src));
  381. kmsan_check_memory((void *)dst, 4);
  382. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  383. }
  384. /*
  385. * Test case: ensure that memcpy() correctly copies uninitialized values between
  386. * aligned `src` and unaligned `dst`.
  387. *
  388. * Copying aligned 4-byte value to an unaligned one leads to touching two
  389. * aligned 4-byte values. This test case checks that KMSAN correctly reports an
  390. * error on the second of the two values.
  391. */
  392. static void test_memcpy_aligned_to_unaligned2(struct kunit *test)
  393. {
  394. EXPECTATION_UNINIT_VALUE_FN(expect,
  395. "test_memcpy_aligned_to_unaligned2");
  396. volatile int uninit_src;
  397. volatile char dst[8] = { 0 };
  398. kunit_info(
  399. test,
  400. "memcpy()ing aligned uninit src to unaligned dst - part 2 (UMR report)\n");
  401. memcpy((void *)&dst[1], (void *)&uninit_src, sizeof(uninit_src));
  402. kmsan_check_memory((void *)&dst[4], sizeof(uninit_src));
  403. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  404. }
  405. static noinline void fibonacci(int *array, int size, int start) {
  406. if (start < 2 || (start == size))
  407. return;
  408. array[start] = array[start - 1] + array[start - 2];
  409. fibonacci(array, size, start + 1);
  410. }
  411. static void test_long_origin_chain(struct kunit *test)
  412. {
  413. EXPECTATION_UNINIT_VALUE_FN(expect,
  414. "test_long_origin_chain");
  415. /* (KMSAN_MAX_ORIGIN_DEPTH * 2) recursive calls to fibonacci(). */
  416. volatile int accum[KMSAN_MAX_ORIGIN_DEPTH * 2 + 2];
  417. int last = ARRAY_SIZE(accum) - 1;
  418. kunit_info(
  419. test,
  420. "origin chain exceeding KMSAN_MAX_ORIGIN_DEPTH (UMR report)\n");
  421. /*
  422. * We do not set accum[1] to 0, so the uninitializedness will be carried
  423. * over to accum[2..last].
  424. */
  425. accum[0] = 1;
  426. fibonacci((int *)accum, ARRAY_SIZE(accum), 2);
  427. kmsan_check_memory((void *)&accum[last], sizeof(int));
  428. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  429. }
  430. static struct kunit_case kmsan_test_cases[] = {
  431. KUNIT_CASE(test_uninit_kmalloc),
  432. KUNIT_CASE(test_init_kmalloc),
  433. KUNIT_CASE(test_init_kzalloc),
  434. KUNIT_CASE(test_uninit_stack_var),
  435. KUNIT_CASE(test_init_stack_var),
  436. KUNIT_CASE(test_params),
  437. KUNIT_CASE(test_uninit_multiple_params),
  438. KUNIT_CASE(test_uninit_kmsan_check_memory),
  439. KUNIT_CASE(test_init_kmsan_vmap_vunmap),
  440. KUNIT_CASE(test_init_vmalloc),
  441. KUNIT_CASE(test_uaf),
  442. KUNIT_CASE(test_percpu_propagate),
  443. KUNIT_CASE(test_printk),
  444. KUNIT_CASE(test_memcpy_aligned_to_aligned),
  445. KUNIT_CASE(test_memcpy_aligned_to_unaligned),
  446. KUNIT_CASE(test_memcpy_aligned_to_unaligned2),
  447. KUNIT_CASE(test_long_origin_chain),
  448. {},
  449. };
  450. /* ===== End test cases ===== */
  451. static int test_init(struct kunit *test)
  452. {
  453. unsigned long flags;
  454. spin_lock_irqsave(&observed.lock, flags);
  455. observed.header[0] = '\0';
  456. observed.ignore = false;
  457. observed.available = false;
  458. spin_unlock_irqrestore(&observed.lock, flags);
  459. return 0;
  460. }
  461. static void test_exit(struct kunit *test)
  462. {
  463. }
  464. static void register_tracepoints(struct tracepoint *tp, void *ignore)
  465. {
  466. check_trace_callback_type_console(probe_console);
  467. if (!strcmp(tp->name, "console"))
  468. WARN_ON(tracepoint_probe_register(tp, probe_console, NULL));
  469. }
  470. static void unregister_tracepoints(struct tracepoint *tp, void *ignore)
  471. {
  472. if (!strcmp(tp->name, "console"))
  473. tracepoint_probe_unregister(tp, probe_console, NULL);
  474. }
  475. static int kmsan_suite_init(struct kunit_suite *suite)
  476. {
  477. /*
  478. * Because we want to be able to build the test as a module, we need to
  479. * iterate through all known tracepoints, since the static registration
  480. * won't work here.
  481. */
  482. for_each_kernel_tracepoint(register_tracepoints, NULL);
  483. return 0;
  484. }
  485. static void kmsan_suite_exit(struct kunit_suite *suite)
  486. {
  487. for_each_kernel_tracepoint(unregister_tracepoints, NULL);
  488. tracepoint_synchronize_unregister();
  489. }
  490. static struct kunit_suite kmsan_test_suite = {
  491. .name = "kmsan",
  492. .test_cases = kmsan_test_cases,
  493. .init = test_init,
  494. .exit = test_exit,
  495. .suite_init = kmsan_suite_init,
  496. .suite_exit = kmsan_suite_exit,
  497. };
  498. kunit_test_suites(&kmsan_test_suite);
  499. MODULE_LICENSE("GPL");
  500. MODULE_AUTHOR("Alexander Potapenko <[email protected]>");