• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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         AssertGCScopeT::gc_flag.fetch_add(1, std::memory_order_relaxed);
46     }
47 
~AssertGCScopeT()48     ~AssertGCScopeT()
49     {
50         AssertGCScopeT::gc_flag.fetch_sub(1, std::memory_order_relaxed);
51     }
52 
53     static bool IsAllowed();
54 
55     NO_COPY_SEMANTIC(AssertGCScopeT);
56     DEFAULT_NOEXCEPT_MOVE_SEMANTIC(AssertGCScopeT);
57 
58 private:
59     static std::atomic<int> gc_flag;
60 };
61 
62 using DisallowGarbageCollection = AssertGCScopeT<IS_GC_ALLOW_CHECK>;
63 
64 #if !defined(NDEBUG)
65 // NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
66 #define DISALLOW_GARGABE_COLLECTION [[maybe_unused]] DisallowGarbageCollection no_gc
67 #else
68 #define DISALLOW_GARGABE_COLLECTION
69 #endif
70 
71 // NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
72 #define DCHECK_ALLOW_GARBAGE_COLLECTION \
73     ASSERT_PRINT(AssertGCScopeT<IS_GC_ALLOW_CHECK>::IsAllowed(), "disallow execute garbage collection.");
74 }  // namespace panda
75 
76 #endif  // PANDA_RUNTIME_ASSERT_GC_SCOPE_H_
77