1 /*
2 * Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy of
5 * this software and associated documentation files (the "Software"), to deal in
6 * the Software without restriction, including without limitation the rights to
7 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 * the Software, and to permit persons to whom the Software is furnished to do so,
9 * subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 */
21
22 /*
23 * How to catch an assert:
24 * - save a jump buffer where execution will resume after the assert
25 * - setup a handler for the abort signal, call longjmp within
26 * - optional - close stderr ( fd 2 ) to discard the assert message
27 *
28 * Unity also does a longjmp within its TEST_ASSERT* macros,
29 * so the macro below restores stderr and the prior abort handler
30 * before calling the Unity macro.
31 */
32
33 #ifndef CATCH_ASSERT_H_
34 #define CATCH_ASSERT_H_
35
36 #include <setjmp.h>
37 #include <signal.h>
38 #include <unistd.h>
39
40 #ifndef CATCH_JMPBUF
41 #define CATCH_JMPBUF waypoint_
42 #endif
43
44 static jmp_buf CATCH_JMPBUF;
45
46 #pragma GCC diagnostic push
47 #pragma GCC diagnostic ignored "-Wunused-function"
catchHandler_(int signal)48 static void catchHandler_( int signal )
49 {
50 longjmp( CATCH_JMPBUF, signal );
51 }
52 #pragma GCC diagnostic pop
53
54 #define catch_assert( x ) \
55 do { \
56 int ltry = 0, lcatch = 0; \
57 int saveFd = dup( 2 ); \
58 struct sigaction sa = { 0 }, saveSa; \
59 sa.sa_handler = catchHandler_; \
60 sigaction( SIGABRT, &sa, &saveSa ); \
61 close( 2 ); \
62 if( setjmp( CATCH_JMPBUF ) == 0 ) \
63 { \
64 ltry++; \
65 x; \
66 } \
67 else \
68 { \
69 lcatch++; \
70 } \
71 sigaction( SIGABRT, &saveSa, NULL ); \
72 dup2( saveFd, 2 ); \
73 close( saveFd ); \
74 TEST_ASSERT_EQUAL( ltry, lcatch ); \
75 } while( 0 )
76
77 #endif /* ifndef CATCH_ASSERT_H_ */
78