Debian Codegraph @

crt/s2n/tests/unit/s2n_cleanup_test.c

raw symbols SCIP
1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 #include <stdbool.h>
17
18 #include "api/s2n.h"
19 #include "s2n_test.h"
20 #include "utils/s2n_mem.h"
21 #include "utils/s2n_safety.h"
22
23 #define S2N_UNUSED(x) \
24 do { \
25 (void) x; \
26 } while (0)
27
28 struct foo {
29 int x;
30 int y;
31 };
32
33 int foo_cleanup_calls;
34
35 void foo_free(struct foo* p)
36 {
37 foo_cleanup_calls++;
38 }
39
40 DEFINE_POINTER_CLEANUP_FUNC(struct foo*, foo_free);
41
42 int check_cleanup_obj_on_fn_exit()
43 {
44 DEFER_CLEANUP(struct foo x = { 0 }, foo_free);
45 S2N_UNUSED(x);
46 return 0;
47 }
48
49 int check_cleanup_pointer_on_fn_exit()
50 {
51 struct foo thefoo = { 0 };
52 DEFER_CLEANUP(struct foo* foop = &thefoo, foo_free_pointer);
53 S2N_UNUSED(thefoo);
54 S2N_UNUSED(foop);
55 return 0;
56 }
57
58 /* check that our macros don't cleanup null objects */
59 int check_dont_cleanup_null_on_fn_exit()
60 {
61 DEFER_CLEANUP(struct foo* foop = NULL, foo_free_pointer);
62 S2N_UNUSED(foop);
63 return 0;
64 }
65
66 /* This test checks that the compiler correctly implements deferred cleanup */
67 int main()
68 {
69 BEGIN_TEST();
70 EXPECT_SUCCESS(s2n_disable_tls13_in_test());
71 int expected_cleanup_count = 0;
72
73 /* check that the cleanup functions are called on each loop exit */
74 for (int i = 0; i < 10; ++i) {
75 DEFER_CLEANUP(struct foo x = { i }, foo_free);
76 S2N_UNUSED(x);
77 EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count);
78 expected_cleanup_count++;
79 }
80
81 EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count);
82
83 EXPECT_SUCCESS(check_cleanup_obj_on_fn_exit());
84 expected_cleanup_count++;
85 EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count);
86
87 EXPECT_SUCCESS(check_cleanup_pointer_on_fn_exit());
88 expected_cleanup_count++;
89 EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count);
90
91 EXPECT_SUCCESS(check_dont_cleanup_null_on_fn_exit());
92 /* don't increment expected_cleanup_count */
93 EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count);
94
95 END_TEST();
96 }