s2n_atomic.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #include "utils/s2n_atomic.h"
  16. #include <signal.h>
  17. #include "utils/s2n_safety.h"
  18. static sig_atomic_t set_val = true;
  19. static sig_atomic_t clear_val = false;
  20. S2N_RESULT s2n_atomic_init()
  21. {
  22. #if S2N_ATOMIC_SUPPORTED && S2N_THREAD_SANITIZER
  23. RESULT_ENSURE(__atomic_always_lock_free(sizeof(s2n_atomic_flag), NULL), S2N_ERR_ATOMIC);
  24. #endif
  25. return S2N_RESULT_OK;
  26. }
  27. void s2n_atomic_flag_set(s2n_atomic_flag *var)
  28. {
  29. #if S2N_ATOMIC_SUPPORTED && S2N_THREAD_SANITIZER
  30. __atomic_store(&var->val, &set_val, __ATOMIC_RELAXED);
  31. #else
  32. var->val = set_val;
  33. #endif
  34. }
  35. void s2n_atomic_flag_clear(s2n_atomic_flag *var)
  36. {
  37. #if S2N_ATOMIC_SUPPORTED && S2N_THREAD_SANITIZER
  38. __atomic_store(&var->val, &clear_val, __ATOMIC_RELAXED);
  39. #else
  40. var->val = clear_val;
  41. #endif
  42. }
  43. bool s2n_atomic_flag_test(s2n_atomic_flag *var)
  44. {
  45. #if S2N_ATOMIC_SUPPORTED && S2N_THREAD_SANITIZER
  46. sig_atomic_t result = 0;
  47. __atomic_load(&var->val, &result, __ATOMIC_RELAXED);
  48. return result;
  49. #else
  50. return var->val;
  51. #endif
  52. }