refcount_test.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #include "internal.h"
  15. #include <gtest/gtest.h>
  16. #if defined(OPENSSL_THREADS)
  17. #include <thread>
  18. #endif
  19. TEST(RefCountTest, Basic) {
  20. CRYPTO_refcount_t count = 0;
  21. CRYPTO_refcount_inc(&count);
  22. EXPECT_EQ(1u, count);
  23. EXPECT_TRUE(CRYPTO_refcount_dec_and_test_zero(&count));
  24. EXPECT_EQ(0u, count);
  25. count = CRYPTO_REFCOUNT_MAX;
  26. CRYPTO_refcount_inc(&count);
  27. EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
  28. << "Count did not saturate correctly when incrementing.";
  29. EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
  30. EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
  31. << "Count did not saturate correctly when decrementing.";
  32. count = 2;
  33. EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
  34. EXPECT_EQ(1u, count);
  35. }
  36. #if defined(OPENSSL_THREADS)
  37. // This test is primarily intended to run under ThreadSanitizer.
  38. TEST(RefCountTest, Threads) {
  39. CRYPTO_refcount_t count = 0;
  40. // Race two increments.
  41. {
  42. std::thread thread([&] { CRYPTO_refcount_inc(&count); });
  43. CRYPTO_refcount_inc(&count);
  44. thread.join();
  45. EXPECT_EQ(2u, count);
  46. }
  47. // Race an increment with a decrement.
  48. {
  49. std::thread thread([&] { CRYPTO_refcount_inc(&count); });
  50. EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
  51. thread.join();
  52. EXPECT_EQ(2u, count);
  53. }
  54. // Race two decrements.
  55. {
  56. bool thread_saw_zero;
  57. std::thread thread(
  58. [&] { thread_saw_zero = CRYPTO_refcount_dec_and_test_zero(&count); });
  59. bool saw_zero = CRYPTO_refcount_dec_and_test_zero(&count);
  60. thread.join();
  61. EXPECT_EQ(0u, count);
  62. // Exactly one thread should see zero.
  63. EXPECT_NE(saw_zero, thread_saw_zero);
  64. }
  65. }
  66. #endif