1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * An API to allow a function, that may fail, to be executed, and recover in a
4  * controlled manner.
5  *
6  * Copyright (C) 2019, Google LLC.
7  * Author: Brendan Higgins <brendanhiggins@google.com>
8  */
9 
10 #ifndef _KUNIT_TRY_CATCH_H
11 #define _KUNIT_TRY_CATCH_H
12 
13 #include <linux/types.h>
14 #include <linux/android_kabi.h>
15 
16 typedef void (*kunit_try_catch_func_t)(void *);
17 
18 struct kunit;
19 
20 /**
21  * struct kunit_try_catch - provides a generic way to run code which might fail.
22  * @test: The test case that is currently being executed.
23  * @try_result: Contains any errno obtained while running test case.
24  * @try: The function, the test case, to attempt to run.
25  * @catch: The function called if @try bails out.
26  * @context: used to pass user data to the try and catch functions.
27  *
28  * kunit_try_catch provides a generic, architecture independent way to execute
29  * an arbitrary function of type kunit_try_catch_func_t which may bail out by
30  * calling kunit_try_catch_throw(). If kunit_try_catch_throw() is called, @try
31  * is stopped at the site of invocation and @catch is called.
32  *
33  * struct kunit_try_catch provides a generic interface for the functionality
34  * needed to implement kunit->abort() which in turn is needed for implementing
35  * assertions. Assertions allow stating a precondition for a test simplifying
36  * how test cases are written and presented.
37  *
38  * Assertions are like expectations, except they abort (call
39  * kunit_try_catch_throw()) when the specified condition is not met. This is
40  * useful when you look at a test case as a logical statement about some piece
41  * of code, where assertions are the premises for the test case, and the
42  * conclusion is a set of predicates, rather expectations, that must all be
43  * true. If your premises are violated, it does not makes sense to continue.
44  */
45 struct kunit_try_catch {
46 	/* private: internal use only. */
47 	struct kunit *test;
48 	int try_result;
49 	kunit_try_catch_func_t try;
50 	kunit_try_catch_func_t catch;
51 	void *context;
52 
53 	ANDROID_KABI_RESERVE(1);
54 };
55 
56 void kunit_try_catch_run(struct kunit_try_catch *try_catch, void *context);
57 
58 void __noreturn kunit_try_catch_throw(struct kunit_try_catch *try_catch);
59 
kunit_try_catch_get_result(struct kunit_try_catch * try_catch)60 static inline int kunit_try_catch_get_result(struct kunit_try_catch *try_catch)
61 {
62 	return try_catch->try_result;
63 }
64 
65 #endif /* _KUNIT_TRY_CATCH_H */
66