1 /* Copyright (C) 2017 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32 #include "ti_thread.h"
33
34 #include <android-base/logging.h>
35 #include <android-base/strings.h>
36
37 #include "art_field-inl.h"
38 #include "art_jvmti.h"
39 #include "base/mutex.h"
40 #include "deopt_manager.h"
41 #include "events-inl.h"
42 #include "gc/collector_type.h"
43 #include "gc/gc_cause.h"
44 #include "gc/scoped_gc_critical_section.h"
45 #include "gc/system_weak.h"
46 #include "gc_root-inl.h"
47 #include "jni/jni_internal.h"
48 #include "metrics/reporter.h"
49 #include "mirror/class.h"
50 #include "mirror/object-inl.h"
51 #include "mirror/string.h"
52 #include "mirror/throwable.h"
53 #include "nativehelper/scoped_local_ref.h"
54 #include "nativehelper/scoped_utf_chars.h"
55 #include "obj_ptr.h"
56 #include "runtime.h"
57 #include "runtime_callbacks.h"
58 #include "scoped_thread_state_change-inl.h"
59 #include "thread-current-inl.h"
60 #include "thread_list.h"
61 #include "ti_phase.h"
62 #include "well_known_classes.h"
63
64 namespace openjdkjvmti {
65
66 static const char* kJvmtiTlsKey = "JvmtiTlsKey";
67
68 art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
69
ScopedNoUserCodeSuspension(art::Thread * self)70 ScopedNoUserCodeSuspension::ScopedNoUserCodeSuspension(art::Thread* self) : self_(self) {
71 DCHECK_EQ(self, art::Thread::Current());
72 // Loop until we both have the user_code_suspension_locK_ and don't have any pending user_code
73 // suspensions.
74 do {
75 art::Locks::user_code_suspension_lock_->AssertNotHeld(self_);
76 ThreadUtil::SuspendCheck(self_);
77
78 art::Locks::user_code_suspension_lock_->ExclusiveLock(self_);
79 if (ThreadUtil::WouldSuspendForUserCodeLocked(self_)) {
80 art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_);
81 continue;
82 }
83
84 art::Locks::user_code_suspension_lock_->AssertHeld(self_);
85
86 return;
87 } while (true);
88 }
89
~ScopedNoUserCodeSuspension()90 ScopedNoUserCodeSuspension::~ScopedNoUserCodeSuspension() {
91 art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_);
92 }
93
94 struct ThreadCallback : public art::ThreadLifecycleCallback {
GetThreadObjectopenjdkjvmti::ThreadCallback95 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
96 if (self->GetPeer() == nullptr) {
97 return nullptr;
98 }
99 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
100 }
101
102 template <ArtJvmtiEvent kEvent>
Postopenjdkjvmti::ThreadCallback103 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
104 DCHECK_EQ(self, art::Thread::Current());
105 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
106 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
107 event_handler->DispatchEvent<kEvent>(self,
108 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
109 thread.get());
110 }
111
ThreadStartopenjdkjvmti::ThreadCallback112 void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
113 // Needs to be checked first because we might start these threads before we actually send the
114 // VMInit event.
115 if (self->IsSystemDaemon()) {
116 // System daemon threads are things like the finalizer or gc thread. It would be dangerous to
117 // allow agents to get in the way of these threads starting up. These threads include things
118 // like the HeapTaskDaemon and the finalizer daemon.
119 //
120 // This event can happen during the time before VMInit or just after zygote fork. Since the
121 // second is hard to distinguish we unfortunately cannot really check the state here.
122 return;
123 }
124 if (!started) {
125 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
126 // started here; this includes the perfetto_hprof_listener signal handler thread for
127 // perfetto_hprof, as well as the metrics background reporting thread.
128 if (art::kIsDebugBuild) {
129 std::string name;
130 self->GetThreadName(name);
131 if (name != "JDWP" && name != "Signal Catcher" && name != "perfetto_hprof_listener" &&
132 name != art::metrics::MetricsReporter::kBackgroundThreadName &&
133 !android::base::StartsWith(name, "Jit thread pool") &&
134 !android::base::StartsWith(name, "Runtime worker thread")) {
135 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
136 << self->GetThreadId();
137 }
138 }
139 return;
140 }
141 Post<ArtJvmtiEvent::kThreadStart>(self);
142 }
143
ThreadDeathopenjdkjvmti::ThreadCallback144 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
145 Post<ArtJvmtiEvent::kThreadEnd>(self);
146 }
147
148 EventHandler* event_handler = nullptr;
149 bool started = false;
150 };
151
152 ThreadCallback gThreadCallback;
153
Register(EventHandler * handler)154 void ThreadUtil::Register(EventHandler* handler) {
155 art::Runtime* runtime = art::Runtime::Current();
156
157 gThreadCallback.started = runtime->IsStarted();
158 gThreadCallback.event_handler = handler;
159
160 art::ScopedThreadStateChange stsc(art::Thread::Current(),
161 art::ThreadState::kWaitingForDebuggerToAttach);
162 art::ScopedSuspendAll ssa("Add thread callback");
163 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
164 }
165
VMInitEventSent()166 void ThreadUtil::VMInitEventSent() {
167 // We should have already started.
168 DCHECK(gThreadCallback.started);
169 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
170 // reported until Init.
171 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
172 }
173
174
WaitForSystemDaemonStart(art::Thread * self)175 static void WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
176 {
177 art::ScopedThreadStateChange strc(self, art::ThreadState::kNative);
178 JNIEnv* jni = self->GetJniEnv();
179 jni->CallStaticVoidMethod(art::WellKnownClasses::java_lang_Daemons,
180 art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart);
181 }
182 if (self->IsExceptionPending()) {
183 LOG(WARNING) << "Exception occurred when waiting for system daemons to start: "
184 << self->GetException()->Dump();
185 self->ClearException();
186 }
187 }
188
CacheData()189 void ThreadUtil::CacheData() {
190 // We must have started since it is now safe to cache our data;
191 gThreadCallback.started = true;
192 art::Thread* self = art::Thread::Current();
193 art::ScopedObjectAccess soa(self);
194 art::ObjPtr<art::mirror::Class> thread_class =
195 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
196 CHECK(thread_class != nullptr);
197 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
198 "Ljava/lang/ClassLoader;");
199 CHECK(context_class_loader_ != nullptr);
200 // Now wait for all required system threads to come up before allowing the rest of loading to
201 // continue.
202 WaitForSystemDaemonStart(self);
203 }
204
Unregister()205 void ThreadUtil::Unregister() {
206 art::ScopedThreadStateChange stsc(art::Thread::Current(),
207 art::ThreadState::kWaitingForDebuggerToAttach);
208 art::ScopedSuspendAll ssa("Remove thread callback");
209 art::Runtime* runtime = art::Runtime::Current();
210 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
211 }
212
GetCurrentThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread * thread_ptr)213 jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
214 art::Thread* self = art::Thread::Current();
215
216 art::ScopedObjectAccess soa(self);
217
218 jthread thread_peer;
219 if (self->IsStillStarting()) {
220 thread_peer = nullptr;
221 } else {
222 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
223 }
224
225 *thread_ptr = thread_peer;
226 return ERR(NONE);
227 }
228
229 // Get the native thread. The spec says a null object denotes the current thread.
GetNativeThread(jthread thread,const art::ScopedObjectAccessAlreadyRunnable & soa,art::Thread ** thr,jvmtiError * err)230 bool ThreadUtil::GetNativeThread(jthread thread,
231 const art::ScopedObjectAccessAlreadyRunnable& soa,
232 /*out*/ art::Thread** thr,
233 /*out*/ jvmtiError* err) {
234 art::ScopedExceptionStorage sse(soa.Self());
235 if (thread == nullptr) {
236 *thr = art::Thread::Current();
237 return true;
238 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
239 *err = ERR(INVALID_THREAD);
240 return false;
241 } else {
242 *thr = art::Thread::FromManagedThread(soa, thread);
243 return true;
244 }
245 }
246
GetAliveNativeThread(jthread thread,const art::ScopedObjectAccessAlreadyRunnable & soa,art::Thread ** thr,jvmtiError * err)247 bool ThreadUtil::GetAliveNativeThread(jthread thread,
248 const art::ScopedObjectAccessAlreadyRunnable& soa,
249 /*out*/ art::Thread** thr,
250 /*out*/ jvmtiError* err) {
251 if (!GetNativeThread(thread, soa, thr, err)) {
252 return false;
253 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
254 *err = ERR(THREAD_NOT_ALIVE);
255 return false;
256 } else {
257 return true;
258 }
259 }
260
GetThreadInfo(jvmtiEnv * env,jthread thread,jvmtiThreadInfo * info_ptr)261 jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
262 if (info_ptr == nullptr) {
263 return ERR(NULL_POINTER);
264 }
265 if (!PhaseUtil::IsLivePhase()) {
266 return JVMTI_ERROR_WRONG_PHASE;
267 }
268
269 art::Thread* self = art::Thread::Current();
270 art::ScopedObjectAccess soa(self);
271 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
272
273 art::Thread* target;
274 jvmtiError err = ERR(INTERNAL);
275 if (!GetNativeThread(thread, soa, &target, &err)) {
276 return err;
277 }
278
279 JvmtiUniquePtr<char[]> name_uptr;
280 if (target != nullptr) {
281 // Have a native thread object, this thread is alive.
282 std::string name;
283 target->GetThreadName(name);
284 jvmtiError name_result;
285 name_uptr = CopyString(env, name.c_str(), &name_result);
286 if (name_uptr == nullptr) {
287 return name_result;
288 }
289 info_ptr->name = name_uptr.get();
290
291 info_ptr->priority = target->GetNativePriority();
292
293 info_ptr->is_daemon = target->IsDaemon();
294
295 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
296
297 // ThreadGroup.
298 if (peer != nullptr) {
299 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
300 CHECK(f != nullptr);
301 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
302 info_ptr->thread_group = group == nullptr
303 ? nullptr
304 : soa.AddLocalReference<jthreadGroup>(group);
305 } else {
306 info_ptr->thread_group = nullptr;
307 }
308
309 // Context classloader.
310 DCHECK(context_class_loader_ != nullptr);
311 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
312 ? context_class_loader_->GetObject(peer)
313 : nullptr;
314 info_ptr->context_class_loader = ccl == nullptr
315 ? nullptr
316 : soa.AddLocalReference<jobject>(ccl);
317 } else {
318 // Only the peer. This thread has either not been started, or is dead. Read things from
319 // the Java side.
320 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
321
322 // Name.
323 {
324 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
325 CHECK(f != nullptr);
326 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
327 std::string name_cpp;
328 const char* name_cstr;
329 if (name != nullptr) {
330 name_cpp = name->AsString()->ToModifiedUtf8();
331 name_cstr = name_cpp.c_str();
332 } else {
333 name_cstr = "";
334 }
335 jvmtiError name_result;
336 name_uptr = CopyString(env, name_cstr, &name_result);
337 if (name_uptr == nullptr) {
338 return name_result;
339 }
340 info_ptr->name = name_uptr.get();
341 }
342
343 // Priority.
344 {
345 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
346 CHECK(f != nullptr);
347 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
348 }
349
350 // Daemon.
351 {
352 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
353 CHECK(f != nullptr);
354 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
355 }
356
357 // ThreadGroup.
358 {
359 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
360 CHECK(f != nullptr);
361 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
362 info_ptr->thread_group = group == nullptr
363 ? nullptr
364 : soa.AddLocalReference<jthreadGroup>(group);
365 }
366
367 // Context classloader.
368 DCHECK(context_class_loader_ != nullptr);
369 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
370 ? context_class_loader_->GetObject(peer)
371 : nullptr;
372 info_ptr->context_class_loader = ccl == nullptr
373 ? nullptr
374 : soa.AddLocalReference<jobject>(ccl);
375 }
376
377 name_uptr.release();
378
379 return ERR(NONE);
380 }
381
382 struct InternalThreadState {
383 art::Thread* native_thread;
384 art::ThreadState art_state;
385 int thread_user_code_suspend_count;
386 };
387
388 // Return the thread's (or current thread, if null) thread state.
GetNativeThreadState(art::Thread * target)389 static InternalThreadState GetNativeThreadState(art::Thread* target)
390 REQUIRES_SHARED(art::Locks::mutator_lock_)
391 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
392 InternalThreadState thread_state = {};
393 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
394 thread_state.native_thread = target;
395 if (target == nullptr || target->IsStillStarting()) {
396 thread_state.art_state = art::ThreadState::kStarting;
397 thread_state.thread_user_code_suspend_count = 0;
398 } else {
399 thread_state.art_state = target->GetState();
400 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
401 }
402 return thread_state;
403 }
404
GetJvmtiThreadStateFromInternal(const InternalThreadState & state)405 static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
406 art::ThreadState internal_thread_state = state.art_state;
407 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
408
409 if (state.thread_user_code_suspend_count != 0) {
410 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
411 // kSuspended state it will move to that once it hits a checkpoint so we can still set this.
412 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
413 // Note: We do not have data about the previous state. Otherwise we should load the previous
414 // state here.
415 }
416
417 if (state.native_thread->IsInterrupted()) {
418 // Interrupted can be set with any thread state so check it here.
419 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
420 }
421
422 // Enumerate all the thread states and fill in the other bits. This contains the results of
423 // following the decision tree in the JVMTI spec GetThreadState documentation.
424 switch (internal_thread_state) {
425 case art::ThreadState::kRunnable:
426 case art::ThreadState::kWaitingWeakGcRootRead:
427 case art::ThreadState::kSuspended:
428 // These are all simply runnable.
429 // kRunnable is self-explanatory.
430 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
431 // so we want to keep it marked as runnable.
432 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
433 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
434 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
435 break;
436 case art::ThreadState::kNative:
437 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
438 // state but we don't have the information to know if it should be present for any but the
439 // kNative state.
440 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
441 JVMTI_THREAD_STATE_RUNNABLE);
442 break;
443 case art::ThreadState::kBlocked:
444 // Blocked is one of the top level states so it sits alone.
445 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
446 break;
447 case art::ThreadState::kWaiting:
448 // Object.wait() so waiting, indefinitely, in object.wait.
449 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
450 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
451 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
452 break;
453 case art::ThreadState::kTimedWaiting:
454 // Object.wait(long) so waiting, with timeout, in object.wait.
455 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
456 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
457 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
458 break;
459 case art::ThreadState::kSleeping:
460 // In object.sleep. This is a timed wait caused by sleep.
461 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
462 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
463 JVMTI_THREAD_STATE_SLEEPING);
464 break;
465 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
466 // attached.
467 case art::ThreadState::kWaitingForDebuggerSend:
468 case art::ThreadState::kWaitingForDebuggerToAttach:
469 case art::ThreadState::kWaitingInMainDebuggerLoop:
470 case art::ThreadState::kWaitingForDebuggerSuspension:
471 case art::ThreadState::kWaitingForLockInflation:
472 case art::ThreadState::kWaitingForTaskProcessor:
473 case art::ThreadState::kWaitingForGcToComplete:
474 case art::ThreadState::kWaitingForCheckPointsToRun:
475 case art::ThreadState::kWaitingPerformingGc:
476 case art::ThreadState::kWaitingForJniOnLoad:
477 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
478 case art::ThreadState::kWaitingForSignalCatcherOutput:
479 case art::ThreadState::kWaitingForDeoptimization:
480 case art::ThreadState::kWaitingForMethodTracingStart:
481 case art::ThreadState::kWaitingForVisitObjects:
482 case art::ThreadState::kWaitingForGetObjectsAllocated:
483 case art::ThreadState::kWaitingForGcThreadFlip:
484 case art::ThreadState::kNativeForAbort:
485 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
486 // caused by sleep, park, or object#wait.
487 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
488 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
489 break;
490 case art::ThreadState::kObsoleteRunnable: // Obsolete value.
491 case art::ThreadState::kStarting:
492 case art::ThreadState::kTerminated:
493 // We only call this if we are alive so we shouldn't see either of these states.
494 LOG(FATAL) << "Should not be in state " << internal_thread_state;
495 UNREACHABLE();
496 }
497 // TODO: PARKED. We'll have to inspect the stack.
498
499 return jvmti_state;
500 }
501
GetJavaStateFromInternal(const InternalThreadState & state)502 static jint GetJavaStateFromInternal(const InternalThreadState& state) {
503 switch (state.art_state) {
504 case art::ThreadState::kTerminated:
505 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
506
507 case art::ThreadState::kRunnable:
508 case art::ThreadState::kNative:
509 case art::ThreadState::kWaitingWeakGcRootRead:
510 case art::ThreadState::kSuspended:
511 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
512
513 case art::ThreadState::kTimedWaiting:
514 case art::ThreadState::kSleeping:
515 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
516
517 case art::ThreadState::kBlocked:
518 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
519
520 case art::ThreadState::kStarting:
521 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
522
523 case art::ThreadState::kWaiting:
524 case art::ThreadState::kWaitingForTaskProcessor:
525 case art::ThreadState::kWaitingForLockInflation:
526 case art::ThreadState::kWaitingForGcToComplete:
527 case art::ThreadState::kWaitingPerformingGc:
528 case art::ThreadState::kWaitingForCheckPointsToRun:
529 case art::ThreadState::kWaitingForDebuggerSend:
530 case art::ThreadState::kWaitingForDebuggerToAttach:
531 case art::ThreadState::kWaitingInMainDebuggerLoop:
532 case art::ThreadState::kWaitingForDebuggerSuspension:
533 case art::ThreadState::kWaitingForDeoptimization:
534 case art::ThreadState::kWaitingForGetObjectsAllocated:
535 case art::ThreadState::kWaitingForJniOnLoad:
536 case art::ThreadState::kWaitingForSignalCatcherOutput:
537 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
538 case art::ThreadState::kWaitingForMethodTracingStart:
539 case art::ThreadState::kWaitingForVisitObjects:
540 case art::ThreadState::kWaitingForGcThreadFlip:
541 case art::ThreadState::kNativeForAbort:
542 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
543
544 case art::ThreadState::kObsoleteRunnable:
545 break; // Obsolete value.
546 }
547 LOG(FATAL) << "Unreachable";
548 UNREACHABLE();
549 }
550
551 // Suspends the current thread if it has any suspend requests on it.
SuspendCheck(art::Thread * self)552 void ThreadUtil::SuspendCheck(art::Thread* self) {
553 art::ScopedObjectAccess soa(self);
554 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
555 self->FullSuspendCheck();
556 }
557
WouldSuspendForUserCodeLocked(art::Thread * self)558 bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
559 DCHECK(self == art::Thread::Current());
560 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
561 return self->GetUserCodeSuspendCount() != 0;
562 }
563
WouldSuspendForUserCode(art::Thread * self)564 bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
565 DCHECK(self == art::Thread::Current());
566 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
567 return WouldSuspendForUserCodeLocked(self);
568 }
569
GetThreadState(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread,jint * thread_state_ptr)570 jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
571 jthread thread,
572 jint* thread_state_ptr) {
573 if (thread_state_ptr == nullptr) {
574 return ERR(NULL_POINTER);
575 }
576
577 art::Thread* self = art::Thread::Current();
578 InternalThreadState state = {};
579 {
580 ScopedNoUserCodeSuspension snucs(self);
581 art::ScopedObjectAccess soa(self);
582 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
583 jvmtiError err = ERR(INTERNAL);
584 art::Thread* target = nullptr;
585 if (!GetNativeThread(thread, soa, &target, &err)) {
586 return err;
587 }
588 state = GetNativeThreadState(target);
589 if (state.art_state != art::ThreadState::kStarting) {
590 DCHECK(state.native_thread != nullptr);
591
592 // Translate internal thread state to JVMTI and Java state.
593 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
594
595 // Java state is derived from nativeGetState.
596 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
597 // different mask if a thread got suspended due to user-code. However, this is for
598 // consistency with the Java view.
599 jint java_state = GetJavaStateFromInternal(state);
600
601 *thread_state_ptr = jvmti_state | java_state;
602
603 return ERR(NONE);
604 }
605 }
606
607 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
608
609 if (thread == nullptr) {
610 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
611 return ERR(WRONG_PHASE);
612 }
613
614 art::ScopedObjectAccess soa(self);
615 art::StackHandleScope<1> hs(self);
616
617 // Need to read the Java "started" field to know whether this is starting or terminated.
618 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
619 art::ObjPtr<art::mirror::Class> thread_klass =
620 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
621 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
622 return ERR(INVALID_THREAD);
623 }
624 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
625 CHECK(started_field != nullptr);
626 bool started = started_field->GetBoolean(peer.Get()) != 0;
627 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
628 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
629 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
630 *thread_state_ptr = started ? kTerminatedState : kStartedState;
631 return ERR(NONE);
632 }
633
GetAllThreads(jvmtiEnv * env,jint * threads_count_ptr,jthread ** threads_ptr)634 jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
635 jint* threads_count_ptr,
636 jthread** threads_ptr) {
637 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
638 return ERR(NULL_POINTER);
639 }
640
641 art::Thread* current = art::Thread::Current();
642
643 art::ScopedObjectAccess soa(current);
644
645 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
646 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
647
648 std::vector<art::ObjPtr<art::mirror::Object>> peers;
649
650 for (art::Thread* thread : thread_list) {
651 // Skip threads that are still starting.
652 if (thread->IsStillStarting()) {
653 continue;
654 }
655
656 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
657 if (peer != nullptr) {
658 peers.push_back(peer);
659 }
660 }
661
662 if (peers.empty()) {
663 *threads_count_ptr = 0;
664 *threads_ptr = nullptr;
665 } else {
666 unsigned char* data;
667 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
668 if (data_result != ERR(NONE)) {
669 return data_result;
670 }
671 jthread* threads = reinterpret_cast<jthread*>(data);
672 for (size_t i = 0; i != peers.size(); ++i) {
673 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
674 }
675
676 *threads_count_ptr = static_cast<jint>(peers.size());
677 *threads_ptr = threads;
678 }
679 return ERR(NONE);
680 }
681
RemoveTLSData(art::Thread * target,void * ctx)682 static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
683 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
684 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
685 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
686 if (global_tls != nullptr) {
687 global_tls->data.erase(env);
688 }
689 }
690
RemoveEnvironment(jvmtiEnv * env)691 void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
692 art::Thread* self = art::Thread::Current();
693 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
694 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
695 list->ForEach(RemoveTLSData, env);
696 }
697
SetThreadLocalStorage(jvmtiEnv * env,jthread thread,const void * data)698 jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
699 art::Thread* self = art::Thread::Current();
700 art::ScopedObjectAccess soa(self);
701 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
702 art::Thread* target = nullptr;
703 jvmtiError err = ERR(INTERNAL);
704 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
705 return err;
706 }
707
708 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
709
710 global_tls->data[env] = data;
711
712 return ERR(NONE);
713 }
714
GetOrCreateGlobalTLSData(art::Thread * thread)715 JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
716 JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
717 if (data != nullptr) {
718 return data;
719 } else {
720 thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
721 return GetGlobalTLSData(thread);
722 }
723 }
724
GetGlobalTLSData(art::Thread * thread)725 JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
726 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
727 }
728
GetThreadLocalStorage(jvmtiEnv * env,jthread thread,void ** data_ptr)729 jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
730 jthread thread,
731 void** data_ptr) {
732 if (data_ptr == nullptr) {
733 return ERR(NULL_POINTER);
734 }
735
736 art::Thread* self = art::Thread::Current();
737 art::ScopedObjectAccess soa(self);
738 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
739 art::Thread* target = nullptr;
740 jvmtiError err = ERR(INTERNAL);
741 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
742 return err;
743 }
744
745 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
746 if (global_tls == nullptr) {
747 *data_ptr = nullptr;
748 return OK;
749 }
750 auto it = global_tls->data.find(env);
751 if (it != global_tls->data.end()) {
752 *data_ptr = const_cast<void*>(it->second);
753 } else {
754 *data_ptr = nullptr;
755 }
756
757 return ERR(NONE);
758 }
759
760 struct AgentData {
761 const void* arg;
762 jvmtiStartFunction proc;
763 jthread thread;
764 JavaVM* java_vm;
765 jvmtiEnv* jvmti_env;
766 jint priority;
767 std::string name;
768 };
769
AgentCallback(void * arg)770 static void* AgentCallback(void* arg) {
771 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
772 CHECK(data->thread != nullptr);
773
774 // We already have a peer. So call our special Attach function.
775 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
776 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
777 // The name in Attach() is only for logging. Set the thread name. This is important so
778 // that the thread is no longer seen as starting up.
779 {
780 art::ScopedObjectAccess soa(self);
781 self->SetThreadName(data->name.c_str());
782 }
783
784 // Release the peer.
785 JNIEnv* env = self->GetJniEnv();
786 env->DeleteGlobalRef(data->thread);
787 data->thread = nullptr;
788
789 {
790 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
791 // before going into the provided code.
792 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
793 art::Runtime::Current()->EndThreadBirth();
794 }
795
796 // Run the agent code.
797 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
798
799 // Detach the thread.
800 int detach_result = data->java_vm->DetachCurrentThread();
801 CHECK_EQ(detach_result, 0);
802
803 return nullptr;
804 }
805
RunAgentThread(jvmtiEnv * jvmti_env,jthread thread,jvmtiStartFunction proc,const void * arg,jint priority)806 jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
807 jthread thread,
808 jvmtiStartFunction proc,
809 const void* arg,
810 jint priority) {
811 if (!PhaseUtil::IsLivePhase()) {
812 return ERR(WRONG_PHASE);
813 }
814 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
815 return ERR(INVALID_PRIORITY);
816 }
817 JNIEnv* env = art::Thread::Current()->GetJniEnv();
818 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
819 return ERR(INVALID_THREAD);
820 }
821 if (proc == nullptr) {
822 return ERR(NULL_POINTER);
823 }
824
825 {
826 art::Runtime* runtime = art::Runtime::Current();
827 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
828 if (runtime->IsShuttingDownLocked()) {
829 // The runtime is shutting down so we cannot create new threads.
830 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
831 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
832 // impossible. Existing agents don't seem to generally do anything with this return value so
833 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
834 // even though code is never actually run.
835 return ERR(INTERNAL);
836 }
837 runtime->StartThreadBirth();
838 }
839
840 std::unique_ptr<AgentData> data(new AgentData);
841 data->arg = arg;
842 data->proc = proc;
843 // We need a global ref for Java objects, as local refs will be invalid.
844 data->thread = env->NewGlobalRef(thread);
845 data->java_vm = art::Runtime::Current()->GetJavaVM();
846 data->jvmti_env = jvmti_env;
847 data->priority = priority;
848 ScopedLocalRef<jstring> s(
849 env,
850 reinterpret_cast<jstring>(
851 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
852 if (s == nullptr) {
853 data->name = "JVMTI Agent Thread";
854 } else {
855 ScopedUtfChars name(env, s.get());
856 data->name = name.c_str();
857 }
858
859 pthread_t pthread;
860 int pthread_create_result = pthread_create(&pthread,
861 nullptr,
862 &AgentCallback,
863 reinterpret_cast<void*>(data.get()));
864 if (pthread_create_result != 0) {
865 // If the create succeeded the other thread will call EndThreadBirth.
866 art::Runtime* runtime = art::Runtime::Current();
867 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
868 runtime->EndThreadBirth();
869 return ERR(INTERNAL);
870 }
871 data.release(); // NOLINT pthreads API.
872
873 return ERR(NONE);
874 }
875
SuspendOther(art::Thread * self,jthread target_jthread)876 jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
877 jthread target_jthread) {
878 // Loop since we need to bail out and try again if we would end up getting suspended while holding
879 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
880 // release the lock, wait to get resumed and try again.
881 do {
882 ScopedNoUserCodeSuspension snucs(self);
883 // We are not going to be suspended by user code from now on.
884 {
885 art::ScopedObjectAccess soa(self);
886 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
887 art::Thread* target = nullptr;
888 jvmtiError err = ERR(INTERNAL);
889 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
890 return err;
891 }
892 art::ThreadState state = target->GetState();
893 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
894 return ERR(THREAD_NOT_ALIVE);
895 } else {
896 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
897 if (target->GetUserCodeSuspendCount() != 0) {
898 return ERR(THREAD_SUSPENDED);
899 }
900 }
901 }
902 bool timeout = true;
903 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
904 target_jthread,
905 art::SuspendReason::kForUserCode,
906 &timeout);
907 if (ret_target == nullptr && !timeout) {
908 // TODO It would be good to get more information about why exactly the thread failed to
909 // suspend.
910 return ERR(INTERNAL);
911 } else if (!timeout) {
912 // we didn't time out and got a result.
913 return OK;
914 }
915 // We timed out. Just go around and try again.
916 } while (true);
917 UNREACHABLE();
918 }
919
SuspendSelf(art::Thread * self)920 jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
921 CHECK(self == art::Thread::Current());
922 {
923 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
924 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
925 if (self->GetUserCodeSuspendCount() != 0) {
926 // This can only happen if we race with another thread to suspend 'self' and we lose.
927 return ERR(THREAD_SUSPENDED);
928 }
929 // We shouldn't be able to fail this.
930 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
931 // TODO More specific error would be nice.
932 return ERR(INTERNAL);
933 }
934 }
935 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
936 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
937 // to go to sleep until we are resumed.
938 SuspendCheck(self);
939 return OK;
940 }
941
SuspendThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)942 jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
943 art::Thread* self = art::Thread::Current();
944 bool target_is_self = false;
945 {
946 art::ScopedObjectAccess soa(self);
947 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
948 art::Thread* target = nullptr;
949 jvmtiError err = ERR(INTERNAL);
950 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
951 return err;
952 } else if (target == self) {
953 target_is_self = true;
954 }
955 }
956 if (target_is_self) {
957 return SuspendSelf(self);
958 } else {
959 return SuspendOther(self, thread);
960 }
961 }
962
ResumeThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)963 jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
964 jthread thread) {
965 if (thread == nullptr) {
966 return ERR(NULL_POINTER);
967 }
968 art::Thread* self = art::Thread::Current();
969 art::Thread* target;
970
971 // Make sure we won't get suspended ourselves while in the middle of resuming another thread.
972 ScopedNoUserCodeSuspension snucs(self);
973 // From now on we know we cannot get suspended by user-code.
974 {
975 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
976 // have the 'suspend_lock' locked here.
977 art::ScopedObjectAccess soa(self);
978 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
979 jvmtiError err = ERR(INTERNAL);
980 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
981 return err;
982 } else if (target == self) {
983 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
984 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
985 // about current state since it's all concurrent.
986 return ERR(THREAD_NOT_SUSPENDED);
987 }
988 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
989 // cannot tell why resume failed.
990 {
991 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
992 if (target->GetUserCodeSuspendCount() == 0) {
993 return ERR(THREAD_NOT_SUSPENDED);
994 }
995 }
996 }
997 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
998 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
999 DCHECK(target != self);
1000 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
1001 art::SuspendReason::kForUserCode)) {
1002 // TODO Give a better error.
1003 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
1004 return ERR(INTERNAL);
1005 } else {
1006 return OK;
1007 }
1008 }
1009
IsCurrentThread(jthread thr)1010 static bool IsCurrentThread(jthread thr) {
1011 if (thr == nullptr) {
1012 return true;
1013 }
1014 art::Thread* self = art::Thread::Current();
1015 art::ScopedObjectAccess soa(self);
1016 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1017 art::Thread* target = nullptr;
1018 jvmtiError err_unused = ERR(INTERNAL);
1019 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1020 return target == self;
1021 } else {
1022 return false;
1023 }
1024 }
1025
1026 // Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1027 // since we can have threads in the list multiple times. This generally doesn't matter unless the
1028 // current thread is present multiple times. In that case we need to suspend only once and either
1029 // return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1030 // it didn't. We also want to handle the current thread last to make the behavior of the code
1031 // simpler to understand.
SuspendThreadList(jvmtiEnv * env,jint request_count,const jthread * threads,jvmtiError * results)1032 jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1033 jint request_count,
1034 const jthread* threads,
1035 jvmtiError* results) {
1036 if (request_count == 0) {
1037 return ERR(ILLEGAL_ARGUMENT);
1038 } else if (results == nullptr || threads == nullptr) {
1039 return ERR(NULL_POINTER);
1040 }
1041 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1042 // running thread. These indexes we need to handle specially since we need to only actually
1043 // suspend a single time.
1044 std::vector<jint> current_thread_indexes;
1045 for (jint i = 0; i < request_count; i++) {
1046 if (IsCurrentThread(threads[i])) {
1047 current_thread_indexes.push_back(i);
1048 } else {
1049 results[i] = env->SuspendThread(threads[i]);
1050 }
1051 }
1052 if (!current_thread_indexes.empty()) {
1053 jint first_current_thread_index = current_thread_indexes[0];
1054 // Suspend self.
1055 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1056 results[first_current_thread_index] = res;
1057 // Fill in the rest of the error values as appropriate.
1058 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1059 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1060 results[*it] = other_results;
1061 }
1062 }
1063 return OK;
1064 }
1065
ResumeThreadList(jvmtiEnv * env,jint request_count,const jthread * threads,jvmtiError * results)1066 jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1067 jint request_count,
1068 const jthread* threads,
1069 jvmtiError* results) {
1070 if (request_count == 0) {
1071 return ERR(ILLEGAL_ARGUMENT);
1072 } else if (results == nullptr || threads == nullptr) {
1073 return ERR(NULL_POINTER);
1074 }
1075 for (jint i = 0; i < request_count; i++) {
1076 results[i] = env->ResumeThread(threads[i]);
1077 }
1078 return OK;
1079 }
1080
StopThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread,jobject exception)1081 jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1082 jthread thread,
1083 jobject exception) {
1084 art::Thread* self = art::Thread::Current();
1085 art::ScopedObjectAccess soa(self);
1086 art::StackHandleScope<1> hs(self);
1087 if (exception == nullptr) {
1088 return ERR(INVALID_OBJECT);
1089 }
1090 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1091 if (!obj->GetClass()->IsThrowableClass()) {
1092 return ERR(INVALID_OBJECT);
1093 }
1094 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
1095 art::Locks::thread_list_lock_->ExclusiveLock(self);
1096 art::Thread* target = nullptr;
1097 jvmtiError err = ERR(INTERNAL);
1098 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1099 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
1100 return err;
1101 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1102 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
1103 return ERR(THREAD_NOT_ALIVE);
1104 }
1105 struct StopThreadClosure : public art::Closure {
1106 public:
1107 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1108
1109 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
1110 // Make sure the thread is prepared to notice the exception.
1111 DeoptManager::Get()->DeoptimizeThread(me);
1112 me->SetAsyncException(exception_.Get());
1113 // Wake up the thread if it is sleeping.
1114 me->Notify();
1115 }
1116
1117 private:
1118 art::Handle<art::mirror::Throwable> exception_;
1119 };
1120 StopThreadClosure c(exc);
1121 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
1122 if (target->RequestSynchronousCheckpoint(&c)) {
1123 return OK;
1124 } else {
1125 // Something went wrong, probably the thread died.
1126 return ERR(THREAD_NOT_ALIVE);
1127 }
1128 }
1129
InterruptThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)1130 jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1131 art::Thread* self = art::Thread::Current();
1132 art::ScopedObjectAccess soa(self);
1133 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1134 art::Thread* target = nullptr;
1135 jvmtiError err = ERR(INTERNAL);
1136 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1137 return err;
1138 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1139 return ERR(THREAD_NOT_ALIVE);
1140 }
1141 target->Interrupt(self);
1142 return OK;
1143 }
1144
1145 } // namespace openjdkjvmti
1146