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