Skip to content

Commit

Permalink
Merge tag 'linux-kselftest-kunit-6.3-rc1' of git://git.kernel.org/pub…
Browse files Browse the repository at this point in the history
…/scm/linux/kernel/git/shuah/linux-kselftest

Pull KUnit update from Shuah Khan:

 - add Function Redirection API to isolate the code being tested from
   other parts of the kernel.

   Documentation/dev-tools/kunit/api/functionredirection.rst has the
   details.

* tag 'linux-kselftest-kunit-6.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest:
  kunit: Add printf attribute to fail_current_test_impl
  lib/hashtable_test.c: add test for the hashtable structure
  Documentation: Add Function Redirection API docs
  kunit: Expose 'static stub' API to redirect functions
  kunit: Add "hooks" to call into KUnit when it's built as a module
  kunit: kunit.py extract handlers
  tools/testing/kunit/kunit.py: remove redundant double check
  • Loading branch information
torvalds committed Feb 23, 2023
2 parents d6296cb + 82649c7 commit 89f1a24
Show file tree
Hide file tree
Showing 15 changed files with 966 additions and 123 deletions.
162 changes: 162 additions & 0 deletions Documentation/dev-tools/kunit/api/functionredirection.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
.. SPDX-License-Identifier: GPL-2.0
========================
Function Redirection API
========================

Overview
========

