kasan: test: improve failure message in KUNIT_EXPECT_KASAN_FAIL()
[linux-2.6-microblaze.git] / lib / kunit / test.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Base unit test (KUnit) API.
4  *
5  * Copyright (C) 2019, Google LLC.
6  * Author: Brendan Higgins <brendanhiggins@google.com>
7  */
8
9 #include <kunit/test.h>
10 #include <kunit/test-bug.h>
11 #include <linux/kernel.h>
12 #include <linux/kref.h>
13 #include <linux/sched/debug.h>
14 #include <linux/sched.h>
15
16 #include "debugfs.h"
17 #include "string-stream.h"
18 #include "try-catch-impl.h"
19
20 #if IS_BUILTIN(CONFIG_KUNIT)
21 /*
22  * Fail the current test and print an error message to the log.
23  */
24 void __kunit_fail_current_test(const char *file, int line, const char *fmt, ...)
25 {
26         va_list args;
27         int len;
28         char *buffer;
29
30         if (!current->kunit_test)
31                 return;
32
33         kunit_set_failure(current->kunit_test);
34
35         /* kunit_err() only accepts literals, so evaluate the args first. */
36         va_start(args, fmt);
37         len = vsnprintf(NULL, 0, fmt, args) + 1;
38         va_end(args);
39
40         buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
41         if (!buffer)
42                 return;
43
44         va_start(args, fmt);
45         vsnprintf(buffer, len, fmt, args);
46         va_end(args);
47
48         kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
49         kunit_kfree(current->kunit_test, buffer);
50 }
51 EXPORT_SYMBOL_GPL(__kunit_fail_current_test);
52 #endif
53
54 /*
55  * Append formatted message to log, size of which is limited to
56  * KUNIT_LOG_SIZE bytes (including null terminating byte).
57  */
58 void kunit_log_append(char *log, const char *fmt, ...)
59 {
60         char line[KUNIT_LOG_SIZE];
61         va_list args;
62         int len_left;
63
64         if (!log)
65                 return;
66
67         len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
68         if (len_left <= 0)
69                 return;
70
71         va_start(args, fmt);
72         vsnprintf(line, sizeof(line), fmt, args);
73         va_end(args);
74
75         strncat(log, line, len_left);
76 }
77 EXPORT_SYMBOL_GPL(kunit_log_append);
78
79 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
80 {
81         struct kunit_case *test_case;
82         size_t len = 0;
83
84         kunit_suite_for_each_test_case(suite, test_case)
85                 len++;
86
87         return len;
88 }
89 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
90
91 static void kunit_print_subtest_start(struct kunit_suite *suite)
92 {
93         kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
94                   suite->name);
95         kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
96                   kunit_suite_num_test_cases(suite));
97 }
98
99 static void kunit_print_ok_not_ok(void *test_or_suite,
100                                   bool is_test,
101                                   bool is_ok,
102                                   size_t test_number,
103                                   const char *description)
104 {
105         struct kunit_suite *suite = is_test ? NULL : test_or_suite;
106         struct kunit *test = is_test ? test_or_suite : NULL;
107
108         /*
109          * We do not log the test suite results as doing so would
110          * mean debugfs display would consist of the test suite
111          * description and status prior to individual test results.
112          * Hence directly printk the suite status, and we will
113          * separately seq_printf() the suite status for the debugfs
114          * representation.
115          */
116         if (suite)
117                 pr_info("%s %zd - %s\n",
118                         kunit_status_to_string(is_ok),
119                         test_number, description);
120         else
121                 kunit_log(KERN_INFO, test, KUNIT_SUBTEST_INDENT "%s %zd - %s",
122                           kunit_status_to_string(is_ok),
123                           test_number, description);
124 }
125
126 bool kunit_suite_has_succeeded(struct kunit_suite *suite)
127 {
128         const struct kunit_case *test_case;
129
130         kunit_suite_for_each_test_case(suite, test_case) {
131                 if (!test_case->success)
132                         return false;
133         }
134
135         return true;
136 }
137 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
138
139 static void kunit_print_subtest_end(struct kunit_suite *suite)
140 {
141         static size_t kunit_suite_counter = 1;
142
143         kunit_print_ok_not_ok((void *)suite, false,
144                               kunit_suite_has_succeeded(suite),
145                               kunit_suite_counter++,
146                               suite->name);
147 }
148
149 unsigned int kunit_test_case_num(struct kunit_suite *suite,
150                                  struct kunit_case *test_case)
151 {
152         struct kunit_case *tc;
153         unsigned int i = 1;
154
155         kunit_suite_for_each_test_case(suite, tc) {
156                 if (tc == test_case)
157                         return i;
158                 i++;
159         }
160
161         return 0;
162 }
163 EXPORT_SYMBOL_GPL(kunit_test_case_num);
164
165 static void kunit_print_string_stream(struct kunit *test,
166                                       struct string_stream *stream)
167 {
168         struct string_stream_fragment *fragment;
169         char *buf;
170
171         if (string_stream_is_empty(stream))
172                 return;
173
174         buf = string_stream_get_string(stream);
175         if (!buf) {
176                 kunit_err(test,
177                           "Could not allocate buffer, dumping stream:\n");
178                 list_for_each_entry(fragment, &stream->fragments, node) {
179                         kunit_err(test, "%s", fragment->fragment);
180                 }
181                 kunit_err(test, "\n");
182         } else {
183                 kunit_err(test, "%s", buf);
184                 kunit_kfree(test, buf);
185         }
186 }
187
188 static void kunit_fail(struct kunit *test, struct kunit_assert *assert)
189 {
190         struct string_stream *stream;
191
192         kunit_set_failure(test);
193
194         stream = alloc_string_stream(test, GFP_KERNEL);
195         if (!stream) {
196                 WARN(true,
197                      "Could not allocate stream to print failed assertion in %s:%d\n",
198                      assert->file,
199                      assert->line);
200                 return;
201         }
202
203         assert->format(assert, stream);
204
205         kunit_print_string_stream(test, stream);
206
207         WARN_ON(string_stream_destroy(stream));
208 }
209
210 static void __noreturn kunit_abort(struct kunit *test)
211 {
212         kunit_try_catch_throw(&test->try_catch); /* Does not return. */
213
214         /*
215          * Throw could not abort from test.
216          *
217          * XXX: we should never reach this line! As kunit_try_catch_throw is
218          * marked __noreturn.
219          */
220         WARN_ONCE(true, "Throw could not abort from test!\n");
221 }
222
223 void kunit_do_assertion(struct kunit *test,
224                         struct kunit_assert *assert,
225                         bool pass,
226                         const char *fmt, ...)
227 {
228         va_list args;
229
230         if (pass)
231                 return;
232
233         va_start(args, fmt);
234
235         assert->message.fmt = fmt;
236         assert->message.va = &args;
237
238         kunit_fail(test, assert);
239
240         va_end(args);
241
242         if (assert->type == KUNIT_ASSERTION)
243                 kunit_abort(test);
244 }
245 EXPORT_SYMBOL_GPL(kunit_do_assertion);
246
247 void kunit_init_test(struct kunit *test, const char *name, char *log)
248 {
249         spin_lock_init(&test->lock);
250         INIT_LIST_HEAD(&test->resources);
251         test->name = name;
252         test->log = log;
253         if (test->log)
254                 test->log[0] = '\0';
255         test->success = true;
256 }
257 EXPORT_SYMBOL_GPL(kunit_init_test);
258
259 /*
260  * Initializes and runs test case. Does not clean up or do post validations.
261  */
262 static void kunit_run_case_internal(struct kunit *test,
263                                     struct kunit_suite *suite,
264                                     struct kunit_case *test_case)
265 {
266         if (suite->init) {
267                 int ret;
268
269                 ret = suite->init(test);
270                 if (ret) {
271                         kunit_err(test, "failed to initialize: %d\n", ret);
272                         kunit_set_failure(test);
273                         return;
274                 }
275         }
276
277         test_case->run_case(test);
278 }
279
280 static void kunit_case_internal_cleanup(struct kunit *test)
281 {
282         kunit_cleanup(test);
283 }
284
285 /*
286  * Performs post validations and cleanup after a test case was run.
287  * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
288  */
289 static void kunit_run_case_cleanup(struct kunit *test,
290                                    struct kunit_suite *suite)
291 {
292         if (suite->exit)
293                 suite->exit(test);
294
295         kunit_case_internal_cleanup(test);
296 }
297
298 struct kunit_try_catch_context {
299         struct kunit *test;
300         struct kunit_suite *suite;
301         struct kunit_case *test_case;
302 };
303
304 static void kunit_try_run_case(void *data)
305 {
306         struct kunit_try_catch_context *ctx = data;
307         struct kunit *test = ctx->test;
308         struct kunit_suite *suite = ctx->suite;
309         struct kunit_case *test_case = ctx->test_case;
310
311         current->kunit_test = test;
312
313         /*
314          * kunit_run_case_internal may encounter a fatal error; if it does,
315          * abort will be called, this thread will exit, and finally the parent
316          * thread will resume control and handle any necessary clean up.
317          */
318         kunit_run_case_internal(test, suite, test_case);
319         /* This line may never be reached. */
320         kunit_run_case_cleanup(test, suite);
321 }
322
323 static void kunit_catch_run_case(void *data)
324 {
325         struct kunit_try_catch_context *ctx = data;
326         struct kunit *test = ctx->test;
327         struct kunit_suite *suite = ctx->suite;
328         int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
329
330         if (try_exit_code) {
331                 kunit_set_failure(test);
332                 /*
333                  * Test case could not finish, we have no idea what state it is
334                  * in, so don't do clean up.
335                  */
336                 if (try_exit_code == -ETIMEDOUT) {
337                         kunit_err(test, "test case timed out\n");
338                 /*
339                  * Unknown internal error occurred preventing test case from
340                  * running, so there is nothing to clean up.
341                  */
342                 } else {
343                         kunit_err(test, "internal error occurred preventing test case from running: %d\n",
344                                   try_exit_code);
345                 }
346                 return;
347         }
348
349         /*
350          * Test case was run, but aborted. It is the test case's business as to
351          * whether it failed or not, we just need to clean up.
352          */
353         kunit_run_case_cleanup(test, suite);
354 }
355
356 /*
357  * Performs all logic to run a test case. It also catches most errors that
358  * occur in a test case and reports them as failures.
359  */
360 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
361                                         struct kunit_case *test_case,
362                                         struct kunit *test)
363 {
364         struct kunit_try_catch_context context;
365         struct kunit_try_catch *try_catch;
366
367         kunit_init_test(test, test_case->name, test_case->log);
368         try_catch = &test->try_catch;
369
370         kunit_try_catch_init(try_catch,
371                              test,
372                              kunit_try_run_case,
373                              kunit_catch_run_case);
374         context.test = test;
375         context.suite = suite;
376         context.test_case = test_case;
377         kunit_try_catch_run(try_catch, &context);
378
379         test_case->success = test->success;
380 }
381
382 int kunit_run_tests(struct kunit_suite *suite)
383 {
384         char param_desc[KUNIT_PARAM_DESC_SIZE];
385         struct kunit_case *test_case;
386
387         kunit_print_subtest_start(suite);
388
389         kunit_suite_for_each_test_case(suite, test_case) {
390                 struct kunit test = { .param_value = NULL, .param_index = 0 };
391                 bool test_success = true;
392
393                 if (test_case->generate_params) {
394                         /* Get initial param. */
395                         param_desc[0] = '\0';
396                         test.param_value = test_case->generate_params(NULL, param_desc);
397                 }
398
399                 do {
400                         kunit_run_case_catch_errors(suite, test_case, &test);
401                         test_success &= test_case->success;
402
403                         if (test_case->generate_params) {
404                                 if (param_desc[0] == '\0') {
405                                         snprintf(param_desc, sizeof(param_desc),
406                                                  "param-%d", test.param_index);
407                                 }
408
409                                 kunit_log(KERN_INFO, &test,
410                                           KUNIT_SUBTEST_INDENT
411                                           "# %s: %s %d - %s",
412                                           test_case->name,
413                                           kunit_status_to_string(test.success),
414                                           test.param_index + 1, param_desc);
415
416                                 /* Get next param. */
417                                 param_desc[0] = '\0';
418                                 test.param_value = test_case->generate_params(test.param_value, param_desc);
419                                 test.param_index++;
420                         }
421                 } while (test.param_value);
422
423                 kunit_print_ok_not_ok(&test, true, test_success,
424                                       kunit_test_case_num(suite, test_case),
425                                       test_case->name);
426         }
427
428         kunit_print_subtest_end(suite);
429
430         return 0;
431 }
432 EXPORT_SYMBOL_GPL(kunit_run_tests);
433
434 static void kunit_init_suite(struct kunit_suite *suite)
435 {
436         kunit_debugfs_create_suite(suite);
437 }
438
439 int __kunit_test_suites_init(struct kunit_suite * const * const suites)
440 {
441         unsigned int i;
442
443         for (i = 0; suites[i] != NULL; i++) {
444                 kunit_init_suite(suites[i]);
445                 kunit_run_tests(suites[i]);
446         }
447         return 0;
448 }
449 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
450
451 static void kunit_exit_suite(struct kunit_suite *suite)
452 {
453         kunit_debugfs_destroy_suite(suite);
454 }
455
456 void __kunit_test_suites_exit(struct kunit_suite **suites)
457 {
458         unsigned int i;
459
460         for (i = 0; suites[i] != NULL; i++)
461                 kunit_exit_suite(suites[i]);
462 }
463 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
464
465 /*
466  * Used for static resources and when a kunit_resource * has been created by
467  * kunit_alloc_resource().  When an init function is supplied, @data is passed
468  * into the init function; otherwise, we simply set the resource data field to
469  * the data value passed in.
470  */
471 int kunit_add_resource(struct kunit *test,
472                        kunit_resource_init_t init,
473                        kunit_resource_free_t free,
474                        struct kunit_resource *res,
475                        void *data)
476 {
477         int ret = 0;
478         unsigned long flags;
479
480         res->free = free;
481         kref_init(&res->refcount);
482
483         if (init) {
484                 ret = init(res, data);
485                 if (ret)
486                         return ret;
487         } else {
488                 res->data = data;
489         }
490
491         spin_lock_irqsave(&test->lock, flags);
492         list_add_tail(&res->node, &test->resources);
493         /* refcount for list is established by kref_init() */
494         spin_unlock_irqrestore(&test->lock, flags);
495
496         return ret;
497 }
498 EXPORT_SYMBOL_GPL(kunit_add_resource);
499
500 int kunit_add_named_resource(struct kunit *test,
501                              kunit_resource_init_t init,
502                              kunit_resource_free_t free,
503                              struct kunit_resource *res,
504                              const char *name,
505                              void *data)
506 {
507         struct kunit_resource *existing;
508
509         if (!name)
510                 return -EINVAL;
511
512         existing = kunit_find_named_resource(test, name);
513         if (existing) {
514                 kunit_put_resource(existing);
515                 return -EEXIST;
516         }
517
518         res->name = name;
519
520         return kunit_add_resource(test, init, free, res, data);
521 }
522 EXPORT_SYMBOL_GPL(kunit_add_named_resource);
523
524 struct kunit_resource *kunit_alloc_and_get_resource(struct kunit *test,
525                                                     kunit_resource_init_t init,
526                                                     kunit_resource_free_t free,
527                                                     gfp_t internal_gfp,
528                                                     void *data)
529 {
530         struct kunit_resource *res;
531         int ret;
532
533         res = kzalloc(sizeof(*res), internal_gfp);
534         if (!res)
535                 return NULL;
536
537         ret = kunit_add_resource(test, init, free, res, data);
538         if (!ret) {
539                 /*
540                  * bump refcount for get; kunit_resource_put() should be called
541                  * when done.
542                  */
543                 kunit_get_resource(res);
544                 return res;
545         }
546         return NULL;
547 }
548 EXPORT_SYMBOL_GPL(kunit_alloc_and_get_resource);
549
550 void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
551 {
552         unsigned long flags;
553
554         spin_lock_irqsave(&test->lock, flags);
555         list_del(&res->node);
556         spin_unlock_irqrestore(&test->lock, flags);
557         kunit_put_resource(res);
558 }
559 EXPORT_SYMBOL_GPL(kunit_remove_resource);
560
561 int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
562                            void *match_data)
563 {
564         struct kunit_resource *res = kunit_find_resource(test, match,
565                                                          match_data);
566
567         if (!res)
568                 return -ENOENT;
569
570         kunit_remove_resource(test, res);
571
572         /* We have a reference also via _find(); drop it. */
573         kunit_put_resource(res);
574
575         return 0;
576 }
577 EXPORT_SYMBOL_GPL(kunit_destroy_resource);
578
579 struct kunit_kmalloc_params {
580         size_t size;
581         gfp_t gfp;
582 };
583
584 static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
585 {
586         struct kunit_kmalloc_params *params = context;
587
588         res->data = kmalloc(params->size, params->gfp);
589         if (!res->data)
590                 return -ENOMEM;
591
592         return 0;
593 }
594
595 static void kunit_kmalloc_free(struct kunit_resource *res)
596 {
597         kfree(res->data);
598 }
599
600 void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
601 {
602         struct kunit_kmalloc_params params = {
603                 .size = size,
604                 .gfp = gfp
605         };
606
607         return kunit_alloc_resource(test,
608                                     kunit_kmalloc_init,
609                                     kunit_kmalloc_free,
610                                     gfp,
611                                     &params);
612 }
613 EXPORT_SYMBOL_GPL(kunit_kmalloc);
614
615 void kunit_kfree(struct kunit *test, const void *ptr)
616 {
617         struct kunit_resource *res;
618
619         res = kunit_find_resource(test, kunit_resource_instance_match,
620                                   (void *)ptr);
621
622         /*
623          * Removing the resource from the list of resources drops the
624          * reference count to 1; the final put will trigger the free.
625          */
626         kunit_remove_resource(test, res);
627
628         kunit_put_resource(res);
629
630 }
631 EXPORT_SYMBOL_GPL(kunit_kfree);
632
633 void kunit_cleanup(struct kunit *test)
634 {
635         struct kunit_resource *res;
636         unsigned long flags;
637
638         /*
639          * test->resources is a stack - each allocation must be freed in the
640          * reverse order from which it was added since one resource may depend
641          * on another for its entire lifetime.
642          * Also, we cannot use the normal list_for_each constructs, even the
643          * safe ones because *arbitrary* nodes may be deleted when
644          * kunit_resource_free is called; the list_for_each_safe variants only
645          * protect against the current node being deleted, not the next.
646          */
647         while (true) {
648                 spin_lock_irqsave(&test->lock, flags);
649                 if (list_empty(&test->resources)) {
650                         spin_unlock_irqrestore(&test->lock, flags);
651                         break;
652                 }
653                 res = list_last_entry(&test->resources,
654                                       struct kunit_resource,
655                                       node);
656                 /*
657                  * Need to unlock here as a resource may remove another
658                  * resource, and this can't happen if the test->lock
659                  * is held.
660                  */
661                 spin_unlock_irqrestore(&test->lock, flags);
662                 kunit_remove_resource(test, res);
663         }
664         current->kunit_test = NULL;
665 }
666 EXPORT_SYMBOL_GPL(kunit_cleanup);
667
668 static int __init kunit_init(void)
669 {
670         kunit_debugfs_init();
671
672         return 0;
673 }
674 late_initcall(kunit_init);
675
676 static void __exit kunit_exit(void)
677 {
678         kunit_debugfs_cleanup();
679 }
680 module_exit(kunit_exit);
681
682 MODULE_LICENSE("GPL v2");