• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2015, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
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