1 /** 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 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 * http://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 16 #ifndef PANDA_RUNTIME_ASSERT_GC_SCOPE_H 17 #define PANDA_RUNTIME_ASSERT_GC_SCOPE_H 18 19 #include "macros.h" 20 21 #include <atomic> 22 23 namespace panda { 24 25 #ifndef NDEBUG 26 constexpr bool IS_GC_ALLOW_CHECK = true; 27 #else 28 constexpr bool IS_GC_ALLOW_CHECK = false; 29 #endif 30 31 template <bool IsDebug = IS_GC_ALLOW_CHECK> 32 class AssertGCScopeT { 33 public: IsAllowed()34 static bool IsAllowed() 35 { 36 return true; 37 } 38 }; 39 40 template <> 41 class AssertGCScopeT<true> { 42 public: AssertGCScopeT()43 AssertGCScopeT() 44 { 45 // Atomic with relaxed order reason: data race with gc_flag with no synchronization or ordering constraints 46 // imposed on other reads or writes 47 AssertGCScopeT::gc_flag.fetch_add(1, std::memory_order_relaxed); 48 } 49 ~AssertGCScopeT()50 ~AssertGCScopeT() 51 { 52 // Atomic with relaxed order reason: data race with gc_flag with no synchronization or ordering constraints 53 // imposed on other reads or writes 54 AssertGCScopeT::gc_flag.fetch_sub(1, std::memory_order_relaxed); 55 } 56 57 static bool IsAllowed(); 58 59 NO_COPY_SEMANTIC(AssertGCScopeT); 60 DEFAULT_NOEXCEPT_MOVE_SEMANTIC(AssertGCScopeT); 61 62 private: 63 static std::atomic<int> gc_flag; 64 }; 65 66 using DisallowGarbageCollection = AssertGCScopeT<IS_GC_ALLOW_CHECK>; 67 68 #if !defined(NDEBUG) 69 // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) 70 #define DISALLOW_GARGABE_COLLECTION [[maybe_unused]] DisallowGarbageCollection no_gc 71 #else 72 #define DISALLOW_GARGABE_COLLECTION 73 #endif 74 75 // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) 76 #define DCHECK_ALLOW_GARBAGE_COLLECTION \ 77 ASSERT_PRINT(AssertGCScopeT<IS_GC_ALLOW_CHECK>::IsAllowed(), "disallow execute garbage collection."); 78 } // namespace panda 79 80 #endif // PANDA_RUNTIME_ASSERT_GC_SCOPE_H 81