1 // Copyright 2015 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "internal.h"
16
17 #include <gtest/gtest.h>
18
19 #if defined(OPENSSL_THREADS)
20 #include <thread>
21 #endif
22
23
TEST(RefCountTest,Basic)24 TEST(RefCountTest, Basic) {
25 CRYPTO_refcount_t count = 0;
26
27 CRYPTO_refcount_inc(&count);
28 EXPECT_EQ(1u, count);
29
30 EXPECT_TRUE(CRYPTO_refcount_dec_and_test_zero(&count));
31 EXPECT_EQ(0u, count);
32
33 count = CRYPTO_REFCOUNT_MAX;
34 CRYPTO_refcount_inc(&count);
35 EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
36 << "Count did not saturate correctly when incrementing.";
37 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
38 EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
39 << "Count did not saturate correctly when decrementing.";
40
41 count = 2;
42 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
43 EXPECT_EQ(1u, count);
44 }
45
46 #if defined(OPENSSL_THREADS)
47 // This test is primarily intended to run under ThreadSanitizer.
TEST(RefCountTest,Threads)48 TEST(RefCountTest, Threads) {
49 CRYPTO_refcount_t count = 0;
50
51 // Race two increments.
52 {
53 std::thread thread([&] { CRYPTO_refcount_inc(&count); });
54 CRYPTO_refcount_inc(&count);
55 thread.join();
56 EXPECT_EQ(2u, count);
57 }
58
59 // Race an increment with a decrement.
60 {
61 std::thread thread([&] { CRYPTO_refcount_inc(&count); });
62 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
63 thread.join();
64 EXPECT_EQ(2u, count);
65 }
66
67 // Race two decrements.
68 {
69 bool thread_saw_zero;
70 std::thread thread(
71 [&] { thread_saw_zero = CRYPTO_refcount_dec_and_test_zero(&count); });
72 bool saw_zero = CRYPTO_refcount_dec_and_test_zero(&count);
73 thread.join();
74 EXPECT_EQ(0u, count);
75 // Exactly one thread should see zero.
76 EXPECT_NE(saw_zero, thread_saw_zero);
77 }
78 }
79 #endif
80