diff mbox series

[RFC,2/2] KUnit: KASAN Integration

Message ID 20200227024301.217042-2-trishalfonso@google.com (mailing list archive)
State New
Headers show
Series [RFC,1/2] Port KASAN Tests to KUnit | expand

Commit Message

Patricia Alfonso Feb. 27, 2020, 2:43 a.m. UTC
Integrate KASAN into KUnit testing framework.
 - Fail tests when KASAN reports an error that is not expected
 - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
 - KUnit struct added to current task to keep track of the current test
from KASAN code
 - Booleans representing if a KASAN report is expected and if a KASAN
 report is found added to kunit struct
 - This prints "line# has passed" or "line# has failed"

Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
---
If anyone has any suggestions on how best to print the failure
messages, please share!

One issue I have found while testing this is the allocation fails in
kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
does cause the test to fail on the KUnit side, as expected, but it
seems to skip all the tests before this one because the output starts
with this failure instead of with the first test, kmalloc_oob_right().

 include/kunit/test.h                | 24 ++++++++++++++++++++++++
 include/linux/sched.h               |  7 ++++++-
 lib/kunit/test.c                    |  7 ++++++-
 mm/kasan/report.c                   | 19 +++++++++++++++++++
 tools/testing/kunit/kunit_kernel.py |  2 +-
 5 files changed, 56 insertions(+), 3 deletions(-)

Comments

Alan Maguire Feb. 27, 2020, 2:04 p.m. UTC | #1
On Wed, 26 Feb 2020, Patricia Alfonso wrote:

> Integrate KASAN into KUnit testing framework.

This is a great idea! Some comments/suggestions below...

>  - Fail tests when KASAN reports an error that is not expected
>  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
>  - KUnit struct added to current task to keep track of the current test
> from KASAN code
>  - Booleans representing if a KASAN report is expected and if a KASAN
>  report is found added to kunit struct
>  - This prints "line# has passed" or "line# has failed"
> 
> Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> ---
> If anyone has any suggestions on how best to print the failure
> messages, please share!
> 
> One issue I have found while testing this is the allocation fails in
> kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> does cause the test to fail on the KUnit side, as expected, but it
> seems to skip all the tests before this one because the output starts
> with this failure instead of with the first test, kmalloc_oob_right().
> 
>  include/kunit/test.h                | 24 ++++++++++++++++++++++++
>  include/linux/sched.h               |  7 ++++++-
>  lib/kunit/test.c                    |  7 ++++++-
>  mm/kasan/report.c                   | 19 +++++++++++++++++++
>  tools/testing/kunit/kunit_kernel.py |  2 +-
>  5 files changed, 56 insertions(+), 3 deletions(-)
> 
> diff --git a/include/kunit/test.h b/include/kunit/test.h
> index 2dfb550c6723..2e388f8937f3 100644
> --- a/include/kunit/test.h
> +++ b/include/kunit/test.h
> @@ -21,6 +21,8 @@ struct kunit_resource;
>  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
>  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
>  
> +void kunit_set_failure(struct kunit *test);
> +
>  /**
>   * struct kunit_resource - represents a *test managed resource*
>   * @allocation: for the user to store arbitrary data.
> @@ -191,6 +193,9 @@ struct kunit {
>  	 * protect it with some type of lock.
>  	 */
>  	struct list_head resources; /* Protected by lock. */
> +
> +	bool kasan_report_expected;
> +	bool kasan_report_found;
>  };
>  

Is this needed here? You're testing something pretty
specific so it seems wrong to add to the generic
kunit resource unless there's a good reason. I see the
code around setting these values in mm/kasan/report.c,
but I wonder if we could do something more generic.

How about the concept of a static resource (assuming a
dynamically allocated one is out because it messes
with memory allocation tests)? Something like this:

#define kunit_add_static_resource(test, resource_ptr, resource_field)	\
	do {								\
		spin_lock(&test->lock);					\
		(resource_ptr)->resource_field.init = NULL;		\
		(resource_ptr)->resource_field.free = NULL;		\
		list_add_tail(&(resource_ptr)->resource_field,		\
 			      &test->resources);			\
		spin_unlock(&test->lock);				\
	} while (0)	      

	  
Within your kasan code you could then create a kasan-specific
structure that embends a kunit_resource, and contains the
values you need:

struct kasan_report_resource {
	struct kunit_resource res;
	bool kasan_report_expected;
	bool kasan_report_found;
};

(One thing we'd need to do for such static resources is fix
kunit_resource_free() to check if there's a free() function,
and if not assume a static resource)

If you then create an init() function associated with your
kunit suite (which will be run for every case) it can do this:

int kunit_kasan_test_init(struct kunit *test)
{
	kunit_add_static_resource(test, &my_kasan_report_resource, res);
	...
}

The above should also be used to initialize current->kasan_unit_test
instead of doing that in kunit_try_run_case().  With those
changes, you don't (I think) need to change anything in core
kunit (assuming support for static resources).

To retrieve the resource during tests or in kasan context, the
method seems to be to use kunit_resource_find(). However, that
requires a match function which seems a bit heavyweight for the
static case.  We should probably have a default "find by name"
or similar function here, and add an optional "name" field
to kunit resources to simplify things.  Anyway here you'd
use something like:

	kasan_report_resource = kunit_resource_find(test, matchfn, 
						    NULL, matchdata); 


Are there any barriers to taking this sort of approach (apart
from the support for static resources not being there yet)?

>  void kunit_init_test(struct kunit *test, const char *name);
> @@ -941,6 +946,25 @@ do {									       \
>  						ptr,			       \
>  						NULL)
>  
> +/**
> + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> + * not cause a KASAN error.
> + *
> + */
> +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {	\
> +	test->kasan_report_expected = true;	\
> +	test->kasan_report_found = false; \
> +	condition; \
> +	if (test->kasan_report_found == test->kasan_report_expected) { \
> +		pr_info("%d has passed", __LINE__); \
> +	} else { \
> +		kunit_set_failure(test); \
> +		pr_info("%d has failed", __LINE__); \
> +	} \
> +	test->kasan_report_expected = false;	\
> +	test->kasan_report_found = false;	\
> +} while (0)
> +

Feels like this belongs in test_kasan.c, and could be reworked
to avoid adding test->kasan_report_[expected|found] as described
above.  Instead of having your own pass/fail logic couldn't you
do this:

	KUNIT_EXPECT_EQ(test, expected, found);

? That will set the failure state too so no need to export
a separate function for that, and no need to log anything
as KUNIT_EXPECT_EQ() should do that for you.

>  /**
>   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
>   * @test: The test context object.
> diff --git a/include/linux/sched.h b/include/linux/sched.h
> index 04278493bf15..db23d56061e7 100644
> --- a/include/linux/sched.h
> +++ b/include/linux/sched.h
> @@ -32,6 +32,8 @@
>  #include <linux/posix-timers.h>
>  #include <linux/rseq.h>
>  
> +#include <kunit/test.h>
> +

This feels like the wrong place to add this #include, and
when I attempted to build to test I ran into a bunch of
compilation errors; for example:

 CC      kernel/sched/core.o
In file included from ./include/linux/uaccess.h:11,
                 from ./arch/x86/include/asm/fpu/xstate.h:5,
                 from ./arch/x86/include/asm/pgtable.h:26,
                 from ./include/linux/kasan.h:16,
                 from ./include/linux/slab.h:136,
                 from ./include/kunit/test.h:16,
                 from ./include/linux/sched.h:35,
                 from init/do_mounts.c:3:
./arch/x86/include/asm/uaccess.h: In function 'set_fs':
./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to 
incomplete type 'struct task_struct'
  current->thread.addr_limit = fs;

(I'm testing with CONFIG_SLUB). Removing this #include
resolves these errors, but then causes problems for
lib/test_kasan.c. I'll dig around a bit more.

>  /* task_struct member predeclarations (sorted alphabetically): */
>  struct audit_context;
>  struct backing_dev_info;
> @@ -1178,7 +1180,10 @@ struct task_struct {
>  
>  #ifdef CONFIG_KASAN
>  	unsigned int			kasan_depth;
> -#endif
> +#ifdef CONFIG_KUNIT
> +	struct kunit *kasan_kunit_test;
> +#endif /* CONFIG_KUNIT */
> +#endif /* CONFIG_KASAN */
>  
>  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
>  	/* Index of current stored address in ret_stack: */
> diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> index 9242f932896c..d266b9495c67 100644
> --- a/lib/kunit/test.c
> +++ b/lib/kunit/test.c
> @@ -9,11 +9,12 @@
>  #include <kunit/test.h>
>  #include <linux/kernel.h>
>  #include <linux/sched/debug.h>
> +#include <linux/sched.h>
>  
>  #include "string-stream.h"
>  #include "try-catch-impl.h"
>  
> -static void kunit_set_failure(struct kunit *test)
> +void kunit_set_failure(struct kunit *test)
>  {
>  	WRITE_ONCE(test->success, false);
>  }
> @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
>  	struct kunit_suite *suite = ctx->suite;
>  	struct kunit_case *test_case = ctx->test_case;
>  
> +#ifdef CONFIG_KASAN
> +	current->kasan_kunit_test = test;
> +#endif
> +
>  	/*
>  	 * kunit_run_case_internal may encounter a fatal error; if it does,
>  	 * abort will be called, this thread will exit, and finally the parent
> diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> index 5ef9f24f566b..5554d23799a5 100644
> --- a/mm/kasan/report.c
> +++ b/mm/kasan/report.c
> @@ -32,6 +32,8 @@
>  
>  #include <asm/sections.h>
>  
> +#include <kunit/test.h>
> +
>  #include "kasan.h"
>  #include "../slab.h"
>  
> @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
>  	u8 tag = get_tag(object);
>  
>  	object = reset_tag(object);
> +
> +	if (current->kasan_kunit_test) {
> +		if (current->kasan_kunit_test->kasan_report_expected) {
> +			current->kasan_kunit_test->kasan_report_found = true;
> +			return;
> +		}
> +		kunit_set_failure(current->kasan_kunit_test);
> +	}
> +
>  	start_report(&flags);
>  	pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
>  	print_tags(tag, object);
> @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
>  	if (likely(!report_enabled()))
>  		return;
>  
> +	if (current->kasan_kunit_test) {
> +		if (current->kasan_kunit_test->kasan_report_expected) {
> +			current->kasan_kunit_test->kasan_report_found = true;
> +			return;
> +		}
> +		kunit_set_failure(current->kasan_kunit_test);
> +	}
> +
>  	disable_trace_on_warning();
>  
>  	tagged_addr = (void *)addr;
> diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> index cc5d844ecca1..63eab18a8c34 100644
> --- a/tools/testing/kunit/kunit_kernel.py
> +++ b/tools/testing/kunit/kunit_kernel.py
> @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
>  		return True
>  
>  	def run_kernel(self, args=[], timeout=None, build_dir=''):
> -		args.extend(['mem=256M'])
> +		args.extend(['mem=256M', 'kasan_multi_shot'])
>  		process = self._ops.linux_bin(args, timeout, build_dir)
>  		with open(os.path.join(build_dir, 'test.log'), 'w') as f:
>  			for line in process.stdout:

I tried applying this to the "kunit" branch of linux-kselftest, and
the above failed. Which branch are you building with? Probably
best to use the kunit branch I think. Thanks!

Alan

> -- 
> 2.25.0.265.gbab2e86ba0-goog
> 
>
Dmitry Vyukov Feb. 27, 2020, 2:39 p.m. UTC | #2
On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
<kasan-dev@googlegroups.com> wrote:
>
> Integrate KASAN into KUnit testing framework.
>  - Fail tests when KASAN reports an error that is not expected
>  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
>  - KUnit struct added to current task to keep track of the current test
> from KASAN code
>  - Booleans representing if a KASAN report is expected and if a KASAN
>  report is found added to kunit struct
>  - This prints "line# has passed" or "line# has failed"
>
> Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> ---
> If anyone has any suggestions on how best to print the failure
> messages, please share!
>
> One issue I have found while testing this is the allocation fails in
> kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> does cause the test to fail on the KUnit side, as expected, but it
> seems to skip all the tests before this one because the output starts
> with this failure instead of with the first test, kmalloc_oob_right().
>
>  include/kunit/test.h                | 24 ++++++++++++++++++++++++
>  include/linux/sched.h               |  7 ++++++-
>  lib/kunit/test.c                    |  7 ++++++-
>  mm/kasan/report.c                   | 19 +++++++++++++++++++
>  tools/testing/kunit/kunit_kernel.py |  2 +-
>  5 files changed, 56 insertions(+), 3 deletions(-)
>
> diff --git a/include/kunit/test.h b/include/kunit/test.h
> index 2dfb550c6723..2e388f8937f3 100644
> --- a/include/kunit/test.h
> +++ b/include/kunit/test.h
> @@ -21,6 +21,8 @@ struct kunit_resource;
>  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
>  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
>
> +void kunit_set_failure(struct kunit *test);
> +
>  /**
>   * struct kunit_resource - represents a *test managed resource*
>   * @allocation: for the user to store arbitrary data.
> @@ -191,6 +193,9 @@ struct kunit {
>          * protect it with some type of lock.
>          */
>         struct list_head resources; /* Protected by lock. */
> +
> +       bool kasan_report_expected;
> +       bool kasan_report_found;
>  };
>
>  void kunit_init_test(struct kunit *test, const char *name);
> @@ -941,6 +946,25 @@ do {                                                                              \
>                                                 ptr,                           \
>                                                 NULL)
>
> +/**
> + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> + * not cause a KASAN error.

Oh, I see, this is not a test, but rather an ASSERT-like macro.
Then maybe we should use it for actual expressions that are supposed
to trigger KASAN errors?

E.g. KUNIT_EXPECT_KASAN_FAIL(test, *(volatile int*)p);


> + *
> + */
> +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {  \

s/condition/expression/

> +       test->kasan_report_expected = true;     \

Check that kasan_report_expected is unset. If these are nested things
will break in confusing ways.
Or otherwise we need to restore the previous value at the end.

> +       test->kasan_report_found = false; \
> +       condition; \
> +       if (test->kasan_report_found == test->kasan_report_expected) { \

We know that kasan_report_expected is true here, so we could just said:

if (!test->kasan_report_found)

> +               pr_info("%d has passed", __LINE__); \
> +       } else { \
> +               kunit_set_failure(test); \
> +               pr_info("%d has failed", __LINE__); \

This needs a more readable error.

> +       } \
> +       test->kasan_report_expected = false;    \
> +       test->kasan_report_found = false;       \
> +} while (0)
> +
>  /**
>   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
>   * @test: The test context object.
> diff --git a/include/linux/sched.h b/include/linux/sched.h
> index 04278493bf15..db23d56061e7 100644
> --- a/include/linux/sched.h
> +++ b/include/linux/sched.h
> @@ -32,6 +32,8 @@
>  #include <linux/posix-timers.h>
>  #include <linux/rseq.h>
>
> +#include <kunit/test.h>
> +
>  /* task_struct member predeclarations (sorted alphabetically): */
>  struct audit_context;
>  struct backing_dev_info;
> @@ -1178,7 +1180,10 @@ struct task_struct {
>
>  #ifdef CONFIG_KASAN
>         unsigned int                    kasan_depth;
> -#endif
> +#ifdef CONFIG_KUNIT
> +       struct kunit *kasan_kunit_test;

I would assume we will use this for other things as well (failing
tests on LOCKDEP errors, WARNINGs, etc).
So I would call this just kunit_test and make non-dependent on KASAN right away.


> +#endif /* CONFIG_KUNIT */
> +#endif /* CONFIG_KASAN */
>
>  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
>         /* Index of current stored address in ret_stack: */
> diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> index 9242f932896c..d266b9495c67 100644
> --- a/lib/kunit/test.c
> +++ b/lib/kunit/test.c
> @@ -9,11 +9,12 @@
>  #include <kunit/test.h>
>  #include <linux/kernel.h>
>  #include <linux/sched/debug.h>
> +#include <linux/sched.h>
>
>  #include "string-stream.h"
>  #include "try-catch-impl.h"
>
> -static void kunit_set_failure(struct kunit *test)
> +void kunit_set_failure(struct kunit *test)
>  {
>         WRITE_ONCE(test->success, false);
>  }
> @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
>         struct kunit_suite *suite = ctx->suite;
>         struct kunit_case *test_case = ctx->test_case;
>
> +#ifdef CONFIG_KASAN
> +       current->kasan_kunit_test = test;
> +#endif
> +
>         /*
>          * kunit_run_case_internal may encounter a fatal error; if it does,
>          * abort will be called, this thread will exit, and finally the parent
> diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> index 5ef9f24f566b..5554d23799a5 100644
> --- a/mm/kasan/report.c
> +++ b/mm/kasan/report.c
> @@ -32,6 +32,8 @@
>
>  #include <asm/sections.h>
>
> +#include <kunit/test.h>
> +
>  #include "kasan.h"
>  #include "../slab.h"
>
> @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
>         u8 tag = get_tag(object);
>
>         object = reset_tag(object);
> +
> +       if (current->kasan_kunit_test) {
> +               if (current->kasan_kunit_test->kasan_report_expected) {
> +                       current->kasan_kunit_test->kasan_report_found = true;
> +                       return;
> +               }
> +               kunit_set_failure(current->kasan_kunit_test);
> +       }
> +
>         start_report(&flags);
>         pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
>         print_tags(tag, object);
> @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
>         if (likely(!report_enabled()))
>                 return;
>
> +       if (current->kasan_kunit_test) {

Strictly saying, this also needs to check in_task().

> +               if (current->kasan_kunit_test->kasan_report_expected) {
> +                       current->kasan_kunit_test->kasan_report_found = true;
> +                       return;
> +               }
> +               kunit_set_failure(current->kasan_kunit_test);
> +       }

This chunk is duplicated 2 times. I think it will be more reasonable
for KASAN code to just notify KUNIT that the error has happened, and
then KUNIT will figure out what it means and what to do.


> +
>         disable_trace_on_warning();
>
>         tagged_addr = (void *)addr;
> diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> index cc5d844ecca1..63eab18a8c34 100644
> --- a/tools/testing/kunit/kunit_kernel.py
> +++ b/tools/testing/kunit/kunit_kernel.py
> @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
>                 return True
>
>         def run_kernel(self, args=[], timeout=None, build_dir=''):
> -               args.extend(['mem=256M'])
> +               args.extend(['mem=256M', 'kasan_multi_shot'])
>                 process = self._ops.linux_bin(args, timeout, build_dir)
>                 with open(os.path.join(build_dir, 'test.log'), 'w') as f:
>                         for line in process.stdout:
> --
> 2.25.0.265.gbab2e86ba0-goog
>
> --
> You received this message because you are subscribed to the Google Groups "kasan-dev" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to kasan-dev+unsubscribe@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/kasan-dev/20200227024301.217042-2-trishalfonso%40google.com.
Dmitry Vyukov Feb. 27, 2020, 2:43 p.m. UTC | #3
On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
<kasan-dev@googlegroups.com> wrote:
>
> Integrate KASAN into KUnit testing framework.
>  - Fail tests when KASAN reports an error that is not expected
>  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
>  - KUnit struct added to current task to keep track of the current test
> from KASAN code
>  - Booleans representing if a KASAN report is expected and if a KASAN
>  report is found added to kunit struct
>  - This prints "line# has passed" or "line# has failed"
>
> Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> ---
> If anyone has any suggestions on how best to print the failure
> messages, please share!
>
> One issue I have found while testing this is the allocation fails in
> kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> does cause the test to fail on the KUnit side, as expected, but it
> seems to skip all the tests before this one because the output starts
> with this failure instead of with the first test, kmalloc_oob_right().

I don't follow this... we don't check output in any way, so how does
output affect execution?...


> --- a/tools/testing/kunit/kunit_kernel.py
> +++ b/tools/testing/kunit/kunit_kernel.py
> @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
>                 return True
>
>         def run_kernel(self, args=[], timeout=None, build_dir=''):
> -               args.extend(['mem=256M'])
> +               args.extend(['mem=256M', 'kasan_multi_shot'])

This is better done somewhere else (different default value if
KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
to be a mandatory part now. This means people will always hit this, be
confused, figure out they need to flip the value, and only then be
able to run kunit+kasan.


>                 process = self._ops.linux_bin(args, timeout, build_dir)
>                 with open(os.path.join(build_dir, 'test.log'), 'w') as f:
>                         for line in process.stdout:
Dmitry Vyukov Feb. 27, 2020, 2:45 p.m. UTC | #4
On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
<kasan-dev@googlegroups.com> wrote:
>
> Integrate KASAN into KUnit testing framework.
>  - Fail tests when KASAN reports an error that is not expected
>  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
>  - KUnit struct added to current task to keep track of the current test
> from KASAN code
>  - Booleans representing if a KASAN report is expected and if a KASAN
>  report is found added to kunit struct
>  - This prints "line# has passed" or "line# has failed"
>
> Signed-off-by: Patricia Alfonso <trishalfonso@google.com>

This does not build for me:

$ make
scripts/kconfig/conf  --syncconfig Kconfig
  CC      arch/x86/kernel/asm-offsets.s
  UPD     include/generated/asm-offsets.h
  CALL    scripts/checksyscalls.sh
  CALL    scripts/atomic/check-atomics.sh
  DESCEND  objtool
  CC      init/main.o
In file included from ./include/linux/uaccess.h:11,
                 from ./arch/x86/include/asm/fpu/xstate.h:5,
                 from ./arch/x86/include/asm/pgtable.h:26,
                 from ./include/linux/kasan.h:15,
                 from ./include/linux/slab.h:136,
                 from ./include/kunit/test.h:16,
                 from ./include/linux/sched.h:35,
                 from ./include/linux/ioprio.h:5,
                 from ./include/linux/fs.h:39,
                 from ./include/linux/proc_fs.h:9,
                 from init/main.c:18:
./arch/x86/include/asm/uaccess.h: In function ‘set_fs’:
./arch/x86/include/asm/uaccess.h:31:9: error: dereferencing pointer to
incomplete type ‘struct task_struct’
   31 |  current->thread.addr_limit = fs;
      |         ^~
make[1]: *** [scripts/Makefile.build:268: init/main.o] Error 1
make: *** [Makefile:1681: init] Error 2


On bfdc6d91a25f4545bcd1b12e3219af4838142ef1 config:
https://pastebin.com/raw/nwnL2N9w
Patricia Alfonso Feb. 29, 2020, 12:46 a.m. UTC | #5
On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:
>
> On Wed, 26 Feb 2020, Patricia Alfonso wrote:
>
> > Integrate KASAN into KUnit testing framework.
>
> This is a great idea! Some comments/suggestions below...
>

Thank you so much for your suggestions!

> >  - Fail tests when KASAN reports an error that is not expected
> >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> >  - KUnit struct added to current task to keep track of the current test
> > from KASAN code
> >  - Booleans representing if a KASAN report is expected and if a KASAN
> >  report is found added to kunit struct
> >  - This prints "line# has passed" or "line# has failed"
> >
> > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > ---
> > If anyone has any suggestions on how best to print the failure
> > messages, please share!
> >
> > One issue I have found while testing this is the allocation fails in
> > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > does cause the test to fail on the KUnit side, as expected, but it
> > seems to skip all the tests before this one because the output starts
> > with this failure instead of with the first test, kmalloc_oob_right().
> >
> >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> >  include/linux/sched.h               |  7 ++++++-
> >  lib/kunit/test.c                    |  7 ++++++-
> >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> >  tools/testing/kunit/kunit_kernel.py |  2 +-
> >  5 files changed, 56 insertions(+), 3 deletions(-)
> >
> > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > index 2dfb550c6723..2e388f8937f3 100644
> > --- a/include/kunit/test.h
> > +++ b/include/kunit/test.h
> > @@ -21,6 +21,8 @@ struct kunit_resource;
> >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> >
> > +void kunit_set_failure(struct kunit *test);
> > +
> >  /**
> >   * struct kunit_resource - represents a *test managed resource*
> >   * @allocation: for the user to store arbitrary data.
> > @@ -191,6 +193,9 @@ struct kunit {
> >        * protect it with some type of lock.
> >        */
> >       struct list_head resources; /* Protected by lock. */
> > +
> > +     bool kasan_report_expected;
> > +     bool kasan_report_found;
> >  };
> >
>
> Is this needed here? You're testing something pretty
> specific so it seems wrong to add to the generic
> kunit resource unless there's a good reason. I see the
> code around setting these values in mm/kasan/report.c,
> but I wonder if we could do something more generic.
>
> How about the concept of a static resource (assuming a
> dynamically allocated one is out because it messes
> with memory allocation tests)? Something like this:
>
> #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
>         do {                                                            \
>                 spin_lock(&test->lock);                                 \
>                 (resource_ptr)->resource_field.init = NULL;             \
>                 (resource_ptr)->resource_field.free = NULL;             \
>                 list_add_tail(&(resource_ptr)->resource_field,          \
>                               &test->resources);                        \
>                 spin_unlock(&test->lock);                               \
>         } while (0)
>
>
> Within your kasan code you could then create a kasan-specific
> structure that embends a kunit_resource, and contains the
> values you need:
>
> struct kasan_report_resource {
>         struct kunit_resource res;
>         bool kasan_report_expected;
>         bool kasan_report_found;
> };
>
> (One thing we'd need to do for such static resources is fix
> kunit_resource_free() to check if there's a free() function,
> and if not assume a static resource)
>
> If you then create an init() function associated with your
> kunit suite (which will be run for every case) it can do this:
>
> int kunit_kasan_test_init(struct kunit *test)
> {
>         kunit_add_static_resource(test, &my_kasan_report_resource, res);
>         ...
> }
>
> The above should also be used to initialize current->kasan_unit_test
> instead of doing that in kunit_try_run_case().  With those
> changes, you don't (I think) need to change anything in core
> kunit (assuming support for static resources).
>
> To retrieve the resource during tests or in kasan context, the
> method seems to be to use kunit_resource_find(). However, that
> requires a match function which seems a bit heavyweight for the
> static case.  We should probably have a default "find by name"
> or similar function here, and add an optional "name" field
> to kunit resources to simplify things.  Anyway here you'd
> use something like:
>
>         kasan_report_resource = kunit_resource_find(test, matchfn,
>                                                     NULL, matchdata);
>
>
> Are there any barriers to taking this sort of approach (apart
> from the support for static resources not being there yet)?
>