When writing unit tests, it's important to be able to isolate the code being
tested from other parts of the kernel. This ensures the reliability of the test
(it won't be affected by external factors), reduces dependencies on specific
hardware or config options (making the test easier to run), and protects the
stability of the rest of the system (making it less likely for test-specific
state to interfere with the rest of the system).

While for some code (typically generic data structures, helpers, and other
"pure functions") this is trivial, for others (like device drivers,
filesystems, core subsystems) the code is heavily coupled with other parts of
the kernel.

This coupling is often due to global state in some way: be it a global list of
devices, the filesystem, or some hardware state. Tests need to either carefully
manage, isolate, and restore state, or they can avoid it altogether by
replacing access to and mutation of this state with a "fake" or "mock" variant.

By refactoring access to such state, such as by introducing a layer of
indirection which can use or emulate a separate set of test state. However,
such refactoring comes with its own costs (and undertaking significant
refactoring before being able to write tests is suboptimal).

A simpler way to intercept and replace some of the function calls is to use
function redirection via static stubs.


Static Stubs
============

Static stubs are a way of redirecting calls to one function (the "real"
function) to another function (the "replacement" function).

It works by adding a macro to the "real" function which checks to see if a test
is running, and if a replacement function is available. If so, that function is
called in place of the original.

Using static stubs is pretty straightforward:

1. Add the KUNIT_STATIC_STUB_REDIRECT() macro to the start of the "real"
function.

This should be the first statement in the function, after any variable
declarations. KUNIT_STATIC_STUB_REDIRECT() takes the name of the
function, followed by all of the arguments passed to the real function.

For example:

.. code-block:: c
void send_data_to_hardware(const char *str)
{
KUNIT_STATIC_STUB_REDIRECT(send_data_to_hardware, str);
/* real implementation */
}
2. Write one or more replacement functions.

These functions should have the same function signature as the real function.
In the event they need to access or modify test-specific state, they can use
kunit_get_current_test() to get a struct kunit pointer. This can then
be passed to the expectation/assertion macros, or used to look up KUnit
resources.

For example:

.. code-block:: c
void fake_send_data_to_hardware(const char *str)
{
struct kunit *test = kunit_get_current_test();
KUNIT_EXPECT_STREQ(test, str, "Hello World!");
}
3. Activate the static stub from your test.

From within a test, the redirection can be enabled with
kunit_activate_static_stub(), which accepts a struct kunit pointer,
the real function, and the replacement function. You can call this several
times with different replacement functions to swap out implementations of the
function.

In our example, this would be

.. code-block:: c
kunit_activate_static_stub(test,
send_data_to_hardware,
fake_send_data_to_hardware);

4. Call (perhaps indirectly) the real function.

Once the redirection is activated, any call to the real function will call
the replacement function instead. Such calls may be buried deep in the
implementation of another function, but must occur from the test's kthread.

For example:

.. code-block:: c
send_data_to_hardware("Hello World!"); /* Succeeds */
send_data_to_hardware("Something else"); /* Fails the test. */
5. (Optionally) disable the stub.

When you no longer need it, disable the redirection (and hence resume the
original behaviour of the 'real' function) using
kunit_deactivate_static_stub(). Otherwise, it will be automatically disabled
when the test exits.

For example:

.. code-block:: c
kunit_deactivate_static_stub(test, send_data_to_hardware);


It's also possible to use these replacement functions to test to see if a
function is called at all, for example:

.. code-block:: c
void send_data_to_hardware(const char *str)
{
KUNIT_STATIC_STUB_REDIRECT(send_data_to_hardware, str);
/* real implementation */
}
/* In test file */
int times_called = 0;
void fake_send_data_to_hardware(const char *str)
{
times_called++;
}
...
/* In the test case, redirect calls for the duration of the test */
kunit_activate_static_stub(test, send_data_to_hardware, fake_send_data_to_hardware);
send_data_to_hardware("hello");
KUNIT_EXPECT_EQ(test, times_called, 1);
/* Can also deactivate the stub early, if wanted */
kunit_deactivate_static_stub(test, send_data_to_hardware);
send_data_to_hardware("hello again");
KUNIT_EXPECT_EQ(test, times_called, 1);
API Reference
=============

.. kernel-doc:: include/kunit/static_stub.h
:internal:
13 changes: 10 additions & 3 deletions Documentation/dev-tools/kunit/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,24 @@
API Reference
=============
.. toctree::
:hidden:

test
resource
functionredirection

This section documents the KUnit kernel testing API. It is divided into the

This page documents the KUnit kernel testing API. It is divided into the
following sections:

Documentation/dev-tools/kunit/api/test.rst

- documents all of the standard testing API
- Documents all of the standard testing API

Documentation/dev-tools/kunit/api/resource.rst

- documents the KUnit resource API
- Documents the KUnit resource API

Documentation/dev-tools/kunit/api/functionredirection.rst

- Documents the KUnit Function Redirection API
15 changes: 6 additions & 9 deletions Documentation/dev-tools/kunit/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -648,10 +648,9 @@ We can do this via the ``kunit_test`` field in ``task_struct``, which we can
access using the ``kunit_get_current_test()`` function in ``kunit/test-bug.h``.

``kunit_get_current_test()`` is safe to call even if KUnit is not enabled. If
KUnit is not enabled, was built as a module (``CONFIG_KUNIT=m``), or no test is
running in the current task, it will return ``NULL``. This compiles down to
either a no-op or a static key check, so will have a negligible performance
impact when no test is running.
KUnit is not enabled, or if no test is running in the current task, it will
return ``NULL``. This compiles down to either a no-op or a static key check,
so will have a negligible performance impact when no test is running.

The example below uses this to implement a "mock" implementation of a function, ``foo``:

Expand Down Expand Up @@ -726,8 +725,6 @@ structures as shown below:
#endif
``kunit_fail_current_test()`` is safe to call even if KUnit is not enabled. If
KUnit is not enabled, was built as a module (``CONFIG_KUNIT=m``), or no test is
running in the current task, it will do nothing. This compiles down to either a
no-op or a static key check, so will have a negligible performance impact when
no test is running.

KUnit is not enabled, or if no test is running in the current task, it will do
nothing. This compiles down to either a no-op or a static key check, so will
have a negligible performance impact when no test is running.
113 changes: 113 additions & 0 deletions include/kunit/static_stub.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/* SPDX-License-Identifier: GPL-2.0 */
/*
* KUnit function redirection (static stubbing) API.
*
* Copyright (C) 2022, Google LLC.
* Author: David Gow <[email protected]>
*/
#ifndef _KUNIT_STATIC_STUB_H
#define _KUNIT_STATIC_STUB_H

#if !IS_ENABLED(CONFIG_KUNIT)

/* If CONFIG_KUNIT is not enabled, these stubs quietly disappear. */
#define KUNIT_TRIGGER_STATIC_STUB(real_fn_name, args...) do {} while (0)

#else

#include <kunit/test.h>
#include <kunit/test-bug.h>

#include <linux/compiler.h> /* for {un,}likely() */
#include <linux/sched.h> /* for task_struct */


/**
* KUNIT_STATIC_STUB_REDIRECT() - call a replacement 'static stub' if one exists
* @real_fn_name: The name of this function (as an identifier, not a string)
* @args: All of the arguments passed to this function
*
* This is a function prologue which is used to allow calls to the current
* function to be redirected by a KUnit test. KUnit tests can call
* kunit_activate_static_stub() to pass a replacement function in. The
* replacement function will be called by KUNIT_TRIGGER_STATIC_STUB(), which
* will then return from the function. If the caller is not in a KUnit context,
* the function will continue execution as normal.
*
* Example:
*
* .. code-block:: c
*
* int real_func(int n)
* {
* KUNIT_STATIC_STUB_REDIRECT(real_func, n);
* return 0;
* }
*
* int replacement_func(int n)
* {
* return 42;
* }
*
* void example_test(struct kunit *test)
* {
* kunit_activate_static_stub(test, real_func, replacement_func);
* KUNIT_EXPECT_EQ(test, real_func(1), 42);
* }
*
*/
#define KUNIT_STATIC_STUB_REDIRECT(real_fn_name, args...) \
do { \
typeof(&real_fn_name) replacement; \
struct kunit *current_test = kunit_get_current_test(); \
\
if (likely(!current_test)) \
break; \
\
replacement = kunit_hooks.get_static_stub_address(current_test, \
&real_fn_name); \
\
if (unlikely(replacement)) \
return replacement(args); \
} while (0)

/* Helper function for kunit_activate_static_stub(). The macro does
* typechecking, so use it instead.
*/
void __kunit_activate_static_stub(struct kunit *test,
void *real_fn_addr,
void *replacement_addr);

/**
* kunit_activate_static_stub() - replace a function using static stubs.
* @test: A pointer to the 'struct kunit' test context for the current test.
* @real_fn_addr: The address of the function to replace.
* @replacement_addr: The address of the function to replace it with.
*
* When activated, calls to real_fn_addr from within this test (even if called
* indirectly) will instead call replacement_addr. The function pointed to by
* real_fn_addr must begin with the static stub prologue in
* KUNIT_TRIGGER_STATIC_STUB() for this to work. real_fn_addr and
* replacement_addr must have the same type.
*
* The redirection can be disabled again with kunit_deactivate_static_stub().
*/
#define kunit_activate_static_stub(test, real_fn_addr, replacement_addr) do { \
typecheck_fn(typeof(&real_fn_addr), replacement_addr); \
__kunit_activate_static_stub(test, real_fn_addr, replacement_addr); \
} while (0)


