xref: /linux/tools/testing/selftests/kselftest_harness.h (revision eb01fe7abbe2d0b38824d2a93fdb4cc3eaf2ccc1)
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 <limits.h>
60 #include <stdbool.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <sys/mman.h>
66 #include <sys/types.h>
67 #include <sys/wait.h>
68 #include <unistd.h>
69 #include <setjmp.h>
70 
71 #include "kselftest.h"
72 
73 #define TEST_TIMEOUT_DEFAULT 30
74 
75 /* Utilities exposed to the test definitions */
76 #ifndef TH_LOG_STREAM
77 #  define TH_LOG_STREAM stderr
78 #endif
79 
80 #ifndef TH_LOG_ENABLED
81 #  define TH_LOG_ENABLED 1
82 #endif
83 
84 /**
85  * TH_LOG()
86  *
87  * @fmt: format string
88  * @...: optional arguments
89  *
90  * .. code-block:: c
91  *
92  *     TH_LOG(format, ...)
93  *
94  * Optional debug logging function available for use in tests.
95  * Logging may be enabled or disabled by defining TH_LOG_ENABLED.
96  * E.g., #define TH_LOG_ENABLED 1
97  *
98  * If no definition is provided, logging is enabled by default.
99  */
100 #define TH_LOG(fmt, ...) do { \
101 	if (TH_LOG_ENABLED) \
102 		__TH_LOG(fmt, ##__VA_ARGS__); \
103 } while (0)
104 
105 /* Unconditional logger for internal use. */
106 #define __TH_LOG(fmt, ...) \
107 		fprintf(TH_LOG_STREAM, "# %s:%d:%s:" fmt "\n", \
108 			__FILE__, __LINE__, _metadata->name, ##__VA_ARGS__)
109 
110 /**
111  * SKIP()
112  *
113  * @statement: statement to run after reporting SKIP
114  * @fmt: format string
115  * @...: optional arguments
116  *
117  * .. code-block:: c
118  *
119  *     SKIP(statement, fmt, ...);
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 	snprintf(_metadata->results->reason, \
126 		 sizeof(_metadata->results->reason), fmt, ##__VA_ARGS__); \
127 	if (TH_LOG_ENABLED) { \
128 		fprintf(TH_LOG_STREAM, "#      SKIP      %s\n", \
129 			_metadata->results->reason); \
130 	} \
131 	_metadata->exit_code = KSFT_SKIP; \
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 		int status = 0; \
386 		memset(&self, 0, sizeof(FIXTURE_DATA(fixture_name))); \
387 		if (setjmp(_metadata->env) == 0) { \
388 			/* Use the same _metadata. */ \
389 			child = vfork(); \
390 			if (child == 0) { \
391 				fixture_name##_setup(_metadata, &self, variant->data); \
392 				/* Let setup failure terminate early. */ \
393 				if (_metadata->exit_code) \
394 					_exit(0); \
395 				_metadata->setup_completed = true; \
396 				fixture_name##_##test_name(_metadata, &self, variant->data); \
397 			} else if (child < 0 || child != waitpid(child, &status, 0)) { \
398 				ksft_print_msg("ERROR SPAWNING TEST GRANDCHILD\n"); \
399 				_metadata->exit_code = KSFT_FAIL; \
400 			} \
401 		} \
402 		if (child == 0) { \
403 			if (_metadata->setup_completed && !_metadata->teardown_parent) \
404 				fixture_name##_teardown(_metadata, &self, variant->data); \
405 			_exit(0); \
406 		} \
407 		if (_metadata->setup_completed && _metadata->teardown_parent) \
408 			fixture_name##_teardown(_metadata, &self, variant->data); \
409 		if (!WIFEXITED(status) && WIFSIGNALED(status)) \
410 			/* Forward signal to __wait_for_test(). */ \
411 			kill(getpid(), WTERMSIG(status)); \
412 		__test_check_assert(_metadata); \
413 	} \
414 	static struct __test_metadata \
415 		      _##fixture_name##_##test_name##_object = { \
416 		.name = #test_name, \
417 		.fn = &wrapper_##fixture_name##_##test_name, \
418 		.fixture = &_##fixture_name##_fixture_object, \
419 		.termsig = signal, \
420 		.timeout = tmout, \
421 		.teardown_parent = false, \
422 	 }; \
423 	static void __attribute__((constructor)) \
424 			_register_##fixture_name##_##test_name(void) \
425 	{ \
426 		__register_test(&_##fixture_name##_##test_name##_object); \
427 	} \
428 	static void fixture_name##_##test_name( \
429 		struct __test_metadata __attribute__((unused)) *_metadata, \
430 		FIXTURE_DATA(fixture_name) __attribute__((unused)) *self, \
431 		const FIXTURE_VARIANT(fixture_name) \
432 			__attribute__((unused)) *variant)
433 
434 /**
435  * TEST_HARNESS_MAIN - Simple wrapper to run the test harness
436  *
437  * .. code-block:: c
438  *
439  *     TEST_HARNESS_MAIN
440  *
441  * Use once to append a main() to the test file.
442  */
443 #define TEST_HARNESS_MAIN \
444 	static void __attribute__((constructor)) \
445 	__constructor_order_last(void) \
446 	{ \
447 		if (!__constructor_order) \
448 			__constructor_order = _CONSTRUCTOR_ORDER_BACKWARD; \
449 	} \
450 	int main(int argc, char **argv) { \
451 		return test_harness_run(argc, argv); \
452 	}
453 
454 /**
455  * DOC: operators
456  *
457  * Operators for use in TEST() and TEST_F().
458  * ASSERT_* calls will stop test execution immediately.
459  * EXPECT_* calls will emit a failure warning, note it, and continue.
460  */
461 
462 /**
463  * ASSERT_EQ()
464  *
465  * @expected: expected value
466  * @seen: measured value
467  *
468  * ASSERT_EQ(expected, measured): expected == measured
469  */
470 #define ASSERT_EQ(expected, seen) \
471 	__EXPECT(expected, #expected, seen, #seen, ==, 1)
472 
473 /**
474  * ASSERT_NE()
475  *
476  * @expected: expected value
477  * @seen: measured value
478  *
479  * ASSERT_NE(expected, measured): expected != measured
480  */
481 #define ASSERT_NE(expected, seen) \
482 	__EXPECT(expected, #expected, seen, #seen, !=, 1)
483 
484 /**
485  * ASSERT_LT()
486  *
487  * @expected: expected value
488  * @seen: measured value
489  *
490  * ASSERT_LT(expected, measured): expected < measured
491  */
492 #define ASSERT_LT(expected, seen) \
493 	__EXPECT(expected, #expected, seen, #seen, <, 1)
494 
495 /**
496  * ASSERT_LE()
497  *
498  * @expected: expected value
499  * @seen: measured value
500  *
501  * ASSERT_LE(expected, measured): expected <= measured
502  */
503 #define ASSERT_LE(expected, seen) \
504 	__EXPECT(expected, #expected, seen, #seen, <=, 1)
505 
506 /**
507  * ASSERT_GT()
508  *
509  * @expected: expected value
510  * @seen: measured value
511  *
512  * ASSERT_GT(expected, measured): expected > measured
513  */
514 #define ASSERT_GT(expected, seen) \
515 	__EXPECT(expected, #expected, seen, #seen, >, 1)
516 
517 /**
518  * ASSERT_GE()
519  *
520  * @expected: expected value
521  * @seen: measured value
522  *
523  * ASSERT_GE(expected, measured): expected >= measured
524  */
525 #define ASSERT_GE(expected, seen) \
526 	__EXPECT(expected, #expected, seen, #seen, >=, 1)
527 
528 /**
529  * ASSERT_NULL()
530  *
531  * @seen: measured value
532  *
533  * ASSERT_NULL(measured): NULL == measured
534  */
535 #define ASSERT_NULL(seen) \
536 	__EXPECT(NULL, "NULL", seen, #seen, ==, 1)
537 
538 /**
539  * ASSERT_TRUE()
540  *
541  * @seen: measured value
542  *
543  * ASSERT_TRUE(measured): measured != 0
544  */
545 #define ASSERT_TRUE(seen) \
546 	__EXPECT(0, "0", seen, #seen, !=, 1)
547 
548 /**
549  * ASSERT_FALSE()
550  *
551  * @seen: measured value
552  *
553  * ASSERT_FALSE(measured): measured == 0
554  */
555 #define ASSERT_FALSE(seen) \
556 	__EXPECT(0, "0", seen, #seen, ==, 1)
557 
558 /**
559  * ASSERT_STREQ()
560  *
561  * @expected: expected value
562  * @seen: measured value
563  *
564  * ASSERT_STREQ(expected, measured): !strcmp(expected, measured)
565  */
566 #define ASSERT_STREQ(expected, seen) \
567 	__EXPECT_STR(expected, seen, ==, 1)
568 
569 /**
570  * ASSERT_STRNE()
571  *
572  * @expected: expected value
573  * @seen: measured value
574  *
575  * ASSERT_STRNE(expected, measured): strcmp(expected, measured)
576  */
577 #define ASSERT_STRNE(expected, seen) \
578 	__EXPECT_STR(expected, seen, !=, 1)
579 
580 /**
581  * EXPECT_EQ()
582  *
583  * @expected: expected value
584  * @seen: measured value
585  *
586  * EXPECT_EQ(expected, measured): expected == measured
587  */
588 #define EXPECT_EQ(expected, seen) \
589 	__EXPECT(expected, #expected, seen, #seen, ==, 0)
590 
591 /**
592  * EXPECT_NE()
593  *
594  * @expected: expected value
595  * @seen: measured value
596  *
597  * EXPECT_NE(expected, measured): expected != measured
598  */
599 #define EXPECT_NE(expected, seen) \
600 	__EXPECT(expected, #expected, seen, #seen, !=, 0)
601 
602 /**
603  * EXPECT_LT()
604  *
605  * @expected: expected value
606  * @seen: measured value
607  *
608  * EXPECT_LT(expected, measured): expected < measured
609  */
610 #define EXPECT_LT(expected, seen) \
611 	__EXPECT(expected, #expected, seen, #seen, <, 0)
612 
613 /**
614  * EXPECT_LE()
615  *
616  * @expected: expected value
617  * @seen: measured value
618  *
619  * EXPECT_LE(expected, measured): expected <= measured
620  */
621 #define EXPECT_LE(expected, seen) \
622 	__EXPECT(expected, #expected, seen, #seen, <=, 0)
623 
624 /**
625  * EXPECT_GT()
626  *
627  * @expected: expected value
628  * @seen: measured value
629  *
630  * EXPECT_GT(expected, measured): expected > measured
631  */
632 #define EXPECT_GT(expected, seen) \
633 	__EXPECT(expected, #expected, seen, #seen, >, 0)
634 
635 /**
636  * EXPECT_GE()
637  *
638  * @expected: expected value
639  * @seen: measured value
640  *
641  * EXPECT_GE(expected, measured): expected >= measured
642  */
643 #define EXPECT_GE(expected, seen) \
644 	__EXPECT(expected, #expected, seen, #seen, >=, 0)
645 
646 /**
647  * EXPECT_NULL()
648  *
649  * @seen: measured value
650  *
651  * EXPECT_NULL(measured): NULL == measured
652  */
653 #define EXPECT_NULL(seen) \
654 	__EXPECT(NULL, "NULL", seen, #seen, ==, 0)
655 
656 /**
657  * EXPECT_TRUE()
658  *
659  * @seen: measured value
660  *
661  * EXPECT_TRUE(measured): 0 != measured
662  */
663 #define EXPECT_TRUE(seen) \
664 	__EXPECT(0, "0", seen, #seen, !=, 0)
665 
666 /**
667  * EXPECT_FALSE()
668  *
669  * @seen: measured value
670  *
671  * EXPECT_FALSE(measured): 0 == measured
672  */
673 #define EXPECT_FALSE(seen) \
674 	__EXPECT(0, "0", seen, #seen, ==, 0)
675 
676 /**
677  * EXPECT_STREQ()
678  *
679  * @expected: expected value
680  * @seen: measured value
681  *
682  * EXPECT_STREQ(expected, measured): !strcmp(expected, measured)
683  */
684 #define EXPECT_STREQ(expected, seen) \
685 	__EXPECT_STR(expected, seen, ==, 0)
686 
687 /**
688  * EXPECT_STRNE()
689  *
690  * @expected: expected value
691  * @seen: measured value
692  *
693  * EXPECT_STRNE(expected, measured): strcmp(expected, measured)
694  */
695 #define EXPECT_STRNE(expected, seen) \
696 	__EXPECT_STR(expected, seen, !=, 0)
697 
698 #ifndef ARRAY_SIZE
699 #define ARRAY_SIZE(a)	(sizeof(a) / sizeof(a[0]))
700 #endif
701 
702 /* Support an optional handler after and ASSERT_* or EXPECT_*.  The approach is
703  * not thread-safe, but it should be fine in most sane test scenarios.
704  *
705  * Using __bail(), which optionally abort()s, is the easiest way to early
706  * return while still providing an optional block to the API consumer.
707  */
708 #define OPTIONAL_HANDLER(_assert) \
709 	for (; _metadata->trigger; _metadata->trigger = \
710 			__bail(_assert, _metadata))
711 
712 #define is_signed_type(var)       (!!(((__typeof__(var))(-1)) < (__typeof__(var))1))
713 
714 #define __EXPECT(_expected, _expected_str, _seen, _seen_str, _t, _assert) do { \
715 	/* Avoid multiple evaluation of the cases */ \
716 	__typeof__(_expected) __exp = (_expected); \
717 	__typeof__(_seen) __seen = (_seen); \
718 	if (!(__exp _t __seen)) { \
719 		/* Report with actual signedness to avoid weird output. */ \
720 		switch (is_signed_type(__exp) * 2 + is_signed_type(__seen)) { \
721 		case 0: { \
722 			unsigned long long __exp_print = (uintptr_t)__exp; \
723 			unsigned long long __seen_print = (uintptr_t)__seen; \
724 			__TH_LOG("Expected %s (%llu) %s %s (%llu)", \
725 				 _expected_str, __exp_print, #_t, \
726 				 _seen_str, __seen_print); \
727 			break; \
728 			} \
729 		case 1: { \
730 			unsigned long long __exp_print = (uintptr_t)__exp; \
731 			long long __seen_print = (intptr_t)__seen; \
732 			__TH_LOG("Expected %s (%llu) %s %s (%lld)", \
733 				 _expected_str, __exp_print, #_t, \
734 				 _seen_str, __seen_print); \
735 			break; \
736 			} \
737 		case 2: { \
738 			long long __exp_print = (intptr_t)__exp; \
739 			unsigned long long __seen_print = (uintptr_t)__seen; \
740 			__TH_LOG("Expected %s (%lld) %s %s (%llu)", \
741 				 _expected_str, __exp_print, #_t, \
742 				 _seen_str, __seen_print); \
743 			break; \
744 			} \
745 		case 3: { \
746 			long long __exp_print = (intptr_t)__exp; \
747 			long long __seen_print = (intptr_t)__seen; \
748 			__TH_LOG("Expected %s (%lld) %s %s (%lld)", \
749 				 _expected_str, __exp_print, #_t, \
750 				 _seen_str, __seen_print); \
751 			break; \
752 			} \
753 		} \
754 		_metadata->exit_code = KSFT_FAIL; \
755 		/* Ensure the optional handler is triggered */ \
756 		_metadata->trigger = 1; \
757 	} \
758 } while (0); OPTIONAL_HANDLER(_assert)
759 
760 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
761 	const char *__exp = (_expected); \
762 	const char *__seen = (_seen); \
763 	if (!(strcmp(__exp, __seen) _t 0))  { \
764 		__TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
765 		_metadata->exit_code = KSFT_FAIL; \
766 		_metadata->trigger = 1; \
767 	} \
768 } while (0); OPTIONAL_HANDLER(_assert)
769 
770 /* List helpers */
771 #define __LIST_APPEND(head, item) \
772 { \
773 	/* Circular linked list where only prev is circular. */ \
774 	if (head == NULL) { \
775 		head = item; \
776 		item->next = NULL; \
777 		item->prev = item; \
778 		return;	\
779 	} \
780 	if (__constructor_order == _CONSTRUCTOR_ORDER_FORWARD) { \
781 		item->next = NULL; \
782 		item->prev = head->prev; \
783 		item->prev->next = item; \
784 		head->prev = item; \
785 	} else { \
786 		item->next = head; \
787 		item->next->prev = item; \
788 		item->prev = item; \
789 		head = item; \
790 	} \
791 }
792 
793 struct __test_results {
794 	char reason[1024];	/* Reason for test result */
795 };
796 
797 struct __test_metadata;
798 struct __fixture_variant_metadata;
799 
800 /* Contains all the information about a fixture. */
801 struct __fixture_metadata {
802 	const char *name;
803 	struct __test_metadata *tests;
804 	struct __fixture_variant_metadata *variant;
805 	struct __fixture_metadata *prev, *next;
806 } _fixture_global __attribute__((unused)) = {
807 	.name = "global",
808 	.prev = &_fixture_global,
809 };
810 
811 struct __test_xfail {
812 	struct __fixture_metadata *fixture;
813 	struct __fixture_variant_metadata *variant;
814 	struct __test_metadata *test;
815 	struct __test_xfail *prev, *next;
816 };
817 
818 /**
819  * XFAIL_ADD() - mark variant + test case combination as expected to fail
820  * @fixture_name: name of the fixture
821  * @variant_name: name of the variant
822  * @test_name: name of the test case
823  *
824  * Mark a combination of variant + test case for a given fixture as expected
825  * to fail. Tests marked this way will report XPASS / XFAIL return codes,
826  * instead of PASS / FAIL,and use respective counters.
827  */
828 #define XFAIL_ADD(fixture_name, variant_name, test_name) \
829 	static struct __test_xfail \
830 		_##fixture_name##_##variant_name##_##test_name##_xfail = \
831 	{ \
832 		.fixture = &_##fixture_name##_fixture_object, \
833 		.variant = &_##fixture_name##_##variant_name##_object, \
834 		.test = &_##fixture_name##_##test_name##_object, \
835 	}; \
836 	static void __attribute__((constructor)) \
837 		_register_##fixture_name##_##variant_name##_##test_name##_xfail(void) \
838 	{ \
839 		__register_xfail(&_##fixture_name##_##variant_name##_##test_name##_xfail); \
840 	}
841 
842 static struct __fixture_metadata *__fixture_list = &_fixture_global;
843 static int __constructor_order;
844 
845 #define _CONSTRUCTOR_ORDER_FORWARD   1
846 #define _CONSTRUCTOR_ORDER_BACKWARD -1
847 
848 static inline void __register_fixture(struct __fixture_metadata *f)
849 {
850 	__LIST_APPEND(__fixture_list, f);
851 }
852 
853 struct __fixture_variant_metadata {
854 	const char *name;
855 	const void *data;
856 	struct __test_xfail *xfails;
857 	struct __fixture_variant_metadata *prev, *next;
858 };
859 
860 static inline void
861 __register_fixture_variant(struct __fixture_metadata *f,
862 			   struct __fixture_variant_metadata *variant)
863 {
864 	__LIST_APPEND(f->variant, variant);
865 }
866 
867 /* Contains all the information for test execution and status checking. */
868 struct __test_metadata {
869 	const char *name;
870 	void (*fn)(struct __test_metadata *,
871 		   struct __fixture_variant_metadata *);
872 	pid_t pid;	/* pid of test when being run */
873 	struct __fixture_metadata *fixture;
874 	int termsig;
875 	int exit_code;
876 	int trigger; /* extra handler after the evaluation */
877 	int timeout;	/* seconds to wait for test timeout */
878 	bool timed_out;	/* did this test timeout instead of exiting? */
879 	bool aborted;	/* stopped test due to failed ASSERT */
880 	bool setup_completed; /* did setup finish? */
881 	bool teardown_parent; /* run teardown in a parent process */
882 	jmp_buf env;	/* for exiting out of test early */
883 	struct __test_results *results;
884 	struct __test_metadata *prev, *next;
885 };
886 
887 static inline bool __test_passed(struct __test_metadata *metadata)
888 {
889 	return metadata->exit_code != KSFT_FAIL &&
890 	       metadata->exit_code <= KSFT_SKIP;
891 }
892 
893 /*
894  * Since constructors are called in reverse order, reverse the test
895  * list so tests are run in source declaration order.
896  * https://gcc.gnu.org/onlinedocs/gccint/Initialization.html
897  * However, it seems not all toolchains do this correctly, so use
898  * __constructor_order to detect which direction is called first
899  * and adjust list building logic to get things running in the right
900  * direction.
901  */
902 static inline void __register_test(struct __test_metadata *t)
903 {
904 	__LIST_APPEND(t->fixture->tests, t);
905 }
906 
907 static inline void __register_xfail(struct __test_xfail *xf)
908 {
909 	__LIST_APPEND(xf->variant->xfails, xf);
910 }
911 
912 static inline int __bail(int for_realz, struct __test_metadata *t)
913 {
914 	/* if this is ASSERT, return immediately. */
915 	if (for_realz) {
916 		t->aborted = true;
917 		longjmp(t->env, 1);
918 	}
919 	/* otherwise, end the for loop and continue. */
920 	return 0;
921 }
922 
923 static inline void __test_check_assert(struct __test_metadata *t)
924 {
925 	if (t->aborted)
926 		abort();
927 }
928 
929 struct __test_metadata *__active_test;
930 static void __timeout_handler(int sig, siginfo_t *info, void *ucontext)
931 {
932 	struct __test_metadata *t = __active_test;
933 
934 	/* Sanity check handler execution environment. */
935 	if (!t) {
936 		fprintf(TH_LOG_STREAM,
937 			"# no active test in SIGALRM handler!?\n");
938 		abort();
939 	}
940 	if (sig != SIGALRM || sig != info->si_signo) {
941 		fprintf(TH_LOG_STREAM,
942 			"# %s: SIGALRM handler caught signal %d!?\n",
943 			t->name, sig != SIGALRM ? sig : info->si_signo);
944 		abort();
945 	}
946 
947 	t->timed_out = true;
948 	// signal process group
949 	kill(-(t->pid), SIGKILL);
950 }
951 
952 void __wait_for_test(struct __test_metadata *t)
953 {
954 	struct sigaction action = {
955 		.sa_sigaction = __timeout_handler,
956 		.sa_flags = SA_SIGINFO,
957 	};
958 	struct sigaction saved_action;
959 	int status;
960 
961 	if (sigaction(SIGALRM, &action, &saved_action)) {
962 		t->exit_code = KSFT_FAIL;
963 		fprintf(TH_LOG_STREAM,
964 			"# %s: unable to install SIGALRM handler\n",
965 			t->name);
966 		return;
967 	}
968 	__active_test = t;
969 	t->timed_out = false;
970 	alarm(t->timeout);
971 	waitpid(t->pid, &status, 0);
972 	alarm(0);
973 	if (sigaction(SIGALRM, &saved_action, NULL)) {
974 		t->exit_code = KSFT_FAIL;
975 		fprintf(TH_LOG_STREAM,
976 			"# %s: unable to uninstall SIGALRM handler\n",
977 			t->name);
978 		return;
979 	}
980 	__active_test = NULL;
981 
982 	if (t->timed_out) {
983 		t->exit_code = KSFT_FAIL;
984 		fprintf(TH_LOG_STREAM,
985 			"# %s: Test terminated by timeout\n", t->name);
986 	} else if (WIFEXITED(status)) {
987 		if (WEXITSTATUS(status) == KSFT_SKIP ||
988 		    WEXITSTATUS(status) == KSFT_XPASS ||
989 		    WEXITSTATUS(status) == KSFT_XFAIL) {
990 			t->exit_code = WEXITSTATUS(status);
991 		} else if (t->termsig != -1) {
992 			t->exit_code = KSFT_FAIL;
993 			fprintf(TH_LOG_STREAM,
994 				"# %s: Test exited normally instead of by signal (code: %d)\n",
995 				t->name,
996 				WEXITSTATUS(status));
997 		} else {
998 			switch (WEXITSTATUS(status)) {
999 			/* Success */
1000 			case KSFT_PASS:
1001 				t->exit_code = KSFT_PASS;
1002 				break;
1003 			/* Failure */
1004 			default:
1005 				t->exit_code = KSFT_FAIL;
1006 				fprintf(TH_LOG_STREAM,
1007 					"# %s: Test failed\n",
1008 					t->name);
1009 			}
1010 		}
1011 	} else if (WIFSIGNALED(status)) {
1012 		t->exit_code = KSFT_FAIL;
1013 		if (WTERMSIG(status) == SIGABRT) {
1014 			fprintf(TH_LOG_STREAM,
1015 				"# %s: Test terminated by assertion\n",
1016 				t->name);
1017 		} else if (WTERMSIG(status) == t->termsig) {
1018 			t->exit_code = KSFT_PASS;
1019 		} else {
1020 			fprintf(TH_LOG_STREAM,
1021 				"# %s: Test terminated unexpectedly by signal %d\n",
1022 				t->name,
1023 				WTERMSIG(status));
1024 		}
1025 	} else {
1026 		fprintf(TH_LOG_STREAM,
1027 			"# %s: Test ended in some other way [%u]\n",
1028 			t->name,
1029 			status);
1030 	}
1031 }
1032 
1033 static void test_harness_list_tests(void)
1034 {
1035 	struct __fixture_variant_metadata *v;
1036 	struct __fixture_metadata *f;
1037 	struct __test_metadata *t;
1038 
1039 	for (f = __fixture_list; f; f = f->next) {
1040 		v = f->variant;
1041 		t = f->tests;
1042 
1043 		if (f == __fixture_list)
1044 			fprintf(stderr, "%-20s %-25s %s\n",
1045 				"# FIXTURE", "VARIANT", "TEST");
1046 		else
1047 			fprintf(stderr, "--------------------------------------------------------------------------------\n");
1048 
1049 		do {
1050 			fprintf(stderr, "%-20s %-25s %s\n",
1051 				t == f->tests ? f->name : "",
1052 				v ? v->name : "",
1053 				t ? t->name : "");
1054 
1055 			v = v ? v->next : NULL;
1056 			t = t ? t->next : NULL;
1057 		} while (v || t);
1058 	}
1059 }
1060 
1061 static int test_harness_argv_check(int argc, char **argv)
1062 {
1063 	int opt;
1064 
1065 	while ((opt = getopt(argc, argv, "hlF:f:V:v:t:T:r:")) != -1) {
1066 		switch (opt) {
1067 		case 'f':
1068 		case 'F':
1069 		case 'v':
1070 		case 'V':
1071 		case 't':
1072 		case 'T':
1073 		case 'r':
1074 			break;
1075 		case 'l':
1076 			test_harness_list_tests();
1077 			return KSFT_SKIP;
1078 		case 'h':
1079 		default:
1080 			fprintf(stderr,
1081 				"Usage: %s [-h|-l] [-t|-T|-v|-V|-f|-F|-r name]\n"
1082 				"\t-h       print help\n"
1083 				"\t-l       list all tests\n"
1084 				"\n"
1085 				"\t-t name  include test\n"
1086 				"\t-T name  exclude test\n"
1087 				"\t-v name  include variant\n"
1088 				"\t-V name  exclude variant\n"
1089 				"\t-f name  include fixture\n"
1090 				"\t-F name  exclude fixture\n"
1091 				"\t-r name  run specified test\n"
1092 				"\n"
1093 				"Test filter options can be specified "
1094 				"multiple times. The filtering stops\n"
1095 				"at the first match. For example to "
1096 				"include all tests from variant 'bla'\n"
1097 				"but not test 'foo' specify '-T foo -v bla'.\n"
1098 				"", argv[0]);
1099 			return opt == 'h' ? KSFT_SKIP : KSFT_FAIL;
1100 		}
1101 	}
1102 
1103 	return KSFT_PASS;
1104 }
1105 
1106 static bool test_enabled(int argc, char **argv,
1107 			 struct __fixture_metadata *f,
1108 			 struct __fixture_variant_metadata *v,
1109 			 struct __test_metadata *t)
1110 {
1111 	unsigned int flen = 0, vlen = 0, tlen = 0;
1112 	bool has_positive = false;
1113 	int opt;
1114 
1115 	optind = 1;
1116 	while ((opt = getopt(argc, argv, "F:f:V:v:t:T:r:")) != -1) {
1117 		has_positive |= islower(opt);
1118 
1119 		switch (tolower(opt)) {
1120 		case 't':
1121 			if (!strcmp(t->name, optarg))
1122 				return islower(opt);
1123 			break;
1124 		case 'f':
1125 			if (!strcmp(f->name, optarg))
1126 				return islower(opt);
1127 			break;
1128 		case 'v':
1129 			if (!strcmp(v->name, optarg))
1130 				return islower(opt);
1131 			break;
1132 		case 'r':
1133 			if (!tlen) {
1134 				flen = strlen(f->name);
1135 				vlen = strlen(v->name);
1136 				tlen = strlen(t->name);
1137 			}
1138 			if (strlen(optarg) == flen + 1 + vlen + !!vlen + tlen &&
1139 			    !strncmp(f->name, &optarg[0], flen) &&
1140 			    !strncmp(v->name, &optarg[flen + 1], vlen) &&
1141 			    !strncmp(t->name, &optarg[flen + 1 + vlen + !!vlen], tlen))
1142 				return true;
1143 			break;
1144 		}
1145 	}
1146 
1147 	/*
1148 	 * If there are no positive tests then we assume user just wants
1149 	 * exclusions and everything else is a pass.
1150 	 */
1151 	return !has_positive;
1152 }
1153 
1154 void __run_test(struct __fixture_metadata *f,
1155 		struct __fixture_variant_metadata *variant,
1156 		struct __test_metadata *t)
1157 {
1158 	struct __test_xfail *xfail;
1159 	char test_name[LINE_MAX];
1160 	const char *diagnostic;
1161 
1162 	/* reset test struct */
1163 	t->exit_code = KSFT_PASS;
1164 	t->trigger = 0;
1165 	memset(t->results->reason, 0, sizeof(t->results->reason));
1166 
1167 	snprintf(test_name, sizeof(test_name), "%s%s%s.%s",
1168 		 f->name, variant->name[0] ? "." : "", variant->name, t->name);
1169 
1170 	ksft_print_msg(" RUN           %s ...\n", test_name);
1171 
1172 	/* Make sure output buffers are flushed before fork */
1173 	fflush(stdout);
1174 	fflush(stderr);
1175 
1176 	t->pid = fork();
1177 	if (t->pid < 0) {
1178 		ksft_print_msg("ERROR SPAWNING TEST CHILD\n");
1179 		t->exit_code = KSFT_FAIL;
1180 	} else if (t->pid == 0) {
1181 		setpgrp();
1182 		t->fn(t, variant);
1183 		_exit(t->exit_code);
1184 	} else {
1185 		__wait_for_test(t);
1186 	}
1187 	ksft_print_msg("         %4s  %s\n",
1188 		       __test_passed(t) ? "OK" : "FAIL", test_name);
1189 
1190 	/* Check if we're expecting this test to fail */
1191 	for (xfail = variant->xfails; xfail; xfail = xfail->next)
1192 		if (xfail->test == t)
1193 			break;
1194 	if (xfail)
1195 		t->exit_code = __test_passed(t) ? KSFT_XPASS : KSFT_XFAIL;
1196 
1197 	if (t->results->reason[0])
1198 		diagnostic = t->results->reason;
1199 	else if (t->exit_code == KSFT_PASS || t->exit_code == KSFT_FAIL)
1200 		diagnostic = NULL;
1201 	else
1202 		diagnostic = "unknown";
1203 
1204 	ksft_test_result_code(t->exit_code, test_name,
1205 			      diagnostic ? "%s" : "", diagnostic);
1206 }
1207 
1208 static int test_harness_run(int argc, char **argv)
1209 {
1210 	struct __fixture_variant_metadata no_variant = { .name = "", };
1211 	struct __fixture_variant_metadata *v;
1212 	struct __fixture_metadata *f;
1213 	struct __test_results *results;
1214 	struct __test_metadata *t;
1215 	int ret;
1216 	unsigned int case_count = 0, test_count = 0;
1217 	unsigned int count = 0;
1218 	unsigned int pass_count = 0;
1219 
1220 	ret = test_harness_argv_check(argc, argv);
1221 	if (ret != KSFT_PASS)
1222 		return ret;
1223 
1224 	for (f = __fixture_list; f; f = f->next) {
1225 		for (v = f->variant ?: &no_variant; v; v = v->next) {
1226 			unsigned int old_tests = test_count;
1227 
1228 			for (t = f->tests; t; t = t->next)
1229 				if (test_enabled(argc, argv, f, v, t))
1230 					test_count++;
1231 
1232 			if (old_tests != test_count)
1233 				case_count++;
1234 		}
1235 	}
1236 
1237 	results = mmap(NULL, sizeof(*results), PROT_READ | PROT_WRITE,
1238 		       MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1239 
1240 	ksft_print_header();
1241 	ksft_set_plan(test_count);
1242 	ksft_print_msg("Starting %u tests from %u test cases.\n",
1243 	       test_count, case_count);
1244 	for (f = __fixture_list; f; f = f->next) {
1245 		for (v = f->variant ?: &no_variant; v; v = v->next) {
1246 			for (t = f->tests; t; t = t->next) {
1247 				if (!test_enabled(argc, argv, f, v, t))
1248 					continue;
1249 				count++;
1250 				t->results = results;
1251 				__run_test(f, v, t);
1252 				t->results = NULL;
1253 				if (__test_passed(t))
1254 					pass_count++;
1255 				else
1256 					ret = 1;
1257 			}
1258 		}
1259 	}
1260 	munmap(results, sizeof(*results));
1261 
1262 	ksft_print_msg("%s: %u / %u tests passed.\n", ret ? "FAILED" : "PASSED",
1263 			pass_count, count);
1264 	ksft_exit(ret == 0);
1265 
1266 	/* unreachable */
1267 	return KSFT_FAIL;
1268 }
1269 
1270 static void __attribute__((constructor)) __constructor_order_first(void)
1271 {
1272 	if (!__constructor_order)
1273 		__constructor_order = _CONSTRUCTOR_ORDER_FORWARD;
1274 }
1275 
1276 #endif  /* __KSELFTEST_HARNESS_H */
1277