1 /**
2 * Copyright (c) 2025 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 #include "runtime/include/runtime.h"
17 #include "runtime/include/thread_proxy.h"
18 #include "runtime/interpreter/runtime_interface.h"
19
20 #include "libpandabase/macros.h"
21
22 namespace ark {
23
GetInitialThreadFlag()24 CONSTEXPR_IN_RELEASE ThreadFlag GetInitialThreadFlag()
25 {
26 #ifndef NDEBUG
27 ThreadFlag initialFlag = Runtime::GetOptions().IsRunGcEverySafepoint() ? SAFEPOINT_REQUEST : NO_FLAGS;
28 return initialFlag;
29 #else
30 return NO_FLAGS;
31 #endif
32 }
33
34 ThreadFlag ThreadProxyStatic::initialThreadFlag_ = NO_FLAGS;
35
36 /* static */
InitializeInitThreadFlag()37 void ThreadProxyStatic::InitializeInitThreadFlag()
38 {
39 initialThreadFlag_ = GetInitialThreadFlag();
40 }
41
TestAllFlags() const42 bool ThreadProxyStatic::TestAllFlags() const
43 {
44 return (fts_.asStruct.flags) != initialThreadFlag_; // NOLINT(cppcoreguidelines-pro-type-union-access)
45 }
46
SetFlag(ThreadFlag flag)47 void ThreadProxyStatic::SetFlag(ThreadFlag flag)
48 {
49 // Atomic with seq_cst order reason: data race with flags with requirement for sequentially consistent order
50 // where threads observe all modifications in the same order
51 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
52 fts_.asAtomic.flags.fetch_or(flag, std::memory_order_seq_cst);
53 }
54
ClearFlag(ThreadFlag flag)55 void ThreadProxyStatic::ClearFlag(ThreadFlag flag)
56 {
57 // Atomic with seq_cst order reason: data race with flags with requirement for sequentially consistent order
58 // where threads observe all modifications in the same order
59 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
60 fts_.asAtomic.flags.fetch_and(UINT16_MAX ^ flag, std::memory_order_seq_cst);
61 }
62
ReadFlagsAndThreadStatusUnsafe()63 uint32_t ThreadProxyStatic::ReadFlagsAndThreadStatusUnsafe()
64 {
65 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
66 return fts_.asInt;
67 }
68
GetStatus() const69 enum ThreadStatus ThreadProxyStatic::GetStatus() const
70 {
71 // Atomic with acquire order reason: data race with flags with dependecies on reads after
72 // the load which should become visible
73 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
74 return static_cast<enum ThreadStatus>(fts_.asAtomic.status.load(std::memory_order_acquire));
75 }
76
ReadFlagsUnsafe() const77 uint32_t ThreadProxyStatic::ReadFlagsUnsafe() const
78 {
79 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
80 return fts_.asStruct.flags;
81 }
82
InitializeThreadFlag()83 void ThreadProxyStatic::InitializeThreadFlag()
84 {
85 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
86 fts_.asInt = initialThreadFlag_;
87 }
88
CleanUpThreadStatus()89 void ThreadProxyStatic::CleanUpThreadStatus()
90 {
91 InitializeThreadFlag();
92 StoreStatus<DONT_CHECK_SAFEPOINT, NO_READLOCK>(ThreadStatus::CREATED);
93 }
94
UpdateStatus(enum ThreadStatus status)95 void ThreadProxyStatic::UpdateStatus(enum ThreadStatus status)
96 {
97 ThreadStatus oldStatus = GetStatus();
98 if (oldStatus == ThreadStatus::RUNNING && status != ThreadStatus::RUNNING) {
99 TransitionFromRunningToSuspended(status);
100 } else if (oldStatus != ThreadStatus::RUNNING && status == ThreadStatus::RUNNING) {
101 // NB! This thread is treated as suspended so when we transition from suspended state to
102 // running we need to check suspension flag and counter so SafepointPoll has to be done before
103 // acquiring mutator_lock.
104 // StoreStatus acquires lock here
105 StoreStatus<CHECK_SAFEPOINT, READLOCK>(ThreadStatus::RUNNING);
106 } else if (oldStatus == ThreadStatus::NATIVE && status != ThreadStatus::IS_TERMINATED_LOOP &&
107 IsRuntimeTerminated()) {
108 // If a daemon thread with NATIVE status was deregistered, it should not access any managed object,
109 // i.e. change its status from NATIVE, because such object may already be deleted by the runtime.
110 // In case its status is changed, we must call a Safepoint to terminate this thread.
111 // For example, if a daemon thread calls ManagedCodeBegin (which changes status from NATIVE to
112 // RUNNING), it may be interrupted by a GC thread, which changes status to IS_SUSPENDED.
113 StoreStatus<CHECK_SAFEPOINT>(status);
114 } else {
115 // NB! Status is not a simple bit, without atomics it can produce faulty GetStatus.
116 StoreStatus(status);
117 }
118 }
119
TransitionFromRunningToSuspended(enum ThreadStatus status)120 void ThreadProxyStatic::TransitionFromRunningToSuspended(enum ThreadStatus status)
121 {
122 // Do Unlock after StoreStatus, because the thread requesting a suspension should see an updated status
123 StoreStatus(status);
124 GetMutatorLock()->Unlock();
125 }
126
SuspendCheck()127 void ThreadProxyStatic::SuspendCheck()
128 {
129 // We should use internal suspension to avoid missing call of IncSuspend
130 SuspendImpl(true);
131 GetMutatorLock()->Unlock();
132 GetMutatorLock()->ReadLock();
133 ResumeImpl(true);
134 }
135
SuspendImpl(bool internalSuspend)136 void ThreadProxyStatic::SuspendImpl(bool internalSuspend)
137 {
138 os::memory::LockHolder lock(suspendLock_);
139 LOG(DEBUG, RUNTIME) << "Suspending thread " << GetId();
140 if (!internalSuspend) {
141 if (IsUserSuspended()) {
142 LOG(DEBUG, RUNTIME) << "thread " << GetId() << " is already suspended";
143 return;
144 }
145 userCodeSuspendCount_++;
146 }
147 auto oldCount = suspendCount_++;
148 if (oldCount == 0) {
149 SetFlag(SUSPEND_REQUEST);
150 }
151 }
152
ResumeImpl(bool internalResume)153 void ThreadProxyStatic::ResumeImpl(bool internalResume)
154 {
155 os::memory::LockHolder lock(suspendLock_);
156 LOG(DEBUG, RUNTIME) << "Resuming thread " << GetId();
157 if (!internalResume) {
158 if (!IsUserSuspended()) {
159 LOG(DEBUG, RUNTIME) << "thread " << GetId() << " is already resumed";
160 return;
161 }
162 ASSERT(userCodeSuspendCount_ != 0);
163 userCodeSuspendCount_--;
164 }
165 if (suspendCount_ > 0) {
166 suspendCount_--;
167 if (suspendCount_ == 0) {
168 ClearFlag(SUSPEND_REQUEST);
169 }
170 }
171 // Help for UnregisterExitedThread
172 TSAN_ANNOTATE_HAPPENS_BEFORE(&fts_);
173 suspendVar_.Signal();
174 }
175
SafepointPoll()176 void ThreadProxyStatic::SafepointPoll()
177 {
178 if (this->TestAllFlags()) {
179 trace::ScopedTrace scopedTrace("RunSafepoint");
180 ark::interpreter::RuntimeInterface::Safepoint();
181 }
182 }
183
IsUserSuspended() const184 bool ThreadProxyStatic::IsUserSuspended() const
185 {
186 return userCodeSuspendCount_ > 0;
187 }
188
WaitSuspension()189 void ThreadProxyStatic::WaitSuspension()
190 {
191 constexpr int TIMEOUT = 100;
192 auto oldStatus = GetStatus();
193 PrintSuspensionStackIfNeeded();
194 UpdateStatus(ThreadStatus::IS_SUSPENDED);
195 {
196 /* @sync 1
197 * @description Right after the thread updates its status to IS_SUSPENDED and right before beginning to wait
198 * for actual suspension
199 */
200 os::memory::LockHolder lock(suspendLock_);
201 while (suspendCount_ > 0) {
202 suspendVar_.TimedWait(&suspendLock_, TIMEOUT);
203 // In case runtime is being terminated, we should abort suspension and release monitors
204 if (UNLIKELY(IsRuntimeTerminated())) {
205 suspendLock_.Unlock();
206 OnRuntimeTerminated();
207 UNREACHABLE();
208 }
209 }
210 ASSERT(!IsSuspended());
211 }
212 UpdateStatus(oldStatus);
213 }
214
MakeTSANHappyForThreadState()215 void ThreadProxyStatic::MakeTSANHappyForThreadState()
216 {
217 TSAN_ANNOTATE_HAPPENS_AFTER(&fts_);
218 }
219
220 #ifdef ARK_HYBRID
221
222 using namespace panda;
223
GetStatus() const224 enum ThreadStatus ThreadProxyHybrid::GetStatus() const
225 {
226 if (GetThreadHolder()->IsInRunningState()) {
227 return ThreadStatus::RUNNING;
228 }
229 return ThreadStatus::NATIVE;
230 }
231
UpdateStatus(enum ThreadStatus status)232 void ThreadProxyHybrid::UpdateStatus([[maybe_unused]] enum ThreadStatus status)
233 {
234 ThreadStatus oldStatus = GetStatus();
235 if (oldStatus == ThreadStatus::RUNNING && status != ThreadStatus::RUNNING) {
236 GetThreadHolder()->TransferToNativeIfInRunning();
237 GetMutatorLock()->Unlock();
238 } else if (oldStatus != ThreadStatus::RUNNING && status == ThreadStatus::RUNNING) {
239 GetThreadHolder()->TransferToRunningIfInNative();
240 GetMutatorLock()->ReadLock();
241 }
242 }
243
TestAllFlags() const244 bool ThreadProxyHybrid::TestAllFlags() const
245 {
246 return GetThreadHolder()->HasSuspendRequest();
247 }
248
IsSuspended() const249 bool ThreadProxyHybrid::IsSuspended() const
250 {
251 return GetThreadHolder()->HasSuspendRequest();
252 }
253
SafepointPoll()254 void ThreadProxyHybrid::SafepointPoll()
255 {
256 GetThreadHolder()->CheckSafepointIfSuspended();
257 }
258
WaitSuspension()259 void ThreadProxyHybrid::WaitSuspension()
260 {
261 GetThreadHolder()->WaitSuspension();
262 }
263
InitializeThreadFlag()264 void ThreadProxyHybrid::InitializeThreadFlag() {}
265
CleanUpThreadStatus()266 void ThreadProxyHybrid::CleanUpThreadStatus() {}
267
IsRuntimeTerminated() const268 bool ThreadProxyHybrid::IsRuntimeTerminated() const
269 {
270 return false;
271 }
272
SetRuntimeTerminated()273 void ThreadProxyHybrid::SetRuntimeTerminated()
274 {
275 UNREACHABLE();
276 }
277
SuspendCheck()278 void ThreadProxyHybrid::SuspendCheck()
279 {
280 UNREACHABLE();
281 }
282
SuspendImpl(bool internalSuspend)283 void ThreadProxyHybrid::SuspendImpl([[maybe_unused]] bool internalSuspend)
284 {
285 UNREACHABLE();
286 }
287
ResumeImpl(bool internalResume)288 void ThreadProxyHybrid::ResumeImpl([[maybe_unused]] bool internalResume)
289 {
290 UNREACHABLE();
291 }
292
IsUserSuspended()293 bool ThreadProxyHybrid::IsUserSuspended()
294 {
295 UNREACHABLE();
296 return false;
297 }
298
MakeTSANHappyForThreadState()299 void ThreadProxyHybrid::MakeTSANHappyForThreadState()
300 {
301 UNREACHABLE();
302 }
303
CreateExternalHolderIfNeeded(bool useSharedHolder)304 bool ThreadProxyHybrid::CreateExternalHolderIfNeeded(bool useSharedHolder)
305 {
306 if (threadHolder_ != nullptr) {
307 return false;
308 }
309 // NOTE(panferovi): replace ThreadHolder::GerCurrent by new interface
310 // that obtain ThreadHolder from JS, when it is implemented
311 threadHolder_ =
312 useSharedHolder ? ThreadHolder::GetCurrent() : ThreadHolder::CreateAndRegisterNewThreadHolder(nullptr);
313 return true;
314 }
315
316 #endif
317
318 } // namespace ark
319