fortify_kunit.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #include <kunit/test.h>
  18. #include <linux/string.h>
  19. static const char array_of_10[] = "this is 10";
  20. static const char *ptr_of_11 = "this is 11!";
  21. static char array_unknown[] = "compiler thinks I might change";
  22. static void known_sizes_test(struct kunit *test)
  23. {
  24. KUNIT_EXPECT_EQ(test, __compiletime_strlen("88888888"), 8);
  25. KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_of_10), 10);
  26. KUNIT_EXPECT_EQ(test, __compiletime_strlen(ptr_of_11), 11);
  27. KUNIT_EXPECT_EQ(test, __compiletime_strlen(array_unknown), SIZE_MAX);
  28. /* Externally defined and dynamically sized string pointer: */
  29. KUNIT_EXPECT_EQ(test, __compiletime_strlen(test->name), SIZE_MAX);
  30. }
  31. /* This is volatile so the optimizer can't perform DCE below. */
  32. static volatile int pick;
  33. /* Not inline to keep optimizer from figuring out which string we want. */
  34. static noinline size_t want_minus_one(int pick)
  35. {
  36. const char *str;
  37. switch (pick) {
  38. case 1:
  39. str = "4444";
  40. break;
  41. case 2:
  42. str = "333";
  43. break;
  44. default:
  45. str = "1";
  46. break;
  47. }
  48. return __compiletime_strlen(str);
  49. }
  50. static void control_flow_split_test(struct kunit *test)
  51. {
  52. KUNIT_EXPECT_EQ(test, want_minus_one(pick), SIZE_MAX);
  53. }
  54. static struct kunit_case fortify_test_cases[] = {
  55. KUNIT_CASE(known_sizes_test),
  56. KUNIT_CASE(control_flow_split_test),
  57. {}
  58. };
  59. static struct kunit_suite fortify_test_suite = {
  60. .name = "fortify",
  61. .test_cases = fortify_test_cases,
  62. };
  63. kunit_test_suite(fortify_test_suite);
  64. MODULE_LICENSE("GPL");