try-catch.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #ifndef _KUNIT_TRY_CATCH_H
  10. #define _KUNIT_TRY_CATCH_H
  11. #include <linux/types.h>
  12. typedef void (*kunit_try_catch_func_t)(void *);
  13. struct completion;
  14. struct kunit;
  15. /**
  16. * struct kunit_try_catch - provides a generic way to run code which might fail.
  17. * @test: The test case that is currently being executed.
  18. * @try_completion: Completion that the control thread waits on while test runs.
  19. * @try_result: Contains any errno obtained while running test case.
  20. * @try: The function, the test case, to attempt to run.
  21. * @catch: The function called if @try bails out.
  22. * @context: used to pass user data to the try and catch functions.
  23. *
  24. * kunit_try_catch provides a generic, architecture independent way to execute
  25. * an arbitrary function of type kunit_try_catch_func_t which may bail out by
  26. * calling kunit_try_catch_throw(). If kunit_try_catch_throw() is called, @try
  27. * is stopped at the site of invocation and @catch is called.
  28. *
  29. * struct kunit_try_catch provides a generic interface for the functionality
  30. * needed to implement kunit->abort() which in turn is needed for implementing
  31. * assertions. Assertions allow stating a precondition for a test simplifying
  32. * how test cases are written and presented.
  33. *
  34. * Assertions are like expectations, except they abort (call
  35. * kunit_try_catch_throw()) when the specified condition is not met. This is
  36. * useful when you look at a test case as a logical statement about some piece
  37. * of code, where assertions are the premises for the test case, and the
  38. * conclusion is a set of predicates, rather expectations, that must all be
  39. * true. If your premises are violated, it does not makes sense to continue.
  40. */
  41. struct kunit_try_catch {
  42. /* private: internal use only. */
  43. struct kunit *test;
  44. struct completion *try_completion;
  45. int try_result;
  46. kunit_try_catch_func_t try;
  47. kunit_try_catch_func_t catch;
  48. void *context;
  49. };
  50. void kunit_try_catch_run(struct kunit_try_catch *try_catch, void *context);
  51. void __noreturn kunit_try_catch_throw(struct kunit_try_catch *try_catch);
  52. static inline int kunit_try_catch_get_result(struct kunit_try_catch *try_catch)
  53. {
  54. return try_catch->try_result;
  55. }
  56. #endif /* _KUNIT_TRY_CATCH_H */