Currently testing of userspace and in-kernel API use two different frameworks. kselftests for the userspace ones and Kunit for the in-kernel ones. Besides their different scopes, both have different strengths and limitations:
Kunit: * Tests are normal kernel code. * They use the regular kernel toolchain. * They can be packaged and distributed as modules conveniently.
Kselftests: * Tests are normal userspace code * They need a userspace toolchain. A kernel cross toolchain is likely not enough. * A fair amout of userland is required to run the tests, which means a full distro or handcrafted rootfs. * There is no way to conveniently package and run kselftests with a given kernel image. * The kselftests makefiles are not as powerful as regular kbuild. For example they are missing proper header dependency tracking or more complex compiler option modifications.
Therefore kunit is much easier to run against different kernel configurations and architectures. This series aims to combine kselftests and kunit, avoiding both their limitations. It works by compiling the userspace kselftests as part of the regular kernel build, embedding them into the kunit kernel or module and executing them from there. If the kernel toolchain is not fit to produce userspace because of a missing libc, the kernel's own nolibc can be used instead. The structured TAP output from the kselftest is integrated into the kunit KTAP output transparently, the kunit parser can parse the combined logs together.
Further room for improvements: * Call each test in its completely dedicated namespace * Handle additional test files besides the test executable through archives. CPIO, cramfs, etc. * Compatibility with kselftest_harness.h (in progress) * Expose the blobs in debugfs * Provide some convience wrappers around compat userprogs * Figure out a migration path/coexistence solution for kunit UAPI and tools/testing/selftests/
Output from the kunit example testcase, note the output of "example_uapi_tests".
$ ./tools/testing/kunit/kunit.py run --kunitconfig lib/kunit example ... Running tests with: $ .kunit/linux kunit.filter_glob=example kunit.enable=1 mem=1G console=tty kunit_shutdown=halt [11:53:53] ================== example (10 subtests) =================== [11:53:53] [PASSED] example_simple_test [11:53:53] [SKIPPED] example_skip_test [11:53:53] [SKIPPED] example_mark_skipped_test [11:53:53] [PASSED] example_all_expect_macros_test [11:53:53] [PASSED] example_static_stub_test [11:53:53] [PASSED] example_static_stub_using_fn_ptr_test [11:53:53] [PASSED] example_priv_test [11:53:53] =================== example_params_test =================== [11:53:53] [SKIPPED] example value 3 [11:53:53] [PASSED] example value 2 [11:53:53] [PASSED] example value 1 [11:53:53] [SKIPPED] example value 0 [11:53:53] =============== [PASSED] example_params_test =============== [11:53:53] [PASSED] example_slow_test [11:53:53] ======================= (4 subtests) ======================= [11:53:53] [PASSED] procfs [11:53:53] [PASSED] userspace test 2 [11:53:53] [SKIPPED] userspace test 3: some reason [11:53:53] [PASSED] userspace test 4 [11:53:53] ================ [PASSED] example_uapi_test ================ [11:53:53] ===================== [PASSED] example ===================== [11:53:53] ============================================================ [11:53:53] Testing complete. Ran 16 tests: passed: 11, skipped: 5 [11:53:53] Elapsed time: 67.543s total, 1.823s configuring, 65.655s building, 0.058s running
Based on v6.15-rc1.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- Changes in v2: - Rebase onto v6.15-rc1 - Add documentation and kernel docs - Resolve invalid kconfig breakages - Drop already applied patch "kbuild: implement CONFIG_HEADERS_INSTALL for Usermode Linux" - Drop userprogs CONFIG_WERROR integration, it doesn't need to be part of this series - Replace patch prefix "kconfig" with "kbuild" - Rename kunit_uapi_run_executable() to kunit_uapi_run_kselftest() - Generate private, conflict-free symbols in the blob framework - Handle kselftest exit codes - Handle SIGABRT - Forward output also to kunit debugfs log - Install a fd=0 stdin filedescriptor - Link to v1: https://lore.kernel.org/r/20250217-kunit-kselftests-v1-0-42b4524c3b0a@linutr...
--- Thomas Weißschuh (11): kbuild: userprogs: add nolibc support kbuild: introduce CONFIG_ARCH_HAS_NOLIBC kbuild: doc: add label for userprogs section kbuild: introduce blob framework kunit: tool: Add test for nested test result reporting kunit: tool: Don't overwrite test status based on subtest counts kunit: tool: Parse skipped tests from kselftest.h kunit: Introduce UAPI testing framework kunit: uapi: Add example for UAPI tests kunit: uapi: Introduce preinit executable kunit: uapi: Validate usability of /proc
Documentation/dev-tools/kunit/api/index.rst | 5 + Documentation/dev-tools/kunit/api/uapi.rst | 12 + Documentation/kbuild/makefiles.rst | 37 ++- MAINTAINERS | 2 + include/kunit/uapi.h | 24 ++ include/linux/blob.h | 32 +++ init/Kconfig | 2 + lib/kunit/.kunitconfig | 2 + lib/kunit/Kconfig | 11 + lib/kunit/Makefile | 18 +- lib/kunit/kunit-example-test.c | 15 ++ lib/kunit/kunit-example-uapi.c | 56 ++++ lib/kunit/uapi-preinit.c | 65 +++++ lib/kunit/uapi.c | 294 +++++++++++++++++++++ scripts/Makefile.blobs | 19 ++ scripts/Makefile.build | 6 + scripts/Makefile.clean | 2 +- scripts/Makefile.userprogs | 16 +- scripts/blob-wrap.c | 27 ++ tools/include/nolibc/Kconfig.nolibc | 13 + tools/testing/kunit/kunit_parser.py | 13 +- tools/testing/kunit/kunit_tool_test.py | 9 + .../test_is_test_passed-failure-nested.log | 10 + .../test_data/test_is_test_passed-kselftest.log | 3 +- 24 files changed, 682 insertions(+), 11 deletions(-) --- base-commit: bf9962cc9ec3ac1dae2bf81b126657c1c49c348a change-id: 20241015-kunit-kselftests-56273bc40442
Best regards,
Userprogs are built with the regular kernel compiler $CC. A kernel compiler does not necessarily contain a libc which is required for a normal userspace application. However the kernel tree does contain a minimal libc implementation "nolibc" which can be used to build userspace applications.
Introduce support to build userprogs against nolibc instead of the default libc of the compiler, which may not exist.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de
--- This could probably be moved out of the generic kbuild makefiles. I think the ergonimics would suffer and this functionality could be used by other users of userprogs.
Also this does currently not support out-of-tree builds. For that tools/include/nolibc/*.h and usr/include/*.h would need to be installed into the build directory. --- Documentation/kbuild/makefiles.rst | 12 ++++++++++++ scripts/Makefile.userprogs | 16 +++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/Documentation/kbuild/makefiles.rst b/Documentation/kbuild/makefiles.rst index 3b9a8bc671e2e92126857059e985d6e5b2c43fd4..f905a6f77c965311c491cfd7ab3103185af7e82e 100644 --- a/Documentation/kbuild/makefiles.rst +++ b/Documentation/kbuild/makefiles.rst @@ -970,6 +970,18 @@ When linking bpfilter_umh, it will be passed the extra option -static.
From command line, :ref:`USERCFLAGS and USERLDFLAGS <userkbuildflags>` will also be used.
+Bulding userprogs against nolibc +-------------------------------- + +Not all kernel toolchains provide a libc. +Simple userprogs can be built against a very simple libc call "nolibc" provided +by the kernel source tree. + +Example:: + + # lib/kunit/Makefile + uapi-preinit-nolibc := $(CONFIG_ARCH_HAS_NOLIBC) + When userspace programs are actually built ------------------------------------------
diff --git a/scripts/Makefile.userprogs b/scripts/Makefile.userprogs index f3a7e1ef3753b54303718fae97f4b3c9d4eac07c..a1447c02b948901631098b585f5cf4d3ea383a57 100644 --- a/scripts/Makefile.userprogs +++ b/scripts/Makefile.userprogs @@ -16,10 +16,20 @@ user-csingle := $(addprefix $(obj)/, $(user-csingle)) user-cmulti := $(addprefix $(obj)/, $(user-cmulti)) user-cobjs := $(addprefix $(obj)/, $(user-cobjs))
+user-libgcc := $(call try-run,$(CC) -Werror $(KBUILD_USERCFLAGS) -lgcc -x c -shared /dev/null -o "$$TMP",-lgcc) + +user_nolibc_ccflags := -nostdlib -nostdinc -static -fno-ident -fno-asynchronous-unwind-tables \ + -ffreestanding -fno-stack-protector \ + -isystem $(objtree)/usr/include -include $(srctree)/tools/include/nolibc/nolibc.h -isystem $(srctree)/tools/include/nolibc/ +user_nolibc_ldflags := -nostdlib -nostdinc -static +user_nolibc_ldlibs := $(user-libgcc) + user_ccflags = -Wp,-MMD,$(depfile) $(KBUILD_USERCFLAGS) $(userccflags) \ - $($(target-stem)-userccflags) -user_ldflags = $(KBUILD_USERLDFLAGS) $(userldflags) $($(target-stem)-userldflags) -user_ldlibs = $(userldlibs) $($(target-stem)-userldlibs) + $($(target-stem)-userccflags) $(if $($(target-stem)-nolibc),$(user_nolibc_ccflags)) +user_ldflags = $(KBUILD_USERLDFLAGS) $(userldflags) $($(target-stem)-userldflags) \ + $(if $($(target-stem)-nolibc),$(user_nolibc_ldflags)) +user_ldlibs = $(userldlibs) $($(target-stem)-userldlibs) \ + $(if $($(target-stem)-nolibc),$(user_nolibc_ldlibs))
# Create an executable from a single .c file quiet_cmd_user_cc_c = CC [U] $@
Nolibc does not support all architectures. Add a kconfig option, so users can know where it is available.
The new option is maintained inside tools/include/nolibc/ as only that directory is responsible for nolibc's availability.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- init/Kconfig | 2 ++ tools/include/nolibc/Kconfig.nolibc | 13 +++++++++++++ 2 files changed, 15 insertions(+)
diff --git a/init/Kconfig b/init/Kconfig index dd2ea3b9a799205daa4c1f0c694a9027e344c690..661079a71f30d8d7894d51726686801f8a25b50b 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -92,6 +92,8 @@ config CC_CAN_LINK_STATIC default $(success,$(srctree)/scripts/cc-can-link.sh $(CC) $(CLANG_FLAGS) $(USERCFLAGS) $(USERLDFLAGS) $(m64-flag) -static) if 64BIT default $(success,$(srctree)/scripts/cc-can-link.sh $(CC) $(CLANG_FLAGS) $(USERCFLAGS) $(USERLDFLAGS) $(m32-flag) -static)
+source "tools/include/nolibc/Kconfig.nolibc" + # Fixed in GCC 14, 13.3, 12.4 and 11.5 # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113921 config GCC_ASM_GOTO_OUTPUT_BROKEN diff --git a/tools/include/nolibc/Kconfig.nolibc b/tools/include/nolibc/Kconfig.nolibc new file mode 100644 index 0000000000000000000000000000000000000000..60408f02d0da3275c70f550b98a9e60c1558238f --- /dev/null +++ b/tools/include/nolibc/Kconfig.nolibc @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: GPL-2.0 + +config ARCH_HAS_NOLIBC + bool + default y if X86 + default y if ARM + default y if ARM64 + default y if PPC + default y if MIPS + default y if LOONGARCH + default y if RISCV + default y if S390 + default y if UML_X86
Some upcoming new documentation should link directly to the userprogs section.
Add a label to the section so it can be referenced.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- Documentation/kbuild/makefiles.rst | 2 ++ 1 file changed, 2 insertions(+)
diff --git a/Documentation/kbuild/makefiles.rst b/Documentation/kbuild/makefiles.rst index f905a6f77c965311c491cfd7ab3103185af7e82e..d5cd73820e406276ee2e3721e265e3ed3cc299c9 100644 --- a/Documentation/kbuild/makefiles.rst +++ b/Documentation/kbuild/makefiles.rst @@ -887,6 +887,8 @@ This is possible in two ways: This will tell kbuild to build lxdialog even if not referenced in any rule.
+.. _kbuild_userprogs: + Userspace Program support =========================
Various subsystems embed non-code build artifacts into the kernel, for example the initramfs, /proc/config.gz, vDSO image, etc. Currently each user has their own implementation for that.
Add a common "blob" framework to provide this functionality. It provides standard kbuild and C APIs to embed and later access non-code build artifacts into the kernel image or modules.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de
--- Due to its closeness to kbuild this is currently added to its MAINTAINER entry. But I can also maintain it on its own. --- Documentation/kbuild/makefiles.rst | 23 +++++++++++++++++++++-- MAINTAINERS | 2 ++ include/linux/blob.h | 32 ++++++++++++++++++++++++++++++++ scripts/Makefile.blobs | 19 +++++++++++++++++++ scripts/Makefile.build | 6 ++++++ scripts/Makefile.clean | 2 +- scripts/blob-wrap.c | 27 +++++++++++++++++++++++++++ 7 files changed, 108 insertions(+), 3 deletions(-)
diff --git a/Documentation/kbuild/makefiles.rst b/Documentation/kbuild/makefiles.rst index d5cd73820e406276ee2e3721e265e3ed3cc299c9..c3a165fcb1ab0bbc090fd61c38ebd78317c7aa85 100644 --- a/Documentation/kbuild/makefiles.rst +++ b/Documentation/kbuild/makefiles.rst @@ -521,8 +521,8 @@ otherwise the command line check will fail, and the target will always be built.
If the target is already listed in the recognized syntax such as -obj-y/m, lib-y/m, extra-y/m, always-y/m, hostprogs, userprogs, Kbuild -automatically adds it to $(targets). Otherwise, the target must be +obj-y/m, lib-y/m, extra-y/m, always-y/m, hostprogs, userprogs, blobs, +Kbuild automatically adds it to $(targets). Otherwise, the target must be explicitly added to $(targets).
Assignments to $(targets) are without $(obj)/ prefix. if_changed may be @@ -1014,6 +1014,25 @@ There are two ways to do this. This will tell Kbuild to build binderfs_example when it visits this Makefile.
+.. _kbuild_blobs: + +Blob framework +============== + +Kbuild supports wrapping source or generated files into object files which are linked +into the kernel and then accessed at runtime through ``include/linux/blob.h``. + +Example:: + + obj-m := some-module.o + userprogs := some-userprog + blobs := some-userprog.blob.o + some-userprog.blob-symbol := some_userprog + some-module-y += some-userprog.blob.o + +Kbuild will build the :ref:`userprog <kbuild_userprogs>` ``some-userprog`` and +link it into ``some-module`` from where it can be accessed as ``BLOB(some_userprog)``. + Kbuild clean infrastructure ===========================
diff --git a/MAINTAINERS b/MAINTAINERS index 96b82704950184bd71623ff41fc4df31e4c7fe87..d61e28e289c7027c026a872cd166342a4761b2a4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -12847,11 +12847,13 @@ Q: https://patchwork.kernel.org/project/linux-kbuild/list/ T: git git://git.kernel.org/pub/scm/linux/kernel/git/masahiroy/linux-kbuild.git F: Documentation/kbuild/ F: Makefile +F: include/linux/blob.h F: scripts/*vmlinux* F: scripts/Kbuild* F: scripts/Makefile* F: scripts/bash-completion/ F: scripts/basic/ +F: scripts/blob-wrap.c F: scripts/clang-tools/ F: scripts/dummy-tools/ F: scripts/include/ diff --git a/include/linux/blob.h b/include/linux/blob.h new file mode 100644 index 0000000000000000000000000000000000000000..de76cdb76cbab388b62f574b80fb13a4c84d1d2d --- /dev/null +++ b/include/linux/blob.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Linkable blob API. + * + * Copyright (C) 2025, Linutronix GmbH. + * Author: Thomas Weißschuh thomas.weissschuh@linutronix.de + */ + +#ifndef _LINUX_BLOB_H +#define _LINUX_BLOB_H + +#include <linux/args.h> +#include <linux/compiler_types.h> +#include <linux/types.h> + +struct blob { + const char *const path; + const u8 *data; + const u8 __private *end; +}; + +#define BLOB(_symbol) ({ \ + extern const struct blob CONCATENATE(__blob_, _symbol); \ + &CONCATENATE(__blob_, _symbol); \ +}) + +static inline size_t blob_size(const struct blob *blob) +{ + return ACCESS_PRIVATE(blob, end) - blob->data; +} + +#endif /* _LINUX_BLOB_H */ diff --git a/scripts/Makefile.blobs b/scripts/Makefile.blobs new file mode 100644 index 0000000000000000000000000000000000000000..fd20ebb41c1d6509750debf7896a08a143d28759 --- /dev/null +++ b/scripts/Makefile.blobs @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# Build linkable blobs +# + +blobs := $(addprefix $(obj)/, $(blobs)) + +blob-stem = $(subst -,_,$(subst .blob,,$(basename $(patsubst $(obj)/%,%,$@)))) +blob-symbol = $(or $($(target-stem)-symbol),$(blob-stem)) + +blob-flags = -DBLOB_SYMBOL="$(blob-symbol)" -DBLOB_INPUT=$< + +quiet_cmd_blob = BLOB $@ + cmd_blob = $(CC) $(c_flags) $(blob-flags) -c -o $@ $(srctree)/scripts/blob-wrap.c + +$(blobs): $(obj)/%.blob.o: $(obj)/% $(srctree)/scripts/blob-wrap.c FORCE + $(call if_changed_dep,blob) + +targets += $(blobs) diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 13dcd86e74ca830ce3fb2587df7f200105490881..c2965ee4002d239bf4e18115e026e7bcd5abb197 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -436,6 +436,12 @@ ifneq ($(need-dtbslist)$(dtb-y)$(dtb-)$(filter %.dtb %.dtb.o %.dtbo.o,$(targets) include $(srctree)/scripts/Makefile.dtbs endif
+# $(sort ...) is used here to remove duplicated words and excessive spaces. +blobs := $(sort $(blobs)) +ifneq ($(blobs),) +include $(srctree)/scripts/Makefile.blobs +endif + # Build # ---------------------------------------------------------------------------
diff --git a/scripts/Makefile.clean b/scripts/Makefile.clean index 6ead00ec7313b3e4330a8de5f1342f2da1d6eb84..536972b0a528d117e17296da9936825c3903af6e 100644 --- a/scripts/Makefile.clean +++ b/scripts/Makefile.clean @@ -25,7 +25,7 @@ subdir-ymn := $(addprefix $(obj)/,$(subdir-ymn)) # directory
__clean-files := \ - $(clean-files) $(targets) $(hostprogs) $(userprogs) \ + $(clean-files) $(targets) $(hostprogs) $(userprogs) $(blobs) \ $(extra-y) $(extra-m) $(extra-) \ $(always-y) $(always-m) $(always-) \ $(hostprogs-always-y) $(hostprogs-always-m) $(hostprogs-always-) \ diff --git a/scripts/blob-wrap.c b/scripts/blob-wrap.c new file mode 100644 index 0000000000000000000000000000000000000000..82ab3bc641bd69ec35029c2f4a9dd6d6c6720a02 --- /dev/null +++ b/scripts/blob-wrap.c @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/args.h> +#include <linux/blob.h> +#include <linux/stringify.h> + +#define BLOB_SYMBOL_DATA CONCATENATE(__blob_data_, BLOB_SYMBOL) +#define BLOB_SYMBOL_END CONCATENATE(__blob_end_, BLOB_SYMBOL) + +asm ( +" .pushsection .rodata, "a"\n" +" .global " __stringify(BLOB_SYMBOL_DATA) "\n" +__stringify(BLOB_SYMBOL_DATA) ":\n" +" .incbin "" __stringify(BLOB_INPUT) ""\n" +" .global " __stringify(BLOB_SYMBOL_END) "\n" +__stringify(BLOB_SYMBOL_END) ":\n" +" .popsection\n" +); + +extern const u8 BLOB_SYMBOL_DATA; +extern const u8 BLOB_SYMBOL_END; + +const struct blob CONCATENATE(__blob_, BLOB_SYMBOL) = { + .path = __stringify(BLOB_INPUT), + .data = &BLOB_SYMBOL_DATA, + .end = &BLOB_SYMBOL_END, +};
Currently there is no test validating the result reporting from nested tests. Add one, it will also be used to validate upcoming changes to the nested test parsing.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- tools/testing/kunit/kunit_tool_test.py | 9 +++++++++ .../kunit/test_data/test_is_test_passed-failure-nested.log | 7 +++++++ 2 files changed, 16 insertions(+)
diff --git a/tools/testing/kunit/kunit_tool_test.py b/tools/testing/kunit/kunit_tool_test.py index 5ff4f6ffd8736de3fca17dd9fcceabd7a68f9f98..755dc24350a76306a5b76998646e56fb3e386232 100755 --- a/tools/testing/kunit/kunit_tool_test.py +++ b/tools/testing/kunit/kunit_tool_test.py @@ -165,6 +165,15 @@ class KUnitParserTest(unittest.TestCase): self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status) self.assertEqual(result.counts.errors, 0)
+ def test_parse_failed_nested_tests_log(self): + nested_log = test_data_path('test_is_test_passed-failure-nested.log') + with open(nested_log) as file: + result = kunit_parser.parse_run_tests(file.readlines(), stdout) + self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status) + self.assertEqual(result.counts.failed, 2) + self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[0].status) + self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[1].status) + def test_no_header(self): empty_log = test_data_path('test_is_test_passed-no_tests_run_no_header.log') with open(empty_log) as file: diff --git a/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log b/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log new file mode 100644 index 0000000000000000000000000000000000000000..835816e0a07715a514f5f5afab1b6250037feaf4 --- /dev/null +++ b/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log @@ -0,0 +1,7 @@ +KTAP version 1 +1..2 +not ok 1 subtest 1 + KTAP version 1 + 1..1 + not ok 1 test 1 +not ok 2 subtest 2
If a subtest itself reports success, but the outer testcase fails, the whole testcase should be reported as a failure. However the status is recalculated based on the test counts, overwriting the outer test result. Synthesize a failed test in this case to make sure the failure is not swallowed.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- tools/testing/kunit/kunit_parser.py | 5 +++++ tools/testing/kunit/kunit_tool_test.py | 2 +- tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log | 3 +++ 3 files changed, 9 insertions(+), 1 deletion(-)
diff --git a/tools/testing/kunit/kunit_parser.py b/tools/testing/kunit/kunit_parser.py index da53a709773a23252703b74109142294899b1bbb..b4a695ed7d2c88120b35b617f0ff2f1cb2be60fb 100644 --- a/tools/testing/kunit/kunit_parser.py +++ b/tools/testing/kunit/kunit_parser.py @@ -686,6 +686,11 @@ def bubble_up_test_results(test: Test) -> None: counts.add_status(status) elif test.counts.get_status() == TestStatus.TEST_CRASHED: test.status = TestStatus.TEST_CRASHED + if not test.ok_status(): + for t in subtests: + if not t.ok_status(): + counts.add_status(t.status) + break
def parse_test(lines: LineStream, expected_num: int, log: List[str], is_subtest: bool, printer: Printer) -> Test: """ diff --git a/tools/testing/kunit/kunit_tool_test.py b/tools/testing/kunit/kunit_tool_test.py index 755dc24350a76306a5b76998646e56fb3e386232..946a68eca16467d9a4bae50f5d50985d9765ed54 100755 --- a/tools/testing/kunit/kunit_tool_test.py +++ b/tools/testing/kunit/kunit_tool_test.py @@ -170,7 +170,7 @@ class KUnitParserTest(unittest.TestCase): with open(nested_log) as file: result = kunit_parser.parse_run_tests(file.readlines(), stdout) self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status) - self.assertEqual(result.counts.failed, 2) + self.assertEqual(result.counts.failed, 3) self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[0].status) self.assertEqual(kunit_parser.TestStatus.FAILURE, result.subtests[1].status)
diff --git a/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log b/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log index 835816e0a07715a514f5f5afab1b6250037feaf4..cd9033c464792e6294905a5676346684182874ad 100644 --- a/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log +++ b/tools/testing/kunit/test_data/test_is_test_passed-failure-nested.log @@ -1,5 +1,8 @@ KTAP version 1 1..2 + KTAP version 1 + 1..1 + ok 1 test 1 not ok 1 subtest 1 KTAP version 1 1..1
Skipped tests reported by kselftest.h use a different format than KTAP, there is no explicit test name. Normally the test name is part of the free-form string after the SKIP keyword:
ok 3 # SKIP test: some reason
Extend the parser to handle those correctly. Use the free-form string as test name instead.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- tools/testing/kunit/kunit_parser.py | 8 +++++--- tools/testing/kunit/test_data/test_is_test_passed-kselftest.log | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-)
diff --git a/tools/testing/kunit/kunit_parser.py b/tools/testing/kunit/kunit_parser.py index b4a695ed7d2c88120b35b617f0ff2f1cb2be60fb..41aaa85d249b592efe6227a4c2d9517a5c13dbef 100644 --- a/tools/testing/kunit/kunit_parser.py +++ b/tools/testing/kunit/kunit_parser.py @@ -352,9 +352,9 @@ def parse_test_plan(lines: LineStream, test: Test) -> bool: lines.pop() return True
-TEST_RESULT = re.compile(r'^\s*(ok|not ok) ([0-9]+) (- )?([^#]*)( # .*)?$') +TEST_RESULT = re.compile(r'^\s*(ok|not ok) ([0-9]+)? ?(- )?([^#]*)( # .*)?$')
-TEST_RESULT_SKIP = re.compile(r'^\s*(ok|not ok) ([0-9]+) (- )?(.*) # SKIP(.*)$') +TEST_RESULT_SKIP = re.compile(r'^\s*(ok|not ok) ([0-9]+)? ?(- )?(.*) # SKIP ?(.*)$')
def peek_test_name_match(lines: LineStream, test: Test) -> bool: """ @@ -379,6 +379,8 @@ def peek_test_name_match(lines: LineStream, test: Test) -> bool: if not match: return False name = match.group(4) + if not name: + return False return name == test.name
def parse_test_result(lines: LineStream, test: Test, @@ -416,7 +418,7 @@ def parse_test_result(lines: LineStream, test: Test,
# Set name of test object if skip_match: - test.name = skip_match.group(4) + test.name = skip_match.group(4) or skip_match.group(5) else: test.name = match.group(4)
diff --git a/tools/testing/kunit/test_data/test_is_test_passed-kselftest.log b/tools/testing/kunit/test_data/test_is_test_passed-kselftest.log index 65d3f27feaf22a3f47ed831c4c24f6f11c625a92..30d9ef18bcec177067288d5242771236f29b7d56 100644 --- a/tools/testing/kunit/test_data/test_is_test_passed-kselftest.log +++ b/tools/testing/kunit/test_data/test_is_test_passed-kselftest.log @@ -1,5 +1,5 @@ TAP version 13 -1..2 +1..3 # selftests: membarrier: membarrier_test_single_thread # TAP version 13 # 1..2 @@ -12,3 +12,4 @@ ok 1 selftests: membarrier: membarrier_test_single_thread # ok 1 sys_membarrier available # ok 2 sys membarrier invalid command test: command = -1, flags = 0, errno = 22. Failed as expected ok 2 selftests: membarrier: membarrier_test_multi_thread +ok 3 # SKIP selftests: membarrier: membarrier_test_multi_thread
Enable running UAPI tests as part of kunit. The selftests are embedded into the kernel image and their output is forwarded to kunit for unified reporting.
The implementation reuses parts of usermode drivers and usermode helpers. However these frameworks are not used directly as they make it impossible to retrieve a thread's exit code.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de
--- Currently this depends on CONFIG_KUNIT=y as it uses some non-exported symbols around process management. --- Documentation/dev-tools/kunit/api/index.rst | 5 + Documentation/dev-tools/kunit/api/uapi.rst | 12 ++ include/kunit/uapi.h | 24 +++ lib/kunit/Kconfig | 11 ++ lib/kunit/Makefile | 2 + lib/kunit/uapi.c | 287 ++++++++++++++++++++++++++++ 6 files changed, 341 insertions(+)
diff --git a/Documentation/dev-tools/kunit/api/index.rst b/Documentation/dev-tools/kunit/api/index.rst index 5cdb552a0808f25baeff5e47a9227b7b62c69e40..34d8fee9a97059d6da919a6fb1a7e359b5e0beef 100644 --- a/Documentation/dev-tools/kunit/api/index.rst +++ b/Documentation/dev-tools/kunit/api/index.rst @@ -9,6 +9,7 @@ API Reference test resource functionredirection + uapi clk of platformdevice @@ -32,6 +33,10 @@ Documentation/dev-tools/kunit/api/functionredirection.rst
- Documents the KUnit Function Redirection API
+Documentation/dev-tools/kunit/api/uapi.rst + + - Documents the KUnit Userspace testing API + Driver KUnit API ================
diff --git a/Documentation/dev-tools/kunit/api/uapi.rst b/Documentation/dev-tools/kunit/api/uapi.rst new file mode 100644 index 0000000000000000000000000000000000000000..b4764424c629bf69194cf2786f52aef154b02bf8 --- /dev/null +++ b/Documentation/dev-tools/kunit/api/uapi.rst @@ -0,0 +1,12 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================== +Userspace Test API +================== + +This file documents all of the userspace testing API. +Userspace tests should be built as :ref:`userprogs <kbuild_userprogs>` and included into the test +module or kernel as :ref:`blobs <kbuild_blobs>`. + +.. kernel-doc:: include/kunit/uapi.h + :internal: diff --git a/include/kunit/uapi.h b/include/kunit/uapi.h new file mode 100644 index 0000000000000000000000000000000000000000..a6181790c96a42df05839097991c1fbfd889cdbe --- /dev/null +++ b/include/kunit/uapi.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * KUnit Userspace testing API. + * + * Copyright (C) 2025, Linutronix GmbH. + * Author: Thomas Weißschuh thomas.weissschuh@linutronix.de + */ + +#ifndef _KUNIT_UAPI_H +#define _KUNIT_UAPI_H + +struct blob; +struct kunit; + +/** + * kunit_uapi_run_kselftest() - Run a userspace kselftest as part of kunit + * @test: The test context object. + * @executable: kselftest executable to run + * + * Runs the kselftest and forwards its TAP output and exit status to kunit. + */ +void kunit_uapi_run_kselftest(struct kunit *test, const struct blob *executable); + +#endif /* _KUNIT_UAPI_H */ diff --git a/lib/kunit/Kconfig b/lib/kunit/Kconfig index a97897edd9642f3e5df7fdd9dee26ee5cf00d6a4..79fcf0565f60100920b9613199421bf9cae1c2b0 100644 --- a/lib/kunit/Kconfig +++ b/lib/kunit/Kconfig @@ -93,4 +93,15 @@ config KUNIT_AUTORUN_ENABLED In most cases this should be left as Y. Only if additional opt-in behavior is needed should this be set to N.
+config KUNIT_UAPI + def_bool y + depends on KUNIT=y + depends on CC_CAN_LINK_STATIC || ARCH_HAS_NOLIBC + depends on TMPFS + select HEADERS_INSTALL + help + Enables support for building and running userspace selftests as part of kunit. + These tests should be statically linked and use kselftest.h or kselftest_harness.h + for status reporting. + endif # KUNIT diff --git a/lib/kunit/Makefile b/lib/kunit/Makefile index 5aa51978e456ab3bb60c12071a26cf2bdcb1b508..989933dab9ad2267f376db470b876ce2a88711b4 100644 --- a/lib/kunit/Makefile +++ b/lib/kunit/Makefile @@ -12,6 +12,8 @@ kunit-objs += test.o \ device.o \ platform.o
+kunit-$(CONFIG_KUNIT_UAPI) += uapi.o + ifeq ($(CONFIG_KUNIT_DEBUGFS),y) kunit-objs += debugfs.o endif diff --git a/lib/kunit/uapi.c b/lib/kunit/uapi.c new file mode 100644 index 0000000000000000000000000000000000000000..081ddc46e3ccb9ef88f9cb2a66d5e2bf41da2eb4 --- /dev/null +++ b/lib/kunit/uapi.c @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit Userspace testing API. + * + * Copyright (C) 2025, Linutronix GmbH. + * Author: Thomas Weißschuh thomas.weissschuh@linutronix.de + */ + +#include <linux/binfmts.h> +#include <linux/blob.h> +#include <linux/file.h> +#include <linux/fs.h> +#include <linux/fs_struct.h> +#include <linux/pid.h> +#include <linux/pipe_fs_i.h> +#include <linux/sched/task.h> +#include <linux/types.h> + +#include <kunit/test.h> +#include <kunit/uapi.h> + +#define KSFT_PASS 0 +#define KSFT_FAIL 1 +#define KSFT_XFAIL 2 +#define KSFT_XPASS 3 +#define KSFT_SKIP 4 + +static struct vfsmount *kunit_uapi_mount_tmpfs(void) +{ + struct file_system_type *type; + struct vfsmount *mnt; + + type = get_fs_type("tmpfs"); + if (!type) + return ERR_PTR(-ENODEV); + + /* FIXME + * The mount setup is supposed to look like this: + * kunit_uapi_mount_tmpfs() sets up a private mount, + * with nothing visible except the new tmpfs. + * Then each executable execution gets a new namespace on top of that + * on which it can mount whatever it needs. + * However I didn't manage to set this up, so keep everything simple + * for now and let somebody familiar with the VFS figure this out. + */ + + mnt = kern_mount(type); + put_filesystem(type); + + return mnt; +} + +static int kunit_uapi_write_file(struct vfsmount *mnt, const char *name, mode_t mode, + const u8 *data, size_t size) +{ + struct file *file; + ssize_t written; + + file = file_open_root_mnt(mnt, name, O_CREAT | O_WRONLY, mode); + if (IS_ERR(file)) + return PTR_ERR(file); + + written = kernel_write(file, data, size, NULL); + filp_close(file, NULL); + if (written != size) { + if (written >= 0) + return -ENOMEM; + return written; + } + + /* Flush delayed fput so exec can open the file read-only */ + flush_delayed_fput(); + + return 0; +} + +struct kunit_uapi_user_mode_thread_ctx { + const char *executable; + + /* Signals mnt, out, pwd and tgid */ + struct completion setup_done; + struct vfsmount *mnt; + struct file *out; + struct path pwd; + pid_t tgid; + + /* Valid after wait(tgid) */ + int exec_err; +}; + +static int kunit_uapi_user_mode_thread_init(void *data) +{ + struct kunit_uapi_user_mode_thread_ctx *ctx = data; + const char *const argv[] = { + ctx->executable, + NULL + }; + struct file *out[2]; + int err; + + err = create_pipe_files(out, 0); + if (err) + return err; + + /* stdin, use the *write* end to the pipe to have an unreadable input */ + err = replace_fd(0, out[1], 0); + if (err < 0) { + fput(out[0]); + fput(out[1]); + return err; + } + + /* stdout */ + err = replace_fd(1, out[1], 0); + if (err < 0) { + replace_fd(0, NULL, 0); + fput(out[0]); + fput(out[1]); + return err; + } + + /* stderr */ + err = replace_fd(2, out[1], 0); + if (err < 0) { + replace_fd(0, NULL, 0); + replace_fd(1, NULL, 0); + fput(out[0]); + fput(out[1]); + return err; + } + + fput(out[1]); + + ctx->out = out[0]; + ctx->tgid = current->tgid; + + set_fs_pwd(current->fs, &ctx->pwd); + kernel_sigaction(SIGKILL, SIG_DFL); + kernel_sigaction(SIGABRT, SIG_DFL); + + complete(&ctx->setup_done); + ctx->exec_err = kernel_execve(ctx->executable, argv, NULL); + if (!ctx->exec_err) + return 0; + do_exit(0); +} + +static size_t kunit_uapi_printk_subtest_lines(struct kunit *test, char *buf, size_t s) +{ + const char *ptr = buf, *newline; + size_t n; + + while (s) { + newline = strnchr(ptr, s, '\n'); + if (!newline) + break; + + n = newline - ptr + 1; + + kunit_log(KERN_INFO, test, KUNIT_SUBSUBTEST_INDENT "%.*s", (int)n, ptr); + ptr += n; + s -= n; + } + + memmove(buf, ptr, s); + + return s; +} + +static int kunit_uapi_forward_to_printk(struct kunit *test, struct file *output) +{ + /* + * printk() automatically adds a newline after each message. + * Therefore only fully accumulated lines can be forwarded. + * Each line needs to fit into the buffer below. + */ + char buf[512]; + size_t s = 0; + ssize_t n; + + while (1) { + n = kernel_read(output, buf + s, sizeof(buf) - s, NULL); + if (n <= 0) + return n; + s = kunit_uapi_printk_subtest_lines(test, buf, s + n); + } +} + +static void kunit_uapi_kill_pid(pid_t pid) +{ + struct pid *p; + + p = find_get_pid(pid); + kill_pid(p, SIGKILL, 1); + put_pid(p); +} + +static int kunit_uapi_run_executable_in_mount(struct kunit *test, const char *executable, + struct vfsmount *mnt) +{ + struct kunit_uapi_user_mode_thread_ctx ctx = { + .setup_done = COMPLETION_INITIALIZER_ONSTACK(ctx.setup_done), + .executable = executable, + .pwd = { + .mnt = mnt, + .dentry = mnt->mnt_root, + }, + }; + int forward_err, wait_err, ret; + pid_t pid; + + /* If SIGCHLD is ignored do_wait won't populate the status. */ + kernel_sigaction(SIGCHLD, SIG_DFL); + pid = user_mode_thread(kunit_uapi_user_mode_thread_init, &ctx, SIGCHLD); + if (pid < 0) { + kernel_sigaction(SIGCHLD, SIG_IGN); + return pid; + } + + wait_for_completion(&ctx.setup_done); + + forward_err = kunit_uapi_forward_to_printk(test, ctx.out); + if (forward_err) + kunit_uapi_kill_pid(ctx.tgid); + + wait_err = kernel_wait(ctx.tgid, &ret); + + /* Restore default kernel sig handler */ + kernel_sigaction(SIGCHLD, SIG_IGN); + + if (ctx.exec_err) + return ctx.exec_err; + if (forward_err) + return forward_err; + if (wait_err < 0) + return wait_err; + return ret; +} + +static int kunit_uapi_run_executable(struct kunit *test, const struct blob *executable) +{ + const char *exe_name = kbasename(executable->path); + struct vfsmount *mnt; + int err; + + mnt = kunit_uapi_mount_tmpfs(); + if (IS_ERR(mnt)) + return PTR_ERR(mnt); + + err = kunit_uapi_write_file(mnt, exe_name, 0755, executable->data, blob_size(executable)); + + if (!err) + err = kunit_uapi_run_executable_in_mount(test, exe_name, mnt); + + kern_unmount(mnt); + + return err; +} + +void kunit_uapi_run_kselftest(struct kunit *test, const struct blob *executable) +{ + u8 exit_code, exit_signal; + int err; + + err = kunit_uapi_run_executable(test, executable); + if (err < 0) + KUNIT_FAIL(test, "Could not run test executable: %pe\n", ERR_PTR(err)); + + exit_code = err >> 8; + exit_signal = err & 0xff; + + if (exit_signal) + KUNIT_FAIL(test, "kselftest exited with signal: %d\n", exit_signal); + else if (exit_code == KSFT_PASS) + ; /* Noop */ + else if (exit_code == KSFT_FAIL) + KUNIT_FAIL(test, "kselftest exited with code KSFT_FAIL\n"); + else if (exit_code == KSFT_XPASS) + KUNIT_FAIL(test, "kselftest exited with code KSFT_XPASS\n"); + else if (exit_code == KSFT_XFAIL) + ; /* Noop */ + else if (exit_code == KSFT_SKIP) + kunit_mark_skipped(test, "kselftest exited with code KSFT_SKIP\n"); + else + KUNIT_FAIL(test, "kselftest exited with unknown exit code: %d\n", exit_code); +} +EXPORT_SYMBOL_GPL(kunit_uapi_run_kselftest);
Extend the example to show how to run a userspace executable.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- lib/kunit/.kunitconfig | 2 ++ lib/kunit/Makefile | 9 ++++++++- lib/kunit/kunit-example-test.c | 15 +++++++++++++++ lib/kunit/kunit-example-uapi.c | 22 ++++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-)
diff --git a/lib/kunit/.kunitconfig b/lib/kunit/.kunitconfig index 9235b7d42d389d2c7bf912546c7bb084eae99235..b7433e691563a3a8442db69874dea88f3b607332 100644 --- a/lib/kunit/.kunitconfig +++ b/lib/kunit/.kunitconfig @@ -1,3 +1,5 @@ CONFIG_KUNIT=y +CONFIG_SHMEM=y +CONFIG_TMPFS=y CONFIG_KUNIT_TEST=y CONFIG_KUNIT_EXAMPLE_TEST=y diff --git a/lib/kunit/Makefile b/lib/kunit/Makefile index 989933dab9ad2267f376db470b876ce2a88711b4..1b6be12676f89cafa34f0093d8136b36f4cf5532 100644 --- a/lib/kunit/Makefile +++ b/lib/kunit/Makefile @@ -30,4 +30,11 @@ obj-$(CONFIG_KUNIT_TEST) += string-stream-test.o obj-$(CONFIG_KUNIT_TEST) += assert_test.o endif
-obj-$(CONFIG_KUNIT_EXAMPLE_TEST) += kunit-example-test.o +userprogs += kunit-example-uapi +kunit-example-uapi-userccflags := -static +kunit-example-uapi-nolibc := $(CONFIG_ARCH_HAS_NOLIBC) +blobs += kunit-example-uapi.blob.o + +obj-$(CONFIG_KUNIT_EXAMPLE_TEST) += kunit-example-mod.o +kunit-example-mod-y += kunit-example-test.o +kunit-example-mod-$(CONFIG_KUNIT_UAPI) += kunit-example-uapi.blob.o diff --git a/lib/kunit/kunit-example-test.c b/lib/kunit/kunit-example-test.c index 3056d6bc705d0a8f196f0f4412e679dbb0e03114..b2681a6e047dfd6fea4a7cca60e81651d09c2eae 100644 --- a/lib/kunit/kunit-example-test.c +++ b/lib/kunit/kunit-example-test.c @@ -6,8 +6,11 @@ * Author: Brendan Higgins brendanhiggins@google.com */
+#include <linux/blob.h> + #include <kunit/test.h> #include <kunit/static_stub.h> +#include <kunit/uapi.h>
/* * This is the most fundamental element of KUnit, the test case. A test case @@ -277,6 +280,17 @@ static void example_slow_test(struct kunit *test) KUNIT_EXPECT_EQ(test, 1 + 1, 2); }
+/* + * This test shows the usage of UAPI tests. + */ +static void example_uapi_test(struct kunit *test) +{ + if (IS_ENABLED(CONFIG_KUNIT_UAPI)) + kunit_uapi_run_kselftest(test, BLOB(kunit_example_uapi)); + else + kunit_skip(test, "CONFIG_KUNIT_UAPI is not enabled"); +} + /* * Here we make a list of all the test cases we want to add to the test suite * below. @@ -297,6 +311,7 @@ static struct kunit_case example_test_cases[] = { KUNIT_CASE(example_priv_test), KUNIT_CASE_PARAM(example_params_test, example_gen_params), KUNIT_CASE_SLOW(example_slow_test), + KUNIT_CASE(example_uapi_test), {} };
diff --git a/lib/kunit/kunit-example-uapi.c b/lib/kunit/kunit-example-uapi.c new file mode 100644 index 0000000000000000000000000000000000000000..4ce657050dd4a576632a41ca0309c4cb5134ce14 --- /dev/null +++ b/lib/kunit/kunit-example-uapi.c @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit Userspace example test. + * + * Copyright (C) 2025, Linutronix GmbH. + * Author: Thomas Weißschuh thomas.weissschuh@linutronix.de + * + * This is *userspace* code. + */ + +#include "../../tools/testing/selftests/kselftest.h" + +int main(void) +{ + ksft_print_header(); + ksft_set_plan(4); + ksft_test_result_pass("userspace test 1\n"); + ksft_test_result_pass("userspace test 2\n"); + ksft_test_result_skip("userspace test 3: some reason\n"); + ksft_test_result_pass("userspace test 4\n"); + ksft_finished(); +}
UAPI selftests may expect a "normal" userspace environment. For example the normal kernel API pseudo-filesystems should be mounted. This could be done from kernel code but it is non-idiomatic.
Add a preinit userspace executable which performs these setup steps before running the final test executable. This preinit executable is only ever run from the kernel. Give it access to autoconf.h and kconfig.h to adapt itself to the tested kernel.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- lib/kunit/Makefile | 9 ++++++- lib/kunit/uapi-preinit.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++ lib/kunit/uapi.c | 11 ++++++-- 3 files changed, 82 insertions(+), 3 deletions(-)
diff --git a/lib/kunit/Makefile b/lib/kunit/Makefile index 1b6be12676f89cafa34f0093d8136b36f4cf5532..0e9a26d90bf4d5128e270ecaa8f3465f28da0fa2 100644 --- a/lib/kunit/Makefile +++ b/lib/kunit/Makefile @@ -12,7 +12,14 @@ kunit-objs += test.o \ device.o \ platform.o
-kunit-$(CONFIG_KUNIT_UAPI) += uapi.o +userprogs += uapi-preinit +uapi-preinit-nolibc := $(CONFIG_ARCH_HAS_NOLIBC) +uapi-preinit-userccflags += -static \ + -include include/generated/autoconf.h \ + -include $(srctree)/tools/include/linux/kconfig.h +blobs += uapi-preinit.blob.o +uapi-preinit.blob-symbol := kunit_uapi_preinit +kunit-$(CONFIG_KUNIT_UAPI) += uapi.o uapi-preinit.blob.o
ifeq ($(CONFIG_KUNIT_DEBUGFS),y) kunit-objs += debugfs.o diff --git a/lib/kunit/uapi-preinit.c b/lib/kunit/uapi-preinit.c new file mode 100644 index 0000000000000000000000000000000000000000..56bd50822b91af15d88cb32476fbbe6a85806761 --- /dev/null +++ b/lib/kunit/uapi-preinit.c @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit Userspace environment setup. + * + * Copyright (C) 2025, Linutronix GmbH. + * Author: Thomas Weißschuh thomas.weissschuh@linutronix.de + * + * This is *userspace* code. + */ + +#ifndef NOLIBC +#include <sys/mount.h> +#include <sys/stat.h> +#endif + +#include "../../tools/testing/selftests/kselftest.h" + +static int setup_api_mount(const char *target, const char *fstype) +{ + int ret; + + ret = mkdir(target, 0755); + if (ret && errno != EEXIST) + return -errno; + + ret = mount("none", target, fstype, 0, NULL); + if (ret && errno != EBUSY) + return -errno; + + return 0; +} + +static void exit_failure(const char *stage, int err) +{ + /* If preinit fails synthesize a failed test report. */ + ksft_print_header(); + ksft_set_plan(1); + ksft_test_result_fail("Failed during test setup: %s: %s\n", stage, strerror(-err)); + ksft_finished(); +} + +int main(int argc, char **argv, char **envp) +{ + int ret; + + ret = setup_api_mount("/proc", "proc"); + if (ret) + exit_failure("mount /proc", ret); + + ret = setup_api_mount("/sys", "sysfs"); + if (ret) + exit_failure("mount /sys", ret); + + if (IS_ENABLED(CONFIG_DEVTMPFS)) { + ret = setup_api_mount("/dev", "devtmpfs"); + if (ret) + exit_failure("mount /dev", ret); + } + + ret = execve(argv[0], argv, envp); + if (ret) + exit_failure("execve", ret); + + return 0; +} diff --git a/lib/kunit/uapi.c b/lib/kunit/uapi.c index 081ddc46e3ccb9ef88f9cb2a66d5e2bf41da2eb4..20eba19cbc0d4e1effcc7813df0da6eb5d1ef846 100644 --- a/lib/kunit/uapi.c +++ b/lib/kunit/uapi.c @@ -139,7 +139,7 @@ static int kunit_uapi_user_mode_thread_init(void *data) kernel_sigaction(SIGABRT, SIG_DFL);
complete(&ctx->setup_done); - ctx->exec_err = kernel_execve(ctx->executable, argv, NULL); + ctx->exec_err = kernel_execve(kbasename(BLOB(kunit_uapi_preinit)->path), argv, NULL); if (!ctx->exec_err) return 0; do_exit(0); @@ -239,6 +239,7 @@ static int kunit_uapi_run_executable_in_mount(struct kunit *test, const char *ex
static int kunit_uapi_run_executable(struct kunit *test, const struct blob *executable) { + const struct blob *preinit = BLOB(kunit_uapi_preinit); const char *exe_name = kbasename(executable->path); struct vfsmount *mnt; int err; @@ -247,7 +248,13 @@ static int kunit_uapi_run_executable(struct kunit *test, const struct blob *exec if (IS_ERR(mnt)) return PTR_ERR(mnt);
- err = kunit_uapi_write_file(mnt, exe_name, 0755, executable->data, blob_size(executable)); + err = kunit_uapi_write_file(mnt, kbasename(preinit->path), 0755, + preinit->data, + blob_size(preinit)); + + if (!err) + err = kunit_uapi_write_file(mnt, exe_name, 0755, + executable->data, blob_size(executable));
if (!err) err = kunit_uapi_run_executable_in_mount(test, exe_name, mnt);
Show that the selftests are executed from a fairly "normal" userspace context.
Signed-off-by: Thomas Weißschuh thomas.weissschuh@linutronix.de --- lib/kunit/kunit-example-uapi.c | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-)
diff --git a/lib/kunit/kunit-example-uapi.c b/lib/kunit/kunit-example-uapi.c index 4ce657050dd4a576632a41ca0309c4cb5134ce14..d121c4620716aadddc38a1d5845e4b51e721fb67 100644 --- a/lib/kunit/kunit-example-uapi.c +++ b/lib/kunit/kunit-example-uapi.c @@ -8,13 +8,47 @@ * This is *userspace* code. */
+#ifndef NOLIBC +#include <fcntl.h> +#endif +#include <unistd.h> +#include <string.h> + #include "../../tools/testing/selftests/kselftest.h"
+static void test_procfs(void) +{ + char buf[256]; + ssize_t r; + int fd; + + fd = open("/proc/self/comm", O_RDONLY); + if (fd == -1) { + ksft_test_result_fail("procfs: open() failed: %s\n", strerror(errno)); + return; + } + + r = read(fd, buf, sizeof(buf)); + close(fd); + + if (r == -1) { + ksft_test_result_fail("procfs: read() failed: %s\n", strerror(errno)); + return; + } + + if (r != 16 || strncmp("kunit-example-u\n", buf, 16) != 0) { + ksft_test_result_fail("procfs: incorrect comm\n"); + return; + } + + ksft_test_result_pass("procfs\n"); +} + int main(void) { ksft_print_header(); ksft_set_plan(4); - ksft_test_result_pass("userspace test 1\n"); + test_procfs(); ksft_test_result_pass("userspace test 2\n"); ksft_test_result_skip("userspace test 3: some reason\n"); ksft_test_result_pass("userspace test 4\n");
linux-kselftest-mirror@lists.linaro.org