I'm not sure. I don't have any experience with kunit resources so I
would have to put some more effort into understanding how this would
work for myself. I wonder if this might be a bit of an over
complicated way of eliminating an extraneous boolean... maybe we can
find a simpler solution for the first version of this patch and add
the notion of a static resource for generic use later.

> >  void kunit_init_test(struct kunit *test, const char *name);
> > @@ -941,6 +946,25 @@ do {                                                                            \
> >                                               ptr,                           \
> >                                               NULL)
> >
> > +/**
> > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > + * not cause a KASAN error.
> > + *
> > + */
> > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {        \
> > +     test->kasan_report_expected = true;     \
> > +     test->kasan_report_found = false; \
> > +     condition; \
> > +     if (test->kasan_report_found == test->kasan_report_expected) { \
> > +             pr_info("%d has passed", __LINE__); \
> > +     } else { \
> > +             kunit_set_failure(test); \
> > +             pr_info("%d has failed", __LINE__); \
> > +     } \
> > +     test->kasan_report_expected = false;    \
> > +     test->kasan_report_found = false;       \
> > +} while (0)
> > +
>
> Feels like this belongs in test_kasan.c, and could be reworked
> to avoid adding test->kasan_report_[expected|found] as described
> above.

You're right. Since I don't see any reason why any other tests should
want to expect a KASAN error, it does make sense to move this logic
inside test_kasan.c. If, in the future, there is a need for this
elsewhere, we can always move it back then.

>  Instead of having your own pass/fail logic couldn't you
> do this:
>
>         KUNIT_EXPECT_EQ(test, expected, found);
>
> ? That will set the failure state too so no need to export
> a separate function for that, and no need to log anything
> as KUNIT_EXPECT_EQ() should do that for you.
>

This is a great idea - I feel a little silly that I didn't think of
that myself! Do we think the failure message for the KUNIT_EXPECT_EQ()
would be sufficient for KASAN developers?
i.e. "Expected kasan_report_expected == kasan_report_found, but
kasan_report_expected == true
kasan_report_found == false"

