selftests: kselftest_harness: use KSFT_* exit codes
[sfrench/cifs-2.6.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 <ctype.h>
58 #include <errno.h>
59 #include <stdbool.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <sys/mman.h>
65 #include <sys/types.h>
66 #include <sys/wait.h>
67 #include <unistd.h>
68 #include <setjmp.h>
69
70 #include "kselftest.h"
71
72 #define TEST_TIMEOUT_DEFAULT 30
73
74 /* Utilities exposed to the test definitions */
75 #ifndef TH_LOG_STREAM
76 #  define TH_LOG_STREAM stderr
77 #endif
78
79 #ifndef TH_LOG_ENABLED
80 #  define TH_LOG_ENABLED 1
81 #endif
82
83 /**
84  * TH_LOG()
85  *
86  * @fmt: format string
87  * @...: optional arguments
88  *
89  * .. code-block:: c
90  *
91  *     TH_LOG(format, ...)
92  *
93  * Optional debug logging function available for use in tests.
94  * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
95  * E.g., #define TH_LOG_ENABLED 1
96  *
97  * If no definition is provided, logging is enabled by default.
98  */
99 #define TH_LOG(fmt, ...) do { \
100         if (TH_LOG_ENABLED) \
101                 __TH_LOG(fmt, ##__VA_ARGS__); \
102 } while (0)
103
104 /* Unconditional logger for internal use. */
105 #define __TH_LOG(fmt, ...) \
106                 fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \
107                         __FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
108
109 /**
110  * SKIP()
111  *
112  * @statement: statement to run after reporting SKIP
113  * @fmt: format string
114  * @...: optional arguments
115  *
116  * .. code-block:: c
117  *
118  *     SKIP(statement, fmt, ...);
119  *
120  * This forces a "pass" after reporting why something is being skipped
121  * and runs "statement", which is usually "return" or "goto skip".
122  */
123 #define SKIP(statement, fmt, ...) do { \
124         snprintf(_metadata->results->reason, \
125                  sizeof(_metadata->results->reason), fmt, ##__VA_ARGS__); \
126         if (TH_LOG_ENABLED) { \
127                 fprintf(TH_LOG_STREAM, "#      SKIP      %s\n", \
128                         _metadata->results->reason); \
129         } \
130         _metadata->passed = 1; \
131         _metadata->skip = 1; \
132         _metadata->trigger = 0; \
133         statement; \
134 } while (0)
135
136 /**
137  * TEST() - Defines the test function and creates the registration
138  * stub
139  *
140  * @test_name: test name
141  *
142  * .. code-block:: c
143  *
144  *     TEST(name) { implementation }
145  *
146  * Defines a test by name.
147  * Names must be unique and tests must not be run in parallel.  The
148  * implementation containing block is a function and scoping should be treated
149  * as such.  Returning early may be performed with a bare "return;" statement.
150  *
151  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
152  */
153 #define TEST(test_name) __TEST_IMPL(test_name, -1)
154
155 /**
156  * TEST_SIGNAL()
157  *
158  * @test_name: test name
159  * @signal: signal number
160  *
161  * .. code-block:: c
162  *
163  *     TEST_SIGNAL(name, signal) { implementation }
164  *
165  * Defines a test by name and the expected term signal.
166  * Names must be unique and tests must not be run in parallel.  The
167  * implementation containing block is a function and scoping should be treated
168  * as such.  Returning early may be performed with a bare "return;" statement.
169  *
170  * EXPECT_* and ASSERT_* are valid in a TEST() { } context.
171  */
172 #define TEST_SIGNAL(test_name, signal) __TEST_IMPL(test_name, signal)
173
174 #define __TEST_IMPL(test_name, _signal) \
175         static void test_name(struct __test_metadata *_metadata); \
176         static inline void wrapper_##test_name( \
177                 struct __test_metadata *_metadata, \
178                 struct __fixture_variant_metadata *variant) \
179         { \
180                 _metadata->setup_completed = true; \
181                 if (setjmp(_metadata->env) == 0) \
182                         test_name(_metadata); \
183                 __test_check_assert(_metadata); \
184         } \
185         static struct __test_metadata _##test_name##_object = \
186                 { .name = #test_name, \
187                   .fn = &wrapper_##test_name, \
188                   .fixture = &_fixture_global, \
189                   .termsig = _signal, \
190                   .timeout = TEST_TIMEOUT_DEFAULT, }; \
191         static void __attribute__((constructor)) _register_##test_name(void) \
192         { \
193                 __register_test(&_##test_name##_object); \
194         } \
195         static void test_name( \
196                 struct __test_metadata __attribute__((unused)) *_metadata)
197
198 /**
199  * FIXTURE_DATA() - Wraps the struct name so we have one less
200  * argument to pass around
201  *
202  * @datatype_name: datatype name
203  *
204  * .. code-block:: c
205  *
206  *     FIXTURE_DATA(datatype_name)
207  *
208  * Almost always, you want just FIXTURE() instead (see below).
209  * This call may be used when the type of the fixture data
210  * is needed.  In general, this should not be needed unless
211  * the *self* is being passed to a helper directly.
212  */
213 #define FIXTURE_DATA(datatype_name) struct _test_data_##datatype_name
214
215 /**
216  * FIXTURE() - Called once per fixture to setup the data and
217  * register
218  *
219  * @fixture_name: fixture name
220  *
221  * .. code-block:: c
222  *
223  *     FIXTURE(fixture_name) {
224  *       type property1;
225  *       ...
226  *     };
227  *
228  * Defines the data provided to TEST_F()-defined tests as *self*.  It should be
229  * populated and cleaned up using FIXTURE_SETUP() and FIXTURE_TEARDOWN().
230  */
231 #define FIXTURE(fixture_name) \
232         FIXTURE_VARIANT(fixture_name); \
233         static struct __fixture_metadata _##fixture_name##_fixture_object = \
234                 { .name =  #fixture_name, }; \
235         static void __attribute__((constructor)) \
236         _register_##fixture_name##_data(void) \
237         { \
238                 __register_fixture(&_##fixture_name##_fixture_object); \
239         } \
240         FIXTURE_DATA(fixture_name)
241
242 /**
243  * FIXTURE_SETUP() - Prepares the setup function for the fixture.
244  * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly.
245  *
246  * @fixture_name: fixture name
247  *
248  * .. code-block:: c
249  *
250  *     FIXTURE_SETUP(fixture_name) { implementation }
251  *
252  * Populates the required "setup" function for a fixture.  An instance of the
253  * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
254  * implementation.
255  *
256  * ASSERT_* are valid for use in this context and will prempt the execution
257  * of any dependent fixture tests.
258  *
259  * A bare "return;" statement may be used to return early.
260  */
261 #define FIXTURE_SETUP(fixture_name) \
262         void fixture_name##_setup( \
263                 struct __test_metadata __attribute__((unused)) *_metadata, \
264                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
265                 const FIXTURE_VARIANT(fixture_name) \
266                         __attribute__((unused)) *variant)
267
268 /**
269  * FIXTURE_TEARDOWN()
270  * *_metadata* is included so that EXPECT_*, ASSERT_* etc. work correctly.
271  *
272  * @fixture_name: fixture name
273  *
274  * .. code-block:: c
275  *
276  *     FIXTURE_TEARDOWN(fixture_name) { implementation }
277  *
278  * Populates the required "teardown" function for a fixture.  An instance of the
279  * datatype defined with FIXTURE_DATA() will be exposed as *self* for the
280  * implementation to clean up.
281  *
282  * A bare "return;" statement may be used to return early.
283  */
284 #define FIXTURE_TEARDOWN(fixture_name) \
285         void fixture_name##_teardown( \
286                 struct __test_metadata __attribute__((unused)) *_metadata, \
287                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
288                 const FIXTURE_VARIANT(fixture_name) \
289                         __attribute__((unused)) *variant)
290
291 /**
292  * FIXTURE_VARIANT() - Optionally called once per fixture
293  * to declare fixture variant
294  *
295  * @fixture_name: fixture name
296  *
297  * .. code-block:: c
298  *
299  *     FIXTURE_VARIANT(fixture_name) {
300  *       type property1;
301  *       ...
302  *     };
303  *
304  * Defines type of constant parameters provided to FIXTURE_SETUP(), TEST_F() and
305  * FIXTURE_TEARDOWN as *variant*. Variants allow the same tests to be run with
306  * different arguments.
307  */
308 #define FIXTURE_VARIANT(fixture_name) struct _fixture_variant_##fixture_name
309
310 /**
311  * FIXTURE_VARIANT_ADD() - Called once per fixture
312  * variant to setup and register the data
313  *
314  * @fixture_name: fixture name
315  * @variant_name: name of the parameter set
316  *
317  * .. code-block:: c
318  *
319  *     FIXTURE_VARIANT_ADD(fixture_name, variant_name) {
320  *       .property1 = val1,
321  *       ...
322  *     };
323  *
324  * Defines a variant of the test fixture, provided to FIXTURE_SETUP() and
325  * TEST_F() as *variant*. Tests of each fixture will be run once for each
326  * variant.
327  */
328 #define FIXTURE_VARIANT_ADD(fixture_name, variant_name) \
329         extern FIXTURE_VARIANT(fixture_name) \
330                 _##fixture_name##_##variant_name##_variant; \
331         static struct __fixture_variant_metadata \
332                 _##fixture_name##_##variant_name##_object = \
333                 { .name = #variant_name, \
334                   .data = &_##fixture_name##_##variant_name##_variant}; \
335         static void __attribute__((constructor)) \
336                 _register_##fixture_name##_##variant_name(void) \
337         { \
338                 __register_fixture_variant(&_##fixture_name##_fixture_object, \
339                         &_##fixture_name##_##variant_name##_object);    \
340         } \
341         FIXTURE_VARIANT(fixture_name) \
342                 _##fixture_name##_##variant_name##_variant =
343
344 /**
345  * TEST_F() - Emits test registration and helpers for
346  * fixture-based test cases
347  *
348  * @fixture_name: fixture name
349  * @test_name: test name
350  *
351  * .. code-block:: c
352  *
353  *     TEST_F(fixture, name) { implementation }
354  *
355  * Defines a test that depends on a fixture (e.g., is part of a test case).
356  * Very similar to TEST() except that *self* is the setup instance of fixture's
357  * datatype exposed for use by the implementation.
358  *
359  * The @test_name code is run in a separate process sharing the same memory
360  * (i.e. vfork), which means that the test process can update its privileges
361  * without impacting the related FIXTURE_TEARDOWN() (e.g. to remove files from
362  * a directory where write access was dropped).
363  */
364 #define TEST_F(fixture_name, test_name) \
365         __TEST_F_IMPL(fixture_name, test_name, -1, TEST_TIMEOUT_DEFAULT)
366
367 #define TEST_F_SIGNAL(fixture_name, test_name, signal) \
368         __TEST_F_IMPL(fixture_name, test_name, signal, TEST_TIMEOUT_DEFAULT)
369
370 #define TEST_F_TIMEOUT(fixture_name, test_name, timeout) \
371         __TEST_F_IMPL(fixture_name, test_name, -1, timeout)
372
373 #define __TEST_F_IMPL(fixture_name, test_name, signal, tmout) \
374         static void fixture_name##_##test_name( \
375                 struct __test_metadata *_metadata, \
376                 FIXTURE_DATA(fixture_name) *self, \
377                 const FIXTURE_VARIANT(fixture_name) *variant); \
378         static inline void wrapper_##fixture_name##_##test_name( \
379                 struct __test_metadata *_metadata, \
380                 struct __fixture_variant_metadata *variant) \
381         { \
382                 /* fixture data is alloced, setup, and torn down per call. */ \
383                 FIXTURE_DATA(fixture_name) self; \
384                 pid_t child = 1; \
385                 memset(&self, 0, sizeof(FIXTURE_DATA(fixture_name))); \
386                 if (setjmp(_metadata->env) == 0) { \
387                         fixture_name##_setup(_metadata, &self, variant->data); \
388                         /* Let setup failure terminate early. */ \
389                         if (!_metadata->passed || _metadata->skip) \
390                                 return; \
391                         _metadata->setup_completed = true; \
392                         /* Use the same _metadata. */ \
393                         child = vfork(); \
394                         if (child == 0) { \
395                                 fixture_name##_##test_name(_metadata, &self, variant->data); \
396                                 _exit(0); \
397                         } \
398                         if (child < 0) { \
399                                 ksft_print_msg("ERROR SPAWNING TEST GRANDCHILD\n"); \
400                                 _metadata->passed = 0; \
401                         } \
402                 } \
403                 if (child == 0) \
404                         /* Child failed and updated the shared _metadata. */ \
405                         _exit(0); \
406                 if (_metadata->setup_completed) \
407                         fixture_name##_teardown(_metadata, &self, variant->data); \
408                 __test_check_assert(_metadata); \
409         } \
410         static struct __test_metadata \
411                       _##fixture_name##_##test_name##_object = { \
412                 .name = #test_name, \
413                 .fn = &wrapper_##fixture_name##_##test_name, \
414                 .fixture = &_##fixture_name##_fixture_object, \
415                 .termsig = signal, \
416                 .timeout = tmout, \
417          }; \
418         static void __attribute__((constructor)) \
419                         _register_##fixture_name##_##test_name(void) \
420         { \
421                 __register_test(&_##fixture_name##_##test_name##_object); \
422         } \
423         static void fixture_name##_##test_name( \
424                 struct __test_metadata __attribute__((unused)) *_metadata, \
425                 FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
426                 const FIXTURE_VARIANT(fixture_name) \
427                         __attribute__((unused)) *variant)
428
429 /**
430  * TEST_HARNESS_MAIN - Simple wrapper to run the test harness
431  *
432  * .. code-block:: c
433  *
434  *     TEST_HARNESS_MAIN
435  *
436  * Use once to append a main() to the test file.
437  */
438 #define TEST_HARNESS_MAIN \
439         static void __attribute__((constructor)) \
440         __constructor_order_last(void) \
441         { \
442                 if (!__constructor_order) \
443                         __constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
444         } \
445         int main(int argc, char **argv) { \
446                 return test_harness_run(argc, argv); \
447         }
448
449 /**
450  * DOC: operators
451  *
452  * Operators for use in TEST() and TEST_F().
453  * ASSERT_* calls will stop test execution immediately.
454  * EXPECT_* calls will emit a failure warning, note it, and continue.
455  */
456
457 /**
458  * ASSERT_EQ()
459  *
460  * @expected: expected value
461  * @seen: measured value
462  *
463  * ASSERT_EQ(expected, measured): expected == measured
464  */
465 #define ASSERT_EQ(expected, seen) \
466         __EXPECT(expected, #expected, seen, #seen, ==, 1)
467
468 /**
469  * ASSERT_NE()
470  *
471  * @expected: expected value
472  * @seen: measured value
473  *
474  * ASSERT_NE(expected, measured): expected != measured
475  */
476 #define ASSERT_NE(expected, seen) \
477         __EXPECT(expected, #expected, seen, #seen, !=, 1)
478
479 /**
480  * ASSERT_LT()
481  *
482  * @expected: expected value
483  * @seen: measured value
484  *
485  * ASSERT_LT(expected, measured): expected < measured
486  */
487 #define ASSERT_LT(expected, seen) \
488         __EXPECT(expected, #expected, seen, #seen, <, 1)
489
490 /**
491  * ASSERT_LE()
492  *
493  * @expected: expected value
494  * @seen: measured value
495  *
496  * ASSERT_LE(expected, measured): expected <= measured
497  */
498 #define ASSERT_LE(expected, seen) \
499         __EXPECT(expected, #expected, seen, #seen, <=, 1)
500
501 /**
502  * ASSERT_GT()
503  *
504  * @expected: expected value
505  * @seen: measured value
506  *
507  * ASSERT_GT(expected, measured): expected > measured
508  */
509 #define ASSERT_GT(expected, seen) \
510         __EXPECT(expected, #expected, seen, #seen, >, 1)
511
512 /**
513  * ASSERT_GE()
514  *
515  * @expected: expected value
516  * @seen: measured value
517  *
518  * ASSERT_GE(expected, measured): expected >= measured
519  */
520 #define ASSERT_GE(expected, seen) \
521         __EXPECT(expected, #expected, seen, #seen, >=, 1)
522
523 /**
524  * ASSERT_NULL()
525  *
526  * @seen: measured value
527  *
528  * ASSERT_NULL(measured): NULL == measured
529  */
530 #define ASSERT_NULL(seen) \
531         __EXPECT(NULL, "NULL", seen, #seen, ==, 1)
532
533 /**
534  * ASSERT_TRUE()
535  *
536  * @seen: measured value
537  *
538  * ASSERT_TRUE(measured): measured != 0
539  */
540 #define ASSERT_TRUE(seen) \
541         __EXPECT(0, "0", seen, #seen, !=, 1)
542
543 /**
544  * ASSERT_FALSE()
545  *
546  * @seen: measured value
547  *
548  * ASSERT_FALSE(measured): measured == 0
549  */
550 #define ASSERT_FALSE(seen) \
551         __EXPECT(0, "0", seen, #seen, ==, 1)
552
553 /**
554  * ASSERT_STREQ()
555  *
556  * @expected: expected value
557  * @seen: measured value
558  *
559  * ASSERT_STREQ(expected, measured): !strcmp(expected, measured)
560  */
561 #define ASSERT_STREQ(expected, seen) \
562         __EXPECT_STR(expected, seen, ==, 1)
563
564 /**
565  * ASSERT_STRNE()
566  *
567  * @expected: expected value
568  * @seen: measured value
569  *
570  * ASSERT_STRNE(expected, measured): strcmp(expected, measured)
571  */
572 #define ASSERT_STRNE(expected, seen) \
573         __EXPECT_STR(expected, seen, !=, 1)
574
575 /**
576  * EXPECT_EQ()
577  *
578  * @expected: expected value
579  * @seen: measured value
580  *
581  * EXPECT_EQ(expected, measured): expected == measured
582  */
583 #define EXPECT_EQ(expected, seen) \
584         __EXPECT(expected, #expected, seen, #seen, ==, 0)
585
586 /**
587  * EXPECT_NE()
588  *
589  * @expected: expected value
590  * @seen: measured value
591  *
592  * EXPECT_NE(expected, measured): expected != measured
593  */
594 #define EXPECT_NE(expected, seen) \
595         __EXPECT(expected, #expected, seen, #seen, !=, 0)
596
597 /**
598  * EXPECT_LT()
599  *
600  * @expected: expected value
601  * @seen: measured value
602  *
603  * EXPECT_LT(expected, measured): expected < measured
604  */
605 #define EXPECT_LT(expected, seen) \
606         __EXPECT(expected, #expected, seen, #seen, <, 0)
607
608 /**
609  * EXPECT_LE()
610  *
611  * @expected: expected value
612  * @seen: measured value
613  *
614  * EXPECT_LE(expected, measured): expected <= measured
615  */
616 #define EXPECT_LE(expected, seen) \
617         __EXPECT(expected, #expected, seen, #seen, <=, 0)
618
619 /**
620  * EXPECT_GT()
621  *
622  * @expected: expected value
623  * @seen: measured value
624  *
625  * EXPECT_GT(expected, measured): expected > measured
626  */
627 #define EXPECT_GT(expected, seen) \
628         __EXPECT(expected, #expected, seen, #seen, >, 0)
629
630 /**
631  * EXPECT_GE()
632  *
633  * @expected: expected value
634  * @seen: measured value
635  *
636  * EXPECT_GE(expected, measured): expected >= measured
637  */
638 #define EXPECT_GE(expected, seen) \
639         __EXPECT(expected, #expected, seen, #seen, >=, 0)
640
641 /**
642  * EXPECT_NULL()
643  *
644  * @seen: measured value
645  *
646  * EXPECT_NULL(measured): NULL == measured
647  */
648 #define EXPECT_NULL(seen) \
649         __EXPECT(NULL, "NULL", seen, #seen, ==, 0)
650
651 /**
652  * EXPECT_TRUE()
653  *
654  * @seen: measured value
655  *
656  * EXPECT_TRUE(measured): 0 != measured
657  */
658 #define EXPECT_TRUE(seen) \
659         __EXPECT(0, "0", seen, #seen, !=, 0)
660
661 /**
662  * EXPECT_FALSE()
663  *
664  * @seen: measured value
665  *
666  * EXPECT_FALSE(measured): 0 == measured
667  */
668 #define EXPECT_FALSE(seen) \
669         __EXPECT(0, "0", seen, #seen, ==, 0)
670
671 /**
672  * EXPECT_STREQ()
673  *
674  * @expected: expected value
675  * @seen: measured value
676  *
677  * EXPECT_STREQ(expected, measured): !strcmp(expected, measured)
678  */
679 #define EXPECT_STREQ(expected, seen) \
680         __EXPECT_STR(expected, seen, ==, 0)
681
682 /**
683  * EXPECT_STRNE()
684  *
685  * @expected: expected value
686  * @seen: measured value
687  *
688  * EXPECT_STRNE(expected, measured): strcmp(expected, measured)
689  */
690 #define EXPECT_STRNE(expected, seen) \
691         __EXPECT_STR(expected, seen, !=, 0)
692
693 #ifndef ARRAY_SIZE
694 #define ARRAY_SIZE(a)   (sizeof(a) / sizeof(a[0]))
695 #endif
696
697 /* Support an optional handler after and ASSERT_* or EXPECT_*.  The approach is
698  * not thread-safe, but it should be fine in most sane test scenarios.
699  *
700  * Using __bail(), which optionally abort()s, is the easiest way to early
701  * return while still providing an optional block to the API consumer.
702  */
703 #define OPTIONAL_HANDLER(_assert) \
704         for (; _metadata->trigger; _metadata->trigger = \
705                         __bail(_assert, _metadata))
706
707 #define is_signed_type(var)       (!!(((__typeof__(var))(-1)) < (__typeof__(var))1))
708
709 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \
710         /* Avoid multiple evaluation of the cases */ \
711         __typeof__(_expected) __exp = (_expected); \
712         __typeof__(_seen) __seen = (_seen); \
713         if (!(__exp _t __seen)) { \
714                 /* Report with actual signedness to avoid weird output. */ \
715                 switch (is_signed_type(__exp) * 2 + is_signed_type(__seen)) { \
716                 case 0: { \
717                         unsigned long long __exp_print = (uintptr_t)__exp; \
718                         unsigned long long __seen_print = (uintptr_t)__seen; \
719                         __TH_LOG("Expected %s (%llu) %s %s (%llu)", \
720                                  _expected_str, __exp_print, #_t, \
721                                  _seen_str, __seen_print); \
722                         break; \
723                         } \
724                 case 1: { \
725                         unsigned long long __exp_print = (uintptr_t)__exp; \
726                         long long __seen_print = (intptr_t)__seen; \
727                         __TH_LOG("Expected %s (%llu) %s %s (%lld)", \
728                                  _expected_str, __exp_print, #_t, \
729                                  _seen_str, __seen_print); \
730                         break; \
731                         } \
732                 case 2: { \
733                         long long __exp_print = (intptr_t)__exp; \
734                         unsigned long long __seen_print = (uintptr_t)__seen; \
735                         __TH_LOG("Expected %s (%lld) %s %s (%llu)", \
736                                  _expected_str, __exp_print, #_t, \
737                                  _seen_str, __seen_print); \
738                         break; \
739                         } \
740                 case 3: { \
741                         long long __exp_print = (intptr_t)__exp; \
742                         long long __seen_print = (intptr_t)__seen; \
743                         __TH_LOG("Expected %s (%lld) %s %s (%lld)", \
744                                  _expected_str, __exp_print, #_t, \
745                                  _seen_str, __seen_print); \
746                         break; \
747                         } \
748                 } \
749                 _metadata->passed = 0; \
750                 /* Ensure the optional handler is triggered */ \
751                 _metadata->trigger = 1; \
752         } \
753 } while (0); OPTIONAL_HANDLER(_assert)
754
755 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
756         const char *__exp = (_expected); \
757         const char *__seen = (_seen); \
758         if (!(strcmp(__exp, __seen) _t 0))  { \
759                 __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
760                 _metadata->passed = 0; \
761                 _metadata->trigger = 1; \
762         } \
763 } while (0); OPTIONAL_HANDLER(_assert)
764
765 /* List helpers */
766 #define __LIST_APPEND(head, item) \
767 { \
768         /* Circular linked list where only prev is circular. */ \
769         if (head == NULL) { \
770                 head = item; \
771                 item->next = NULL; \
772                 item->prev = item; \
773                 return; \
774         } \
775         if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \
776                 item->next = NULL; \
777                 item->prev = head->prev; \
778                 item->prev->next = item; \
779                 head->prev = item; \
780         } else { \
781                 item->next = head; \
782                 item->next->prev = item; \
783                 item->prev = item; \
784                 head = item; \
785         } \
786 }
787
788 struct __test_results {
789         char reason[1024];      /* Reason for test result */
790 };
791
792 struct __test_metadata;
793 struct __fixture_variant_metadata;
794
795 /* Contains all the information about a fixture. */
796 struct __fixture_metadata {
797         const char *name;
798         struct __test_metadata *tests;
799         struct __fixture_variant_metadata *variant;
800         struct __fixture_metadata *prev, *next;
801 } _fixture_global __attribute__((unused)) = {
802         .name = "global",
803         .prev = &_fixture_global,
804 };
805
806 static struct __fixture_metadata *__fixture_list = &_fixture_global;
807 static int __constructor_order;
808
809 #define _CONSTRUCTOR_ORDER_FORWARD   1
810 #define _CONSTRUCTOR_ORDER_BACKWARD -1
811
812 static inline void __register_fixture(struct __fixture_metadata *f)
813 {
814         __LIST_APPEND(__fixture_list, f);
815 }
816
817 struct __fixture_variant_metadata {
818         const char *name;
819         const void *data;
820         struct __fixture_variant_metadata *prev, *next;
821 };
822
823 static inline void
824 __register_fixture_variant(struct __fixture_metadata *f,
825                            struct __fixture_variant_metadata *variant)
826 {
827         __LIST_APPEND(f->variant, variant);
828 }
829
830 /* Contains all the information for test execution and status checking. */
831 struct __test_metadata {
832         const char *name;
833         void (*fn)(struct __test_metadata *,
834                    struct __fixture_variant_metadata *);
835         pid_t pid;      /* pid of test when being run */
836         struct __fixture_metadata *fixture;
837         int termsig;
838         int passed;
839         int skip;       /* did SKIP get used? */
840         int trigger; /* extra handler after the evaluation */
841         int timeout;    /* seconds to wait for test timeout */
842         bool timed_out; /* did this test timeout instead of exiting? */
843         bool aborted;   /* stopped test due to failed ASSERT */
844         bool setup_completed; /* did setup finish? */
845         jmp_buf env;    /* for exiting out of test early */
846         struct __test_results *results;
847         struct __test_metadata *prev, *next;
848 };
849
850 /*
851  * Since constructors are called in reverse order, reverse the test
852  * list so tests are run in source declaration order.
853  * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
854  * However, it seems not all toolchains do this correctly, so use
855  * __constructor_order to detect which direction is called first
856  * and adjust list building logic to get things running in the right
857  * direction.
858  */
859 static inline void __register_test(struct __test_metadata *t)
860 {
861         __LIST_APPEND(t->fixture->tests, t);
862 }
863
864 static inline int __bail(int for_realz, struct __test_metadata *t)
865 {
866         /* if this is ASSERT, return immediately. */
867         if (for_realz) {
868                 t->aborted = true;
869                 longjmp(t->env, 1);
870         }
871         /* otherwise, end the for loop and continue. */
872         return 0;
873 }
874
875 static inline void __test_check_assert(struct __test_metadata *t)
876 {
877         if (t->aborted)
878                 abort();
879 }
880
881 struct __test_metadata *__active_test;
882 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext)
883 {
884         struct __test_metadata *t = __active_test;
885
886         /* Sanity check handler execution environment. */
887         if (!t) {
888                 fprintf(TH_LOG_STREAM,
889                         "# no active test in SIGALRM handler!?\n");
890                 abort();
891         }
892         if (sig != SIGALRM || sig != info->si_signo) {
893                 fprintf(TH_LOG_STREAM,
894                         "# %s: SIGALRM handler caught signal %d!?\n",
895                         t->name, sig != SIGALRM ? sig : info->si_signo);
896                 abort();
897         }
898
899         t->timed_out = true;
900         // signal process group
901         kill(-(t->pid), SIGKILL);
902 }
903
904 void __wait_for_test(struct __test_metadata *t)
905 {
906         struct sigaction action = {
907                 .sa_sigaction = __timeout_handler,
908                 .sa_flags = SA_SIGINFO,
909         };
910         struct sigaction saved_action;
911         int status;
912
913         if (sigaction(SIGALRM, &action, &saved_action)) {
914                 t->passed = 0;
915                 fprintf(TH_LOG_STREAM,
916                         "# %s: unable to install SIGALRM handler\n",
917                         t->name);
918                 return;
919         }
920         __active_test = t;
921         t->timed_out = false;
922         alarm(t->timeout);
923         waitpid(t->pid, &status, 0);
924         alarm(0);
925         if (sigaction(SIGALRM, &saved_action, NULL)) {
926                 t->passed = 0;
927                 fprintf(TH_LOG_STREAM,
928                         "# %s: unable to uninstall SIGALRM handler\n",
929                         t->name);
930                 return;
931         }
932         __active_test = NULL;
933
934         if (t->timed_out) {
935                 t->passed = 0;
936                 fprintf(TH_LOG_STREAM,
937                         "# %s: Test terminated by timeout\n", t->name);
938         } else if (WIFEXITED(status)) {
939                 if (WEXITSTATUS(status) == KSFT_SKIP) {
940                         /* SKIP */
941                         t->passed = 1;
942                         t->skip = 1;
943                 } else if (t->termsig != -1) {
944                         t->passed = 0;
945                         fprintf(TH_LOG_STREAM,
946                                 "# %s: Test exited normally instead of by signal (code: %d)\n",
947                                 t->name,
948                                 WEXITSTATUS(status));
949                 } else {
950                         switch (WEXITSTATUS(status)) {
951                         /* Success */
952                         case KSFT_PASS:
953                                 t->passed = 1;
954                                 break;
955                         /* Failure */
956                         default:
957                                 t->passed = 0;
958                                 fprintf(TH_LOG_STREAM,
959                                         "# %s: Test failed\n",
960                                         t->name);
961                         }
962                 }
963         } else if (WIFSIGNALED(status)) {
964                 t->passed = 0;
965                 if (WTERMSIG(status) == SIGABRT) {
966                         fprintf(TH_LOG_STREAM,
967                                 "# %s: Test terminated by assertion\n",
968                                 t->name);
969                 } else if (WTERMSIG(status) == t->termsig) {
970                         t->passed = 1;
971                 } else {
972                         fprintf(TH_LOG_STREAM,
973                                 "# %s: Test terminated unexpectedly by signal %d\n",
974                                 t->name,
975                                 WTERMSIG(status));
976                 }
977         } else {
978                 fprintf(TH_LOG_STREAM,
979                         "# %s: Test ended in some other way [%u]\n",
980                         t->name,
981                         status);
982         }
983 }
984
985 static void test_harness_list_tests(void)
986 {
987         struct __fixture_variant_metadata *v;
988         struct __fixture_metadata *f;
989         struct __test_metadata *t;
990
991         for (f = __fixture_list; f; f = f->next) {
992                 v = f->variant;
993                 t = f->tests;
994
995                 if (f == __fixture_list)
996                         fprintf(stderr, "%-20s %-25s %s\n",
997                                 "# FIXTURE", "VARIANT", "TEST");
998                 else
999                         fprintf(stderr, "--------------------------------------------------------------------------------\n");
1000
1001                 do {
1002                         fprintf(stderr, "%-20s %-25s %s\n",
1003                                 t == f->tests ? f->name : "",
1004                                 v ? v->name : "",
1005                                 t ? t->name : "");
1006
1007                         v = v ? v->next : NULL;
1008                         t = t ? t->next : NULL;
1009                 } while (v || t);
1010         }
1011 }
1012
1013 static int test_harness_argv_check(int argc, char **argv)
1014 {
1015         int opt;
1016
1017         while ((opt = getopt(argc, argv, "hlF:f:V:v:t:T:r:")) != -1) {
1018                 switch (opt) {
1019                 case 'f':
1020                 case 'F':
1021                 case 'v':
1022                 case 'V':
1023                 case 't':
1024                 case 'T':
1025                 case 'r':
1026                         break;
1027                 case 'l':
1028                         test_harness_list_tests();
1029                         return KSFT_SKIP;
1030                 case 'h':
1031                 default:
1032                         fprintf(stderr,
1033                                 "Usage: %s [-h|-l] [-t|-T|-v|-V|-f|-F|-r name]\n"
1034                                 "\t-h       print help\n"
1035                                 "\t-l       list all tests\n"
1036                                 "\n"
1037                                 "\t-t name  include test\n"
1038                                 "\t-T name  exclude test\n"
1039                                 "\t-v name  include variant\n"
1040                                 "\t-V name  exclude variant\n"
1041                                 "\t-f name  include fixture\n"
1042                                 "\t-F name  exclude fixture\n"
1043                                 "\t-r name  run specified test\n"
1044                                 "\n"
1045                                 "Test filter options can be specified "
1046                                 "multiple times. The filtering stops\n"
1047                                 "at the first match. For example to "
1048                                 "include all tests from variant 'bla'\n"
1049                                 "but not test 'foo' specify '-T foo -v bla'.\n"
1050                                 "", argv[0]);
1051                         return opt == 'h' ? KSFT_SKIP : KSFT_FAIL;
1052                 }
1053         }
1054
1055         return KSFT_PASS;
1056 }
1057
1058 static bool test_enabled(int argc, char **argv,
1059                          struct __fixture_metadata *f,
1060                          struct __fixture_variant_metadata *v,
1061                          struct __test_metadata *t)
1062 {
1063         unsigned int flen = 0, vlen = 0, tlen = 0;
1064         bool has_positive = false;
1065         int opt;
1066
1067         optind = 1;
1068         while ((opt = getopt(argc, argv, "F:f:V:v:t:T:r:")) != -1) {
1069                 has_positive |= islower(opt);
1070
1071                 switch (tolower(opt)) {
1072                 case 't':
1073                         if (!strcmp(t->name, optarg))
1074                                 return islower(opt);
1075                         break;
1076                 case 'f':
1077                         if (!strcmp(f->name, optarg))
1078                                 return islower(opt);
1079                         break;
1080                 case 'v':
1081                         if (!strcmp(v->name, optarg))
1082                                 return islower(opt);
1083                         break;
1084                 case 'r':
1085                         if (!tlen) {
1086                                 flen = strlen(f->name);
1087                                 vlen = strlen(v->name);
1088                                 tlen = strlen(t->name);
1089                         }
1090                         if (strlen(optarg) == flen + 1 + vlen + !!vlen + tlen &&
1091                             !strncmp(f->name, &optarg[0], flen) &&
1092                             !strncmp(v->name, &optarg[flen + 1], vlen) &&
1093                             !strncmp(t->name, &optarg[flen + 1 + vlen + !!vlen], tlen))
1094                                 return true;
1095                         break;
1096                 }
1097         }
1098
1099         /*
1100          * If there are no positive tests then we assume user just wants
1101          * exclusions and everything else is a pass.
1102          */
1103         return !has_positive;
1104 }
1105
1106 void __run_test(struct __fixture_metadata *f,
1107                 struct __fixture_variant_metadata *variant,
1108                 struct __test_metadata *t)
1109 {
1110         /* reset test struct */
1111         t->passed = 1;
1112         t->skip = 0;
1113         t->trigger = 0;
1114         memset(t->results->reason, 0, sizeof(t->results->reason));
1115
1116         ksft_print_msg(" RUN           %s%s%s.%s ...\n",
1117                f->name, variant->name[0] ? "." : "", variant->name, t->name);
1118
1119         /* Make sure output buffers are flushed before fork */
1120         fflush(stdout);
1121         fflush(stderr);
1122
1123         t->pid = fork();
1124         if (t->pid < 0) {
1125                 ksft_print_msg("ERROR SPAWNING TEST CHILD\n");
1126                 t->passed = 0;
1127         } else if (t->pid == 0) {
1128                 setpgrp();
1129                 t->fn(t, variant);
1130                 if (t->skip)
1131                         _exit(KSFT_SKIP);
1132                 if (t->passed)
1133                         _exit(KSFT_PASS);
1134                 _exit(KSFT_FAIL);
1135         } else {
1136                 __wait_for_test(t);
1137         }
1138         ksft_print_msg("         %4s  %s%s%s.%s\n", t->passed ? "OK" : "FAIL",
1139                f->name, variant->name[0] ? "." : "", variant->name, t->name);
1140
1141         if (t->skip)
1142                 ksft_test_result_skip("%s\n", t->results->reason[0] ?
1143                                         t->results->reason : "unknown");
1144         else
1145                 ksft_test_result(t->passed, "%s%s%s.%s\n",
1146                         f->name, variant->name[0] ? "." : "", variant->name, t->name);
1147 }
1148
1149 static int test_harness_run(int argc, char **argv)
1150 {
1151         struct __fixture_variant_metadata no_variant = { .name = "", };
1152         struct __fixture_variant_metadata *v;
1153         struct __fixture_metadata *f;
1154         struct __test_results *results;
1155         struct __test_metadata *t;
1156         int ret;
1157         unsigned int case_count = 0, test_count = 0;
1158         unsigned int count = 0;
1159         unsigned int pass_count = 0;
1160
1161         ret = test_harness_argv_check(argc, argv);
1162         if (ret != KSFT_PASS)
1163                 return ret;
1164
1165         for (f = __fixture_list; f; f = f->next) {
1166                 for (v = f->variant ?: &no_variant; v; v = v->next) {
1167                         unsigned int old_tests = test_count;
1168
1169                         for (t = f->tests; t; t = t->next)
1170                                 if (test_enabled(argc, argv, f, v, t))
1171                                         test_count++;
1172
1173                         if (old_tests != test_count)
1174                                 case_count++;
1175                 }
1176         }
1177
1178         results = mmap(NULL, sizeof(*results), PROT_READ | PROT_WRITE,
1179                        MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1180
1181         ksft_print_header();
1182         ksft_set_plan(test_count);
1183         ksft_print_msg("Starting %u tests from %u test cases.\n",
1184                test_count, case_count);
1185         for (f = __fixture_list; f; f = f->next) {
1186                 for (v = f->variant ?: &no_variant; v; v = v->next) {
1187                         for (t = f->tests; t; t = t->next) {
1188                                 if (!test_enabled(argc, argv, f, v, t))
1189                                         continue;
1190                                 count++;
1191                                 t->results = results;
1192                                 __run_test(f, v, t);
1193                                 t->results = NULL;
1194                                 if (t->passed)
1195                                         pass_count++;
1196                                 else
1197                                         ret = 1;
1198                         }
1199                 }
1200         }
1201         munmap(results, sizeof(*results));
1202
1203         ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED",
1204                         pass_count, count);
1205         ksft_exit(ret == 0);
1206
1207         /* unreachable */
1208         return KSFT_FAIL;
1209 }
1210
1211 static void __attribute__((constructor)) __constructor_order_first(void)
1212 {
1213         if (!__constructor_order)
1214                 __constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
1215 }
1216
1217 #endif  /* __KSELFTEST_HARNESS_H */