/**
* kunit_deactivate_static_stub() - disable a function redirection
* @test: A pointer to the 'struct kunit' test context for the current test.
* @real_fn_addr: The address of the function to no-longer redirect
*
* Deactivates a redirection configured with kunit_activate_static_stub(). After
* this function returns, calls to real_fn_addr() will execute the original
* real_fn, not any previously-configured replacement.
*/
void kunit_deactivate_static_stub(struct kunit *test, void *real_fn_addr);

#endif
#endif
29 changes: 11 additions & 18 deletions include/kunit/test-bug.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* SPDX-License-Identifier: GPL-2.0 */
/*
* KUnit API allowing dynamic analysis tools to interact with KUnit tests
* KUnit API providing hooks for non-test code to interact with tests.
*
* Copyright (C) 2020, Google LLC.
* Author: Uriel Guajardo <[email protected]>
Expand All @@ -9,14 +9,20 @@
#ifndef _KUNIT_TEST_BUG_H
#define _KUNIT_TEST_BUG_H

#if IS_BUILTIN(CONFIG_KUNIT)
#if IS_ENABLED(CONFIG_KUNIT)

#include <linux/jump_label.h> /* For static branch */
#include <linux/sched.h>

/* Static key if KUnit is running any tests. */
DECLARE_STATIC_KEY_FALSE(kunit_running);

/* Hooks table: a table of function pointers filled in when kunit loads */
extern struct kunit_hooks_table {
__printf(3, 4) void (*fail_current_test)(const char*, int, const char*, ...);
void *(*get_static_stub_address)(struct kunit *test, void *real_fn_addr);
} kunit_hooks;

/**
* kunit_get_current_test() - Return a pointer to the currently running
* KUnit test.
Expand All @@ -43,33 +49,20 @@ static inline struct kunit *kunit_get_current_test(void)
* kunit_fail_current_test() - If a KUnit test is running, fail it.
*
* If a KUnit test is running in the current task, mark that test as failed.
*
* This macro will only work if KUnit is built-in (though the tests
* themselves can be modules). Otherwise, it compiles down to nothing.
*/
#define kunit_fail_current_test(fmt, ...) do { \
if (static_branch_unlikely(&kunit_running)) { \
__kunit_fail_current_test(__FILE__, __LINE__, \
/* Guaranteed to be non-NULL when kunit_running true*/ \
kunit_hooks.fail_current_test(__FILE__, __LINE__, \
fmt, ##__VA_ARGS__); \
} \
} while (0)


extern __printf(3, 4) void __kunit_fail_current_test(const char *file, int line,
const char *fmt, ...);

#else

static inline struct kunit *kunit_get_current_test(void) { return NULL; }

/* We define this with an empty helper function so format string warnings work */
#define kunit_fail_current_test(fmt, ...) \
__kunit_fail_current_test(__FILE__, __LINE__, fmt, ##__VA_ARGS__)

static inline __printf(3, 4) void __kunit_fail_current_test(const char *file, int line,
const char *fmt, ...)
{
}
#define kunit_fail_current_test(fmt, ...) do {} while (0)

#endif

Expand Down
Loading

0 comments on commit 89f1a24

Please sign in to comment.