refcount_lock.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 <stdlib.h>
  16. #include <openssl/type_check.h>
  17. #if !defined(OPENSSL_C11_ATOMIC)
  18. OPENSSL_STATIC_ASSERT((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX,
  19. "CRYPTO_REFCOUNT_MAX is incorrect");
  20. static struct CRYPTO_STATIC_MUTEX g_refcount_lock = CRYPTO_STATIC_MUTEX_INIT;
  21. void CRYPTO_refcount_inc(CRYPTO_refcount_t *count) {
  22. CRYPTO_STATIC_MUTEX_lock_write(&g_refcount_lock);
  23. if (*count < CRYPTO_REFCOUNT_MAX) {
  24. (*count)++;
  25. }
  26. CRYPTO_STATIC_MUTEX_unlock_write(&g_refcount_lock);
  27. }
  28. int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count) {
  29. int ret;
  30. CRYPTO_STATIC_MUTEX_lock_write(&g_refcount_lock);
  31. if (*count == 0) {
  32. abort();
  33. }
  34. if (*count < CRYPTO_REFCOUNT_MAX) {
  35. (*count)--;
  36. }
  37. ret = (*count == 0);
  38. CRYPTO_STATIC_MUTEX_unlock_write(&g_refcount_lock);
  39. return ret;
  40. }
  41. #endif // OPENSSL_C11_ATOMIC