selftests/harness: Refactor XFAIL into SKIP
[linux-2.6-microblaze.git] / tools / testing / selftests / kselftest_harness.h
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4  *
5  * kselftest_harness.h: simple C unit test helper.
6  *
7  * See documentation in Documentation/dev-tools/kselftest.rst
8  *
9  * API inspired by code.google.com/p/googletest
10  */
11
12 /**
13  * DOC: example
14  *
15  * .. code-block:: c
16  *
17  *    #include "../kselftest_harness.h"
18  *
19  *    TEST(standalone_test) {
20  *      do_some_stuff;
21  *      EXPECT_GT(10, stuff) {
22  *         stuff_state_t state;
23  *         enumerate_stuff_state(&state);
24  *         TH_LOG("expectation failed with state: %s", state.msg);
25  *      }
26  *      more_stuff;
27  *      ASSERT_NE(some_stuff, NULL) TH_LOG("how did it happen?!");
28  *      last_stuff;
29  *      EXPECT_EQ(0, last_stuff);
30  *    }
31  *
32  *    FIXTURE(my_fixture) {
33  *      mytype_t *data;
34  *      int awesomeness_level;
35  *    };
36  *    FIXTURE_SETUP(my_fixture) {
37  *      self->data = mytype_new();
38  *      ASSERT_NE(NULL, self->data);
39  *    }
40  *    FIXTURE_TEARDOWN(my_fixture) {
41  *      mytype_free(self->data);
42  *    }
43  *    TEST_F(my_fixture, data_is_good) {
44  *      EXPECT_EQ(1, is_my_data_good(self->data));
45  *    }
46  *
47  *    TEST_HARNESS_MAIN
48  */
49
50 #ifndef __KSELFTEST_HARNESS_H
51 #define __KSELFTEST_HARNESS_H
52
53 #ifndef _GNU_SOURCE
54 #define _GNU_SOURCE
55 #endif
56 #include <asm/types.h>
57 #include <errno.h>
58 #include <stdbool.h>
59 #include <stdint.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <sys/types.h>
64 #include <sys/wait.h>
65 #include <unistd.h>
66
67 #include "kselftest.h"
68
69 #define TEST_TIMEOUT_DEFAULT 30
70
71 /* Utilities exposed to the test definitions */
72 #ifndef TH_LOG_STREAM
73 #  define TH_LOG_STREAM stderr
74 #endif
75
76 #ifndef TH_LOG_ENABLED
77 #  define TH_LOG_ENABLED 1
78 #endif
79
80 /**
81  * TH_LOG(fmt, ...)
82  *
83  * @fmt: format string
84  * @...: optional arguments
85  *
86  * .. code-block:: c
87  *
88  *     TH_LOG(format, ...)
89  *
90  * Optional debug logging function available for use in tests.
91  * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
92  * E.g., #define TH_LOG_ENABLED 1
93  *
94  * If no definition is provided, logging is enabled by default.
95  *
96  * If there is no way to print an error message for the process running the
97  * test (e.g. not allowed to write to stderr), it is still possible to get the
98  * ASSERT_* number for which the test failed.  This behavior can be enabled by
99  * writing `_metadata->no_print = true;` before the check sequence that is
100  * unable to print.  When an error occur, instead of printing an error message
101  * and calling `abort(3)`, the test process call `_exit(2)` with the assert
102  * number as argument, which is then printed by the parent process.
103  */
104 #define TH_LOG(fmt, ...) do { \
105         if (TH_LOG_ENABLED) \
106                 __TH_LOG(fmt, ##__VA_ARGS__); \
107 } while (0)
108
109 /* Unconditional logger for internal use. */
110 #define __TH_LOG(fmt, ...) \
111                 fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \
112                         __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
113
114 /**
115  * SKIP(statement, fmt, ...)
116  *
117  * @statement: statement to run after reporting SKIP
118  * @fmt: format string
119  * @...: optional arguments
120  *
121  * This forces a "pass" after reporting why something is being skipped
122  * and runs "statement", which is usually "return" or "goto skip".
123  */
124 #define SKIP(statement, fmt, ...) do { \
125         if (TH_LOG_ENABLED) { \
126                 fprintf(TH_LOG_STREAM, "#      SKIP     " fmt "\n", \
127                         ##__VA_ARGS__); \
128         } \
129         _metadata->passed = 1; \
130         _metadata->skip = 1; \
131         _metadata->trigger = 0; \
132         statement; \
133 } while (0)
134
135 /**
136  * TEST(test_name) - Defines the test function and creates the registration
137  * stub
138  *
139  * @test_name: test name
140  *
141  * .. code-block:: c
142  *
143  *     TEST(name) { implementation }
144  *
145  * Defines a test by name.
146  * Names must be unique and tests must not be run in parallel.  The
147  * implementation containing block is a function and scoping should be treated
148  * as such.  Returning early may be performed with a bare "return;" statement.
149  *
150  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
151  */
152 #define TEST(test_name) __TEST_IMPL(test_name, -1)
153
154 /**
155  * TEST_SIGNAL(test_name, signal)
156  *
157  * @test_name: test name
158  * @signal: signal number
159  *
160  * .. code-block:: c
161  *
162  *     TEST_SIGNAL(name, signal) { implementation }
163  *
164  * Defines a test by name and the expected term signal.
165  * Names must be unique and tests must not be run in parallel.  The
166  * implementation containing block is a function and scoping should be treated
167  * as such.  Returning early may be performed with a bare "return;" statement.
168  *
169  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
170  */
171 #define TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
172
173 #define __TEST_IMPL(test_name, _signal) \
174         static void test_name(struct __test_metadata *_metadata); \
175         static inline void wrapper_##test_name( \
176                 struct __test_metadata *_metadata, \
177                 struct __fixture_variant_metadata *variant) \
178         { \
179                 test_name(_metadata); \
180         } \
181         static struct __test_metadata _##test_name##_object = \
182                 { .name = #test_name, \
183                   .fn = &wrapper_##test_name, \
184                   .fixture = &_fixture_global, \
185                   .termsig = _signal, \
186                   .timeout = TEST_TIMEOUT_DEFAULT, }; \
187         static void __attribute__((constructor)) _register_##test_name(void) \
188         { \
189                 __register_test(&_##test_name##_object); \
190         } \
191         static void test_name( \
192                 struct __test_metadata __attribute__((unused)) *_metadata)
193
194 /**
195  * FIXTURE_DATA(datatype_name) - Wraps the struct name so we have one less
196  * argument to pass around
197  *
198  * @datatype_name: datatype name
199  *
200  * .. code-block:: c
201  *
202  *     FIXTURE_DATA(datatype name)
203  *
204  * This call may be used when the type of the fixture data
205  * is needed.  In general, this should not be needed unless
206  * the *self* is being passed to a helper directly.
207  */
208 #define FIXTURE_DATA(datatype_name) struct _test_data_##datatype_name
209
210 /**
211  * FIXTURE(fixture_name) - Called once per fixture to setup the data and
212  * register
213  *
214  * @fixture_name: fixture name
215  *
216  * .. code-block:: c
217  *
218  *     FIXTURE(datatype name) {
219  *       type property1;
220  *       ...
221  *     };
222  *
223  * Defines the data provided to TEST_F()-defined tests as *self*.  It should be
224  * populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN().
225  */
226 #define FIXTURE(fixture_name) \
227         FIXTURE_VARIANT(fixture_name); \
228         static struct __fixture_metadata _##fixture_name##_fixture_object = \
229                 { .name =  #fixture_name, }; \
230         static void __attribute__((constructor)) \
231         _register_##fixture_name##_data(void) \
232         { \
233                 __register_fixture(&_##fixture_name##_fixture_object); \
234         } \
235         FIXTURE_DATA(fixture_name)
236
237 /**
238  * FIXTURE_SETUP(fixture_name) - Prepares the setup function for the fixture.
239  * *_metadata* is included so that EXPECT_* and ASSERT_* work correctly.
240  *
241  * @fixture_name: fixture name
242  *
243  * .. code-block:: c
244  *
245  *     FIXTURE_SETUP(fixture name) { implementation }
246  *
247  * Populates the required "setup" function for a fixture.  An instance of the
248  * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
249  * implementation.
250  *
251  * ASSERT_* are valid for use in this context and will prempt the execution
252  * of any dependent fixture tests.
253  *
254  * A bare "return;" statement may be used to return early.
255  */
256 #define FIXTURE_SETUP(fixture_name) \
257         void fixture_name##_setup( \
258                 struct __test_metadata __attribute__((unused)) *_metadata, \
259                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
260                 const FIXTURE_VARIANT(fixture_name) \
261                         __attribute__((unused)) *variant)
262
263 /**
264  * FIXTURE_TEARDOWN(fixture_name)
265  * *_metadata* is included so that EXPECT_* and ASSERT_* work correctly.
266  *
267  * @fixture_name: fixture name
268  *
269  * .. code-block:: c
270  *
271  *     FIXTURE_TEARDOWN(fixture name) { implementation }
272  *
273  * Populates the required "teardown" function for a fixture.  An instance of the
274  * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
275  * implementation to clean up.
276  *
277  * A bare "return;" statement may be used to return early.
278  */
279 #define FIXTURE_TEARDOWN(fixture_name) \
280         void fixture_name##_teardown( \
281                 struct __test_metadata __attribute__((unused)) *_metadata, \
282                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self)
283
284 /**
285  * FIXTURE_VARIANT(fixture_name) - Optionally called once per fixture
286  * to declare fixture variant
287  *
288  * @fixture_name: fixture name
289  *
290  * .. code-block:: c
291  *
292  *     FIXTURE_VARIANT(datatype name) {
293  *       type property1;
294  *       ...
295  *     };
296  *
297  * Defines type of constant parameters provided to FIXTURE_SETUP() and TEST_F()
298  * as *variant*. Variants allow the same tests to be run with different
299  * arguments.
300  */
301 #define FIXTURE_VARIANT(fixture_name) struct _fixture_variant_##fixture_name
302
303 /**
304  * FIXTURE_VARIANT_ADD(fixture_name, variant_name) - Called once per fixture
305  * variant to setup and register the data
306  *
307  * @fixture_name: fixture name
308  * @variant_name: name of the parameter set
309  *
310  * .. code-block:: c
311  *
312  *     FIXTURE_ADD(datatype name) {
313  *       .property1 = val1;
314  *       ...
315  *     };
316  *
317  * Defines a variant of the test fixture, provided to FIXTURE_SETUP() and
318  * TEST_F() as *variant*. Tests of each fixture will be run once for each
319  * variant.
320  */
321 #define FIXTURE_VARIANT_ADD(fixture_name, variant_name) \
322         extern FIXTURE_VARIANT(fixture_name) \
323                 _##fixture_name##_##variant_name##_variant; \
324         static struct __fixture_variant_metadata \
325                 _##fixture_name##_##variant_name##_object = \
326                 { .name = #variant_name, \
327                   .data = &_##fixture_name##_##variant_name##_variant}; \
328         static void __attribute__((constructor)) \
329                 _register_##fixture_name##_##variant_name(void) \
330         { \
331                 __register_fixture_variant(&_##fixture_name##_fixture_object, \
332                         &_##fixture_name##_##variant_name##_object);    \
333         } \
334         FIXTURE_VARIANT(fixture_name) \
335                 _##fixture_name##_##variant_name##_variant =
336
337 /**
338  * TEST_F(fixture_name, test_name) - Emits test registration and helpers for
339  * fixture-based test cases
340  *
341  * @fixture_name: fixture name
342  * @test_name: test name
343  *
344  * .. code-block:: c
345  *
346  *     TEST_F(fixture, name) { implementation }
347  *
348  * Defines a test that depends on a fixture (e.g., is part of a test case).
349  * Very similar to TEST() except that *self* is the setup instance of fixture's
350  * datatype exposed for use by the implementation.
351  *
352  * Warning: use of ASSERT_* here will skip TEARDOWN.
353  */
354 /* TODO(wad) register fixtures on dedicated test lists. */
355 #define TEST_F(fixture_name, test_name) \
356         __TEST_F_IMPL(fixture_name, test_name, -1, TEST_TIMEOUT_DEFAULT)
357
358 #define TEST_F_SIGNAL(fixture_name, test_name, signal) \
359         __TEST_F_IMPL(fixture_name, test_name, signal, TEST_TIMEOUT_DEFAULT)
360
361 #define TEST_F_TIMEOUT(fixture_name, test_name, timeout) \
362         __TEST_F_IMPL(fixture_name, test_name, -1, timeout)
363
364 #define __TEST_F_IMPL(fixture_name, test_name, signal, tmout) \
365         static void fixture_name##_##test_name( \
366                 struct __test_metadata *_metadata, \
367                 FIXTURE_DATA(fixture_name) *self, \
368                 const FIXTURE_VARIANT(fixture_name) *variant); \
369         static inline void wrapper_##fixture_name##_##test_name( \
370                 struct __test_metadata *_metadata, \
371                 struct __fixture_variant_metadata *variant) \
372         { \
373                 /* fixture data is alloced, setup, and torn down per call. */ \
374                 FIXTURE_DATA(fixture_name) self; \
375                 memset(&self, 0, sizeof(FIXTURE_DATA(fixture_name))); \
376                 fixture_name##_setup(_metadata, &self, variant->data); \
377                 /* Let setup failure terminate early. */ \
378                 if (!_metadata->passed) \
379                         return; \
380                 fixture_name##_##test_name(_metadata, &self, variant->data); \
381                 fixture_name##_teardown(_metadata, &self); \
382         } \
383         static struct __test_metadata \
384                       _##fixture_name##_##test_name##_object = { \
385                 .name = #test_name, \
386                 .fn = &wrapper_##fixture_name##_##test_name, \
387                 .fixture = &_##fixture_name##_fixture_object, \
388                 .termsig = signal, \
389                 .timeout = tmout, \
390          }; \
391         static void __attribute__((constructor)) \
392                         _register_##fixture_name##_##test_name(void) \
393         { \
394                 __register_test(&_##fixture_name##_##test_name##_object); \
395         } \
396         static void fixture_name##_##test_name( \
397                 struct __test_metadata __attribute__((unused)) *_metadata, \
398                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
399                 const FIXTURE_VARIANT(fixture_name) \
400                         __attribute__((unused)) *variant)
401
402 /**
403  * TEST_HARNESS_MAIN - Simple wrapper to run the test harness
404  *
405  * .. code-block:: c
406  *
407  *     TEST_HARNESS_MAIN
408  *
409  * Use once to append a main() to the test file.
410  */
411 #define TEST_HARNESS_MAIN \
412         static void __attribute__((constructor)) \
413         __constructor_order_last(void) \
414         { \
415                 if (!__constructor_order) \
416                         __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
417         } \
418         int main(int argc, char **argv) { \
419                 return test_harness_run(argc, argv); \
420         }
421
422 /**
423  * DOC: operators
424  *
425  * Operators for use in TEST() and TEST_F().
426  * ASSERT_* calls will stop test execution immediately.
427  * EXPECT_* calls will emit a failure warning, note it, and continue.
428  */
429
430 /**
431  * ASSERT_EQ(expected, seen)
432  *
433  * @expected: expected value
434  * @seen: measured value
435  *
436  * ASSERT_EQ(expected, measured): expected == measured
437  */
438 #define ASSERT_EQ(expected, seen) \
439         __EXPECT(expected, #expected, seen, #seen, ==, 1)
440
441 /**
442  * ASSERT_NE(expected, seen)
443  *
444  * @expected: expected value
445  * @seen: measured value
446  *
447  * ASSERT_NE(expected, measured): expected != measured
448  */
449 #define ASSERT_NE(expected, seen) \
450         __EXPECT(expected, #expected, seen, #seen, !=, 1)
451
452 /**
453  * ASSERT_LT(expected, seen)
454  *
455  * @expected: expected value
456  * @seen: measured value
457  *
458  * ASSERT_LT(expected, measured): expected < measured
459  */
460 #define ASSERT_LT(expected, seen) \
461         __EXPECT(expected, #expected, seen, #seen, <, 1)
462
463 /**
464  * ASSERT_LE(expected, seen)
465  *
466  * @expected: expected value
467  * @seen: measured value
468  *
469  * ASSERT_LE(expected, measured): expected <= measured
470  */
471 #define ASSERT_LE(expected, seen) \
472         __EXPECT(expected, #expected, seen, #seen, <=, 1)
473
474 /**
475  * ASSERT_GT(expected, seen)
476  *
477  * @expected: expected value
478  * @seen: measured value
479  *
480  * ASSERT_GT(expected, measured): expected > measured
481  */
482 #define ASSERT_GT(expected, seen) \
483         __EXPECT(expected, #expected, seen, #seen, >, 1)
484
485 /**
486  * ASSERT_GE(expected, seen)
487  *
488  * @expected: expected value
489  * @seen: measured value
490  *
491  * ASSERT_GE(expected, measured): expected >= measured
492  */
493 #define ASSERT_GE(expected, seen) \
494         __EXPECT(expected, #expected, seen, #seen, >=, 1)
495
496 /**
497  * ASSERT_NULL(seen)
498  *
499  * @seen: measured value
500  *
501  * ASSERT_NULL(measured): NULL == measured
502  */
503 #define ASSERT_NULL(seen) \
504         __EXPECT(NULL, "NULL", seen, #seen, ==, 1)
505
506 /**
507  * ASSERT_TRUE(seen)
508  *
509  * @seen: measured value
510  *
511  * ASSERT_TRUE(measured): measured != 0
512  */
513 #define ASSERT_TRUE(seen) \
514         __EXPECT(0, "0", seen, #seen, !=, 1)
515
516 /**
517  * ASSERT_FALSE(seen)
518  *
519  * @seen: measured value
520  *
521  * ASSERT_FALSE(measured): measured == 0
522  */
523 #define ASSERT_FALSE(seen) \
524         __EXPECT(0, "0", seen, #seen, ==, 1)
525
526 /**
527  * ASSERT_STREQ(expected, seen)
528  *
529  * @expected: expected value
530  * @seen: measured value
531  *
532  * ASSERT_STREQ(expected, measured): !strcmp(expected, measured)
533  */
534 #define ASSERT_STREQ(expected, seen) \
535         __EXPECT_STR(expected, seen, ==, 1)
536
537 /**
538  * ASSERT_STRNE(expected, seen)
539  *
540  * @expected: expected value
541  * @seen: measured value
542  *
543  * ASSERT_STRNE(expected, measured): strcmp(expected, measured)
544  */
545 #define ASSERT_STRNE(expected, seen) \
546         __EXPECT_STR(expected, seen, !=, 1)
547
548 /**
549  * EXPECT_EQ(expected, seen)
550  *
551  * @expected: expected value
552  * @seen: measured value
553  *
554  * EXPECT_EQ(expected, measured): expected == measured
555  */
556 #define EXPECT_EQ(expected, seen) \
557         __EXPECT(expected, #expected, seen, #seen, ==, 0)
558
559 /**
560  * EXPECT_NE(expected, seen)
561  *
562  * @expected: expected value
563  * @seen: measured value
564  *
565  * EXPECT_NE(expected, measured): expected != measured
566  */
567 #define EXPECT_NE(expected, seen) \
568         __EXPECT(expected, #expected, seen, #seen, !=, 0)
569
570 /**
571  * EXPECT_LT(expected, seen)
572  *
573  * @expected: expected value
574  * @seen: measured value
575  *
576  * EXPECT_LT(expected, measured): expected < measured
577  */
578 #define EXPECT_LT(expected, seen) \
579         __EXPECT(expected, #expected, seen, #seen, <, 0)
580
581 /**
582  * EXPECT_LE(expected, seen)
583  *
584  * @expected: expected value
585  * @seen: measured value
586  *
587  * EXPECT_LE(expected, measured): expected <= measured
588  */
589 #define EXPECT_LE(expected, seen) \
590         __EXPECT(expected, #expected, seen, #seen, <=, 0)
591
592 /**
593  * EXPECT_GT(expected, seen)
594  *
595  * @expected: expected value
596  * @seen: measured value
597  *
598  * EXPECT_GT(expected, measured): expected > measured
599  */
600 #define EXPECT_GT(expected, seen) \
601         __EXPECT(expected, #expected, seen, #seen, >, 0)
602
603 /**
604  * EXPECT_GE(expected, seen)
605  *
606  * @expected: expected value
607  * @seen: measured value
608  *
609  * EXPECT_GE(expected, measured): expected >= measured
610  */
611 #define EXPECT_GE(expected, seen) \
612         __EXPECT(expected, #expected, seen, #seen, >=, 0)
613
614 /**
615  * EXPECT_NULL(seen)
616  *
617  * @seen: measured value
618  *
619  * EXPECT_NULL(measured): NULL == measured
620  */
621 #define EXPECT_NULL(seen) \
622         __EXPECT(NULL, "NULL", seen, #seen, ==, 0)
623
624 /**
625  * EXPECT_TRUE(seen)
626  *
627  * @seen: measured value
628  *
629  * EXPECT_TRUE(measured): 0 != measured
630  */
631 #define EXPECT_TRUE(seen) \
632         __EXPECT(0, "0", seen, #seen, !=, 0)
633
634 /**
635  * EXPECT_FALSE(seen)
636  *
637  * @seen: measured value
638  *
639  * EXPECT_FALSE(measured): 0 == measured
640  */
641 #define EXPECT_FALSE(seen) \
642         __EXPECT(0, "0", seen, #seen, ==, 0)
643
644 /**
645  * EXPECT_STREQ(expected, seen)
646  *
647  * @expected: expected value
648  * @seen: measured value
649  *
650  * EXPECT_STREQ(expected, measured): !strcmp(expected, measured)
651  */
652 #define EXPECT_STREQ(expected, seen) \
653         __EXPECT_STR(expected, seen, ==, 0)
654
655 /**
656  * EXPECT_STRNE(expected, seen)
657  *
658  * @expected: expected value
659  * @seen: measured value
660  *
661  * EXPECT_STRNE(expected, measured): strcmp(expected, measured)
662  */
663 #define EXPECT_STRNE(expected, seen) \
664         __EXPECT_STR(expected, seen, !=, 0)
665
666 #define ARRAY_SIZE(a)   (sizeof(a) / sizeof(a[0]))
667
668 /* Support an optional handler after and ASSERT_* or EXPECT_*.  The approach is
669  * not thread-safe, but it should be fine in most sane test scenarios.
670  *
671  * Using __bail(), which optionally abort()s, is the easiest way to early
672  * return while still providing an optional block to the API consumer.
673  */
674 #define OPTIONAL_HANDLER(_assert) \
675         for (; _metadata->trigger; _metadata->trigger = \
676                         __bail(_assert, _metadata->no_print, _metadata->step))
677
678 #define __INC_STEP(_metadata) \
679         if (_metadata->passed && _metadata->step < 255) \
680                 _metadata->step++;
681
682 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \
683         /* Avoid multiple evaluation of the cases */ \
684         __typeof__(_expected) __exp = (_expected); \
685         __typeof__(_seen) __seen = (_seen); \
686         if (_assert) __INC_STEP(_metadata); \
687         if (!(__exp _t __seen)) { \
688                 unsigned long long __exp_print = (uintptr_t)__exp; \
689                 unsigned long long __seen_print = (uintptr_t)__seen; \
690                 __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
691                          _expected_str, __exp_print, #_t, \
692                          _seen_str, __seen_print); \
693                 _metadata->passed = 0; \
694                 /* Ensure the optional handler is triggered */ \
695                 _metadata->trigger = 1; \
696         } \
697 } while (0); OPTIONAL_HANDLER(_assert)
698
699 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
700         const char *__exp = (_expected); \
701         const char *__seen = (_seen); \
702         if (_assert) __INC_STEP(_metadata); \
703         if (!(strcmp(__exp, __seen) _t 0))  { \
704                 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
705                 _metadata->passed = 0; \
706                 _metadata->trigger = 1; \
707         } \
708 } while (0); OPTIONAL_HANDLER(_assert)
709
710 /* List helpers */
711 #define __LIST_APPEND(head, item) \
712 { \
713         /* Circular linked list where only prev is circular. */ \
714         if (head == NULL) { \
715                 head = item; \
716                 item->next = NULL; \
717                 item->prev = item; \
718                 return; \
719         } \
720         if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \
721                 item->next = NULL; \
722                 item->prev = head->prev; \
723                 item->prev->next = item; \
724                 head->prev = item; \
725         } else { \
726                 item->next = head; \
727                 item->next->prev = item; \
728                 item->prev = item; \
729                 head = item; \
730         } \
731 }
732
733 struct __test_metadata;
734 struct __fixture_variant_metadata;
735
736 /* Contains all the information about a fixture. */
737 struct __fixture_metadata {
738         const char *name;
739         struct __test_metadata *tests;
740         struct __fixture_variant_metadata *variant;
741         struct __fixture_metadata *prev, *next;
742 } _fixture_global __attribute__((unused)) = {
743         .name = "global",
744         .prev = &_fixture_global,
745 };
746
747 static struct __fixture_metadata *__fixture_list = &_fixture_global;
748 static int __constructor_order;
749
750 #define _CONSTRUCTOR_ORDER_FORWARD   1
751 #define _CONSTRUCTOR_ORDER_BACKWARD -1
752
753 static inline void __register_fixture(struct __fixture_metadata *f)
754 {
755         __LIST_APPEND(__fixture_list, f);
756 }
757
758 struct __fixture_variant_metadata {
759         const char *name;
760         const void *data;
761         struct __fixture_variant_metadata *prev, *next;
762 };
763
764 static inline void
765 __register_fixture_variant(struct __fixture_metadata *f,
766                            struct __fixture_variant_metadata *variant)
767 {
768         __LIST_APPEND(f->variant, variant);
769 }
770
771 /* Contains all the information for test execution and status checking. */
772 struct __test_metadata {
773         const char *name;
774         void (*fn)(struct __test_metadata *,
775                    struct __fixture_variant_metadata *);
776         pid_t pid;      /* pid of test when being run */
777         struct __fixture_metadata *fixture;
778         int termsig;
779         int passed;
780         int skip;       /* did SKIP get used? */
781         int trigger; /* extra handler after the evaluation */
782         int timeout;    /* seconds to wait for test timeout */
783         bool timed_out; /* did this test timeout instead of exiting? */
784         __u8 step;
785         bool no_print; /* manual trigger when TH_LOG_STREAM is not available */
786         struct __test_metadata *prev, *next;
787 };
788
789 /*
790  * Since constructors are called in reverse order, reverse the test
791  * list so tests are run in source declaration order.
792  * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
793  * However, it seems not all toolchains do this correctly, so use
794  * __constructor_order to detect which direction is called first
795  * and adjust list building logic to get things running in the right
796  * direction.
797  */
798 static inline void __register_test(struct __test_metadata *t)
799 {
800         __LIST_APPEND(t->fixture->tests, t);
801 }
802
803 static inline int __bail(int for_realz, bool no_print, __u8 step)
804 {
805         if (for_realz) {
806                 if (no_print)
807                         _exit(step);
808                 abort();
809         }
810         return 0;
811 }
812
813 struct __test_metadata *__active_test;
814 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext)
815 {
816         struct __test_metadata *t = __active_test;
817
818         /* Sanity check handler execution environment. */
819         if (!t) {
820                 fprintf(TH_LOG_STREAM,
821                         "# no active test in SIGALRM handler!?\n");
822                 abort();
823         }
824         if (sig != SIGALRM || sig != info->si_signo) {
825                 fprintf(TH_LOG_STREAM,
826                         "# %s: SIGALRM handler caught signal %d!?\n",
827                         t->name, sig != SIGALRM ? sig : info->si_signo);
828                 abort();
829         }
830
831         t->timed_out = true;
832         kill(t->pid, SIGKILL);
833 }
834
835 void __wait_for_test(struct __test_metadata *t)
836 {
837         struct sigaction action = {
838                 .sa_sigaction = __timeout_handler,
839                 .sa_flags = SA_SIGINFO,
840         };
841         struct sigaction saved_action;
842         int status;
843
844         if (sigaction(SIGALRM, &action, &saved_action)) {
845                 t->passed = 0;
846                 fprintf(TH_LOG_STREAM,
847                         "# %s: unable to install SIGALRM handler\n",
848                         t->name);
849                 return;
850         }
851         __active_test = t;
852         t->timed_out = false;
853         alarm(t->timeout);
854         waitpid(t->pid, &status, 0);
855         alarm(0);
856         if (sigaction(SIGALRM, &saved_action, NULL)) {
857                 t->passed = 0;
858                 fprintf(TH_LOG_STREAM,
859                         "# %s: unable to uninstall SIGALRM handler\n",
860                         t->name);
861                 return;
862         }
863         __active_test = NULL;
864
865         if (t->timed_out) {
866                 t->passed = 0;
867                 fprintf(TH_LOG_STREAM,
868                         "# %s: Test terminated by timeout\n", t->name);
869         } else if (WIFEXITED(status)) {
870                 if (t->termsig != -1) {
871                         t->passed = 0;
872                         fprintf(TH_LOG_STREAM,
873                                 "# %s: Test exited normally instead of by signal (code: %d)\n",
874                                 t->name,
875                                 WEXITSTATUS(status));
876                 } else {
877                         switch (WEXITSTATUS(status)) {
878                         /* Success */
879                         case 0:
880                                 t->passed = 1;
881                                 break;
882                         /* SKIP */
883                         case 255:
884                                 t->passed = 1;
885                                 t->skip = 1;
886                                 break;
887                         /* Other failure, assume step report. */
888                         default:
889                                 t->passed = 0;
890                                 fprintf(TH_LOG_STREAM,
891                                         "# %s: Test failed at step #%d\n",
892                                         t->name,
893                                         WEXITSTATUS(status));
894                         }
895                 }
896         } else if (WIFSIGNALED(status)) {
897                 t->passed = 0;
898                 if (WTERMSIG(status) == SIGABRT) {
899                         fprintf(TH_LOG_STREAM,
900                                 "# %s: Test terminated by assertion\n",
901                                 t->name);
902                 } else if (WTERMSIG(status) == t->termsig) {
903                         t->passed = 1;
904                 } else {
905                         fprintf(TH_LOG_STREAM,
906                                 "# %s: Test terminated unexpectedly by signal %d\n",
907                                 t->name,
908                                 WTERMSIG(status));
909                 }
910         } else {
911                 fprintf(TH_LOG_STREAM,
912                         "# %s: Test ended in some other way [%u]\n",
913                         t->name,
914                         status);
915         }
916 }
917
918 void __run_test(struct __fixture_metadata *f,
919                 struct __fixture_variant_metadata *variant,
920                 struct __test_metadata *t)
921 {
922         /* reset test struct */
923         t->passed = 1;
924         t->skip = 0;
925         t->trigger = 0;
926         t->step = 0;
927         t->no_print = 0;
928
929         ksft_print_msg(" RUN           %s%s%s.%s ...\n",
930                f->name, variant->name[0] ? "." : "", variant->name, t->name);
931         t->pid = fork();
932         if (t->pid < 0) {
933                 ksft_print_msg("ERROR SPAWNING TEST CHILD\n");
934                 t->passed = 0;
935         } else if (t->pid == 0) {
936                 t->fn(t, variant);
937                 /* Make sure step doesn't get lost in reporting */
938                 if (t->step >= 255) {
939                         ksft_print_msg("Too many test steps (%u)!?\n", t->step);
940                         t->step = 254;
941                 }
942                 /* Use 255 for SKIP */
943                 if (t->skip)
944                         _exit(255);
945                 /* Pass is exit 0 */
946                 if (t->passed)
947                         _exit(0);
948                 /* Something else happened, report the step. */
949                 _exit(t->step);
950         } else {
951                 __wait_for_test(t);
952         }
953         ksft_print_msg("         %4s  %s%s%s.%s\n", t->passed ? "OK" : "FAIL",
954                f->name, variant->name[0] ? "." : "", variant->name, t->name);
955
956         if (t->skip)
957                 ksft_test_result_skip("%s%s%s.%s\n",
958                         f->name, variant->name[0] ? "." : "", variant->name, t->name);
959         else
960                 ksft_test_result(t->passed, "%s%s%s.%s\n",
961                         f->name, variant->name[0] ? "." : "", variant->name, t->name);
962 }
963
964 static int test_harness_run(int __attribute__((unused)) argc,
965                             char __attribute__((unused)) **argv)
966 {
967         struct __fixture_variant_metadata no_variant = { .name = "", };
968         struct __fixture_variant_metadata *v;
969         struct __fixture_metadata *f;
970         struct __test_metadata *t;
971         int ret = 0;
972         unsigned int case_count = 0, test_count = 0;
973         unsigned int count = 0;
974         unsigned int pass_count = 0;
975
976         for (f = __fixture_list; f; f = f->next) {
977                 for (v = f->variant ?: &no_variant; v; v = v->next) {
978                         case_count++;
979                         for (t = f->tests; t; t = t->next)
980                                 test_count++;
981                 }
982         }
983
984         ksft_print_header();
985         ksft_set_plan(test_count);
986         ksft_print_msg("Starting %u tests from %u test cases.\n",
987                test_count, case_count);
988         for (f = __fixture_list; f; f = f->next) {
989                 for (v = f->variant ?: &no_variant; v; v = v->next) {
990                         for (t = f->tests; t; t = t->next) {
991                                 count++;
992                                 __run_test(f, v, t);
993                                 if (t->passed)
994                                         pass_count++;
995                                 else
996                                         ret = 1;
997                         }
998                 }
999         }
1000         ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED",
1001                         pass_count, count);
1002         ksft_exit(ret == 0);
1003
1004         /* unreachable */
1005         return KSFT_FAIL;
1006 }
1007
1008 static void __attribute__((constructor)) __constructor_order_first(void)
1009 {
1010         if (!__constructor_order)
1011                 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
1012 }
1013
1014 #endif  /* __KSELFTEST_HARNESS_H */