> >  /**
> >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> >   * @test: The test context object.
> > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > index 04278493bf15..db23d56061e7 100644
> > --- a/include/linux/sched.h
> > +++ b/include/linux/sched.h
> > @@ -32,6 +32,8 @@
> >  #include <linux/posix-timers.h>
> >  #include <linux/rseq.h>
> >
> > +#include <kunit/test.h>
> > +
>
> This feels like the wrong place to add this #include, and
> when I attempted to build to test I ran into a bunch of
> compilation errors; for example:
>
>  CC      kernel/sched/core.o
> In file included from ./include/linux/uaccess.h:11,
>                  from ./arch/x86/include/asm/fpu/xstate.h:5,
>                  from ./arch/x86/include/asm/pgtable.h:26,
>                  from ./include/linux/kasan.h:16,
>                  from ./include/linux/slab.h:136,
>                  from ./include/kunit/test.h:16,
>                  from ./include/linux/sched.h:35,
>                  from init/do_mounts.c:3:
> ./arch/x86/include/asm/uaccess.h: In function 'set_fs':
> ./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to
> incomplete type 'struct task_struct'
>   current->thread.addr_limit = fs;
>
> (I'm testing with CONFIG_SLUB). Removing this #include
> resolves these errors, but then causes problems for
> lib/test_kasan.c. I'll dig around a bit more.
>

Yes, I was only testing with UML. Removing that #include fixed the
problem for me for both x86 and UML. Could you share more about the
errors you have encountered in lib/test_kasan.c?

> >  /* task_struct member predeclarations (sorted alphabetically): */
> >  struct audit_context;
> >  struct backing_dev_info;
> > @@ -1178,7 +1180,10 @@ struct task_struct {
> >
> >  #ifdef CONFIG_KASAN
> >       unsigned int                    kasan_depth;
> > -#endif
> > +#ifdef CONFIG_KUNIT
> > +     struct kunit *kasan_kunit_test;
> > +#endif /* CONFIG_KUNIT */
> > +#endif /* CONFIG_KASAN */
> >
> >  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
> >       /* Index of current stored address in ret_stack: */
> > diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> > index 9242f932896c..d266b9495c67 100644
> > --- a/lib/kunit/test.c
> > +++ b/lib/kunit/test.c
> > @@ -9,11 +9,12 @@
> >  #include <kunit/test.h>
> >  #include <linux/kernel.h>
> >  #include <linux/sched/debug.h>
> > +#include <linux/sched.h>
> >
> >  #include "string-stream.h"
> >  #include "try-catch-impl.h"
> >
> > -static void kunit_set_failure(struct kunit *test)
> > +void kunit_set_failure(struct kunit *test)
> >  {
> >       WRITE_ONCE(test->success, false);
> >  }
> > @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
> >       struct kunit_suite *suite = ctx->suite;
> >       struct kunit_case *test_case = ctx->test_case;
> >
> > +#ifdef CONFIG_KASAN
> > +     current->kasan_kunit_test = test;
> > +#endif
> > +
> >       /*
> >        * kunit_run_case_internal may encounter a fatal error; if it does,
> >        * abort will be called, this thread will exit, and finally the parent
> > diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> > index 5ef9f24f566b..5554d23799a5 100644
> > --- a/mm/kasan/report.c
> > +++ b/mm/kasan/report.c
> > @@ -32,6 +32,8 @@
> >
> >  #include <asm/sections.h>
> >
> > +#include <kunit/test.h>
> > +
> >  #include "kasan.h"
> >  #include "../slab.h"
> >
> > @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
> >       u8 tag = get_tag(object);
> >
> >       object = reset_tag(object);
> > +
> > +     if (current->kasan_kunit_test) {
> > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > +                     current->kasan_kunit_test->kasan_report_found = true;
> > +                     return;
> > +             }
> > +             kunit_set_failure(current->kasan_kunit_test);
> > +     }
> > +
> >       start_report(&flags);
> >       pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
> >       print_tags(tag, object);
> > @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
> >       if (likely(!report_enabled()))
> >               return;
> >
> > +     if (current->kasan_kunit_test) {
> > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > +                     current->kasan_kunit_test->kasan_report_found = true;
> > +                     return;
> > +             }
> > +             kunit_set_failure(current->kasan_kunit_test);
> > +     }
> > +
> >       disable_trace_on_warning();
> >
> >       tagged_addr = (void *)addr;
> > diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> > index cc5d844ecca1..63eab18a8c34 100644
> > --- a/tools/testing/kunit/kunit_kernel.py
> > +++ b/tools/testing/kunit/kunit_kernel.py
> > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> >               return True
> >
> >       def run_kernel(self, args=[], timeout=None, build_dir=''):
> > -             args.extend(['mem=256M'])
> > +             args.extend(['mem=256M', 'kasan_multi_shot'])
> >               process = self._ops.linux_bin(args, timeout, build_dir)
> >               with open(os.path.join(build_dir, 'test.log'), 'w') as f:
> >                       for line in process.stdout:
>
> I tried applying this to the "kunit" branch of linux-kselftest, and
> the above failed. Which branch are you building with? Probably
> best to use the kunit branch I think. Thanks!
>
I believe I am on Torvalds/master. There was some debate as to which
branch I should be developing on when I started, but it probably makes
sense for me to move to the "kunit" branch.

> Alan
>
> > --
> > 2.25.0.265.gbab2e86ba0-goog
> >
> >
Patricia Alfonso Feb. 29, 2020, 12:49 a.m. UTC | #6
On Thu, Feb 27, 2020 at 6:45 AM Dmitry Vyukov <dvyukov@google.com> wrote:
>
> On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> <kasan-dev@googlegroups.com> wrote:
> >
> > Integrate KASAN into KUnit testing framework.
> >  - Fail tests when KASAN reports an error that is not expected
> >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> >  - KUnit struct added to current task to keep track of the current test
> > from KASAN code
> >  - Booleans representing if a KASAN report is expected and if a KASAN
> >  report is found added to kunit struct
> >  - This prints "line# has passed" or "line# has failed"
> >
> > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
>
> This does not build for me:
>
> $ make
> scripts/kconfig/conf  --syncconfig Kconfig
>   CC      arch/x86/kernel/asm-offsets.s
>   UPD     include/generated/asm-offsets.h
>   CALL    scripts/checksyscalls.sh
>   CALL    scripts/atomic/check-atomics.sh
>   DESCEND  objtool
>   CC      init/main.o
> In file included from ./include/linux/uaccess.h:11,
>                  from ./arch/x86/include/asm/fpu/xstate.h:5,
>                  from ./arch/x86/include/asm/pgtable.h:26,
>                  from ./include/linux/kasan.h:15,
>                  from ./include/linux/slab.h:136,
>                  from ./include/kunit/test.h:16,
>                  from ./include/linux/sched.h:35,
>                  from ./include/linux/ioprio.h:5,
>                  from ./include/linux/fs.h:39,
>                  from ./include/linux/proc_fs.h:9,
>                  from init/main.c:18:
> ./arch/x86/include/asm/uaccess.h: In function ‘set_fs’:
> ./arch/x86/include/asm/uaccess.h:31:9: error: dereferencing pointer to
> incomplete type ‘struct task_struct’
>    31 |  current->thread.addr_limit = fs;
>       |         ^~
> make[1]: *** [scripts/Makefile.build:268: init/main.o] Error 1
> make: *** [Makefile:1681: init] Error 2
>
>
> On bfdc6d91a25f4545bcd1b12e3219af4838142ef1 config:
> https://pastebin.com/raw/nwnL2N9w

I'm sorry. It seems I only ever tested locally on UML. As Alan
suggested, removing "#include <kunit/test.h>" from
include/linux/sched.h seems to fix this problem.
Patricia Alfonso Feb. 29, 2020, 1:09 a.m. UTC | #7
On Thu, Feb 27, 2020 at 6:39 AM Dmitry Vyukov <dvyukov@google.com> wrote:
>
> On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> <kasan-dev@googlegroups.com> wrote:
> >
> > Integrate KASAN into KUnit testing framework.
> >  - Fail tests when KASAN reports an error that is not expected
> >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> >  - KUnit struct added to current task to keep track of the current test
> > from KASAN code
> >  - Booleans representing if a KASAN report is expected and if a KASAN
> >  report is found added to kunit struct
> >  - This prints "line# has passed" or "line# has failed"
> >
> > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > ---
> > If anyone has any suggestions on how best to print the failure
> > messages, please share!
> >
> > One issue I have found while testing this is the allocation fails in
> > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > does cause the test to fail on the KUnit side, as expected, but it
> > seems to skip all the tests before this one because the output starts
> > with this failure instead of with the first test, kmalloc_oob_right().
> >
> >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> >  include/linux/sched.h               |  7 ++++++-
> >  lib/kunit/test.c                    |  7 ++++++-
> >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> >  tools/testing/kunit/kunit_kernel.py |  2 +-
> >  5 files changed, 56 insertions(+), 3 deletions(-)
> >
> > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > index 2dfb550c6723..2e388f8937f3 100644
> > --- a/include/kunit/test.h
> > +++ b/include/kunit/test.h
> > @@ -21,6 +21,8 @@ struct kunit_resource;
> >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> >
> > +void kunit_set_failure(struct kunit *test);
> > +
> >  /**
> >   * struct kunit_resource - represents a *test managed resource*
> >   * @allocation: for the user to store arbitrary data.
> > @@ -191,6 +193,9 @@ struct kunit {
> >          * protect it with some type of lock.
> >          */
> >         struct list_head resources; /* Protected by lock. */
> > +
> > +       bool kasan_report_expected;
> > +       bool kasan_report_found;
> >  };
> >
> >  void kunit_init_test(struct kunit *test, const char *name);
> > @@ -941,6 +946,25 @@ do {                                                                              \
> >                                                 ptr,                           \
> >                                                 NULL)
> >
> > +/**
> > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > + * not cause a KASAN error.
>
> Oh, I see, this is not a test, but rather an ASSERT-like macro.
> Then maybe we should use it for actual expressions that are supposed
> to trigger KASAN errors?
>
> E.g. KUNIT_EXPECT_KASAN_FAIL(test, *(volatile int*)p);
>

This is one possible approach. I wasn't sure what would be the most
useful. Would it be most useful to assert an error is reported on a
function or assert an error is reported at a specific address?

>
> > + *
> > + */
> > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {  \
>
> s/condition/expression/
>
> > +       test->kasan_report_expected = true;     \
>
> Check that kasan_report_expected is unset. If these are nested things
> will break in confusing ways.
> Or otherwise we need to restore the previous value at the end.
>
Good point! I think I was just unsure of where I should set this value
and what the default should be.

> > +       test->kasan_report_found = false; \
> > +       condition; \
> > +       if (test->kasan_report_found == test->kasan_report_expected) { \
>
> We know that kasan_report_expected is true here, so we could just said:
>
> if (!test->kasan_report_found)
>
Good point! This is much more readable

> > +               pr_info("%d has passed", __LINE__); \
> > +       } else { \
> > +               kunit_set_failure(test); \
> > +               pr_info("%d has failed", __LINE__); \
>
> This needs a more readable error.
>
Yes, this was just a stand-in. I was wondering if you might have a
suggestion for the best way to print this failure message? Alan
suggested reusing the KUNIT_EXPECT_EQ() macro so the error message
would look something like:
"Expected kasan_report_expected == kasan_report_found, but
kasan_report_expected == true
kasan_report_found == false"

What do you think of this?

> > +       } \
> > +       test->kasan_report_expected = false;    \
> > +       test->kasan_report_found = false;       \
> > +} while (0)
> > +
> >  /**
> >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> >   * @test: The test context object.
> > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > index 04278493bf15..db23d56061e7 100644
> > --- a/include/linux/sched.h
> > +++ b/include/linux/sched.h
> > @@ -32,6 +32,8 @@
> >  #include <linux/posix-timers.h>
> >  #include <linux/rseq.h>
> >
> > +#include <kunit/test.h>
> > +
> >  /* task_struct member predeclarations (sorted alphabetically): */
> >  struct audit_context;
> >  struct backing_dev_info;
> > @@ -1178,7 +1180,10 @@ struct task_struct {
> >
> >  #ifdef CONFIG_KASAN
> >         unsigned int                    kasan_depth;
> > -#endif
> > +#ifdef CONFIG_KUNIT
> > +       struct kunit *kasan_kunit_test;
>
> I would assume we will use this for other things as well (failing
> tests on LOCKDEP errors, WARNINGs, etc).
> So I would call this just kunit_test and make non-dependent on KASAN right away.
>
Yeah, I think I just wanted to make it clear that this is only used
for KASAN, but I believe that was before we talked about extending
this.

> > +       if (current->kasan_kunit_test) {
>
> Strictly saying, this also needs to check in_task().
>

I was not aware of in_task()... can you explain its importance to me?

> > +               if (current->kasan_kunit_test->kasan_report_expected) {
> > +                       current->kasan_kunit_test->kasan_report_found = true;
> > +                       return;
> > +               }
> > +               kunit_set_failure(current->kasan_kunit_test);
> > +       }
>
> This chunk is duplicated 2 times. I think it will be more reasonable
> for KASAN code to just notify KUNIT that the error has happened, and
> then KUNIT will figure out what it means and what to do.
>
>
Yeah, I think moving this to the KUnit files is best too. I would like
to keep kunit_set_failure a static function as well.
Patricia Alfonso Feb. 29, 2020, 1:23 a.m. UTC | #8
On Thu, Feb 27, 2020 at 6:43 AM Dmitry Vyukov <dvyukov@google.com> wrote:
>
> On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> <kasan-dev@googlegroups.com> wrote:
> >
> > Integrate KASAN into KUnit testing framework.
> >  - Fail tests when KASAN reports an error that is not expected
> >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> >  - KUnit struct added to current task to keep track of the current test
> > from KASAN code
> >  - Booleans representing if a KASAN report is expected and if a KASAN
> >  report is found added to kunit struct
> >  - This prints "line# has passed" or "line# has failed"
> >
> > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > ---
> > If anyone has any suggestions on how best to print the failure
> > messages, please share!
> >
> > One issue I have found while testing this is the allocation fails in
> > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > does cause the test to fail on the KUnit side, as expected, but it
> > seems to skip all the tests before this one because the output starts
> > with this failure instead of with the first test, kmalloc_oob_right().
>
> I don't follow this... we don't check output in any way, so how does
> output affect execution?...
>
I'm sorry. I think I was just reading the results wrong before - no
wonder I was confused!

I just recreated the error and it does work as expected.

>
> > --- a/tools/testing/kunit/kunit_kernel.py
> > +++ b/tools/testing/kunit/kunit_kernel.py
> > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> >                 return True
> >
> >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > -               args.extend(['mem=256M'])
> > +               args.extend(['mem=256M', 'kasan_multi_shot'])
>
> This is better done somewhere else (different default value if
> KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> to be a mandatory part now. This means people will always hit this, be
> confused, figure out they need to flip the value, and only then be
> able to run kunit+kasan.
>
I agree. Is the best way to do this with "bool multishot =
kasan_save_enable_multi_shot();"  and
"kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
was done in the tests before?
Dmitry Vyukov March 1, 2020, 6:26 a.m. UTC | #9
On Sat, Feb 29, 2020 at 2:09 AM Patricia Alfonso
<trishalfonso@google.com> wrote:
> > <kasan-dev@googlegroups.com> wrote:
> > >
> > > Integrate KASAN into KUnit testing framework.
> > >  - Fail tests when KASAN reports an error that is not expected
> > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > >  - KUnit struct added to current task to keep track of the current test
> > > from KASAN code
> > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > >  report is found added to kunit struct
> > >  - This prints "line# has passed" or "line# has failed"
> > >
> > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > ---
> > > If anyone has any suggestions on how best to print the failure
> > > messages, please share!
> > >
> > > One issue I have found while testing this is the allocation fails in
> > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > does cause the test to fail on the KUnit side, as expected, but it
> > > seems to skip all the tests before this one because the output starts
> > > with this failure instead of with the first test, kmalloc_oob_right().
> > >
> > >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> > >  include/linux/sched.h               |  7 ++++++-
> > >  lib/kunit/test.c                    |  7 ++++++-
> > >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> > >  tools/testing/kunit/kunit_kernel.py |  2 +-
> > >  5 files changed, 56 insertions(+), 3 deletions(-)
> > >
> > > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > > index 2dfb550c6723..2e388f8937f3 100644
> > > --- a/include/kunit/test.h
> > > +++ b/include/kunit/test.h
> > > @@ -21,6 +21,8 @@ struct kunit_resource;
> > >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> > >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> > >
> > > +void kunit_set_failure(struct kunit *test);
> > > +
> > >  /**
> > >   * struct kunit_resource - represents a *test managed resource*
> > >   * @allocation: for the user to store arbitrary data.
> > > @@ -191,6 +193,9 @@ struct kunit {
> > >          * protect it with some type of lock.
> > >          */
> > >         struct list_head resources; /* Protected by lock. */
> > > +
> > > +       bool kasan_report_expected;
> > > +       bool kasan_report_found;
> > >  };
> > >
> > >  void kunit_init_test(struct kunit *test, const char *name);
> > > @@ -941,6 +946,25 @@ do {                                                                              \
> > >                                                 ptr,                           \
> > >                                                 NULL)
> > >
> > > +/**
> > > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > > + * not cause a KASAN error.
> >
> > Oh, I see, this is not a test, but rather an ASSERT-like macro.
> > Then maybe we should use it for actual expressions that are supposed
> > to trigger KASAN errors?
> >
> > E.g. KUNIT_EXPECT_KASAN_FAIL(test, *(volatile int*)p);
> >
>
> This is one possible approach. I wasn't sure what would be the most
> useful. Would it be most useful to assert an error is reported on a
> function or assert an error is reported at a specific address?

I would say assert on a specific line of code/expression for locality reasons.
This will also solve the problem for tests that trigger several
reports, this way we can check that we get N reports.


> > > + *
> > > + */
> > > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {  \
> >
> > s/condition/expression/
> >
> > > +       test->kasan_report_expected = true;     \
> >
> > Check that kasan_report_expected is unset. If these are nested things
> > will break in confusing ways.
> > Or otherwise we need to restore the previous value at the end.
> >
> Good point! I think I was just unsure of where I should set this value
> and what the default should be.
>
> > > +       test->kasan_report_found = false; \
> > > +       condition; \
> > > +       if (test->kasan_report_found == test->kasan_report_expected) { \
> >
> > We know that kasan_report_expected is true here, so we could just said:
> >
> > if (!test->kasan_report_found)
> >
> Good point! This is much more readable
>
> > > +               pr_info("%d has passed", __LINE__); \
> > > +       } else { \
> > > +               kunit_set_failure(test); \
> > > +               pr_info("%d has failed", __LINE__); \
> >
> > This needs a more readable error.
> >
> Yes, this was just a stand-in. I was wondering if you might have a
> suggestion for the best way to print this failure message? Alan
> suggested reusing the KUNIT_EXPECT_EQ() macro so the error message
> would look something like:
> "Expected kasan_report_expected == kasan_report_found, but
> kasan_report_expected == true
> kasan_report_found == false"
>
> What do you think of this?

I will be able to understand why the test has failed reading this error message.
A more human-friendly message may be better, but if this makes for
better consistency I am fine with this.

> > > +       } \
> > > +       test->kasan_report_expected = false;    \
> > > +       test->kasan_report_found = false;       \
> > > +} while (0)
> > > +
> > >  /**
> > >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> > >   * @test: The test context object.
> > > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > > index 04278493bf15..db23d56061e7 100644
> > > --- a/include/linux/sched.h
> > > +++ b/include/linux/sched.h
> > > @@ -32,6 +32,8 @@
> > >  #include <linux/posix-timers.h>
> > >  #include <linux/rseq.h>
> > >
> > > +#include <kunit/test.h>
> > > +
> > >  /* task_struct member predeclarations (sorted alphabetically): */
> > >  struct audit_context;
> > >  struct backing_dev_info;
> > > @@ -1178,7 +1180,10 @@ struct task_struct {
> > >
> > >  #ifdef CONFIG_KASAN
> > >         unsigned int                    kasan_depth;
> > > -#endif
> > > +#ifdef CONFIG_KUNIT
> > > +       struct kunit *kasan_kunit_test;
> >
> > I would assume we will use this for other things as well (failing
> > tests on LOCKDEP errors, WARNINGs, etc).
> > So I would call this just kunit_test and make non-dependent on KASAN right away.
> >
> Yeah, I think I just wanted to make it clear that this is only used
> for KASAN, but I believe that was before we talked about extending
> this.
>
> > > +       if (current->kasan_kunit_test) {
> >
> > Strictly saying, this also needs to check in_task().
> >
>
> I was not aware of in_task()... can you explain its importance to me?
>
> > > +               if (current->kasan_kunit_test->kasan_report_expected) {
> > > +                       current->kasan_kunit_test->kasan_report_found = true;
> > > +                       return;
> > > +               }
> > > +               kunit_set_failure(current->kasan_kunit_test);
> > > +       }
> >
> > This chunk is duplicated 2 times. I think it will be more reasonable
> > for KASAN code to just notify KUNIT that the error has happened, and
> > then KUNIT will figure out what it means and what to do.
> >
> >
> Yeah, I think moving this to the KUnit files is best too. I would like
> to keep kunit_set_failure a static function as well.
>
>
> --
> Thank you for the comments!
>
> Patricia Alfonso
Dmitry Vyukov March 1, 2020, 6:29 a.m. UTC | #10
On Sat, Feb 29, 2020 at 2:23 AM Patricia Alfonso
<trishalfonso@google.com> wrote:
> >
> > On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> > <kasan-dev@googlegroups.com> wrote:
> > >
> > > Integrate KASAN into KUnit testing framework.
> > >  - Fail tests when KASAN reports an error that is not expected
> > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > >  - KUnit struct added to current task to keep track of the current test
> > > from KASAN code
> > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > >  report is found added to kunit struct
> > >  - This prints "line# has passed" or "line# has failed"
> > >
> > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > ---
> > > If anyone has any suggestions on how best to print the failure
> > > messages, please share!
> > >
> > > One issue I have found while testing this is the allocation fails in
> > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > does cause the test to fail on the KUnit side, as expected, but it
> > > seems to skip all the tests before this one because the output starts
> > > with this failure instead of with the first test, kmalloc_oob_right().
> >
> > I don't follow this... we don't check output in any way, so how does
> > output affect execution?...
> >
> I'm sorry. I think I was just reading the results wrong before - no
> wonder I was confused!
>
> I just recreated the error and it does work as expected.
>
> >
> > > --- a/tools/testing/kunit/kunit_kernel.py
> > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > >                 return True
> > >
> > >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > -               args.extend(['mem=256M'])
> > > +               args.extend(['mem=256M', 'kasan_multi_shot'])
> >
> > This is better done somewhere else (different default value if
> > KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> > Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> > to be a mandatory part now. This means people will always hit this, be
> > confused, figure out they need to flip the value, and only then be
> > able to run kunit+kasan.
> >
> I agree. Is the best way to do this with "bool multishot =
> kasan_save_enable_multi_shot();"  and
> "kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
> was done in the tests before?

This will fix KASAN tests, but not non-KASAN tests running under KUNIT
and triggering KASAN reports.
You set kasan_multi_shot for all KUNIT tests. I am reading this as
that we don't want to abort on the first test that triggered a KASAN
report. Or not?
Alan Maguire March 3, 2020, 4:40 p.m. UTC | #11
On Fri, 28 Feb 2020, Patricia Alfonso wrote:

> On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> >
> > On Wed, 26 Feb 2020, Patricia Alfonso wrote:
> >
> > > Integrate KASAN into KUnit testing framework.
> >
> > This is a great idea! Some comments/suggestions below...
> >
> 
> Thank you so much for your suggestions!
>

No problem! Extending KUnit to test things like KASAN
is really valuable, as it shows us ways we can improve
the framework. More below...
 
> > >  - Fail tests when KASAN reports an error that is not expected
> > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > >  - KUnit struct added to current task to keep track of the current test
> > > from KASAN code
> > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > >  report is found added to kunit struct
> > >  - This prints "line# has passed" or "line# has failed"
> > >
> > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > ---
> > > If anyone has any suggestions on how best to print the failure
> > > messages, please share!
> > >
> > > One issue I have found while testing this is the allocation fails in
> > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > does cause the test to fail on the KUnit side, as expected, but it
> > > seems to skip all the tests before this one because the output starts
> > > with this failure instead of with the first test, kmalloc_oob_right().
> > >
> > >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> > >  include/linux/sched.h               |  7 ++++++-
> > >  lib/kunit/test.c                    |  7 ++++++-
> > >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> > >  tools/testing/kunit/kunit_kernel.py |  2 +-
> > >  5 files changed, 56 insertions(+), 3 deletions(-)
> > >
> > > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > > index 2dfb550c6723..2e388f8937f3 100644
> > > --- a/include/kunit/test.h
> > > +++ b/include/kunit/test.h
> > > @@ -21,6 +21,8 @@ struct kunit_resource;
> > >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> > >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> > >
> > > +void kunit_set_failure(struct kunit *test);
> > > +
> > >  /**
> > >   * struct kunit_resource - represents a *test managed resource*
> > >   * @allocation: for the user to store arbitrary data.
> > > @@ -191,6 +193,9 @@ struct kunit {
> > >        * protect it with some type of lock.
> > >        */
> > >       struct list_head resources; /* Protected by lock. */
> > > +
> > > +     bool kasan_report_expected;
> > > +     bool kasan_report_found;
> > >  };
> > >
> >
> > Is this needed here? You're testing something pretty
> > specific so it seems wrong to add to the generic
> > kunit resource unless there's a good reason. I see the
> > code around setting these values in mm/kasan/report.c,
> > but I wonder if we could do something more generic.
> >
> > How about the concept of a static resource (assuming a
> > dynamically allocated one is out because it messes
> > with memory allocation tests)? Something like this:
> >
> > #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
> >         do {                                                            \
> >                 spin_lock(&test->lock);                                 \
> >                 (resource_ptr)->resource_field.init = NULL;             \
> >                 (resource_ptr)->resource_field.free = NULL;             \
> >                 list_add_tail(&(resource_ptr)->resource_field,          \
> >                               &test->resources);                        \
> >                 spin_unlock(&test->lock);                               \
> >         } while (0)
> >
> >
> > Within your kasan code you could then create a kasan-specific
> > structure that embends a kunit_resource, and contains the
> > values you need:
> >
> > struct kasan_report_resource {
> >         struct kunit_resource res;
> >         bool kasan_report_expected;
> >         bool kasan_report_found;
> > };
> >
> > (One thing we'd need to do for such static resources is fix
> > kunit_resource_free() to check if there's a free() function,
> > and if not assume a static resource)
> >
> > If you then create an init() function associated with your
> > kunit suite (which will be run for every case) it can do this:
> >
> > int kunit_kasan_test_init(struct kunit *test)
> > {
> >         kunit_add_static_resource(test, &my_kasan_report_resource, res);
> >         ...
> > }
> >
> > The above should also be used to initialize current->kasan_unit_test
> > instead of doing that in kunit_try_run_case().  With those
> > changes, you don't (I think) need to change anything in core
> > kunit (assuming support for static resources).
> >
> > To retrieve the resource during tests or in kasan context, the
> > method seems to be to use kunit_resource_find(). However, that
> > requires a match function which seems a bit heavyweight for the
> > static case.  We should probably have a default "find by name"
> > or similar function here, and add an optional "name" field
> > to kunit resources to simplify things.  Anyway here you'd
> > use something like:
> >
> >         kasan_report_resource = kunit_resource_find(test, matchfn,
> >                                                     NULL, matchdata);
> >
> >
> > Are there any barriers to taking this sort of approach (apart
> > from the support for static resources not being there yet)?
> >
> 
> I'm not sure. I don't have any experience with kunit resources so I
> would have to put some more effort into understanding how this would
> work for myself. I wonder if this might be a bit of an over
> complicated way of eliminating an extraneous boolean... maybe we can
> find a simpler solution for the first version of this patch and add
> the notion of a static resource for generic use later.
>

My personal preference would be to try and learn what's needed
by KASAN and improve the KUnit APIs so the next developer finds
life a bit easier. More hassle for you I know, but actual use cases
like this are invaluable for improving the API.  I've sent
out an RFC patchset which has the functionality I _think_ you
need but I may be missing something:

https://lore.kernel.org/linux-kselftest/1583251361-12748-1-git-send-email-alan.maguire@oracle.com/T/#t

The idea is your test can do something like this:

struct kasan_data {
	bool report_expected;
	bool report_found;
};


my_kasan_test(struct kunit *test)
{
	struct kunit_resource resource;
	struct kasan_data kasan_data;

...
	// add our named resource using static resource/data
	kunit_add_named_resource(test, NULL, NULL, &resource, 
				 "kasan_data", &kasan_data);
...

}

(The NULLs in the function arguments above reflect the fact we
don't require initialization or cleanup for such static resources)

Then, in KASAN context you can look the above resource up like so:

	struct kunit_resource *resource;
	struct kasan_data *kasan_data;

	resource = kunit_find_named_resource(test, "kasan_data");
	kasan_data = resource->data;

	// when finished, reduce reference count on resource
	kunit_put_resource(resource);
 
Does that work for your use case?

> > >  void kunit_init_test(struct kunit *test, const char *name);
> > > @@ -941,6 +946,25 @@ do {                                                                            \
> > >                                               ptr,                           \
> > >                                               NULL)
> > >
> > > +/**
> > > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > > + * not cause a KASAN error.
> > > + *
> > > + */
> > > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {        \
> > > +     test->kasan_report_expected = true;     \
> > > +     test->kasan_report_found = false; \
> > > +     condition; \
> > > +     if (test->kasan_report_found == test->kasan_report_expected) { \
> > > +             pr_info("%d has passed", __LINE__); \
> > > +     } else { \
> > > +             kunit_set_failure(test); \
> > > +             pr_info("%d has failed", __LINE__); \
> > > +     } \
> > > +     test->kasan_report_expected = false;    \
> > > +     test->kasan_report_found = false;       \
> > > +} while (0)
> > > +
> >
> > Feels like this belongs in test_kasan.c, and could be reworked
> > to avoid adding test->kasan_report_[expected|found] as described
> > above.
> 
> You're right. Since I don't see any reason why any other tests should
> want to expect a KASAN error, it does make sense to move this logic
> inside test_kasan.c. If, in the future, there is a need for this
> elsewhere, we can always move it back then.
> 
> >  Instead of having your own pass/fail logic couldn't you
> > do this:
> >
> >         KUNIT_EXPECT_EQ(test, expected, found);
> >
> > ? That will set the failure state too so no need to export
> > a separate function for that, and no need to log anything
> > as KUNIT_EXPECT_EQ() should do that for you.
> >
> 
> This is a great idea - I feel a little silly that I didn't think of
> that myself! Do we think the failure message for the KUNIT_EXPECT_EQ()
> would be sufficient for KASAN developers?
> i.e. "Expected kasan_report_expected == kasan_report_found, but
> kasan_report_expected == true
> kasan_report_found == false"
>

I guess the missing piece above is the line number where
the test failure was encountered, is that the concern?
 
> > >  /**
> > >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> > >   * @test: The test context object.
> > > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > > index 04278493bf15..db23d56061e7 100644
> > > --- a/include/linux/sched.h
> > > +++ b/include/linux/sched.h
> > > @@ -32,6 +32,8 @@
> > >  #include <linux/posix-timers.h>
> > >  #include <linux/rseq.h>
> > >
> > > +#include <kunit/test.h>
> > > +
> >
> > This feels like the wrong place to add this #include, and
> > when I attempted to build to test I ran into a bunch of
> > compilation errors; for example:
> >
> >  CC      kernel/sched/core.o
> > In file included from ./include/linux/uaccess.h:11,
> >                  from ./arch/x86/include/asm/fpu/xstate.h:5,
> >                  from ./arch/x86/include/asm/pgtable.h:26,
> >                  from ./include/linux/kasan.h:16,
> >                  from ./include/linux/slab.h:136,
> >                  from ./include/kunit/test.h:16,
> >                  from ./include/linux/sched.h:35,
> >                  from init/do_mounts.c:3:
> > ./arch/x86/include/asm/uaccess.h: In function 'set_fs':
> > ./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to
> > incomplete type 'struct task_struct'
> >   current->thread.addr_limit = fs;
> >
> > (I'm testing with CONFIG_SLUB). Removing this #include
> > resolves these errors, but then causes problems for
> > lib/test_kasan.c. I'll dig around a bit more.
> >
> 
> Yes, I was only testing with UML. Removing that #include fixed the
> problem for me for both x86 and UML. Could you share more about the
> errors you have encountered in lib/test_kasan.c?
> 

I'll try this again and send details.

I think broadly the issue is that if we #include kunit headers
in the kasan headers, we end up creating all kinds of problems
for ourselves, since the kasan headers are in turn included
in so many places (including the kunit headers themselves, since
kunit uses memory allocation APIs). I suspect the way forward is
to try and ensure that we don't utilize the kunit headers in any
of the kasan headers, but rather just include kunit headers
in test_kasan.c, and any other kasan .c files we need KUnit APIs
for. Not sure if that's possible, but it's likely the best way to
go if it is.

> > >  /* task_struct member predeclarations (sorted alphabetically): */
> > >  struct audit_context;
> > >  struct backing_dev_info;
> > > @@ -1178,7 +1180,10 @@ struct task_struct {
> > >
> > >  #ifdef CONFIG_KASAN
> > >       unsigned int                    kasan_depth;
> > > -#endif
> > > +#ifdef CONFIG_KUNIT
> > > +     struct kunit *kasan_kunit_test;
> > > +#endif /* CONFIG_KUNIT */
> > > +#endif /* CONFIG_KASAN */
> > >
> > >  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
> > >       /* Index of current stored address in ret_stack: */
> > > diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> > > index 9242f932896c..d266b9495c67 100644
> > > --- a/lib/kunit/test.c
> > > +++ b/lib/kunit/test.c
> > > @@ -9,11 +9,12 @@
> > >  #include <kunit/test.h>
> > >  #include <linux/kernel.h>
> > >  #include <linux/sched/debug.h>
> > > +#include <linux/sched.h>
> > >
> > >  #include "string-stream.h"
> > >  #include "try-catch-impl.h"
> > >
> > > -static void kunit_set_failure(struct kunit *test)
> > > +void kunit_set_failure(struct kunit *test)
> > >  {
> > >       WRITE_ONCE(test->success, false);
> > >  }
> > > @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
> > >       struct kunit_suite *suite = ctx->suite;
> > >       struct kunit_case *test_case = ctx->test_case;
> > >
> > > +#ifdef CONFIG_KASAN
> > > +     current->kasan_kunit_test = test;
> > > +#endif
> > > +
> > >       /*
> > >        * kunit_run_case_internal may encounter a fatal error; if it does,
> > >        * abort will be called, this thread will exit, and finally the parent
> > > diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> > > index 5ef9f24f566b..5554d23799a5 100644
> > > --- a/mm/kasan/report.c
> > > +++ b/mm/kasan/report.c
> > > @@ -32,6 +32,8 @@
> > >
> > >  #include <asm/sections.h>
> > >
> > > +#include <kunit/test.h>
> > > +
> > >  #include "kasan.h"
> > >  #include "../slab.h"
> > >
> > > @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
> > >       u8 tag = get_tag(object);
> > >
> > >       object = reset_tag(object);
> > > +
> > > +     if (current->kasan_kunit_test) {
> > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > +                     return;
> > > +             }
> > > +             kunit_set_failure(current->kasan_kunit_test);
> > > +     }
> > > +
> > >       start_report(&flags);
> > >       pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
> > >       print_tags(tag, object);
> > > @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
> > >       if (likely(!report_enabled()))
> > >               return;
> > >
> > > +     if (current->kasan_kunit_test) {
> > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > +                     return;
> > > +             }
> > > +             kunit_set_failure(current->kasan_kunit_test);
> > > +     }
> > > +
> > >       disable_trace_on_warning();
> > >
> > >       tagged_addr = (void *)addr;
> > > diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> > > index cc5d844ecca1..63eab18a8c34 100644
> > > --- a/tools/testing/kunit/kunit_kernel.py
> > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > >               return True
> > >
> > >       def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > -             args.extend(['mem=256M'])
> > > +             args.extend(['mem=256M', 'kasan_multi_shot'])
> > >               process = self._ops.linux_bin(args, timeout, build_dir)
> > >               with open(os.path.join(build_dir, 'test.log'), 'w') as f:
> > >                       for line in process.stdout:
> >
> > I tried applying this to the "kunit" branch of linux-kselftest, and
> > the above failed. Which branch are you building with? Probably
> > best to use the kunit branch I think. Thanks!
> >
> I believe I am on Torvalds/master. There was some debate as to which
> branch I should be developing on when I started, but it probably makes
> sense for me to move to the "kunit" branch.
>

I think for this case - given that we may need some new KUnit
functionality - that would be best. Thanks!

Alan
 
> > Alan
> >
> > > --
> > > 2.25.0.265.gbab2e86ba0-goog
> > >
> > >
> 
> -- 
> Thank you for all your comments!
> Patricia Alfonso
>
Patricia Alfonso March 4, 2020, 1:26 a.m. UTC | #12
On Sat, Feb 29, 2020 at 10:29 PM Dmitry Vyukov <dvyukov@google.com> wrote:
>
> On Sat, Feb 29, 2020 at 2:23 AM Patricia Alfonso
> <trishalfonso@google.com> wrote:
> > >
> > > On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> > > <kasan-dev@googlegroups.com> wrote:
> > > >
> > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > >                 return True
> > > >
> > > >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > -               args.extend(['mem=256M'])
> > > > +               args.extend(['mem=256M', 'kasan_multi_shot'])
> > >
> > > This is better done somewhere else (different default value if
> > > KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> > > Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> > > to be a mandatory part now. This means people will always hit this, be
> > > confused, figure out they need to flip the value, and only then be
> > > able to run kunit+kasan.
> > >
> > I agree. Is the best way to do this with "bool multishot =
> > kasan_save_enable_multi_shot();"  and
> > "kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
> > was done in the tests before?
>
> This will fix KASAN tests, but not non-KASAN tests running under KUNIT
> and triggering KASAN reports.
> You set kasan_multi_shot for all KUNIT tests. I am reading this as
> that we don't want to abort on the first test that triggered a KASAN
> report. Or not?

I don't think I understand the question, but let me try to explain my
thinking and see if that resonates with you. We know that the KASAN
tests will require more than one report, and we want that. For most
users, since a KASAN error can cause unexpected kernel behavior for
anything after a KASAN error, it is best for just one unexpected KASAN
error to be the only error printed to the user, unless they specify
kasan-multi-shot. The way I understand it, the way to implement this
is to use  "bool multishot = kasan_save_enable_multi_shot();"  and
"kasan_restore_multi_shot(multishot);" around the KASAN tests so that
kasan-multi-shot is temporarily enabled for the tests we expect
multiple reports. I assume "kasan_restore_multi_shot(multishot);"
restores the value to what the user input was so after the KASAN tests
are finished, if the user did not specify kasan-multi-shot and an
unexpected kasan error is reported, it will print the full report and
only that first one. Is this understanding correct? If you have a
better way of implementing this or a better expected behavior, I
appreciate your thoughts.
Dmitry Vyukov March 4, 2020, 6:23 a.m. UTC | #13
On Wed, Mar 4, 2020 at 2:26 AM Patricia Alfonso <trishalfonso@google.com> wrote:
>
> On Sat, Feb 29, 2020 at 10:29 PM Dmitry Vyukov <dvyukov@google.com> wrote:
> >
> > On Sat, Feb 29, 2020 at 2:23 AM Patricia Alfonso
> > <trishalfonso@google.com> wrote:
> > > >
> > > > On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> > > > <kasan-dev@googlegroups.com> wrote:
> > > > >
> > > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > > >                 return True
> > > > >
> > > > >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > > -               args.extend(['mem=256M'])
> > > > > +               args.extend(['mem=256M', 'kasan_multi_shot'])
> > > >
> > > > This is better done somewhere else (different default value if
> > > > KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> > > > Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> > > > to be a mandatory part now. This means people will always hit this, be
> > > > confused, figure out they need to flip the value, and only then be
> > > > able to run kunit+kasan.
> > > >
> > > I agree. Is the best way to do this with "bool multishot =
> > > kasan_save_enable_multi_shot();"  and
> > > "kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
> > > was done in the tests before?
> >
> > This will fix KASAN tests, but not non-KASAN tests running under KUNIT
> > and triggering KASAN reports.
> > You set kasan_multi_shot for all KUNIT tests. I am reading this as
> > that we don't want to abort on the first test that triggered a KASAN
> > report. Or not?
>
> I don't think I understand the question, but let me try to explain my
> thinking and see if that resonates with you. We know that the KASAN
> tests will require more than one report, and we want that. For most
> users, since a KASAN error can cause unexpected kernel behavior for
> anything after a KASAN error, it is best for just one unexpected KASAN
> error to be the only error printed to the user, unless they specify
> kasan-multi-shot. The way I understand it, the way to implement this
> is to use  "bool multishot = kasan_save_enable_multi_shot();"  and
> "kasan_restore_multi_shot(multishot);" around the KASAN tests so that
> kasan-multi-shot is temporarily enabled for the tests we expect
> multiple reports. I assume "kasan_restore_multi_shot(multishot);"
> restores the value to what the user input was so after the KASAN tests
> are finished, if the user did not specify kasan-multi-shot and an
> unexpected kasan error is reported, it will print the full report and
> only that first one. Is this understanding correct? If you have a
> better way of implementing this or a better expected behavior, I
> appreciate your thoughts.

Everything you say is correct.
What I tried to point at is that this new behavior is different from
the original behavior of your change. Initially you added
kasan_multi_shot to command line for _all_ kunit tests (not just
KASAN). The question is: do we want kasan_multi_shot for non-KASAN
tests or not?
Dmitry Vyukov March 4, 2020, 6:35 a.m. UTC | #14
On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
<kasan-dev@googlegroups.com> wrote:
>
> Integrate KASAN into KUnit testing framework.
>  - Fail tests when KASAN reports an error that is not expected
>  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
>  - KUnit struct added to current task to keep track of the current test
> from KASAN code
>  - Booleans representing if a KASAN report is expected and if a KASAN
>  report is found added to kunit struct
>  - This prints "line# has passed" or "line# has failed"
>
> Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> ---
> If anyone has any suggestions on how best to print the failure
> messages, please share!
>
> One issue I have found while testing this is the allocation fails in
> kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> does cause the test to fail on the KUnit side, as expected, but it
> seems to skip all the tests before this one because the output starts
> with this failure instead of with the first test, kmalloc_oob_right().
>
>  include/kunit/test.h                | 24 ++++++++++++++++++++++++
>  include/linux/sched.h               |  7 ++++++-
>  lib/kunit/test.c                    |  7 ++++++-
>  mm/kasan/report.c                   | 19 +++++++++++++++++++
>  tools/testing/kunit/kunit_kernel.py |  2 +-
>  5 files changed, 56 insertions(+), 3 deletions(-)
>
> diff --git a/include/kunit/test.h b/include/kunit/test.h
> index 2dfb550c6723..2e388f8937f3 100644
> --- a/include/kunit/test.h
> +++ b/include/kunit/test.h
> @@ -21,6 +21,8 @@ struct kunit_resource;
>  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
>  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
>
> +void kunit_set_failure(struct kunit *test);
> +
>  /**
>   * struct kunit_resource - represents a *test managed resource*
>   * @allocation: for the user to store arbitrary data.
> @@ -191,6 +193,9 @@ struct kunit {
>          * protect it with some type of lock.
>          */
>         struct list_head resources; /* Protected by lock. */
> +
> +       bool kasan_report_expected;
> +       bool kasan_report_found;
>  };
>
>  void kunit_init_test(struct kunit *test, const char *name);
> @@ -941,6 +946,25 @@ do {                                                                              \
>                                                 ptr,                           \
>                                                 NULL)
>
> +/**
> + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> + * not cause a KASAN error.
> + *
> + */
> +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {  \
> +       test->kasan_report_expected = true;     \
> +       test->kasan_report_found = false; \
> +       condition; \
> +       if (test->kasan_report_found == test->kasan_report_expected) { \
> +               pr_info("%d has passed", __LINE__); \
> +       } else { \
> +               kunit_set_failure(test); \
> +               pr_info("%d has failed", __LINE__); \
> +       } \
> +       test->kasan_report_expected = false;    \
> +       test->kasan_report_found = false;       \
> +} while (0)
> +
>  /**
>   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
>   * @test: The test context object.
> diff --git a/include/linux/sched.h b/include/linux/sched.h
> index 04278493bf15..db23d56061e7 100644
> --- a/include/linux/sched.h
> +++ b/include/linux/sched.h
> @@ -32,6 +32,8 @@
>  #include <linux/posix-timers.h>
>  #include <linux/rseq.h>
>
> +#include <kunit/test.h>
> +
>  /* task_struct member predeclarations (sorted alphabetically): */
>  struct audit_context;
>  struct backing_dev_info;
> @@ -1178,7 +1180,10 @@ struct task_struct {
>
>  #ifdef CONFIG_KASAN
>         unsigned int                    kasan_depth;
> -#endif
> +#ifdef CONFIG_KUNIT
> +       struct kunit *kasan_kunit_test;
> +#endif /* CONFIG_KUNIT */
> +#endif /* CONFIG_KASAN */
>
>  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
>         /* Index of current stored address in ret_stack: */
> diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> index 9242f932896c..d266b9495c67 100644
> --- a/lib/kunit/test.c
> +++ b/lib/kunit/test.c
> @@ -9,11 +9,12 @@
>  #include <kunit/test.h>
>  #include <linux/kernel.h>
>  #include <linux/sched/debug.h>
> +#include <linux/sched.h>
>
>  #include "string-stream.h"
>  #include "try-catch-impl.h"
>
> -static void kunit_set_failure(struct kunit *test)
> +void kunit_set_failure(struct kunit *test)
>  {
>         WRITE_ONCE(test->success, false);
>  }
> @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
>         struct kunit_suite *suite = ctx->suite;
>         struct kunit_case *test_case = ctx->test_case;
>
> +#ifdef CONFIG_KASAN
> +       current->kasan_kunit_test = test;
> +#endif
> +
>         /*
>          * kunit_run_case_internal may encounter a fatal error; if it does,
>          * abort will be called, this thread will exit, and finally the parent
> diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> index 5ef9f24f566b..5554d23799a5 100644
> --- a/mm/kasan/report.c
> +++ b/mm/kasan/report.c
> @@ -32,6 +32,8 @@
>
>  #include <asm/sections.h>
>
> +#include <kunit/test.h>
> +
>  #include "kasan.h"
>  #include "../slab.h"
>
> @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
>         u8 tag = get_tag(object);
>
>         object = reset_tag(object);
> +
> +       if (current->kasan_kunit_test) {
> +               if (current->kasan_kunit_test->kasan_report_expected) {
> +                       current->kasan_kunit_test->kasan_report_found = true;
> +                       return;

I think we need to continue and print KASAN report even in this case.
2 reasons:
 - tests don't check validity of printed reports, but at least human
can verify sanity of the report
 - report printing code also needs to be tested, at least that it does
not crash/hang
If we don't print reports, it may look nicer, but will be less useful.

> +               }
> +               kunit_set_failure(current->kasan_kunit_test);
> +       }
> +
Patricia Alfonso March 5, 2020, 12:07 a.m. UTC | #15
On Tue, Mar 3, 2020 at 10:23 PM Dmitry Vyukov <dvyukov@google.com> wrote:
>
> On Wed, Mar 4, 2020 at 2:26 AM Patricia Alfonso <trishalfonso@google.com> wrote:
> >
> > On Sat, Feb 29, 2020 at 10:29 PM Dmitry Vyukov <dvyukov@google.com> wrote:
> > >
> > > On Sat, Feb 29, 2020 at 2:23 AM Patricia Alfonso
> > > <trishalfonso@google.com> wrote:
> > > > >
> > > > > On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> > > > > <kasan-dev@googlegroups.com> wrote:
> > > > > >
> > > > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > > > >                 return True
> > > > > >
> > > > > >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > > > -               args.extend(['mem=256M'])
> > > > > > +               args.extend(['mem=256M', 'kasan_multi_shot'])
> > > > >
> > > > > This is better done somewhere else (different default value if
> > > > > KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> > > > > Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> > > > > to be a mandatory part now. This means people will always hit this, be
> > > > > confused, figure out they need to flip the value, and only then be
> > > > > able to run kunit+kasan.
> > > > >
> > > > I agree. Is the best way to do this with "bool multishot =
> > > > kasan_save_enable_multi_shot();"  and
> > > > "kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
> > > > was done in the tests before?
> > >
> > > This will fix KASAN tests, but not non-KASAN tests running under KUNIT
> > > and triggering KASAN reports.
> > > You set kasan_multi_shot for all KUNIT tests. I am reading this as
> > > that we don't want to abort on the first test that triggered a KASAN
> > > report. Or not?
> >
> > I don't think I understand the question, but let me try to explain my
> > thinking and see if that resonates with you. We know that the KASAN
> > tests will require more than one report, and we want that. For most
> > users, since a KASAN error can cause unexpected kernel behavior for
> > anything after a KASAN error, it is best for just one unexpected KASAN
> > error to be the only error printed to the user, unless they specify
> > kasan-multi-shot. The way I understand it, the way to implement this
> > is to use  "bool multishot = kasan_save_enable_multi_shot();"  and
> > "kasan_restore_multi_shot(multishot);" around the KASAN tests so that
> > kasan-multi-shot is temporarily enabled for the tests we expect
> > multiple reports. I assume "kasan_restore_multi_shot(multishot);"
> > restores the value to what the user input was so after the KASAN tests
> > are finished, if the user did not specify kasan-multi-shot and an
> > unexpected kasan error is reported, it will print the full report and
> > only that first one. Is this understanding correct? If you have a
> > better way of implementing this or a better expected behavior, I
> > appreciate your thoughts.
>
> Everything you say is correct.
> What I tried to point at is that this new behavior is different from
> the original behavior of your change. Initially you added
> kasan_multi_shot to command line for _all_ kunit tests (not just
> KASAN). The question is: do we want kasan_multi_shot for non-KASAN
> tests or not?

Ah, yes. I thought your first comment was suggesting I change it from
printing all KASAN tests by default because the intended behavior of
KASAN is to only print the first report. I think I'll pose the
question back to you. Do we want kasan_multi_shot for non-KASAN tests?
For functionality sake, it is only required for the KASAN tests so
this is more of a judgement call for the user experience.

--
Best,
Patricia Alfonso
Patricia Alfonso March 5, 2020, 2:14 a.m. UTC | #16
On Tue, Mar 3, 2020 at 8:40 AM Alan Maguire <alan.maguire@oracle.com> wrote:
>
> On Fri, 28 Feb 2020, Patricia Alfonso wrote:
>
> > On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> > >
> > > On Wed, 26 Feb 2020, Patricia Alfonso wrote:
> > >
> > > > Integrate KASAN into KUnit testing framework.
> > >
> > > This is a great idea! Some comments/suggestions below...
> > >
> >
> > Thank you so much for your suggestions!
> >
>
> No problem! Extending KUnit to test things like KASAN
> is really valuable, as it shows us ways we can improve
> the framework. More below...
>
> > > >  - Fail tests when KASAN reports an error that is not expected
> > > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > > >  - KUnit struct added to current task to keep track of the current test
> > > > from KASAN code
> > > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > > >  report is found added to kunit struct
> > > >  - This prints "line# has passed" or "line# has failed"
> > > >
> > > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > > ---
> > > > If anyone has any suggestions on how best to print the failure
> > > > messages, please share!
> > > >
> > > > One issue I have found while testing this is the allocation fails in
> > > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > > does cause the test to fail on the KUnit side, as expected, but it
> > > > seems to skip all the tests before this one because the output starts
> > > > with this failure instead of with the first test, kmalloc_oob_right().
> > > >
> > > >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> > > >  include/linux/sched.h               |  7 ++++++-
> > > >  lib/kunit/test.c                    |  7 ++++++-
> > > >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> > > >  tools/testing/kunit/kunit_kernel.py |  2 +-
> > > >  5 files changed, 56 insertions(+), 3 deletions(-)
> > > >
> > > > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > > > index 2dfb550c6723..2e388f8937f3 100644
> > > > --- a/include/kunit/test.h
> > > > +++ b/include/kunit/test.h
> > > > @@ -21,6 +21,8 @@ struct kunit_resource;
> > > >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> > > >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> > > >
> > > > +void kunit_set_failure(struct kunit *test);
> > > > +
> > > >  /**
> > > >   * struct kunit_resource - represents a *test managed resource*
> > > >   * @allocation: for the user to store arbitrary data.
> > > > @@ -191,6 +193,9 @@ struct kunit {
> > > >        * protect it with some type of lock.
> > > >        */
> > > >       struct list_head resources; /* Protected by lock. */
> > > > +
> > > > +     bool kasan_report_expected;
> > > > +     bool kasan_report_found;
> > > >  };
> > > >
> > >
> > > Is this needed here? You're testing something pretty
> > > specific so it seems wrong to add to the generic
> > > kunit resource unless there's a good reason. I see the
> > > code around setting these values in mm/kasan/report.c,
> > > but I wonder if we could do something more generic.
> > >
> > > How about the concept of a static resource (assuming a
> > > dynamically allocated one is out because it messes
> > > with memory allocation tests)? Something like this:
> > >
> > > #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
> > >         do {                                                            \
> > >                 spin_lock(&test->lock);                                 \
> > >                 (resource_ptr)->resource_field.init = NULL;             \
> > >                 (resource_ptr)->resource_field.free = NULL;             \
> > >                 list_add_tail(&(resource_ptr)->resource_field,          \
> > >                               &test->resources);                        \
> > >                 spin_unlock(&test->lock);                               \
> > >         } while (0)
> > >
> > >
> > > Within your kasan code you could then create a kasan-specific
> > > structure that embends a kunit_resource, and contains the
> > > values you need:
> > >
> > > struct kasan_report_resource {
> > >         struct kunit_resource res;
> > >         bool kasan_report_expected;
> > >         bool kasan_report_found;
> > > };
> > >
> > > (One thing we'd need to do for such static resources is fix
> > > kunit_resource_free() to check if there's a free() function,
> > > and if not assume a static resource)
> > >
> > > If you then create an init() function associated with your
> > > kunit suite (which will be run for every case) it can do this:
> > >
> > > int kunit_kasan_test_init(struct kunit *test)
> > > {
> > >         kunit_add_static_resource(test, &my_kasan_report_resource, res);
> > >         ...
> > > }
> > >
> > > The above should also be used to initialize current->kasan_unit_test
> > > instead of doing that in kunit_try_run_case().  With those
> > > changes, you don't (I think) need to change anything in core
> > > kunit (assuming support for static resources).
> > >
> > > To retrieve the resource during tests or in kasan context, the
> > > method seems to be to use kunit_resource_find(). However, that
> > > requires a match function which seems a bit heavyweight for the
> > > static case.  We should probably have a default "find by name"
> > > or similar function here, and add an optional "name" field
> > > to kunit resources to simplify things.  Anyway here you'd
> > > use something like:
> > >
> > >         kasan_report_resource = kunit_resource_find(test, matchfn,
> > >                                                     NULL, matchdata);
> > >
> > >
> > > Are there any barriers to taking this sort of approach (apart
> > > from the support for static resources not being there yet)?
> > >
> >
> > I'm not sure. I don't have any experience with kunit resources so I
> > would have to put some more effort into understanding how this would
> > work for myself. I wonder if this might be a bit of an over
> > complicated way of eliminating an extraneous boolean... maybe we can
> > find a simpler solution for the first version of this patch and add
> > the notion of a static resource for generic use later.
> >
>
> My personal preference would be to try and learn what's needed
> by KASAN and improve the KUnit APIs so the next developer finds
> life a bit easier. More hassle for you I know, but actual use cases
> like this are invaluable for improving the API.  I've sent
> out an RFC patchset which has the functionality I _think_ you
> need but I may be missing something:
>
> https://lore.kernel.org/linux-kselftest/1583251361-12748-1-git-send-email-alan.maguire@oracle.com/T/#t
>
> The idea is your test can do something like this:
>
> struct kasan_data {
>         bool report_expected;
>         bool report_found;
> };
>
>
> my_kasan_test(struct kunit *test)
> {
>         struct kunit_resource resource;
>         struct kasan_data kasan_data;
>
> ...
>         // add our named resource using static resource/data
>         kunit_add_named_resource(test, NULL, NULL, &resource,
>                                  "kasan_data", &kasan_data);
> ...
>
> }
Does this require the user to set up this kasan_data resource in each
KASAN test? Or can we set up the resource on the KUnit side whenever a
user writes a test that expects a KASAN failure? I've been playing
around with it and I can only seem to get it to work when I add the
resource within the test, but I could be missing something.

>
> (The NULLs in the function arguments above reflect the fact we
> don't require initialization or cleanup for such static resources)
>
> Then, in KASAN context you can look the above resource up like so:
>
>         struct kunit_resource *resource;
>         struct kasan_data *kasan_data;
>
>         resource = kunit_find_named_resource(test, "kasan_data");
>         kasan_data = resource->data;
>
>         // when finished, reduce reference count on resource
>         kunit_put_resource(resource);
>
> Does that work for your use case?
>
> > > >  void kunit_init_test(struct kunit *test, const char *name);
> > > > @@ -941,6 +946,25 @@ do {                                                                            \
> > > >                                               ptr,                           \
> > > >                                               NULL)
> > > >
> > > > +/**
> > > > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > > > + * not cause a KASAN error.
> > > > + *
> > > > + */
> > > > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {        \
> > > > +     test->kasan_report_expected = true;     \
> > > > +     test->kasan_report_found = false; \
> > > > +     condition; \
> > > > +     if (test->kasan_report_found == test->kasan_report_expected) { \
> > > > +             pr_info("%d has passed", __LINE__); \
> > > > +     } else { \
> > > > +             kunit_set_failure(test); \
> > > > +             pr_info("%d has failed", __LINE__); \
> > > > +     } \
> > > > +     test->kasan_report_expected = false;    \
> > > > +     test->kasan_report_found = false;       \
> > > > +} while (0)
> > > > +
> > >
> > > Feels like this belongs in test_kasan.c, and could be reworked
> > > to avoid adding test->kasan_report_[expected|found] as described
> > > above.
> >
> > You're right. Since I don't see any reason why any other tests should
> > want to expect a KASAN error, it does make sense to move this logic
> > inside test_kasan.c. If, in the future, there is a need for this
> > elsewhere, we can always move it back then.
> >
> > >  Instead of having your own pass/fail logic couldn't you
> > > do this:
> > >
> > >         KUNIT_EXPECT_EQ(test, expected, found);
> > >
> > > ? That will set the failure state too so no need to export
> > > a separate function for that, and no need to log anything
> > > as KUNIT_EXPECT_EQ() should do that for you.
> > >
> >
> > This is a great idea - I feel a little silly that I didn't think of
> > that myself! Do we think the failure message for the KUNIT_EXPECT_EQ()
> > would be sufficient for KASAN developers?
> > i.e. "Expected kasan_report_expected == kasan_report_found, but
> > kasan_report_expected == true
> > kasan_report_found == false"
> >
>
> I guess the missing piece above is the line number where
> the test failure was encountered, is that the concern?
>
> > > >  /**
> > > >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> > > >   * @test: The test context object.
> > > > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > > > index 04278493bf15..db23d56061e7 100644
> > > > --- a/include/linux/sched.h
> > > > +++ b/include/linux/sched.h
> > > > @@ -32,6 +32,8 @@
> > > >  #include <linux/posix-timers.h>
> > > >  #include <linux/rseq.h>
> > > >
> > > > +#include <kunit/test.h>
> > > > +
> > >
> > > This feels like the wrong place to add this #include, and
> > > when I attempted to build to test I ran into a bunch of
> > > compilation errors; for example:
> > >
> > >  CC      kernel/sched/core.o
> > > In file included from ./include/linux/uaccess.h:11,
> > >                  from ./arch/x86/include/asm/fpu/xstate.h:5,
> > >                  from ./arch/x86/include/asm/pgtable.h:26,
> > >                  from ./include/linux/kasan.h:16,
> > >                  from ./include/linux/slab.h:136,
> > >                  from ./include/kunit/test.h:16,
> > >                  from ./include/linux/sched.h:35,
> > >                  from init/do_mounts.c:3:
> > > ./arch/x86/include/asm/uaccess.h: In function 'set_fs':
> > > ./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to
> > > incomplete type 'struct task_struct'
> > >   current->thread.addr_limit = fs;
> > >
> > > (I'm testing with CONFIG_SLUB). Removing this #include
> > > resolves these errors, but then causes problems for
> > > lib/test_kasan.c. I'll dig around a bit more.
> > >
> >
> > Yes, I was only testing with UML. Removing that #include fixed the
> > problem for me for both x86 and UML. Could you share more about the
> > errors you have encountered in lib/test_kasan.c?
> >
>
> I'll try this again and send details.
>
> I think broadly the issue is that if we #include kunit headers
> in the kasan headers, we end up creating all kinds of problems
> for ourselves, since the kasan headers are in turn included
> in so many places (including the kunit headers themselves, since
> kunit uses memory allocation APIs). I suspect the way forward is
> to try and ensure that we don't utilize the kunit headers in any
> of the kasan headers, but rather just include kunit headers
> in test_kasan.c, and any other kasan .c files we need KUnit APIs
> for. Not sure if that's possible, but it's likely the best way to
> go if it is.
>
> > > >  /* task_struct member predeclarations (sorted alphabetically): */
> > > >  struct audit_context;
> > > >  struct backing_dev_info;
> > > > @@ -1178,7 +1180,10 @@ struct task_struct {
> > > >
> > > >  #ifdef CONFIG_KASAN
> > > >       unsigned int                    kasan_depth;
> > > > -#endif
> > > > +#ifdef CONFIG_KUNIT
> > > > +     struct kunit *kasan_kunit_test;
> > > > +#endif /* CONFIG_KUNIT */
> > > > +#endif /* CONFIG_KASAN */
> > > >
> > > >  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
> > > >       /* Index of current stored address in ret_stack: */
> > > > diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> > > > index 9242f932896c..d266b9495c67 100644
> > > > --- a/lib/kunit/test.c
> > > > +++ b/lib/kunit/test.c
> > > > @@ -9,11 +9,12 @@
> > > >  #include <kunit/test.h>
> > > >  #include <linux/kernel.h>
> > > >  #include <linux/sched/debug.h>
> > > > +#include <linux/sched.h>
> > > >
> > > >  #include "string-stream.h"
> > > >  #include "try-catch-impl.h"
> > > >
> > > > -static void kunit_set_failure(struct kunit *test)
> > > > +void kunit_set_failure(struct kunit *test)
> > > >  {
> > > >       WRITE_ONCE(test->success, false);
> > > >  }
> > > > @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
> > > >       struct kunit_suite *suite = ctx->suite;
> > > >       struct kunit_case *test_case = ctx->test_case;
> > > >
> > > > +#ifdef CONFIG_KASAN
> > > > +     current->kasan_kunit_test = test;
> > > > +#endif
> > > > +
> > > >       /*
> > > >        * kunit_run_case_internal may encounter a fatal error; if it does,
> > > >        * abort will be called, this thread will exit, and finally the parent
> > > > diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> > > > index 5ef9f24f566b..5554d23799a5 100644
> > > > --- a/mm/kasan/report.c
> > > > +++ b/mm/kasan/report.c
> > > > @@ -32,6 +32,8 @@
> > > >
> > > >  #include <asm/sections.h>
> > > >
> > > > +#include <kunit/test.h>
> > > > +
> > > >  #include "kasan.h"
> > > >  #include "../slab.h"
> > > >
> > > > @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
> > > >       u8 tag = get_tag(object);
> > > >
> > > >       object = reset_tag(object);
> > > > +
> > > > +     if (current->kasan_kunit_test) {
> > > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > > +                     return;
> > > > +             }
> > > > +             kunit_set_failure(current->kasan_kunit_test);
> > > > +     }
> > > > +
> > > >       start_report(&flags);
> > > >       pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
> > > >       print_tags(tag, object);
> > > > @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
> > > >       if (likely(!report_enabled()))
> > > >               return;
> > > >
> > > > +     if (current->kasan_kunit_test) {
> > > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > > +                     return;
> > > > +             }
> > > > +             kunit_set_failure(current->kasan_kunit_test);
> > > > +     }
> > > > +
> > > >       disable_trace_on_warning();
> > > >
> > > >       tagged_addr = (void *)addr;
> > > > diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> > > > index cc5d844ecca1..63eab18a8c34 100644
> > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > >               return True
> > > >
> > > >       def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > -             args.extend(['mem=256M'])
> > > > +             args.extend(['mem=256M', 'kasan_multi_shot'])
> > > >               process = self._ops.linux_bin(args, timeout, build_dir)
> > > >               with open(os.path.join(build_dir, 'test.log'), 'w') as f:
> > > >                       for line in process.stdout:
> > >
> > > I tried applying this to the "kunit" branch of linux-kselftest, and
> > > the above failed. Which branch are you building with? Probably
> > > best to use the kunit branch I think. Thanks!
> > >
> > I believe I am on Torvalds/master. There was some debate as to which
> > branch I should be developing on when I started, but it probably makes
> > sense for me to move to the "kunit" branch.
> >
>
> I think for this case - given that we may need some new KUnit
> functionality - that would be best. Thanks!
>
> Alan
>
> > > Alan
> > >
> > > > --
> > > > 2.25.0.265.gbab2e86ba0-goog
> > > >
> > > >
> >
> > --
> > Thank you for all your comments!
> > Patricia Alfonso
> >
Dmitry Vyukov March 5, 2020, 6:44 a.m. UTC | #17
On Thu, Mar 5, 2020 at 1:08 AM Patricia Alfonso <trishalfonso@google.com> wrote:
> > > On Sat, Feb 29, 2020 at 10:29 PM Dmitry Vyukov <dvyukov@google.com> wrote:
> > > >
> > > > On Sat, Feb 29, 2020 at 2:23 AM Patricia Alfonso
> > > > <trishalfonso@google.com> wrote:
> > > > > >
> > > > > > On Thu, Feb 27, 2020 at 3:44 AM 'Patricia Alfonso' via kasan-dev
> > > > > > <kasan-dev@googlegroups.com> wrote:
> > > > > > >
> > > > > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > > > > >                 return True
> > > > > > >
> > > > > > >         def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > > > > -               args.extend(['mem=256M'])
> > > > > > > +               args.extend(['mem=256M', 'kasan_multi_shot'])
> > > > > >
> > > > > > This is better done somewhere else (different default value if
> > > > > > KASAN_TEST is enabled or something). Or overridden in the KASAN tests.
> > > > > > Not everybody uses tools/testing/kunit/kunit_kernel.py and this seems
> > > > > > to be a mandatory part now. This means people will always hit this, be
> > > > > > confused, figure out they need to flip the value, and only then be
> > > > > > able to run kunit+kasan.
> > > > > >
> > > > > I agree. Is the best way to do this with "bool multishot =
> > > > > kasan_save_enable_multi_shot();"  and
> > > > > "kasan_restore_multi_shot(multishot);" inside test_kasan.c like what
> > > > > was done in the tests before?
> > > >
> > > > This will fix KASAN tests, but not non-KASAN tests running under KUNIT
> > > > and triggering KASAN reports.
> > > > You set kasan_multi_shot for all KUNIT tests. I am reading this as
> > > > that we don't want to abort on the first test that triggered a KASAN
> > > > report. Or not?
> > >
> > > I don't think I understand the question, but let me try to explain my
> > > thinking and see if that resonates with you. We know that the KASAN
> > > tests will require more than one report, and we want that. For most
> > > users, since a KASAN error can cause unexpected kernel behavior for
> > > anything after a KASAN error, it is best for just one unexpected KASAN
> > > error to be the only error printed to the user, unless they specify
> > > kasan-multi-shot. The way I understand it, the way to implement this
> > > is to use  "bool multishot = kasan_save_enable_multi_shot();"  and
> > > "kasan_restore_multi_shot(multishot);" around the KASAN tests so that
> > > kasan-multi-shot is temporarily enabled for the tests we expect
> > > multiple reports. I assume "kasan_restore_multi_shot(multishot);"
> > > restores the value to what the user input was so after the KASAN tests
> > > are finished, if the user did not specify kasan-multi-shot and an
> > > unexpected kasan error is reported, it will print the full report and
> > > only that first one. Is this understanding correct? If you have a
> > > better way of implementing this or a better expected behavior, I
> > > appreciate your thoughts.
> >
> > Everything you say is correct.
> > What I tried to point at is that this new behavior is different from
> > the original behavior of your change. Initially you added
> > kasan_multi_shot to command line for _all_ kunit tests (not just
> > KASAN). The question is: do we want kasan_multi_shot for non-KASAN
> > tests or not?
>
> Ah, yes. I thought your first comment was suggesting I change it from
> printing all KASAN tests by default because the intended behavior of
> KASAN is to only print the first report. I think I'll pose the
> question back to you. Do we want kasan_multi_shot for non-KASAN tests?
> For functionality sake, it is only required for the KASAN tests so
> this is more of a judgement call for the user experience.

Good question. I don't see strong arguments either way. So I guess we
can leave the current version (only for kasan tests) and wait when/if
somebody has real arguments. I wanted to point to change in behavior
and understand if it's intentional/accidental.
Alan Maguire March 5, 2020, 7:46 a.m. UTC | #18
On Wed, 4 Mar 2020, Patricia Alfonso wrote:

> On Tue, Mar 3, 2020 at 8:40 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> >
> > On Fri, 28 Feb 2020, Patricia Alfonso wrote:
> >
> > > On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> > > >
> > > > On Wed, 26 Feb 2020, Patricia Alfonso wrote:
> > > >
> > > > > Integrate KASAN into KUnit testing framework.
> > > >
> > > > This is a great idea! Some comments/suggestions below...
> > > >
> > >
> > > Thank you so much for your suggestions!
> > >
> >
> > No problem! Extending KUnit to test things like KASAN
> > is really valuable, as it shows us ways we can improve
> > the framework. More below...
> >
> > > > >  - Fail tests when KASAN reports an error that is not expected
> > > > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > > > >  - KUnit struct added to current task to keep track of the current test
> > > > > from KASAN code
> > > > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > > > >  report is found added to kunit struct
> > > > >  - This prints "line# has passed" or "line# has failed"
> > > > >
> > > > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > > > ---
> > > > > If anyone has any suggestions on how best to print the failure
> > > > > messages, please share!
> > > > >
> > > > > One issue I have found while testing this is the allocation fails in
> > > > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > > > does cause the test to fail on the KUnit side, as expected, but it
> > > > > seems to skip all the tests before this one because the output starts
> > > > > with this failure instead of with the first test, kmalloc_oob_right().
> > > > >
> > > > >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> > > > >  include/linux/sched.h               |  7 ++++++-
> > > > >  lib/kunit/test.c                    |  7 ++++++-
> > > > >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> > > > >  tools/testing/kunit/kunit_kernel.py |  2 +-
> > > > >  5 files changed, 56 insertions(+), 3 deletions(-)
> > > > >
> > > > > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > > > > index 2dfb550c6723..2e388f8937f3 100644
> > > > > --- a/include/kunit/test.h
> > > > > +++ b/include/kunit/test.h
> > > > > @@ -21,6 +21,8 @@ struct kunit_resource;
> > > > >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> > > > >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> > > > >
> > > > > +void kunit_set_failure(struct kunit *test);
> > > > > +
> > > > >  /**
> > > > >   * struct kunit_resource - represents a *test managed resource*
> > > > >   * @allocation: for the user to store arbitrary data.
> > > > > @@ -191,6 +193,9 @@ struct kunit {
> > > > >        * protect it with some type of lock.
> > > > >        */
> > > > >       struct list_head resources; /* Protected by lock. */
> > > > > +
> > > > > +     bool kasan_report_expected;
> > > > > +     bool kasan_report_found;
> > > > >  };
> > > > >
> > > >
> > > > Is this needed here? You're testing something pretty
> > > > specific so it seems wrong to add to the generic
> > > > kunit resource unless there's a good reason. I see the
> > > > code around setting these values in mm/kasan/report.c,
> > > > but I wonder if we could do something more generic.
> > > >
> > > > How about the concept of a static resource (assuming a
> > > > dynamically allocated one is out because it messes
> > > > with memory allocation tests)? Something like this:
> > > >
> > > > #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
> > > >         do {                                                            \
> > > >                 spin_lock(&test->lock);                                 \
> > > >                 (resource_ptr)->resource_field.init = NULL;             \
> > > >                 (resource_ptr)->resource_field.free = NULL;             \
> > > >                 list_add_tail(&(resource_ptr)->resource_field,          \
> > > >                               &test->resources);                        \
> > > >                 spin_unlock(&test->lock);                               \
> > > >         } while (0)
> > > >
> > > >
> > > > Within your kasan code you could then create a kasan-specific
> > > > structure that embends a kunit_resource, and contains the
> > > > values you need:
> > > >
> > > > struct kasan_report_resource {
> > > >         struct kunit_resource res;
> > > >         bool kasan_report_expected;
> > > >         bool kasan_report_found;
> > > > };
> > > >
> > > > (One thing we'd need to do for such static resources is fix
> > > > kunit_resource_free() to check if there's a free() function,
> > > > and if not assume a static resource)
> > > >
> > > > If you then create an init() function associated with your
> > > > kunit suite (which will be run for every case) it can do this:
> > > >
> > > > int kunit_kasan_test_init(struct kunit *test)
> > > > {
> > > >         kunit_add_static_resource(test, &my_kasan_report_resource, res);
> > > >         ...
> > > > }
> > > >
> > > > The above should also be used to initialize current->kasan_unit_test
> > > > instead of doing that in kunit_try_run_case().  With those
> > > > changes, you don't (I think) need to change anything in core
> > > > kunit (assuming support for static resources).
> > > >
> > > > To retrieve the resource during tests or in kasan context, the
> > > > method seems to be to use kunit_resource_find(). However, that
> > > > requires a match function which seems a bit heavyweight for the
> > > > static case.  We should probably have a default "find by name"
> > > > or similar function here, and add an optional "name" field
> > > > to kunit resources to simplify things.  Anyway here you'd
> > > > use something like:
> > > >
> > > >         kasan_report_resource = kunit_resource_find(test, matchfn,
> > > >                                                     NULL, matchdata);
> > > >
> > > >
> > > > Are there any barriers to taking this sort of approach (apart
> > > > from the support for static resources not being there yet)?
> > > >
> > >
> > > I'm not sure. I don't have any experience with kunit resources so I
> > > would have to put some more effort into understanding how this would
> > > work for myself. I wonder if this might be a bit of an over
> > > complicated way of eliminating an extraneous boolean... maybe we can
> > > find a simpler solution for the first version of this patch and add
> > > the notion of a static resource for generic use later.
> > >
> >
> > My personal preference would be to try and learn what's needed
> > by KASAN and improve the KUnit APIs so the next developer finds
> > life a bit easier. More hassle for you I know, but actual use cases
> > like this are invaluable for improving the API.  I've sent
> > out an RFC patchset which has the functionality I _think_ you
> > need but I may be missing something:
> >
> > https://lore.kernel.org/linux-kselftest/1583251361-12748-1-git-send-email-alan.maguire@oracle.com/T/#t
> >
> > The idea is your test can do something like this:
> >
> > struct kasan_data {
> >         bool report_expected;
> >         bool report_found;
> > };
> >
> >
> > my_kasan_test(struct kunit *test)
> > {
> >         struct kunit_resource resource;
> >         struct kasan_data kasan_data;
> >
> > ...
> >         // add our named resource using static resource/data
> >         kunit_add_named_resource(test, NULL, NULL, &resource,
> >                                  "kasan_data", &kasan_data);
> > ...
> >
> > }
> Does this require the user to set up this kasan_data resource in each
> KASAN test? Or can we set up the resource on the KUnit side whenever a
> user writes a test that expects a KASAN failure? I've been playing
> around with it and I can only seem to get it to work when I add the
> resource within the test, but I could be missing something.
> 

The current model of resources is they are associated with
the running state of a test for the lifetime of that test.
If it's a resource common to many/most tests, I'd suggest
creating an init() function for the associated suite; this
will get run prior to executing each test, and in it you
could initialize your resource. If the resource isn't
used in the test, it doesn't really matter so this might be
the simplest way to handle things:

struct kasan_data {
         bool report_expected;
         bool report_found;
};

struct kasan_data kasan_data;
struct kunit_resource resource;

kasan_init(struct kunit *test)
{                                

         // add our named resource using static resource/data
         kunit_add_named_resource(test, NULL, NULL, &resource,
                                  "kasan_data", &kasan_data);

	return 0;
}

static struct kunit_suite kasan_suite = {
	.name = "kasan",
	.init = kasan_init,
	...
};


This all presumes however that KASAN will only need access to the
resource during the lifetime of each test.  There's currently
no concept of free-floating resources outside of test execution
context.

Alan

> >
> > (The NULLs in the function arguments above reflect the fact we
> > don't require initialization or cleanup for such static resources)
> >
> > Then, in KASAN context you can look the above resource up like so:
> >
> >         struct kunit_resource *resource;
> >         struct kasan_data *kasan_data;
> >
> >         resource = kunit_find_named_resource(test, "kasan_data");
> >         kasan_data = resource->data;
> >
> >         // when finished, reduce reference count on resource
> >         kunit_put_resource(resource);
> >
> > Does that work for your use case?
> >
> > > > >  void kunit_init_test(struct kunit *test, const char *name);
> > > > > @@ -941,6 +946,25 @@ do {                                                                            \
> > > > >                                               ptr,                           \
> > > > >                                               NULL)
> > > > >
> > > > > +/**
> > > > > + * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
> > > > > + * not cause a KASAN error.
> > > > > + *
> > > > > + */
> > > > > +#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {        \
> > > > > +     test->kasan_report_expected = true;     \
> > > > > +     test->kasan_report_found = false; \
> > > > > +     condition; \
> > > > > +     if (test->kasan_report_found == test->kasan_report_expected) { \
> > > > > +             pr_info("%d has passed", __LINE__); \
> > > > > +     } else { \
> > > > > +             kunit_set_failure(test); \
> > > > > +             pr_info("%d has failed", __LINE__); \
> > > > > +     } \
> > > > > +     test->kasan_report_expected = false;    \
> > > > > +     test->kasan_report_found = false;       \
> > > > > +} while (0)
> > > > > +
> > > >
> > > > Feels like this belongs in test_kasan.c, and could be reworked
> > > > to avoid adding test->kasan_report_[expected|found] as described
> > > > above.
> > >
> > > You're right. Since I don't see any reason why any other tests should
> > > want to expect a KASAN error, it does make sense to move this logic
> > > inside test_kasan.c. If, in the future, there is a need for this
> > > elsewhere, we can always move it back then.
> > >
> > > >  Instead of having your own pass/fail logic couldn't you
> > > > do this:
> > > >
> > > >         KUNIT_EXPECT_EQ(test, expected, found);
> > > >
> > > > ? That will set the failure state too so no need to export
> > > > a separate function for that, and no need to log anything
> > > > as KUNIT_EXPECT_EQ() should do that for you.
> > > >
> > >
> > > This is a great idea - I feel a little silly that I didn't think of
> > > that myself! Do we think the failure message for the KUNIT_EXPECT_EQ()
> > > would be sufficient for KASAN developers?
> > > i.e. "Expected kasan_report_expected == kasan_report_found, but
> > > kasan_report_expected == true
> > > kasan_report_found == false"
> > >
> >
> > I guess the missing piece above is the line number where
> > the test failure was encountered, is that the concern?
> >
> > > > >  /**
> > > > >   * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
> > > > >   * @test: The test context object.
> > > > > diff --git a/include/linux/sched.h b/include/linux/sched.h
> > > > > index 04278493bf15..db23d56061e7 100644
> > > > > --- a/include/linux/sched.h
> > > > > +++ b/include/linux/sched.h
> > > > > @@ -32,6 +32,8 @@
> > > > >  #include <linux/posix-timers.h>
> > > > >  #include <linux/rseq.h>
> > > > >
> > > > > +#include <kunit/test.h>
> > > > > +
> > > >
> > > > This feels like the wrong place to add this #include, and
> > > > when I attempted to build to test I ran into a bunch of
> > > > compilation errors; for example:
> > > >
> > > >  CC      kernel/sched/core.o
> > > > In file included from ./include/linux/uaccess.h:11,
> > > >                  from ./arch/x86/include/asm/fpu/xstate.h:5,
> > > >                  from ./arch/x86/include/asm/pgtable.h:26,
> > > >                  from ./include/linux/kasan.h:16,
> > > >                  from ./include/linux/slab.h:136,
> > > >                  from ./include/kunit/test.h:16,
> > > >                  from ./include/linux/sched.h:35,
> > > >                  from init/do_mounts.c:3:
> > > > ./arch/x86/include/asm/uaccess.h: In function 'set_fs':
> > > > ./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to
> > > > incomplete type 'struct task_struct'
> > > >   current->thread.addr_limit = fs;
> > > >
> > > > (I'm testing with CONFIG_SLUB). Removing this #include
> > > > resolves these errors, but then causes problems for
> > > > lib/test_kasan.c. I'll dig around a bit more.
> > > >
> > >
> > > Yes, I was only testing with UML. Removing that #include fixed the
> > > problem for me for both x86 and UML. Could you share more about the
> > > errors you have encountered in lib/test_kasan.c?
> > >
> >
> > I'll try this again and send details.
> >
> > I think broadly the issue is that if we #include kunit headers
> > in the kasan headers, we end up creating all kinds of problems
> > for ourselves, since the kasan headers are in turn included
> > in so many places (including the kunit headers themselves, since
> > kunit uses memory allocation APIs). I suspect the way forward is
> > to try and ensure that we don't utilize the kunit headers in any
> > of the kasan headers, but rather just include kunit headers
> > in test_kasan.c, and any other kasan .c files we need KUnit APIs
> > for. Not sure if that's possible, but it's likely the best way to
> > go if it is.
> >
> > > > >  /* task_struct member predeclarations (sorted alphabetically): */
> > > > >  struct audit_context;
> > > > >  struct backing_dev_info;
> > > > > @@ -1178,7 +1180,10 @@ struct task_struct {
> > > > >
> > > > >  #ifdef CONFIG_KASAN
> > > > >       unsigned int                    kasan_depth;
> > > > > -#endif
> > > > > +#ifdef CONFIG_KUNIT
> > > > > +     struct kunit *kasan_kunit_test;
> > > > > +#endif /* CONFIG_KUNIT */
> > > > > +#endif /* CONFIG_KASAN */
> > > > >
> > > > >  #ifdef CONFIG_FUNCTION_GRAPH_TRACER
> > > > >       /* Index of current stored address in ret_stack: */
> > > > > diff --git a/lib/kunit/test.c b/lib/kunit/test.c
> > > > > index 9242f932896c..d266b9495c67 100644
> > > > > --- a/lib/kunit/test.c
> > > > > +++ b/lib/kunit/test.c
> > > > > @@ -9,11 +9,12 @@
> > > > >  #include <kunit/test.h>
> > > > >  #include <linux/kernel.h>
> > > > >  #include <linux/sched/debug.h>
> > > > > +#include <linux/sched.h>
> > > > >
> > > > >  #include "string-stream.h"
> > > > >  #include "try-catch-impl.h"
> > > > >
> > > > > -static void kunit_set_failure(struct kunit *test)
> > > > > +void kunit_set_failure(struct kunit *test)
> > > > >  {
> > > > >       WRITE_ONCE(test->success, false);
> > > > >  }
> > > > > @@ -236,6 +237,10 @@ static void kunit_try_run_case(void *data)
> > > > >       struct kunit_suite *suite = ctx->suite;
> > > > >       struct kunit_case *test_case = ctx->test_case;
> > > > >
> > > > > +#ifdef CONFIG_KASAN
> > > > > +     current->kasan_kunit_test = test;
> > > > > +#endif
> > > > > +
> > > > >       /*
> > > > >        * kunit_run_case_internal may encounter a fatal error; if it does,
> > > > >        * abort will be called, this thread will exit, and finally the parent
> > > > > diff --git a/mm/kasan/report.c b/mm/kasan/report.c
> > > > > index 5ef9f24f566b..5554d23799a5 100644
> > > > > --- a/mm/kasan/report.c
> > > > > +++ b/mm/kasan/report.c
> > > > > @@ -32,6 +32,8 @@
> > > > >
> > > > >  #include <asm/sections.h>
> > > > >
> > > > > +#include <kunit/test.h>
> > > > > +
> > > > >  #include "kasan.h"
> > > > >  #include "../slab.h"
> > > > >
> > > > > @@ -461,6 +463,15 @@ void kasan_report_invalid_free(void *object, unsigned long ip)
> > > > >       u8 tag = get_tag(object);
> > > > >
> > > > >       object = reset_tag(object);
> > > > > +
> > > > > +     if (current->kasan_kunit_test) {
> > > > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > > > +                     return;
> > > > > +             }
> > > > > +             kunit_set_failure(current->kasan_kunit_test);
> > > > > +     }
> > > > > +
> > > > >       start_report(&flags);
> > > > >       pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
> > > > >       print_tags(tag, object);
> > > > > @@ -481,6 +492,14 @@ void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
> > > > >       if (likely(!report_enabled()))
> > > > >               return;
> > > > >
> > > > > +     if (current->kasan_kunit_test) {
> > > > > +             if (current->kasan_kunit_test->kasan_report_expected) {
> > > > > +                     current->kasan_kunit_test->kasan_report_found = true;
> > > > > +                     return;
> > > > > +             }
> > > > > +             kunit_set_failure(current->kasan_kunit_test);
> > > > > +     }
> > > > > +
> > > > >       disable_trace_on_warning();
> > > > >
> > > > >       tagged_addr = (void *)addr;
> > > > > diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
> > > > > index cc5d844ecca1..63eab18a8c34 100644
> > > > > --- a/tools/testing/kunit/kunit_kernel.py
> > > > > +++ b/tools/testing/kunit/kunit_kernel.py
> > > > > @@ -141,7 +141,7 @@ class LinuxSourceTree(object):
> > > > >               return True
> > > > >
> > > > >       def run_kernel(self, args=[], timeout=None, build_dir=''):
> > > > > -             args.extend(['mem=256M'])
> > > > > +             args.extend(['mem=256M', 'kasan_multi_shot'])
> > > > >               process = self._ops.linux_bin(args, timeout, build_dir)
> > > > >               with open(os.path.join(build_dir, 'test.log'), 'w') as f:
> > > > >                       for line in process.stdout:
> > > >
> > > > I tried applying this to the "kunit" branch of linux-kselftest, and
> > > > the above failed. Which branch are you building with? Probably
> > > > best to use the kunit branch I think. Thanks!
> > > >
> > > I believe I am on Torvalds/master. There was some debate as to which
> > > branch I should be developing on when I started, but it probably makes
> > > sense for me to move to the "kunit" branch.
> > >
> >
> > I think for this case - given that we may need some new KUnit
> > functionality - that would be best. Thanks!
> >
> > Alan
> >
> > > > Alan
> > > >
> > > > > --
> > > > > 2.25.0.265.gbab2e86ba0-goog
> > > > >
> > > > >
> > >
> > > --
> > > Thank you for all your comments!
> > > Patricia Alfonso
> > >
> 
> 
> 
> -- 
> 
> Patricia Alfonso
> Software Engineer
> trishalfonso@google.com
>
Brendan Higgins March 10, 2020, 9:39 p.m. UTC | #19
On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:

Sorry for the delay in reviews. I have been preoccupied by some Google
internal stuff.

> On Wed, 26 Feb 2020, Patricia Alfonso wrote:
>
> > Integrate KASAN into KUnit testing framework.
>
> This is a great idea! Some comments/suggestions below...
>
> >  - Fail tests when KASAN reports an error that is not expected
> >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> >  - KUnit struct added to current task to keep track of the current test
> > from KASAN code
> >  - Booleans representing if a KASAN report is expected and if a KASAN
> >  report is found added to kunit struct
> >  - This prints "line# has passed" or "line# has failed"
> >
> > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > ---
> > If anyone has any suggestions on how best to print the failure
> > messages, please share!
> >
> > One issue I have found while testing this is the allocation fails in
> > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > does cause the test to fail on the KUnit side, as expected, but it
> > seems to skip all the tests before this one because the output starts
> > with this failure instead of with the first test, kmalloc_oob_right().
> >
> >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> >  include/linux/sched.h               |  7 ++++++-
> >  lib/kunit/test.c                    |  7 ++++++-
> >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> >  tools/testing/kunit/kunit_kernel.py |  2 +-
> >  5 files changed, 56 insertions(+), 3 deletions(-)
> >
> > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > index 2dfb550c6723..2e388f8937f3 100644
> > --- a/include/kunit/test.h
> > +++ b/include/kunit/test.h
> > @@ -21,6 +21,8 @@ struct kunit_resource;
> >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> >
> > +void kunit_set_failure(struct kunit *test);
> > +
> >  /**
> >   * struct kunit_resource - represents a *test managed resource*
> >   * @allocation: for the user to store arbitrary data.
> > @@ -191,6 +193,9 @@ struct kunit {
> >        * protect it with some type of lock.
> >        */
> >       struct list_head resources; /* Protected by lock. */
> > +
> > +     bool kasan_report_expected;
> > +     bool kasan_report_found;
> >  };
> >
>
> Is this needed here? You're testing something pretty
> specific so it seems wrong to add to the generic
> kunit resource unless there's a good reason. I see the
> code around setting these values in mm/kasan/report.c,
> but I wonder if we could do something more generic.
>
> How about the concept of a static resource (assuming a
> dynamically allocated one is out because it messes
> with memory allocation tests)? Something like this:
>
> #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
>         do {                                                            \
>                 spin_lock(&test->lock);                                 \
>                 (resource_ptr)->resource_field.init = NULL;             \
>                 (resource_ptr)->resource_field.free = NULL;             \
>                 list_add_tail(&(resource_ptr)->resource_field,          \
>                               &test->resources);                        \
>                 spin_unlock(&test->lock);                               \
>         } while (0)
>
>
> Within your kasan code you could then create a kasan-specific
> structure that embends a kunit_resource, and contains the
> values you need:
>
> struct kasan_report_resource {
>         struct kunit_resource res;
>         bool kasan_report_expected;
>         bool kasan_report_found;
> };
>
> (One thing we'd need to do for such static resources is fix
> kunit_resource_free() to check if there's a free() function,
> and if not assume a static resource)
>
> If you then create an init() function associated with your
> kunit suite (which will be run for every case) it can do this:
>
> int kunit_kasan_test_init(struct kunit *test)
> {
>         kunit_add_static_resource(test, &my_kasan_report_resource, res);
>         ...
> }
>
> The above should also be used to initialize current->kasan_unit_test
> instead of doing that in kunit_try_run_case().  With those
> changes, you don't (I think) need to change anything in core
> kunit (assuming support for static resources).
>
> To retrieve the resource during tests or in kasan context, the
> method seems to be to use kunit_resource_find(). However, that
> requires a match function which seems a bit heavyweight for the
> static case.  We should probably have a default "find by name"
> or similar function here, and add an optional "name" field
> to kunit resources to simplify things.  Anyway here you'd
> use something like:
>
>         kasan_report_resource = kunit_resource_find(test, matchfn,
>                                                     NULL, matchdata);
>
>
> Are there any barriers to taking this sort of approach (apart
> from the support for static resources not being there yet)?

This is a really interesting idea, Alan! I never imagined
kunit_resources being used this way, and I like it. I saw you sent
some patches to implement this stuff, so I will withhold further
comments on that here.
Brendan Higgins March 10, 2020, 9:42 p.m. UTC | #20
On Wed, Mar 4, 2020 at 11:47 PM Alan Maguire <alan.maguire@oracle.com> wrote:
>
> On Wed, 4 Mar 2020, Patricia Alfonso wrote:
>
> > On Tue, Mar 3, 2020 at 8:40 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> > >
> > > On Fri, 28 Feb 2020, Patricia Alfonso wrote:
> > >
> > > > On Thu, Feb 27, 2020 at 6:04 AM Alan Maguire <alan.maguire@oracle.com> wrote:
> > > > >
> > > > > On Wed, 26 Feb 2020, Patricia Alfonso wrote:
> > > > >
> > > > > > Integrate KASAN into KUnit testing framework.
> > > > >
> > > > > This is a great idea! Some comments/suggestions below...
> > > > >
> > > >
> > > > Thank you so much for your suggestions!
> > > >
> > >
> > > No problem! Extending KUnit to test things like KASAN
> > > is really valuable, as it shows us ways we can improve
> > > the framework. More below...
> > >
> > > > > >  - Fail tests when KASAN reports an error that is not expected
> > > > > >  - Use KUNIT_EXPECT_KASAN_FAIL to expect a KASAN error in KASAN tests
> > > > > >  - KUnit struct added to current task to keep track of the current test
> > > > > > from KASAN code
> > > > > >  - Booleans representing if a KASAN report is expected and if a KASAN
> > > > > >  report is found added to kunit struct
> > > > > >  - This prints "line# has passed" or "line# has failed"
> > > > > >
> > > > > > Signed-off-by: Patricia Alfonso <trishalfonso@google.com>
> > > > > > ---
> > > > > > If anyone has any suggestions on how best to print the failure
> > > > > > messages, please share!
> > > > > >
> > > > > > One issue I have found while testing this is the allocation fails in
> > > > > > kmalloc_pagealloc_oob_right() sometimes, but not consistently. This
> > > > > > does cause the test to fail on the KUnit side, as expected, but it
> > > > > > seems to skip all the tests before this one because the output starts
> > > > > > with this failure instead of with the first test, kmalloc_oob_right().
> > > > > >
> > > > > >  include/kunit/test.h                | 24 ++++++++++++++++++++++++
> > > > > >  include/linux/sched.h               |  7 ++++++-
> > > > > >  lib/kunit/test.c                    |  7 ++++++-
> > > > > >  mm/kasan/report.c                   | 19 +++++++++++++++++++
> > > > > >  tools/testing/kunit/kunit_kernel.py |  2 +-
> > > > > >  5 files changed, 56 insertions(+), 3 deletions(-)
> > > > > >
> > > > > > diff --git a/include/kunit/test.h b/include/kunit/test.h
> > > > > > index 2dfb550c6723..2e388f8937f3 100644
> > > > > > --- a/include/kunit/test.h
> > > > > > +++ b/include/kunit/test.h
> > > > > > @@ -21,6 +21,8 @@ struct kunit_resource;
> > > > > >  typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
> > > > > >  typedef void (*kunit_resource_free_t)(struct kunit_resource *);
> > > > > >
> > > > > > +void kunit_set_failure(struct kunit *test);
> > > > > > +
> > > > > >  /**
> > > > > >   * struct kunit_resource - represents a *test managed resource*
> > > > > >   * @allocation: for the user to store arbitrary data.
> > > > > > @@ -191,6 +193,9 @@ struct kunit {
> > > > > >        * protect it with some type of lock.
> > > > > >        */
> > > > > >       struct list_head resources; /* Protected by lock. */
> > > > > > +
> > > > > > +     bool kasan_report_expected;
> > > > > > +     bool kasan_report_found;
> > > > > >  };
> > > > > >
> > > > >
> > > > > Is this needed here? You're testing something pretty
> > > > > specific so it seems wrong to add to the generic
> > > > > kunit resource unless there's a good reason. I see the
> > > > > code around setting these values in mm/kasan/report.c,
> > > > > but I wonder if we could do something more generic.
> > > > >
> > > > > How about the concept of a static resource (assuming a
> > > > > dynamically allocated one is out because it messes
> > > > > with memory allocation tests)? Something like this:
> > > > >
> > > > > #define kunit_add_static_resource(test, resource_ptr, resource_field)   \
> > > > >         do {                                                            \
> > > > >                 spin_lock(&test->lock);                                 \
> > > > >                 (resource_ptr)->resource_field.init = NULL;             \
> > > > >                 (resource_ptr)->resource_field.free = NULL;             \
> > > > >                 list_add_tail(&(resource_ptr)->resource_field,          \
> > > > >                               &test->resources);                        \
> > > > >                 spin_unlock(&test->lock);                               \
> > > > >         } while (0)
> > > > >
> > > > >
> > > > > Within your kasan code you could then create a kasan-specific
> > > > > structure that embends a kunit_resource, and contains the
> > > > > values you need:
> > > > >
> > > > > struct kasan_report_resource {
> > > > >         struct kunit_resource res;
> > > > >         bool kasan_report_expected;
> > > > >         bool kasan_report_found;
> > > > > };
> > > > >
> > > > > (One thing we'd need to do for such static resources is fix
> > > > > kunit_resource_free() to check if there's a free() function,
> > > > > and if not assume a static resource)
> > > > >
> > > > > If you then create an init() function associated with your
> > > > > kunit suite (which will be run for every case) it can do this:
> > > > >
> > > > > int kunit_kasan_test_init(struct kunit *test)
> > > > > {
> > > > >         kunit_add_static_resource(test, &my_kasan_report_resource, res);
> > > > >         ...
> > > > > }
> > > > >
> > > > > The above should also be used to initialize current->kasan_unit_test
> > > > > instead of doing that in kunit_try_run_case().  With those
> > > > > changes, you don't (I think) need to change anything in core
> > > > > kunit (assuming support for static resources).
> > > > >
> > > > > To retrieve the resource during tests or in kasan context, the
> > > > > method seems to be to use kunit_resource_find(). However, that
> > > > > requires a match function which seems a bit heavyweight for the
> > > > > static case.  We should probably have a default "find by name"
> > > > > or similar function here, and add an optional "name" field
> > > > > to kunit resources to simplify things.  Anyway here you'd
> > > > > use something like:
> > > > >
> > > > >         kasan_report_resource = kunit_resource_find(test, matchfn,
> > > > >                                                     NULL, matchdata);
> > > > >
> > > > >
> > > > > Are there any barriers to taking this sort of approach (apart
> > > > > from the support for static resources not being there yet)?
> > > > >
> > > >
> > > > I'm not sure. I don't have any experience with kunit resources so I
> > > > would have to put some more effort into understanding how this would
> > > > work for myself. I wonder if this might be a bit of an over
> > > > complicated way of eliminating an extraneous boolean... maybe we can
> > > > find a simpler solution for the first version of this patch and add
> > > > the notion of a static resource for generic use later.
> > > >
> > >
> > > My personal preference would be to try and learn what's needed
> > > by KASAN and improve the KUnit APIs so the next developer finds
> > > life a bit easier. More hassle for you I know, but actual use cases
> > > like this are invaluable for improving the API.  I've sent
> > > out an RFC patchset which has the functionality I _think_ you
> > > need but I may be missing something:
> > >
> > > https://lore.kernel.org/linux-kselftest/1583251361-12748-1-git-send-email-alan.maguire@oracle.com/T/#t
> > >
> > > The idea is your test can do something like this:
> > >
> > > struct kasan_data {
> > >         bool report_expected;
> > >         bool report_found;
> > > };
> > >
> > >
> > > my_kasan_test(struct kunit *test)
> > > {
> > >         struct kunit_resource resource;
> > >         struct kasan_data kasan_data;
> > >
> > > ...
> > >         // add our named resource using static resource/data
> > >         kunit_add_named_resource(test, NULL, NULL, &resource,
> > >                                  "kasan_data", &kasan_data);
> > > ...
> > >
> > > }
> > Does this require the user to set up this kasan_data resource in each
> > KASAN test? Or can we set up the resource on the KUnit side whenever a
> > user writes a test that expects a KASAN failure? I've been playing
> > around with it and I can only seem to get it to work when I add the
> > resource within the test, but I could be missing something.
> >
>
> The current model of resources is they are associated with
> the running state of a test for the lifetime of that test.
> If it's a resource common to many/most tests, I'd suggest
> creating an init() function for the associated suite; this
> will get run prior to executing each test, and in it you
> could initialize your resource. If the resource isn't
> used in the test, it doesn't really matter so this might be
> the simplest way to handle things:
>
> struct kasan_data {
>          bool report_expected;
>          bool report_found;
> };
>
> struct kasan_data kasan_data;
> struct kunit_resource resource;
>
> kasan_init(struct kunit *test)
> {
>
>          // add our named resource using static resource/data
>          kunit_add_named_resource(test, NULL, NULL, &resource,
>                                   "kasan_data", &kasan_data);
>
>         return 0;
> }
>
> static struct kunit_suite kasan_suite = {
>         .name = "kasan",
>         .init = kasan_init,
>         ...
> };
>
>
> This all presumes however that KASAN will only need access to the
> resource during the lifetime of each test.  There's currently
> no concept of free-floating resources outside of test execution
> context.

So we do have some patches lying around that add support for resources
associated with a suite of tests that I can send out if anyone is
interested; nevertheless, I think it makes sense for KASAN to only
care about tests cases; you still get the KASAN report either way and
KUnit isn't really supposed to care what happens outside of KUnit.

Cheers
diff mbox series

Patch

diff --git a/include/kunit/test.h b/include/kunit/test.h
index 2dfb550c6723..2e388f8937f3 100644
--- a/include/kunit/test.h
+++ b/include/kunit/test.h
@@ -21,6 +21,8 @@  struct kunit_resource;
 typedef int (*kunit_resource_init_t)(struct kunit_resource *, void *);
 typedef void (*kunit_resource_free_t)(struct kunit_resource *);
 
+void kunit_set_failure(struct kunit *test);
+
 /**
  * struct kunit_resource - represents a *test managed resource*
  * @allocation: for the user to store arbitrary data.
@@ -191,6 +193,9 @@  struct kunit {
 	 * protect it with some type of lock.
 	 */
 	struct list_head resources; /* Protected by lock. */
+
+	bool kasan_report_expected;
+	bool kasan_report_found;
 };
 
 void kunit_init_test(struct kunit *test, const char *name);
@@ -941,6 +946,25 @@  do {									       \
 						ptr,			       \
 						NULL)
 
+/**
+ * KUNIT_EXPECT_KASAN_FAIL() - Causes a test failure when the expression does
+ * not cause a KASAN error.
+ *
+ */
+#define KUNIT_EXPECT_KASAN_FAIL(test, condition) do {	\
+	test->kasan_report_expected = true;	\
+	test->kasan_report_found = false; \
+	condition; \
+	if (test->kasan_report_found == test->kasan_report_expected) { \
+		pr_info("%d has passed", __LINE__); \
+	} else { \
+		kunit_set_failure(test); \
+		pr_info("%d has failed", __LINE__); \
+	} \
+	test->kasan_report_expected = false;	\
+	test->kasan_report_found = false;	\
+} while (0)
+
 /**
  * KUNIT_EXPECT_TRUE() - Causes a test failure when the expression is not true.
  * @test: The test context object.
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 04278493bf15..db23d56061e7 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -32,6 +32,8 @@ 
 #include <linux/posix-timers.h>
 #include <linux/rseq.h>
 
+#include <kunit/test.h>
+
 /* task_struct member predeclarations (sorted alphabetically): */
 struct audit_context;
 struct backing_dev_info;
@@ -1178,7 +1180,10 @@  struct task_struct {
 
 #ifdef CONFIG_KASAN
 	unsigned int			kasan_depth;
-#endif
+#ifdef CONFIG_KUNIT
+	struct kunit *kasan_kunit_test;
+#endif /* CONFIG_KUNIT */
+#endif /* CONFIG_KASAN */
 
 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
 	/* Index of current stored address in ret_stack: */
diff --git a/lib/kunit/test.c b/lib/kunit/test.c
index 9242f932896c..d266b9495c67 100644
--- a/lib/kunit/test.c
+++ b/lib/kunit/test.c
@@ -9,11 +9,12 @@ 
 #include <kunit/test.h>
 #include <linux/kernel.h>
 #include <linux/sched/debug.h>
+#include <linux/sched.h>
 
 #include "string-stream.h"
 #include "try-catch-impl.h"
 
-static void kunit_set_failure(struct kunit *test)
+void kunit_set_failure(struct kunit *test)
 {
 	WRITE_ONCE(test->success, false);
 }
@@ -236,6 +237,10 @@  static void kunit_try_run_case(void *data)
 	struct kunit_suite *suite = ctx->suite;
 	struct kunit_case *test_case = ctx->test_case;
 
+#ifdef CONFIG_KASAN
+	current->kasan_kunit_test = test;
+#endif
+
 	/*
 	 * kunit_run_case_internal may encounter a fatal error; if it does,
 	 * abort will be called, this thread will exit, and finally the parent
diff --git a/mm/kasan/report.c b/mm/kasan/report.c
index 5ef9f24f566b..5554d23799a5 100644
--- a/mm/kasan/report.c
+++ b/mm/kasan/report.c
@@ -32,6 +32,8 @@ 
 
 #include <asm/sections.h>
 
+#include <kunit/test.h>
+
 #include "kasan.h"
 #include "../slab.h"
 
@@ -461,6 +463,15 @@  void kasan_report_invalid_free(void *object, unsigned long ip)
 	u8 tag = get_tag(object);
 
 	object = reset_tag(object);
+
+	if (current->kasan_kunit_test) {
+		if (current->kasan_kunit_test->kasan_report_expected) {
+			current->kasan_kunit_test->kasan_report_found = true;
+			return;
+		}
+		kunit_set_failure(current->kasan_kunit_test);
+	}
+
 	start_report(&flags);
 	pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
 	print_tags(tag, object);
@@ -481,6 +492,14 @@  void __kasan_report(unsigned long addr, size_t size, bool is_write, unsigned lon
 	if (likely(!report_enabled()))
 		return;
 
+	if (current->kasan_kunit_test) {
+		if (current->kasan_kunit_test->kasan_report_expected) {
+			current->kasan_kunit_test->kasan_report_found = true;
+			return;
+		}
+		kunit_set_failure(current->kasan_kunit_test);
+	}
+
 	disable_trace_on_warning();
 
 	tagged_addr = (void *)addr;
diff --git a/tools/testing/kunit/kunit_kernel.py b/tools/testing/kunit/kunit_kernel.py
index cc5d844ecca1..63eab18a8c34 100644
--- a/tools/testing/kunit/kunit_kernel.py
+++ b/tools/testing/kunit/kunit_kernel.py
@@ -141,7 +141,7 @@  class LinuxSourceTree(object):
 		return True
 
 	def run_kernel(self, args=[], timeout=None, build_dir=''):
-		args.extend(['mem=256M'])
+		args.extend(['mem=256M', 'kasan_multi_shot'])
 		process = self._ops.linux_bin(args, timeout, build_dir)
 		with open(os.path.join(build_dir, 'test.log'), 'w') as f:
 			for line in process.stdout: