Convert overflow and stackinit to KUnit
Subsystems (7)
v3 cover Convert overflow and stackinit to KUnit
Hi,
These changes all build on each other, so I'm sending this as a series to hopefully reduce confusion. I chose "v3" because it seemed the least confusing of various options.
The um changes are needed to get Clang building with um to test the stackinit KUnit test more easily (i.e. needing neither GCC 12 nor QEMU).
-Kees
David Gow (2):
um: Cleanup syscall_handler_t definition/cast, fix warning
um: Remove unused timeval_to_ns() function
Kees Cook (5):
overflow: Provide constant expression struct_size
lib: overflow: Convert to Kunit
um: Allow builds with Clang
lib: stackinit: Convert to KUnit
UAPI: Introduce KUnit userspace compatibility
arch/um/os-Linux/execvp.c | 1 +
arch/um/os-Linux/time.c | 6 -
arch/x86/um/shared/sysdep/syscalls_64.h | 5 +-
arch/x86/um/user-offsets.c | 9 +-
include/linux/overflow.h | 10 +-
include/uapi/misc/kunit.h | 181 +++++++
lib/Kconfig.debug | 38 +-
lib/Makefile | 6 +-
lib/{test_overflow.c => overflow_kunit.c} | 562 +++++++++-----------
lib/{test_stackinit.c => stackinit_kunit.c} | 268 ++++------
scripts/Makefile.clang | 1 +
11 files changed, 593 insertions(+), 494 deletions(-)
create mode 100644 include/uapi/misc/kunit.h
rename lib/{test_overflow.c => overflow_kunit.c} (54%)
rename lib/{test_stackinit.c => stackinit_kunit.c} (67%)Signature · 1 line
2.32.0
PATCH v3 1/7 overflow: Provide constant expression struct_size
There have been cases where struct_size() (or flex_array_size()) needs to be calculated for an initializer, which requires it be a constant expression. This is possible when the "count" argument is a constant expression, so provide this ability for the helpers.
---
v1: https://lore.kernel.org/linux-hardening/[email protected]
v2:
- fix broken self-test due to CE optimization
--- include/linux/overflow.h | 10 +++++++--- lib/test_overflow.c | 26 +++++++++++++++++--------- 2 files changed, 24 insertions(+), 12 deletions(-)
include/linux/overflow.h +7 -3
@@ -4,6 +4,7 @@#include <linux/compiler.h> #include <linux/limits.h> +#include <linux/const.h> /* * We need to compute the minimum and maximum values representable in a given
@@ -221,8 +222,9 @@ static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)* Return: number of bytes needed or SIZE_MAX on overflow. */ #define flex_array_size (p, member, count) \ - size_mul(count, \ - sizeof(*(p)->member) + __must_be_array((p)->member)) + __builtin_choose_expr(__is_constexpr(count), \ + (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \ + size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))/** * struct_size() - Calculate size of structure with trailing flexible array.
@@ -237,6 +239,8 @@ static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)* Return: number of bytes needed or SIZE_MAX on overflow. */ #define struct_size (p, member, count) \ - size_add(sizeof(*(p)), flex_array_size(p, member, count)) + __builtin_choose_expr(__is_constexpr(count), \ + sizeof(*(p)) + flex_array_size(p, member, count), \ + size_add(sizeof(*(p)), flex_array_size(p, member, count)))#endif /* __LINUX_OVERFLOW_H */
lib/test_overflow.c +17 -9
@@ -602,10 +602,18 @@ struct __test_flex_array {static int __init test_overflow_size_helpers (void ) { +/* Make sure struct_size() can be used in a constant expression. */ +u8 ce_array[struct_size ((struct __test_flex_array *)0 , data,55 )];struct __test_flex_array *obj;int count =0 ;int err =0 ;int var; +volatile int unconst =0 ; + +/* Verify constant expression against runtime version. */ + var =55 ; +OPTIMIZER_HIDE_VAR (var); + err |=sizeof (ce_array) !=struct_size (obj, data, var); #define check_one_size_helper(expected, func, args...) ({ \ bool __failure = false; \
@@ -663,28 +671,28 @@ static int __init test_overflow_size_helpers(void) flex_array_size, obj, data, var++); err |=check_one_size_helper (5 *sizeof (*obj->data), flex_array_size, obj, data, var++); - err |=check_one_size_helper (0 , flex_array_size, obj, data,0 ); + err |=check_one_size_helper (0 , flex_array_size, obj, data,0 + unconst); err |=check_one_size_helper (sizeof (*obj->data), - flex_array_size, obj, data,1 ); + flex_array_size, obj, data,1 + unconst); err |=check_one_size_helper (7 *sizeof (*obj->data), - flex_array_size, obj, data,7 ); + flex_array_size, obj, data,7 + unconst); err |=check_one_size_helper (SIZE_MAX , - flex_array_size, obj, data,-1 ); + flex_array_size, obj, data,-1 + unconst); err |=check_one_size_helper (SIZE_MAX , - flex_array_size, obj, data,SIZE_MAX -4 ); + flex_array_size, obj, data,SIZE_MAX -4 + unconst); var =4 ; err |=check_one_size_helper (sizeof (*obj) + (4 *sizeof (*obj->data)), struct_size, obj, data, var++); err |=check_one_size_helper (sizeof (*obj) + (5 *sizeof (*obj->data)), struct_size, obj, data, var++); - err |=check_one_size_helper (sizeof (*obj), struct_size, obj, data,0 ); + err |=check_one_size_helper (sizeof (*obj), struct_size, obj, data,0 + unconst); err |=check_one_size_helper (sizeof (*obj) +sizeof (*obj->data), - struct_size, obj, data,1 ); + struct_size, obj, data,1 + unconst); err |=check_one_size_helper (SIZE_MAX , - struct_size, obj, data,-3 ); + struct_size, obj, data,-3 + unconst); err |=check_one_size_helper (SIZE_MAX , - struct_size, obj, data,SIZE_MAX -3 ); + struct_size, obj, data,SIZE_MAX -3 + unconst);pr_info ("%d overflow size helper tests finished\n" , count);
Signature · 1 line
2.32.0
PATCH v3 2/7 lib: overflow: Convert to Kunit
In reply to Kees CookConvert overflow unit tests to KUnit, for better integration into the kernel self test framework. Includes a rename of test_overflow.c to overflow_kunit.c, and CONFIG_TEST_OVERFLOW to CONFIG_OVERFLOW_KUNIT_TEST.
$ ./tools/testing/kunit/kunit.py run overflow ... [14:33:51] Starting KUnit Kernel (1/1)... [14:33:51] ============================================================ [14:33:51] ================== overflow (11 subtests) ================== [14:33:51] [PASSED] u8_overflow_test [14:33:51] [PASSED] s8_overflow_test [14:33:51] [PASSED] u16_overflow_test [14:33:51] [PASSED] s16_overflow_test [14:33:51] [PASSED] u32_overflow_test [14:33:51] [PASSED] s32_overflow_test [14:33:51] [PASSED] u64_overflow_test [14:33:51] [PASSED] s64_overflow_test [14:33:51] [PASSED] overflow_shift_test [14:33:51] [PASSED] overflow_allocation_test [14:33:51] [PASSED] overflow_size_helpers_test [14:33:51] ==================== [PASSED] overflow ===================== [14:33:51] ============================================================ [14:33:51] Testing complete. Passed: 11, Failed: 0, Crashed: 0, Skipped: 0, Errors: 0 [14:33:51] Elapsed time: 12.525s total, 0.001s configuring, 12.402s building, 0.101s running
---
v1: https://lore.kernel.org/lkml/[email protected]
v2: https://lore.kernel.org/lkml/[email protected]
v3:
- tweak commit log (David)
---
lib/Kconfig.debug | 16 +-
lib/Makefile | 2 +-
lib/{test_overflow.c => overflow_kunit.c} | 554 ++++++++++------------
3 files changed, 263 insertions(+), 309 deletions(-)
rename lib/{test_overflow.c => overflow_kunit.c} (54%)lib/Kconfig.debug +13 -3
@@ -2214,9 +2214,6 @@ config TEST_UUID config TEST_XARRAY tristate "Test the XArray code at runtime" -config TEST_OVERFLOW - tristate "Test check_*_overflow() functions at runtime" - config TEST_RHASHTABLE tristate "Perform selftest on resizable hash table" help
@@ -2501,6 +2498,19 @@ config MEMCPY_KUNIT_TEST If unsure, say N. +config OVERFLOW_KUNIT_TEST + tristate "Test check_*_overflow() functions at runtime" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Builds unit tests for the check_*_overflow(), size_*(), allocation, and + related functions. + + For more information on KUnit and unit tests in general please refer + to the KUnit documentation in Documentation/dev-tools/kunit/. + + If unsure, say N. + config TEST_UDELAY tristate "udelay test driver" help
lib/Makefile +1 -1
@@ -77,7 +77,6 @@ obj-$(CONFIG_TEST_LIST_SORT) += test_list_sort.o obj-$(CONFIG_TEST_MIN_HEAP) += test_min_heap.o obj-$(CONFIG_TEST_LKM) += test_module.o obj-$(CONFIG_TEST_VMALLOC) += test_vmalloc.o -obj-$(CONFIG_TEST_OVERFLOW) += test_overflow.o obj-$(CONFIG_TEST_RHASHTABLE) += test_rhashtable.o obj-$(CONFIG_TEST_SORT) += test_sort.o obj-$(CONFIG_TEST_USER_COPY) += test_user_copy.o
@@ -363,6 +362,7 @@ obj-$(CONFIG_BITS_TEST) += test_bits.o obj-$(CONFIG_CMDLINE_KUNIT_TEST) += cmdline_kunit.o obj-$(CONFIG_SLUB_KUNIT_TEST) += slub_kunit.o obj-$(CONFIG_MEMCPY_KUNIT_TEST) += memcpy_kunit.o +obj-$(CONFIG_OVERFLOW_KUNIT_TEST) += overflow_kunit.o obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o
lib/overflow_kunit.c renamed from lib/test_overflow.c +249 -305
733 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v3 3/7 um: Cleanup syscall_handler_t definition/cast, fix warning
In reply to Kees CookFrom: David Gow <[email protected]>
The syscall_handler_t type for x86_64 was defined as 'long (*)(void)', but always cast to 'long (*)(long, long, long, long, long, long)' before use. This now triggers a warning (see below).
Define syscall_handler_t as the latter instead, and remove the cast. This simplifies the code, and fixes the warning.
Warning:
In file included from ../arch/um/include/asm/processor-generic.h:13
from ../arch/x86/um/asm/processor.h:41
from ../include/linux/rcupdate.h:30
from ../include/linux/rculist.h:11
from ../include/linux/pid.h:5
from ../include/linux/sched.h:14
from ../include/linux/ptrace.h:6
from ../arch/um/kernel/skas/syscall.c:7:../arch/um/kernel/skas/syscall.c: In function ‘handle_syscall’:../arch/x86/um/shared/sysdep/syscalls_64.h:18:11: warning: cast between incompatible function types from ‘long int (*)(void)’ to ‘long int (*)(long int, long int, long int, long int, long int, long int)’ [ -Wcast-function-type]
18 | (((long (*)(long, long, long, long, long, long)) \
| ^../arch/x86/um/asm/ptrace.h:36:62: note: in definition of macro ‘PT_REGS_SET_SYSCALL_RETURN’
36 | #define PT_REGS_SET_SYSCALL_RETURN(r, res) (PT_REGS_AX(r) = (res))
| ^~~../arch/um/kernel/skas/syscall.c:46:33: note: in expansion of macro ‘EXECUTE_SYSCALL’
46 | EXECUTE_SYSCALL(syscall, regs));
| ^~~~~~~~~~~~~~~---
This is just a re-send of the above linked patch, collecting it into this series.
--- arch/x86/um/shared/sysdep/syscalls_64.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
arch/x86/um/shared/sysdep/syscalls_64.h +2 -3
@@ -10,13 +10,12 @@#include <linux/msg.h> #include <linux/shm.h> -typedef long syscall_handler_t (void ); +typedef long syscall_handler_t (long ,long ,long ,long ,long ,long );extern syscall_handler_t *sys_call_table[];#define EXECUTE_SYSCALL (syscall, regs) \ - (((long (*)(long, long, long, long, long, long)) \ - (*sys_call_table[syscall]))(UPT_SYSCALL_ARG1(®s->regs), \ + (((*sys_call_table[syscall]))(UPT_SYSCALL_ARG1(®s->regs), \ UPT_SYSCALL_ARG2(®s->regs), \ UPT_SYSCALL_ARG3(®s->regs), \ UPT_SYSCALL_ARG4(®s->regs), \
Signature · 1 line
2.32.0
PATCH v3 4/7 um: Remove unused timeval_to_ns() function
In reply to Kees CookFrom: David Gow <[email protected]>
The timeval_to_ns() function doesn't appear to be used anywhere, as far as I (or git grep) can tell, and clang throws up a warning about it:
../arch/um/os-Linux/time.c:21:25: warning: unused function 'timeval_to_ns' [-Wunused-function] static inline long long timeval_to_ns(const struct timeval *tv)
^
1 warning generated.
---
This is a resend of the above linked patch, just included in this series.
--- arch/um/os-Linux/time.c | 6 ------ 1 file changed, 6 deletions(-)
arch/um/os-Linux/time.c +0 -6
@@ -18,12 +18,6 @@static timer_t event_high_res_timer =0 ; -static inline long long timeval_to_ns (const struct timeval *tv) -{ -return ((long long ) tv->tv_sec *UM_NSEC_PER_SEC ) + - tv->tv_usec *UM_NSEC_PER_USEC ; -} -static inline long long timespec_to_ns (const struct timespec *ts) {return ((long long ) ts->tv_sec *UM_NSEC_PER_SEC ) + ts->tv_nsec;
Signature · 1 line
2.32.0
PATCH v3 5/7 um: Allow builds with Clang
In reply to Kees CookAdd SUBARCH target for Clang+um (which must go last, not alphabetically, so the other SUBARCHes are assigned). Remove open-coded "DEFINE" macro, instead using linux/kbuild.h's version which was updated to use Clang-friendly assembly in commit cf0c3e68aa81 ("kbuild: fix asm-offset generation to work with clang"). Redefine "DEFINE_LONGS" in terms of "COMMENT" and "DEFINE" so that the intended coment actually has useful content. Add a missed "break" to avoid implicit fall-through warnings.
This lets me run KUnit tests with Clang:
$ ./tools/testing/kunit/kunit.py run --make_options LLVM=1 ...
---
v1: https://lore.kernel.org/lkml/[email protected]
v2: https://lore.kernel.org/lkml/[email protected]
v3:
- use kbuild.h to avoid duplication (Masahiro)
- fix intended comments (Masahiro)
- use SUBARCH (Nathan)
--- arch/um/os-Linux/execvp.c | 1 + arch/x86/um/user-offsets.c | 9 ++++----- scripts/Makefile.clang | 1 + 3 files changed, 6 insertions(+), 5 deletions(-)
arch/um/os-Linux/execvp.c +1 -0
@@ -93,6 +93,7 @@ int execvp_noalloc(char *buf, const char *file, char *const argv[])up finding no executable we can use, we want to diagnose that we did find one but were denied access. */ got_eacces =1 ; +break ;case ENOENT :case ESTALE :case ENOTDIR :
arch/x86/um/user-offsets.c +4 -5
@@ -8,12 +8,11 @@#define __FRAME_OFFSETS#include <linux/ptrace.h> #include <asm/types.h> +#include <linux/kbuild.h> -#define DEFINE (sym, val) \ - asm volatile("\n->" #sym " %0 " #val : : "i" (val)) - -#define DEFINE_LONGS (sym, val) \ - asm volatile("\n->" #sym " %0 " #val : : "i" (val/sizeof(unsigned long))) +#define DEFINE_LONGS (sym, val) \ + COMMENT(#val " / sizeof(unsigned long)"); \ + DEFINE(sym, val / sizeof(unsigned long))void foo (void ) {
scripts/Makefile.clang +1 -0
@@ -10,6 +10,7 @@ CLANG_TARGET_FLAGS_powerpc := powerpc64le-linux-gnu CLANG_TARGET_FLAGS_riscv := riscv64-linux-gnu CLANG_TARGET_FLAGS_s390 := s390x-linux-gnu CLANG_TARGET_FLAGS_x86 := x86_64-linux-gnu +CLANG_TARGET_FLAGS_um := $(CLANG_TARGET_FLAGS_$(SUBARCH)) CLANG_TARGET_FLAGS := $(CLANG_TARGET_FLAGS_$(SRCARCH)) ifeq ($(CROSS_COMPILE),)
Signature · 1 line
2.32.0
PATCH v3 6/7 lib: stackinit: Convert to KUnit
In reply to Kees CookConvert stackinit unit tests to KUnit, for better integration into the kernel self test framework. Includes a rename of test_stackinit.c to stackinit_kunit.c, and CONFIG_TEST_STACKINIT to CONFIG_STACKINIT_KUNIT_TEST.
Adjust expected test results based on which stack initialization method was chosen:
$ CMD="./tools/testing/kunit/kunit.py run stackinit --raw_output \
--arch=x86_64 --kconfig_add"$ $CMD | grep stackinit: # stackinit: pass:36 fail:0 skip:29 total:65
$ $CMD CONFIG_GCC_PLUGIN_STRUCTLEAK_USER=y | grep stackinit: # stackinit: pass:37 fail:0 skip:28 total:65
$ $CMD CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF=y | grep stackinit: # stackinit: pass:55 fail:0 skip:10 total:65
$ $CMD CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL=y | grep stackinit: # stackinit: pass:62 fail:0 skip:3 total:65
$ $CMD CONFIG_INIT_STACK_ALL_PATTERN=y --make_option LLVM=1 | grep stackinit: # stackinit: pass:60 fail:0 skip:5 total:65
$ $CMD CONFIG_INIT_STACK_ALL_ZERO=y --make_option LLVM=1 | grep stackinit: # stackinit: pass:60 fail:0 skip:5 total:65
Temporarily remove the userspace-build mode, which will be restored in a later patch.
Expand the size of the pre-case switch variable so it doesn't get accidentally cleared.
---
v1: https://lore.kernel.org/lkml/[email protected]
v2:
- split "userspace KUnit stub" into separate header and patch (Daniel)
- Improve commit log and comments (David)
- Provide mapping of expected XFAIL tests to CONFIGs (David)
---
lib/Kconfig.debug | 22 +-
lib/Makefile | 4 +-
lib/{test_stackinit.c => stackinit_kunit.c} | 269 ++++++++------------
3 files changed, 121 insertions(+), 174 deletions(-)
rename lib/{test_stackinit.c => stackinit_kunit.c} (66%)lib/Kconfig.debug +11 -11
@@ -2511,6 +2511,17 @@ config OVERFLOW_KUNIT_TEST If unsure, say N. +config STACKINIT_KUNIT_TEST + tristate "Test level of stack variable initialization" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Test if the kernel is zero-initializing stack variables and + padding. Coverage is controlled by compiler flags, + CONFIG_INIT_STACK_ALL_PATTERN, CONFIG_INIT_STACK_ALL_ZERO, + CONFIG_GCC_PLUGIN_STRUCTLEAK, CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF, + or CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL. + config TEST_UDELAY tristate "udelay test driver" help
@@ -2602,17 +2613,6 @@ config TEST_OBJAGG Enable this option to test object aggregation manager on boot (or module load). - -config TEST_STACKINIT - tristate "Test level of stack variable initialization" - help - Test if the kernel is zero-initializing stack variables and - padding. Coverage is controlled by compiler flags, - CONFIG_GCC_PLUGIN_STRUCTLEAK, CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF, - or CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL. - - If unsure, say N. - config TEST_MEMINIT tristate "Test heap/page initialization" help
lib/Makefile +2 -2
@@ -93,8 +93,6 @@ obj-$(CONFIG_TEST_KMOD) += test_kmod.o obj-$(CONFIG_TEST_DEBUG_VIRTUAL) += test_debug_virtual.o obj-$(CONFIG_TEST_MEMCAT_P) += test_memcat_p.o obj-$(CONFIG_TEST_OBJAGG) += test_objagg.o -CFLAGS_test_stackinit.o += $(call cc-disable-warning, switch-unreachable) -obj-$(CONFIG_TEST_STACKINIT) += test_stackinit.o obj-$(CONFIG_TEST_BLACKHOLE_DEV) += test_blackhole_dev.o obj-$(CONFIG_TEST_MEMINIT) += test_meminit.o obj-$(CONFIG_TEST_LOCKUP) += test_lockup.o
@@ -363,6 +361,8 @@ obj-$(CONFIG_CMDLINE_KUNIT_TEST) += cmdline_kunit.o obj-$(CONFIG_SLUB_KUNIT_TEST) += slub_kunit.o obj-$(CONFIG_MEMCPY_KUNIT_TEST) += memcpy_kunit.o obj-$(CONFIG_OVERFLOW_KUNIT_TEST) += overflow_kunit.o +CFLAGS_stackinit_kunit.o += $(call cc-disable-warning, switch-unreachable) +obj-$(CONFIG_STACKINIT_KUNIT_TEST) += stackinit_kunit.o obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o
lib/stackinit_kunit.c renamed from lib/test_stackinit.c +108 -161
369 lines not on this page · raw message
Signature · 1 line
2.32.0
PATCH v3 7/7 UAPI: Introduce KUnit userspace compatibility
In reply to Kees CookThe original lib/test_stackinit.c, which exclusively tests toolchain features, was designed to also be built without the full Linux kernel sources so that compiler developers and distro maintainers had an easy way to check for toolchain behaviors. When it was ported to KUnit, this mode was removed to simplify the code.
Add a small header that provides a minimally operational KUnit API that can allow unit tests that don't depend on kernel-specific behaviors to build and run strictly from userspace without kernel sources. Add userspace-build support back to the renamed lib/stackinit_kunit.c test.
---
v1: https://lore.kernel.org/lkml/[email protected]
v2:
- split from stackinit_kunit.c refactoring patch
- add missing returns (Daniel)
- report expression mismatch in assert msg (Daniel)
- emulate kunit_test_suites() (Daniel)
- emit valid KTAP (David)
--- include/uapi/misc/kunit.h | 181 ++++++++++++++++++++++++++++++++++++++ lib/stackinit_kunit.c | 11 +++ 2 files changed, 192 insertions(+) create mode 100644 include/uapi/misc/kunit.h
include/uapi/misc/kunit.h new file +181 -0
@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel +* KUnit API. It seeks to implement a minimal subset of features so that +* a concisely written KUnit test can be made to run entirely in userspace +* when it doesn't actually depend on any real kernel internals. +* +* Additionally contains many refactored kernel-isms to support building +* and running in userspace without full kernel source. +*/ + +#define _GNU_SOURCE +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <stdbool.h> +#include <errno.h> +#include <sys/types.h> + +#define __user/**/ +#define noinline __attribute__((__noinline__)) +#define __aligned (x) __attribute__((__aligned__(x))) +#ifdef __clang__ +# define __compiletime_error (message)/**/ +#else +# define __compiletime_error (message) __attribute__((__error__(message))) +#endif +#define __compiletime_assert (condition, msg, prefix, suffix) \ + do { \ + extern void prefix ## suffix(void) __compiletime_error(msg); \ + if (!(condition)) \ + prefix ## suffix(); \ + } while (0) +#define _compiletime_assert (condition, msg, prefix, suffix) \ + __compiletime_assert(condition, msg, prefix, suffix) +#define compiletime_assert (condition, msg) \ + _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__) +#define BUILD_BUG_ON_MSG (cond, msg) compiletime_assert(!(cond), msg) +#define BUILD_BUG_ON (condition) \ + BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition) + +#define ARRAY_SIZE (a) (sizeof (a) / sizeof ((a)[0])) + +#define MODULE_LICENSE (str)/* str */ + +typedef uint8_t u8 ; +typedef uint16_t u16 ; +typedef uint32_t u32 ; +typedef uint64_t u64 ; + +#define TEST_PASS 0 +#define TEST_SKIP 1 +#define TEST_FAIL 2 +struct kunit { +int status; +char *msg; +}; +struct kunit_case { +void (*run_case)(struct kunit *test); +const char *name; +}; +struct kunit_suite { +const char *name; +const struct kunit_case *test_cases; +}; +#define KUNIT_CASE (test_name) { .run_case = test_name, .name = #test_name } + +#define KUNIT_ASSERT_TRUE_MSG (test, expr, fmt, ...) \ +do { \ + if (!(expr)) { \ + if (test->status != TEST_SKIP) \ + test->status = TEST_FAIL; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ + } \ +} while (0) + +#define KUNIT_ASSERT_EQ_MSG (test, left, right, fmt, ...) \ + KUNIT_ASSERT_TRUE_MSG(test, (left) == (right), \ + #left " != " #right ": " fmt, \ + ##__VA_ARGS__) + +#define kunit_skip (test, fmt, ...) \ +do { \ + test->status = TEST_SKIP; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ +} while (0) + +static int do_kunit_test_suite (struct kunit_suite *suite) +{ +const struct kunit_case *test_case; +int pass =0 , fail =0 , skip =0 ; +int rc =0 ; +size_t i =0 ; + +printf (" TAP version 14\n" ); +for (test_case = suite->test_cases; test_case->run_case; test_case++) + i++; +printf (" 1..%zu\n" , i); + i =0 ; +for (test_case = suite->test_cases; test_case->run_case; test_case++) { +struct kunit test = { }; + + i++; + test_case->run_case (&test); +switch (test.status) { +default : +case TEST_FAIL : +fprintf (stderr," not ok %zu - %s%s%s" , + i, test_case->name, + test.msg ?" # ERROR " :"" , + test.msg ?:"\n" ); + rc =1 ; + fail++; +break ; +case TEST_SKIP : +fprintf (stdout," ok %zu - %s # SKIP%s%s" , + i, test_case->name, + test.msg ?" " :"" , + test.msg ?:"\n" ); + skip++; +break ; +case TEST_PASS : +fprintf (stdout," ok %zu - %s\n" , + i, test_case->name); + pass++; +break ; + } +if (test.msg) +free (test.msg); + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + suite->name, pass, fail, skip, i); +return rc; +} + +static int run_suites (char *name,struct kunit_suite *suites[],size_t count) +{ +int pass =0 , fail =0 , skip =0 ; +int one, ret =0 ; +size_t i; + +printf ("TAP version 14\n" ); +printf ("1..%zu\n" , count); +for (i =0 ; i < count; ++i) { + one =do_kunit_test_suite (suites[i]); +switch (one) { +case TEST_SKIP : + skip++; +break ; +case TEST_PASS : + pass++; +break ; +default : + fail++; +break ; + } +printf ("%sok %zu - %s\n" , + one ==TEST_FAIL ?"not " :"" , + i +1 , suites[i]->name); + ret |= one; + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + name, pass, fail, skip, count); +return ret; +} + +#define kunit_test_suites(suite...) \ +int main(int argc, char *argv[]) { \ + static struct kunit_suite *suites[] = { suite }; \ + return run_suites(argv[0], suites, ARRAY_SIZE(suites)); \ +} + +#endif /* __UAPI_MISC_KUNIT_H__ */
lib/stackinit_kunit.c +11 -0
@@ -8,7 +8,13 @@* --make_option LLVM=1 \ * --kconfig_add CONFIG_INIT_STACK_ALL_ZERO=y * +* External build example: +* clang -O2 -Wall -ftrivial-auto-var-init=pattern \ +* -o stackinit_kunit stackinit_kunit.c +* ./stackinit_kunit +* */ +#ifdef __KERNEL__#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <kunit/test.h>
@@ -17,6 +23,11 @@#include <linux/module.h> #include <linux/string.h> +#else +/* Userspace KUnit stub header. */ +#include <misc/kunit.h> +#endif +/* Exfiltration buffer. */ #define MAX_VAR_SIZE 128static u8 check_buf[MAX_VAR_SIZE ];
Signature · 1 line
2.32.0
Re: [PATCH v3 7/7] UAPI: Introduce KUnit userspace compatibility
Quoted 6 lines · Kees Cook
The original
lib/test_stackinit.c, which exclusively tests toolchain features, was designed to also be built without the full Linux kernel sources so that compiler developers and distro maintainers had an easy way to check for toolchain behaviors. When it was ported to KUnit, this mode was removed to simplify the code.
Quoted 6 lines
Add a small header that provides a minimally operational KUnit API that can allow unit tests that don't depend on kernel-specific behaviors to build and run strictly from userspace without kernel sources. Add userspace-build support back to the renamed
lib/stackinit_kunit.ctest.Signed-off-by Kees Cook <[email protected]>
This fails the hdrtest checks, so I'll need to rework it...
-Kees
Quoted 234 lines
---
v1: https://lore.kernel.org/lkml/[email protected]
v2:
- split fromstackinit_kunit.crefactoring patch
- add missing returns (Daniel)
- report expression mismatch in assert msg (Daniel)
- emulatekunit_test_suites()(Daniel)
- emit valid KTAP (David)--- include/uapi/misc/kunit.h | 181 ++++++++++++++++++++++++++++++++++++++ lib/stackinit_kunit.c | 11 +++ 2 files changed, 192 insertions(+) create mode 100644 include/uapi/misc/kunit.hinclude/uapi/misc/kunit.h new file +181
-0@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel +* KUnit API. It seeks to implement a minimal subset of features so that +* a concisely written KUnit test can be made to run entirely in userspace +* when it doesn't actually depend on any real kernel internals. +* +* Additionally contains many refactored kernel-isms to support building +* and running in userspace without full kernel source. +*/ + +#define _GNU_SOURCE +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <stdbool.h> +#include <errno.h> +#include <sys/types.h> + +#define __user/**/ +#define noinline __attribute__((__noinline__)) +#define __aligned (x) __attribute__((__aligned__(x))) +#ifdef __clang__ +# define __compiletime_error (message)/**/ +#else +# define __compiletime_error (message) __attribute__((__error__(message))) +#endif +#define __compiletime_assert (condition, msg, prefix, suffix) \ + do { \ + extern void prefix ## suffix(void) __compiletime_error(msg); \ + if (!(condition)) \ + prefix ## suffix(); \ + } while (0) +#define _compiletime_assert (condition, msg, prefix, suffix) \ + __compiletime_assert(condition, msg, prefix, suffix) +#define compiletime_assert (condition, msg) \ + _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__) +#define BUILD_BUG_ON_MSG (cond, msg) compiletime_assert(!(cond), msg) +#define BUILD_BUG_ON (condition) \ + BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition) + +#define ARRAY_SIZE (a) (sizeof (a) / sizeof ((a)[0])) + +#define MODULE_LICENSE (str)/* str */ + +typedef uint8_t u8 ; +typedef uint16_t u16 ; +typedef uint32_t u32 ; +typedef uint64_t u64 ; + +#define TEST_PASS 0 +#define TEST_SKIP 1 +#define TEST_FAIL 2 +struct kunit { +int status; +char *msg; +}; +struct kunit_case { +void (*run_case)(struct kunit *test); +const char *name; +}; +struct kunit_suite { +const char *name; +const struct kunit_case *test_cases; +}; +#define KUNIT_CASE (test_name) { .run_case = test_name, .name = #test_name } + +#define KUNIT_ASSERT_TRUE_MSG (test, expr, fmt, ...) \ +do { \ + if (!(expr)) { \ + if (test->status != TEST_SKIP) \ + test->status = TEST_FAIL; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ + } \ +} while (0) + +#define KUNIT_ASSERT_EQ_MSG (test, left, right, fmt, ...) \ + KUNIT_ASSERT_TRUE_MSG(test, (left) == (right), \ + #left " != " #right ": " fmt, \ + ##__VA_ARGS__) + +#define kunit_skip (test, fmt, ...) \ +do { \ + test->status = TEST_SKIP; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ +} while (0) + +static int do_kunit_test_suite (struct kunit_suite *suite) +{ +const struct kunit_case *test_case; +int pass =0 , fail =0 , skip =0 ; +int rc =0 ; +size_t i =0 ; + +printf (" TAP version 14\n" ); +for (test_case = suite->test_cases; test_case->run_case; test_case++) + i++; +printf (" 1..%zu\n" , i); + i =0 ; +for (test_case = suite->test_cases; test_case->run_case; test_case++) { +struct kunit test = { }; + + i++; + test_case->run_case (&test); +switch (test.status) { +default : +case TEST_FAIL : +fprintf (stderr," not ok %zu - %s%s%s" , + i, test_case->name, + test.msg ?" # ERROR " :"" , + test.msg ?:"\n" ); + rc =1 ; + fail++; +break ; +case TEST_SKIP : +fprintf (stdout," ok %zu - %s # SKIP%s%s" , + i, test_case->name, + test.msg ?" " :"" , + test.msg ?:"\n" ); + skip++; +break ; +case TEST_PASS : +fprintf (stdout," ok %zu - %s\n" , + i, test_case->name); + pass++; +break ; + } +if (test.msg) +free (test.msg); + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + suite->name, pass, fail, skip, i); +return rc; +} + +static int run_suites (char *name,struct kunit_suite *suites[],size_t count) +{ +int pass =0 , fail =0 , skip =0 ; +int one, ret =0 ; +size_t i; + +printf ("TAP version 14\n" ); +printf ("1..%zu\n" , count); +for (i =0 ; i < count; ++i) { + one =do_kunit_test_suite (suites[i]); +switch (one) { +case TEST_SKIP : + skip++; +break ; +case TEST_PASS : + pass++; +break ; +default : + fail++; +break ; + } +printf ("%sok %zu - %s\n" , + one ==TEST_FAIL ?"not " :"" , + i +1 , suites[i]->name); + ret |= one; + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + name, pass, fail, skip, count); +return ret; +} + +#define kunit_test_suites(suite...) \ +int main(int argc, char *argv[]) { \ + static struct kunit_suite *suites[] = { suite }; \ + return run_suites(argv[0], suites, ARRAY_SIZE(suites)); \ +} + +#endif /* __UAPI_MISC_KUNIT_H__ */ lib/stackinit_kunit.c +11
-0@@ -8,7 +8,13 @@* --make_option LLVM=1 \ * --kconfig_add CONFIG_INIT_STACK_ALL_ZERO=y * +* External build example: +* clang -O2 -Wall -ftrivial-auto-var-init=pattern \ +* -o stackinit_kunit stackinit_kunit.c +* ./stackinit_kunit +* */ +#ifdef __KERNEL__#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <kunit/test.h> @@ -17,6 +23,11 @@#include <linux/module.h> #include <linux/string.h> +#else +/* Userspace KUnit stub header. */ +#include <misc/kunit.h> +#endif +/* Exfiltration buffer. */ #define MAX_VAR_SIZE 128static u8 check_buf[MAX_VAR_SIZE ];Signature · 1 line
2.32.0
Signature · 1 line
Kees Cook
Re: [PATCH v3 7/7] UAPI: Introduce KUnit userspace compatibility
In reply to Kees Cook+Bart Van Assche - I don't know if you are still working on those configfs tests, but I wonder if this would be interesting to you.
Quoted 11 lines · Kees Cook
The original
lib/test_stackinit.c, which exclusively tests toolchain features, was designed to also be built without the full Linux kernel sources so that compiler developers and distro maintainers had an easy way to check for toolchain behaviors. When it was ported to KUnit, this mode was removed to simplify the code.Add a small header that provides a minimally operational KUnit API that can allow unit tests that don't depend on kernel-specific behaviors to build and run strictly from userspace without kernel sources. Add userspace-build support back to the renamed
lib/stackinit_kunit.ctest.
Very cool. I was hoping to achieve a true UAPI KUnit via LKL, but that's clearly a long way out. Besides you have a point with being able to distribute just a couple of files.
My initial thought is that a UAPI for KUnit would mostly be useful for testing parts of the kernel that have very few dependencies. However, I remembered that Bart (cc'ed) was working on some KUnit tests that would probably be better as userspace tests. I think there might be some potential for a KUnit UAPI in decoupling the test library from the test environment.
I have been thinking off and on for a little while about enabling some kind of KUnit kselftest fusion tests, where you could manage an environment in kselftest and use KUnit for testing in kernel structures. I think this is kind of going from the opposite direction, but is probably an easier place to start.
I will refrain myself from getting into too many wild ideas, but I like where this is going. I think it is reasonable to just start off with a duplicate implementation of KUnit as you have done here: we can see if this has any legs, and if so, we can do something more complicated later.
Quoted 1 line
Signed-off-by Kees Cook <[email protected]>
I have some thoughts for some things that can be improved, but after thinking about it; I think they are all things that make sense once we see if there are other potential users. I think as an initial version, this looks pretty good.
(leaving the rest of the email unclipped for Bart's benefit)
Quoted 238 lines
---
v1: https://lore.kernel.org/lkml/[email protected]
v2:
- split fromstackinit_kunit.crefactoring patch
- add missing returns (Daniel)
- report expression mismatch in assert msg (Daniel)
- emulatekunit_test_suites()(Daniel)
- emit valid KTAP (David)--- include/uapi/misc/kunit.h | 181 ++++++++++++++++++++++++++++++++++++++ lib/stackinit_kunit.c | 11 +++ 2 files changed, 192 insertions(+) create mode 100644 include/uapi/misc/kunit.hinclude/uapi/misc/kunit.h new file +181
-0@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel +* KUnit API. It seeks to implement a minimal subset of features so that +* a concisely written KUnit test can be made to run entirely in userspace +* when it doesn't actually depend on any real kernel internals. +* +* Additionally contains many refactored kernel-isms to support building +* and running in userspace without full kernel source. +*/ + +#define _GNU_SOURCE +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <stdbool.h> +#include <errno.h> +#include <sys/types.h> + +#define __user/**/ +#define noinline __attribute__((__noinline__)) +#define __aligned (x) __attribute__((__aligned__(x))) +#ifdef __clang__ +# define __compiletime_error (message)/**/ +#else +# define __compiletime_error (message) __attribute__((__error__(message))) +#endif +#define __compiletime_assert (condition, msg, prefix, suffix) \ + do { \ + extern void prefix ## suffix(void) __compiletime_error(msg); \ + if (!(condition)) \ + prefix ## suffix(); \ + } while (0) +#define _compiletime_assert (condition, msg, prefix, suffix) \ + __compiletime_assert(condition, msg, prefix, suffix) +#define compiletime_assert (condition, msg) \ + _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__) +#define BUILD_BUG_ON_MSG (cond, msg) compiletime_assert(!(cond), msg) +#define BUILD_BUG_ON (condition) \ + BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition) + +#define ARRAY_SIZE (a) (sizeof (a) / sizeof ((a)[0])) + +#define MODULE_LICENSE (str)/* str */ + +typedef uint8_t u8 ; +typedef uint16_t u16 ; +typedef uint32_t u32 ; +typedef uint64_t u64 ; + +#define TEST_PASS 0 +#define TEST_SKIP 1 +#define TEST_FAIL 2 +struct kunit { +int status; +char *msg; +}; +struct kunit_case { +void (*run_case)(struct kunit *test); +const char *name; +}; +struct kunit_suite { +const char *name; +const struct kunit_case *test_cases; +}; +#define KUNIT_CASE (test_name) { .run_case = test_name, .name = #test_name } + +#define KUNIT_ASSERT_TRUE_MSG (test, expr, fmt, ...) \ +do { \ + if (!(expr)) { \ + if (test->status != TEST_SKIP) \ + test->status = TEST_FAIL; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ + } \ +} while (0) + +#define KUNIT_ASSERT_EQ_MSG (test, left, right, fmt, ...) \ + KUNIT_ASSERT_TRUE_MSG(test, (left) == (right), \ + #left " != " #right ": " fmt, \ + ##__VA_ARGS__) + +#define kunit_skip (test, fmt, ...) \ +do { \ + test->status = TEST_SKIP; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ +} while (0) + +static int do_kunit_test_suite (struct kunit_suite *suite) +{ +const struct kunit_case *test_case; +int pass =0 , fail =0 , skip =0 ; +int rc =0 ; +size_t i =0 ; + +printf (" TAP version 14\n" ); +for (test_case = suite->test_cases; test_case->run_case; test_case++) + i++; +printf (" 1..%zu\n" , i); + i =0 ; +for (test_case = suite->test_cases; test_case->run_case; test_case++) { +struct kunit test = { }; + + i++; + test_case->run_case (&test); +switch (test.status) { +default : +case TEST_FAIL : +fprintf (stderr," not ok %zu - %s%s%s" , + i, test_case->name, + test.msg ?" # ERROR " :"" , + test.msg ?:"\n" ); + rc =1 ; + fail++; +break ; +case TEST_SKIP : +fprintf (stdout," ok %zu - %s # SKIP%s%s" , + i, test_case->name, + test.msg ?" " :"" , + test.msg ?:"\n" ); + skip++; +break ; +case TEST_PASS : +fprintf (stdout," ok %zu - %s\n" , + i, test_case->name); + pass++; +break ; + } +if (test.msg) +free (test.msg); + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + suite->name, pass, fail, skip, i); +return rc; +} + +static int run_suites (char *name,struct kunit_suite *suites[],size_t count) +{ +int pass =0 , fail =0 , skip =0 ; +int one, ret =0 ; +size_t i; + +printf ("TAP version 14\n" ); +printf ("1..%zu\n" , count); +for (i =0 ; i < count; ++i) { + one =do_kunit_test_suite (suites[i]); +switch (one) { +case TEST_SKIP : + skip++; +break ; +case TEST_PASS : + pass++; +break ; +default : + fail++; +break ; + } +printf ("%sok %zu - %s\n" , + one ==TEST_FAIL ?"not " :"" , + i +1 , suites[i]->name); + ret |= one; + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + name, pass, fail, skip, count); +return ret; +} + +#define kunit_test_suites(suite...) \ +int main(int argc, char *argv[]) { \ + static struct kunit_suite *suites[] = { suite }; \ + return run_suites(argv[0], suites, ARRAY_SIZE(suites)); \ +} + +#endif /* __UAPI_MISC_KUNIT_H__ */ lib/stackinit_kunit.c +11
-1@@ -8,7 +8,13 @@* --make_option LLVM=1 \ * --kconfig_add CONFIG_INIT_STACK_ALL_ZERO=y * +* External build example: +* clang -O2 -Wall -ftrivial-auto-var-init=pattern \ +* -o stackinit_kunit stackinit_kunit.c +* ./stackinit_kunit +* */ +#ifdef __KERNEL__#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <kunit/test.h> @@ -17,6 +23,11 @@#include <linux/module.h> #include <linux/string.h> +#else +/* Userspace KUnit stub header. */ +#include <misc/kunit.h> +#endif +/* Exfiltration buffer. */ #define MAX_VAR_SIZE 128static u8 check_buf[MAX_VAR_SIZE ]; --2.32.0
--
You received this message because you are subscribed to the Google Groups "KUnit Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/kunit-dev/20220227184517.504931-8-keescook%40chromium.org.
Re: [PATCH v3 7/7] UAPI: Introduce KUnit userspace compatibility
In reply to Kees CookQuoted 13 lines · Kees Cook
The original
lib/test_stackinit.c, which exclusively tests toolchain features, was designed to also be built without the full Linux kernel sources so that compiler developers and distro maintainers had an easy way to check for toolchain behaviors. When it was ported to KUnit, this mode was removed to simplify the code.Add a small header that provides a minimally operational KUnit API that can allow unit tests that don't depend on kernel-specific behaviors to build and run strictly from userspace without kernel sources. Add userspace-build support back to the renamed
lib/stackinit_kunit.ctest.Signed-off-by Kees Cook <[email protected]>
Quoted 9 lines
---
v1: https://lore.kernel.org/lkml/[email protected]
v2:
- split fromstackinit_kunit.crefactoring patch
- add missing returns (Daniel)
- report expression mismatch in assert msg (Daniel)
- emulatekunit_test_suites()(Daniel)
- emit valid KTAP (David)
---
This looks pretty good on-the-whole to me, modulo one bug (test suites being marked as SKIPPED instead of FAILED) below. And checkpatch being grumpy.
I do like the idea of putting this in uapi/ -- it solves the problem of distributing it quite elegantly, IMO.
-- David
Quoted 64 lines
include/uapi/misc/kunit.h | 181 ++++++++++++++++++++++++++++++++++++++ lib/stackinit_kunit.c | 11 +++ 2 files changed, 192 insertions(+) create mode 100644 include/uapi/misc/kunit.hinclude/uapi/misc/kunit.h new file +53
-0@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel +* KUnit API. It seeks to implement a minimal subset of features so that +* a concisely written KUnit test can be made to run entirely in userspace +* when it doesn't actually depend on any real kernel internals. +* +* Additionally contains many refactored kernel-isms to support building +* and running in userspace without full kernel source. +*/ + +#define _GNU_SOURCE +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <stdbool.h> +#include <errno.h> +#include <sys/types.h> + +#define __user/**/ +#define noinline __attribute__((__noinline__)) +#define __aligned (x) __attribute__((__aligned__(x))) +#ifdef __clang__ +# define __compiletime_error (message)/**/ +#else +# define __compiletime_error (message) __attribute__((__error__(message))) +#endif +#define __compiletime_assert (condition, msg, prefix, suffix) \ + do { \ + extern void prefix ## suffix(void) __compiletime_error(msg); \ + if (!(condition)) \ + prefix ## suffix(); \ + } while (0) +#define _compiletime_assert (condition, msg, prefix, suffix) \ + __compiletime_assert(condition, msg, prefix, suffix) +#define compiletime_assert (condition, msg) \ + _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__) +#define BUILD_BUG_ON_MSG (cond, msg) compiletime_assert(!(cond), msg) +#define BUILD_BUG_ON (condition) \ + BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition) + +#define ARRAY_SIZE (a) (sizeof (a) / sizeof ((a)[0])) + +#define MODULE_LICENSE (str)/* str */ + +typedef uint8_t u8 ; +typedef uint16_t u16 ; +typedef uint32_t u32 ; +typedef uint64_t u64 ; + +#define TEST_PASS 0
include/uapi/misc/kunit.h line 63
Quoted 10 lines
include/uapi/misc/kunit.h new file +10
-0+#define TEST_SKIP 1 +#define TEST_FAIL 2 +struct kunit { +int status; +char *msg; +}; +struct kunit_case { +void (*run_case)(struct kunit *test); +const char *name; +};
Nit: tabs/spaces.
There are a few other checkpatch warnings, mostly it just complaining about the use of 'return' in macros, which I think is probably still better than trying to hack something out of setjmp/longjmp at this point.
Quoted 47 lines
include/uapi/misc/kunit.h new file +47
-0+struct kunit_suite { +const char *name; +const struct kunit_case *test_cases; +}; +#define KUNIT_CASE (test_name) { .run_case = test_name, .name = #test_name } + +#define KUNIT_ASSERT_TRUE_MSG (test, expr, fmt, ...) \ +do { \ + if (!(expr)) { \ + if (test->status != TEST_SKIP) \ + test->status = TEST_FAIL; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ + } \ +} while (0) + +#define KUNIT_ASSERT_EQ_MSG (test, left, right, fmt, ...) \ + KUNIT_ASSERT_TRUE_MSG(test, (left) == (right), \ + #left " != " #right ": " fmt, \ + ##__VA_ARGS__) + +#define kunit_skip (test, fmt, ...) \ +do { \ + test->status = TEST_SKIP; \ + if (test->msg) \ + free(test->msg); \ + asprintf(&test->msg, fmt, ##__VA_ARGS__); \ + return; \ +} while (0) + +static int do_kunit_test_suite (struct kunit_suite *suite) +{ +const struct kunit_case *test_case; +int pass =0 , fail =0 , skip =0 ; +int rc =0 ; +size_t i =0 ; + +printf (" TAP version 14\n" ); +for (test_case = suite->test_cases; test_case->run_case; test_case++) + i++; +printf (" 1..%zu\n" , i); + i =0 ; +for (test_case = suite->test_cases; test_case->run_case; test_case++) { +struct kunit test = { }; +
include/uapi/misc/kunit.h line 120
Quoted 10 lines
include/uapi/misc/kunit.h new file +10
-0+ i++; + test_case->run_case (&test); +switch (test.status) { +default : +case TEST_FAIL : +fprintf (stderr," not ok %zu - %s%s%s" , + i, test_case->name, + test.msg ?" # ERROR " :"" , + test.msg ?:"\n" ); + rc =1 ;
What is this function trying to return? If 'rc' is supposed to be a result status, this should be TEST_FAIL (2)?
As-is, when a test case fails, the whole suite is being marked as SKIPPED.
The other thing worth noting is that -- if this is fixed -- there's no way a whole suite can be marked SKIPPED. KUnit will mark a suite as skipped if all of its subtests are skipped. (This is a much more niche case, though.)
Quoted 46 lines
include/uapi/misc/kunit.h new file +46
-0+ fail++; +break ; +case TEST_SKIP : +fprintf (stdout," ok %zu - %s # SKIP%s%s" , + i, test_case->name, + test.msg ?" " :"" , + test.msg ?:"\n" ); + skip++; +break ; +case TEST_PASS : +fprintf (stdout," ok %zu - %s\n" , + i, test_case->name); + pass++; +break ; + } +if (test.msg) +free (test.msg); + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + suite->name, pass, fail, skip, i); +return rc; +} + +static int run_suites (char *name,struct kunit_suite *suites[],size_t count) +{ +int pass =0 , fail =0 , skip =0 ; +int one, ret =0 ; +size_t i; + +printf ("TAP version 14\n" ); +printf ("1..%zu\n" , count); +for (i =0 ; i < count; ++i) { + one =do_kunit_test_suite (suites[i]); +switch (one) { +case TEST_SKIP : + skip++; +break ; +case TEST_PASS : + pass++; +break ; +default : + fail++; +break ; + } + printf("%sok %zu - %s\n", + one == TEST_FAIL ? "not " : "",
include/uapi/misc/kunit.h line 176
Quoted 10 lines
include/uapi/misc/kunit.h new file +10
-0+ i + 1, suites[i]->name); + ret |= one; + } +printf ("# %s: pass:%d fail:%d skip:%d total:%zu\n" , + name, pass, fail, skip, count); +return ret; +} + +#define kunit_test_suites(suite...) \ +int main(int argc, char *argv[]) { \
Nit: checkpatch really wants the '{' on the next line.
Quoted 38 lines
include/uapi/misc/kunit.h new file +5
-0+static struct kunit_suite *suites[] = { suite }; \ + return run_suites(argv[0], suites, ARRAY_SIZE(suites)); \ +} + +#endif /* __UAPI_MISC_KUNIT_H__ */ lib/stackinit_kunit.c +11
-1@@ -8,7 +8,13 @@* --make_option LLVM=1 \ * --kconfig_add CONFIG_INIT_STACK_ALL_ZERO=y * +* External build example: +* clang -O2 -Wall -ftrivial-auto-var-init=pattern \ +* -o stackinit_kunit stackinit_kunit.c +* ./stackinit_kunit +* */ +#ifdef __KERNEL__#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <kunit/test.h> @@ -17,6 +23,11 @@#include <linux/module.h> #include <linux/string.h> +#else +/* Userspace KUnit stub header. */ +#include <misc/kunit.h> +#endif +/* Exfiltration buffer. */ #define MAX_VAR_SIZE 128static u8 check_buf[MAX_VAR_SIZE ]; --2.32.0
Re: [PATCH v3 7/7] UAPI: Introduce KUnit userspace compatibility
Quoted 11 lines · David Gow
include/uapi/misc/kunit.h line 4
Quoted 10 lines · Kees Cook
include/uapi/misc/kunit.h new file +4
-0@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel
<snip>
Someone forgot a SPDX license line for the new file. Didn't checkpatch complain about this? :(
thanks,
greg k-h
Re: [PATCH v3 7/7] UAPI: Introduce KUnit userspace compatibility
Quoted 15 lines · Greg KH
Quoted 11 lines · David Gow
Quoted 10 lines · Kees Cook
include/uapi/misc/kunit.h new file +4
-0@@ -0,0 +1,181 @@ +#ifndef __UAPI_MISC_KUNIT_H__ +#define __UAPI_MISC_KUNIT_H__ +/* +* This is a light-weight userspace drop-in replacement for the in-kernel <snip>
Quoted 2 lines
Someone forgot a SPDX license line for the new file. Didn't checkpatch complain about this? :(
Yeah, that file has a bunch of problems. ;) The UAPI header checking logic also freaks out, etc, etc. I'll being fixing that and the other issues.
Signature · 1 line
Kees Cook
Quoted 39 lines · Kees Cook
Hi,
These changes all build on each other, so I'm sending this as a series to hopefully reduce confusion. I chose "v3" because it seemed the least confusing of various options.
The um changes are needed to get Clang building with um to test the stackinit KUnit test more easily (i.e. needing neither GCC 12 nor QEMU).
-Kees
David Gow (2):
um: Cleanupsyscall_handler_tdefinition/cast, fix warning
um: Remove unusedtimeval_to_ns()functionKees Cook (5):
overflow: Provide constant expressionstruct_size
lib: overflow: Convert to Kunit
um: Allow builds with Clang
lib: stackinit: Convert to KUnit
UAPI: Introduce KUnit userspace compatibilityarch/um/os-Linux/execvp.c | 1 + arch/um/os-Linux/time.c | 6 - arch/x86/um/shared/sysdep/syscalls_64.h | 5 +- arch/x86/um/user-offsets.c | 9 +- include/linux/overflow.h | 10 +- include/uapi/misc/kunit.h | 181 +++++++ lib/Kconfig.debug | 38 +- lib/Makefile | 6 +- lib/{test_overflow.c => overflow_kunit.c} | 562 +++++++++----------- lib/{test_stackinit.c => stackinit_kunit.c} | 268 ++++------ scripts/Makefile.clang | 1 + 11 files changed, 593 insertions(+), 494 deletions(-) create mode 100644 include/uapi/misc/kunit.h rename lib/{test_overflow.c => overflow_kunit.c} (54%) rename lib/{test_stackinit.c => stackinit_kunit.c} (67%)
Quoted 1 line
--
Thanks for putting all of these together. Apart from some minor checkpatch warnings (some of which are inevitable, some of which are trivial "don't put a space here" things) and an issue with the KUnit userspace compatibility layer misreporting failed suites, this all worked pretty well on my machine.
(There's also still a warning with -mno-global-merge on uml USER_CFLAGS users which shows up with clang, but that's a minor issue at best. I've sent out a patch to fix it up, though I'm not 100% convinced it's the right solution:
https://lore.kernel.org/linux-kselftest/[email protected]/
)
Otherwise, this series is:
(And, as a note to anyone else trying to apply it on another branch, it has a prerequisite of:
https://lore.kernel.org/linux-hardening/[email protected]/
)
Cheers,
-- David