selftests/harness: Fix fixture teardown
authorMickaël Salaün <mic@digikod.net>
Sat, 11 May 2024 17:14:38 +0000 (19:14 +0200)
committerMickaël Salaün <mic@digikod.net>
Sat, 11 May 2024 17:18:43 +0000 (19:18 +0200)
Make sure fixture teardowns are run when test cases failed, including
when _metadata->teardown_parent is set to true.

Make sure only one fixture teardown is run per test case, handling the
case where the test child forks.

Cc: Jakub Kicinski <kuba@kernel.org>
Cc: Shengyu Li <shengyu.li.evgeny@gmail.com>
Cc: Shuah Khan <skhan@linuxfoundation.org>
Fixes: 72d7cb5c190b ("selftests/harness: Prevent infinite loop due to Assert in FIXTURE_TEARDOWN")
Fixes: 0710a1a73fb4 ("selftests/harness: Merge TEST_F_FORK() into TEST_F()")
Reviewed-by: Kees Cook <keescook@chromium.org>
Link: https://lore.kernel.org/r/20240511171445.904356-4-mic@digikod.net
Rule: add
Link: https://lore.kernel.org/stable/20240506165518.474504-4-mic%40digikod.net
Signed-off-by: Mickaël Salaün <mic@digikod.net>
tools/testing/selftests/kselftest_harness.h

index d98702b6955df24e72366f2246ad5b3da7951b5a..55699a762c45446d31b81970f2139fc1ca47d334 100644 (file)
                FIXTURE_DATA(fixture_name) self; \
                pid_t child = 1; \
                int status = 0; \
-               bool jmp = false; \
+               /* Makes sure there is only one teardown, even when child forks again. */ \
+               bool *teardown = mmap(NULL, sizeof(*teardown), \
+                       PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); \
+               *teardown = false; \
                memset(&self, 0, sizeof(FIXTURE_DATA(fixture_name))); \
                if (setjmp(_metadata->env) == 0) { \
                        /* Use the same _metadata. */ \
                                _metadata->exit_code = KSFT_FAIL; \
                        } \
                } \
-               else \
-                       jmp = true; \
                if (child == 0) { \
-                       if (_metadata->setup_completed && !_metadata->teardown_parent && !jmp) \
+                       if (_metadata->setup_completed && !_metadata->teardown_parent && \
+                                       __sync_bool_compare_and_swap(teardown, false, true)) \
                                fixture_name##_teardown(_metadata, &self, variant->data); \
                        _exit(0); \
                } \
-               if (_metadata->setup_completed && _metadata->teardown_parent) \
+               if (_metadata->setup_completed && _metadata->teardown_parent && \
+                               __sync_bool_compare_and_swap(teardown, false, true)) \
                        fixture_name##_teardown(_metadata, &self, variant->data); \
+               munmap(teardown, sizeof(*teardown)); \
                if (!WIFEXITED(status) && WIFSIGNALED(status)) \
                        /* Forward signal to __wait_for_test(). */ \
                        kill(getpid(), WTERMSIG(status)); \