• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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-inl.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, "Heap thread pool worker thread") &&
135             !android::base::StartsWith(name, "Runtime worker thread")) {
136           LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
137                      << self->GetThreadId();
138         }
139       }
140       return;
141     }
142     Post<ArtJvmtiEvent::kThreadStart>(self);
143   }
144 
ThreadDeathopenjdkjvmti::ThreadCallback145   void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
146     Post<ArtJvmtiEvent::kThreadEnd>(self);
147   }
148 
149   EventHandler* event_handler = nullptr;
150   bool started = false;
151 };
152 
153 ThreadCallback gThreadCallback;
154 
Register(EventHandler * handler)155 void ThreadUtil::Register(EventHandler* handler) {
156   art::Runtime* runtime = art::Runtime::Current();
157 
158   gThreadCallback.started = runtime->IsStarted();
159   gThreadCallback.event_handler = handler;
160 
161   art::ScopedThreadStateChange stsc(art::Thread::Current(),
162                                     art::ThreadState::kWaitingForDebuggerToAttach);
163   art::ScopedSuspendAll ssa("Add thread callback");
164   runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
165 }
166 
VMInitEventSent()167 void ThreadUtil::VMInitEventSent() {
168   // We should have already started.
169   DCHECK(gThreadCallback.started);
170   // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
171   // reported until Init.
172   gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
173 }
174 
175 
WaitForSystemDaemonStart(art::Thread * self)176 static void WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
177   art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart->InvokeStatic<'V'>(self);
178   if (self->IsExceptionPending()) {
179     LOG(WARNING) << "Exception occurred when waiting for system daemons to start: "
180                  << self->GetException()->Dump();
181     self->ClearException();
182   }
183 }
184 
CacheData()185 void ThreadUtil::CacheData() {
186   // We must have started since it is now safe to cache our data;
187   gThreadCallback.started = true;
188   art::Thread* self = art::Thread::Current();
189   art::ScopedObjectAccess soa(self);
190   art::ObjPtr<art::mirror::Class> thread_class = art::WellKnownClasses::java_lang_Thread.Get();
191   CHECK(thread_class != nullptr);
192   context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
193                                                                   "Ljava/lang/ClassLoader;");
194   CHECK(context_class_loader_ != nullptr);
195   // Now wait for all required system threads to come up before allowing the rest of loading to
196   // continue.
197   WaitForSystemDaemonStart(self);
198 }
199 
Unregister()200 void ThreadUtil::Unregister() {
201   art::ScopedThreadStateChange stsc(art::Thread::Current(),
202                                     art::ThreadState::kWaitingForDebuggerToAttach);
203   art::ScopedSuspendAll ssa("Remove thread callback");
204   art::Runtime* runtime = art::Runtime::Current();
205   runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
206 }
207 
GetCurrentThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread * thread_ptr)208 jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
209   art::Thread* self = art::Thread::Current();
210 
211   art::ScopedObjectAccess soa(self);
212 
213   jthread thread_peer;
214   if (self->IsStillStarting()) {
215     thread_peer = nullptr;
216   } else {
217     thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
218   }
219 
220   *thread_ptr = thread_peer;
221   return ERR(NONE);
222 }
223 
224 // 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)225 bool ThreadUtil::GetNativeThread(jthread thread,
226                                  const art::ScopedObjectAccessAlreadyRunnable& soa,
227                                  /*out*/ art::Thread** thr,
228                                  /*out*/ jvmtiError* err) {
229   art::ScopedExceptionStorage sse(soa.Self());
230   if (thread == nullptr) {
231     *thr = art::Thread::Current();
232     return true;
233   }
234   art::ObjPtr<art::mirror::Object> othread = soa.Decode<art::mirror::Object>(thread);
235   if (!othread->InstanceOf(art::WellKnownClasses::java_lang_Thread.Get())) {
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::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::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::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::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::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::kObsoleteRunnable:  // Obsolete value.
488     case art::ThreadState::kStarting:
489     case art::ThreadState::kTerminated:
490       // We only call this if we are alive so we shouldn't see either of these states.
491       LOG(FATAL) << "Should not be in state " << internal_thread_state;
492       UNREACHABLE();
493   }
494   // TODO: PARKED. We'll have to inspect the stack.
495 
496   return jvmti_state;
497 }
498 
GetJavaStateFromInternal(const InternalThreadState & state)499 static jint GetJavaStateFromInternal(const InternalThreadState& state) {
500   switch (state.art_state) {
501     case art::ThreadState::kTerminated:
502       return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
503 
504     case art::ThreadState::kRunnable:
505     case art::ThreadState::kNative:
506     case art::ThreadState::kWaitingWeakGcRootRead:
507     case art::ThreadState::kSuspended:
508       return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
509 
510     case art::ThreadState::kTimedWaiting:
511     case art::ThreadState::kSleeping:
512       return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
513 
514     case art::ThreadState::kBlocked:
515       return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
516 
517     case art::ThreadState::kStarting:
518       return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
519 
520     case art::ThreadState::kWaiting:
521     case art::ThreadState::kWaitingForTaskProcessor:
522     case art::ThreadState::kWaitingForLockInflation:
523     case art::ThreadState::kWaitingForGcToComplete:
524     case art::ThreadState::kWaitingPerformingGc:
525     case art::ThreadState::kWaitingForCheckPointsToRun:
526     case art::ThreadState::kWaitingForDebuggerSend:
527     case art::ThreadState::kWaitingForDebuggerToAttach:
528     case art::ThreadState::kWaitingInMainDebuggerLoop:
529     case art::ThreadState::kWaitingForDebuggerSuspension:
530     case art::ThreadState::kWaitingForDeoptimization:
531     case art::ThreadState::kWaitingForGetObjectsAllocated:
532     case art::ThreadState::kWaitingForJniOnLoad:
533     case art::ThreadState::kWaitingForSignalCatcherOutput:
534     case art::ThreadState::kWaitingInMainSignalCatcherLoop:
535     case art::ThreadState::kWaitingForMethodTracingStart:
536     case art::ThreadState::kWaitingForVisitObjects:
537     case art::ThreadState::kWaitingForGcThreadFlip:
538     case art::ThreadState::kNativeForAbort:
539       return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
540 
541     case art::ThreadState::kObsoleteRunnable:
542       break;  // Obsolete value.
543   }
544   LOG(FATAL) << "Unreachable";
545   UNREACHABLE();
546 }
547 
548 // Suspends the current thread if it has any suspend requests on it.
SuspendCheck(art::Thread * self)549 void ThreadUtil::SuspendCheck(art::Thread* self) {
550   art::ScopedObjectAccess soa(self);
551   // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
552   self->FullSuspendCheck();
553 }
554 
WouldSuspendForUserCodeLocked(art::Thread * self)555 bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
556   DCHECK(self == art::Thread::Current());
557   art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
558   return self->GetUserCodeSuspendCount() != 0;
559 }
560 
WouldSuspendForUserCode(art::Thread * self)561 bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
562   DCHECK(self == art::Thread::Current());
563   art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
564   return WouldSuspendForUserCodeLocked(self);
565 }
566 
GetThreadState(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread,jint * thread_state_ptr)567 jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
568                                       jthread thread,
569                                       jint* thread_state_ptr) {
570   if (thread_state_ptr == nullptr) {
571     return ERR(NULL_POINTER);
572   }
573 
574   art::Thread* self = art::Thread::Current();
575   InternalThreadState state = {};
576   {
577     ScopedNoUserCodeSuspension snucs(self);
578     art::ScopedObjectAccess soa(self);
579     art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
580     jvmtiError err = ERR(INTERNAL);
581     art::Thread* target = nullptr;
582     if (!GetNativeThread(thread, soa, &target, &err)) {
583       return err;
584     }
585     state = GetNativeThreadState(target);
586     if (state.art_state != art::ThreadState::kStarting) {
587       DCHECK(state.native_thread != nullptr);
588 
589       // Translate internal thread state to JVMTI and Java state.
590       jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
591 
592       // Java state is derived from nativeGetState.
593       // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
594       //       different mask if a thread got suspended due to user-code. However, this is for
595       //       consistency with the Java view.
596       jint java_state = GetJavaStateFromInternal(state);
597 
598       *thread_state_ptr = jvmti_state | java_state;
599 
600       return ERR(NONE);
601     }
602   }
603 
604   DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
605 
606   if (thread == nullptr) {
607     // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
608     return ERR(WRONG_PHASE);
609   }
610 
611   art::ScopedObjectAccess soa(self);
612   art::StackHandleScope<1> hs(self);
613 
614   // Need to read the Java "started" field to know whether this is starting or terminated.
615   art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
616   art::ObjPtr<art::mirror::Class> thread_klass = art::WellKnownClasses::java_lang_Thread.Get();
617   if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
618     return ERR(INVALID_THREAD);
619   }
620   art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
621   CHECK(started_field != nullptr);
622   bool started = started_field->GetBoolean(peer.Get()) != 0;
623   constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
624   constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
625                                     JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
626   *thread_state_ptr = started ? kTerminatedState : kStartedState;
627   return ERR(NONE);
628 }
629 
GetAllThreads(jvmtiEnv * env,jint * threads_count_ptr,jthread ** threads_ptr)630 jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
631                                      jint* threads_count_ptr,
632                                      jthread** threads_ptr) {
633   if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
634     return ERR(NULL_POINTER);
635   }
636 
637   art::Thread* current = art::Thread::Current();
638 
639   art::ScopedObjectAccess soa(current);
640 
641   art::MutexLock mu(current, *art::Locks::thread_list_lock_);
642   std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
643 
644   std::vector<art::ObjPtr<art::mirror::Object>> peers;
645 
646   for (art::Thread* thread : thread_list) {
647     // Skip threads that are still starting.
648     if (thread->IsStillStarting()) {
649       continue;
650     }
651 
652     art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
653     if (peer != nullptr) {
654       peers.push_back(peer);
655     }
656   }
657 
658   if (peers.empty()) {
659     *threads_count_ptr = 0;
660     *threads_ptr = nullptr;
661   } else {
662     unsigned char* data;
663     jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
664     if (data_result != ERR(NONE)) {
665       return data_result;
666     }
667     jthread* threads = reinterpret_cast<jthread*>(data);
668     for (size_t i = 0; i != peers.size(); ++i) {
669       threads[i] = soa.AddLocalReference<jthread>(peers[i]);
670     }
671 
672     *threads_count_ptr = static_cast<jint>(peers.size());
673     *threads_ptr = threads;
674   }
675   return ERR(NONE);
676 }
677 
RemoveTLSData(art::Thread * target,void * ctx)678 static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
679   jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
680   art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
681   JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
682   if (global_tls != nullptr) {
683     global_tls->data.erase(env);
684   }
685 }
686 
RemoveEnvironment(jvmtiEnv * env)687 void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
688   art::Thread* self = art::Thread::Current();
689   art::MutexLock mu(self, *art::Locks::thread_list_lock_);
690   art::ThreadList* list = art::Runtime::Current()->GetThreadList();
691   list->ForEach(RemoveTLSData, env);
692 }
693 
SetThreadLocalStorage(jvmtiEnv * env,jthread thread,const void * data)694 jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
695   art::Thread* self = art::Thread::Current();
696   art::ScopedObjectAccess soa(self);
697   art::MutexLock mu(self, *art::Locks::thread_list_lock_);
698   art::Thread* target = nullptr;
699   jvmtiError err = ERR(INTERNAL);
700   if (!GetAliveNativeThread(thread, soa, &target, &err)) {
701     return err;
702   }
703 
704   JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
705 
706   global_tls->data[env] = data;
707 
708   return ERR(NONE);
709 }
710 
GetOrCreateGlobalTLSData(art::Thread * thread)711 JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
712   JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
713   if (data != nullptr) {
714     return data;
715   } else {
716     thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
717     return GetGlobalTLSData(thread);
718   }
719 }
720 
GetGlobalTLSData(art::Thread * thread)721 JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
722   return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
723 }
724 
GetThreadLocalStorage(jvmtiEnv * env,jthread thread,void ** data_ptr)725 jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
726                                              jthread thread,
727                                              void** data_ptr) {
728   if (data_ptr == nullptr) {
729     return ERR(NULL_POINTER);
730   }
731 
732   art::Thread* self = art::Thread::Current();
733   art::ScopedObjectAccess soa(self);
734   art::MutexLock mu(self, *art::Locks::thread_list_lock_);
735   art::Thread* target = nullptr;
736   jvmtiError err = ERR(INTERNAL);
737   if (!GetAliveNativeThread(thread, soa, &target, &err)) {
738     return err;
739   }
740 
741   JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
742   if (global_tls == nullptr) {
743     *data_ptr = nullptr;
744     return OK;
745   }
746   auto it = global_tls->data.find(env);
747   if (it != global_tls->data.end()) {
748     *data_ptr = const_cast<void*>(it->second);
749   } else {
750     *data_ptr = nullptr;
751   }
752 
753   return ERR(NONE);
754 }
755 
756 struct AgentData {
757   const void* arg;
758   jvmtiStartFunction proc;
759   jthread thread;
760   JavaVM* java_vm;
761   jvmtiEnv* jvmti_env;
762   jint priority;
763   std::string name;
764 };
765 
AgentCallback(void * arg)766 static void* AgentCallback(void* arg) {
767   std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
768   CHECK(data->thread != nullptr);
769 
770   // We already have a peer. So call our special Attach function.
771   art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
772   CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
773   // The name in Attach() is only for logging. Set the thread name. This is important so
774   // that the thread is no longer seen as starting up.
775   {
776     art::ScopedObjectAccess soa(self);
777     self->SetThreadName(data->name.c_str());
778   }
779 
780   // Release the peer.
781   JNIEnv* env = self->GetJniEnv();
782   env->DeleteGlobalRef(data->thread);
783   data->thread = nullptr;
784 
785   {
786     // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
787     // before going into the provided code.
788     art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
789     art::Runtime::Current()->EndThreadBirth();
790   }
791 
792   // Run the agent code.
793   data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
794 
795   // Detach the thread.
796   int detach_result = data->java_vm->DetachCurrentThread();
797   CHECK_EQ(detach_result, 0);
798 
799   return nullptr;
800 }
801 
RunAgentThread(jvmtiEnv * jvmti_env,jthread thread,jvmtiStartFunction proc,const void * arg,jint priority)802 jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
803                                       jthread thread,
804                                       jvmtiStartFunction proc,
805                                       const void* arg,
806                                       jint priority) {
807   if (!PhaseUtil::IsLivePhase()) {
808     return ERR(WRONG_PHASE);
809   }
810   if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
811     return ERR(INVALID_PRIORITY);
812   }
813   if (thread == nullptr) {
814     return ERR(INVALID_THREAD);
815   }
816   art::Runtime* runtime = art::Runtime::Current();
817   art::Thread* self = art::Thread::Current();
818   std::unique_ptr<AgentData> data;
819   {
820     art::ScopedObjectAccess soa(self);
821     art::ObjPtr<art::mirror::Object> othread = soa.Decode<art::mirror::Object>(thread);
822     if (!othread->InstanceOf(art::WellKnownClasses::java_lang_Thread.Get())) {
823       return ERR(INVALID_THREAD);
824     }
825     if (proc == nullptr) {
826       return ERR(NULL_POINTER);
827     }
828 
829     {
830       art::MutexLock mu(soa.Self(), *art::Locks::runtime_shutdown_lock_);
831       if (runtime->IsShuttingDownLocked()) {
832         // The runtime is shutting down so we cannot create new threads.
833         // TODO It's not fully clear from the spec what we should do here. We aren't yet in
834         // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
835         // impossible. Existing agents don't seem to generally do anything with this return value so
836         // it doesn't matter too much. We could do something like sending a fake ThreadStart event
837         // even though code is never actually run.
838         return ERR(INTERNAL);
839       }
840       runtime->StartThreadBirth();
841     }
842 
843     data.reset(new AgentData);
844     data->arg = arg;
845     data->proc = proc;
846     // We need a global ref for Java objects, as local refs will be invalid.
847     data->thread = runtime->GetJavaVM()->AddGlobalRef(soa.Self(), othread);
848     data->java_vm = runtime->GetJavaVM();
849     data->jvmti_env = jvmti_env;
850     data->priority = priority;
851     art::ObjPtr<art::mirror::Object> name =
852         art::WellKnownClasses::java_lang_Thread_name->GetObject(
853             soa.Decode<art::mirror::Object>(thread));
854     if (name == nullptr) {
855       data->name = "JVMTI Agent Thread";
856     } else {
857       data->name = name->AsString()->ToModifiedUtf8();
858     }
859   }
860 
861   pthread_t pthread;
862   int pthread_create_result = pthread_create(&pthread,
863                                             nullptr,
864                                             &AgentCallback,
865                                             reinterpret_cast<void*>(data.get()));
866   if (pthread_create_result != 0) {
867     // If the create succeeded the other thread will call EndThreadBirth.
868     art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
869     runtime->EndThreadBirth();
870     return ERR(INTERNAL);
871   }
872   data.release();  // NOLINT pthreads API.
873 
874   return ERR(NONE);
875 }
876 
SuspendOther(art::Thread * self,jthread target_jthread)877 jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
878                                     jthread target_jthread) {
879   // Loop since we need to bail out and try again if we would end up getting suspended while holding
880   // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
881   // release the lock, wait to get resumed and try again.
882   do {
883     ScopedNoUserCodeSuspension snucs(self);
884     // We are not going to be suspended by user code from now on.
885     {
886       art::ScopedObjectAccess soa(self);
887       art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
888       art::Thread* target = nullptr;
889       jvmtiError err = ERR(INTERNAL);
890       if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
891         return err;
892       }
893       art::ThreadState state = target->GetState();
894       if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
895         return ERR(THREAD_NOT_ALIVE);
896       } else {
897         art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
898         if (target->GetUserCodeSuspendCount() != 0) {
899           return ERR(THREAD_SUSPENDED);
900         }
901       }
902     }
903     bool timeout = true;
904     art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
905         target_jthread,
906         art::SuspendReason::kForUserCode,
907         &timeout);
908     if (ret_target == nullptr && !timeout) {
909       // TODO It would be good to get more information about why exactly the thread failed to
910       // suspend.
911       return ERR(INTERNAL);
912     } else if (!timeout) {
913       // we didn't time out and got a result.
914       return OK;
915     }
916     // We timed out. Just go around and try again.
917   } while (true);
918   UNREACHABLE();
919 }
920 
SuspendSelf(art::Thread * self)921 jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
922   CHECK(self == art::Thread::Current());
923   {
924     art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
925     art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
926     if (self->GetUserCodeSuspendCount() != 0) {
927       // This can only happen if we race with another thread to suspend 'self' and we lose.
928       return ERR(THREAD_SUSPENDED);
929     }
930     // We shouldn't be able to fail this.
931     if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
932       // TODO More specific error would be nice.
933       return ERR(INTERNAL);
934     }
935   }
936   // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
937   // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
938   // to go to sleep until we are resumed.
939   SuspendCheck(self);
940   return OK;
941 }
942 
SuspendThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)943 jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
944   art::Thread* self = art::Thread::Current();
945   bool target_is_self = false;
946   {
947     art::ScopedObjectAccess soa(self);
948     art::MutexLock mu(self, *art::Locks::thread_list_lock_);
949     art::Thread* target = nullptr;
950     jvmtiError err = ERR(INTERNAL);
951     if (!GetAliveNativeThread(thread, soa, &target, &err)) {
952       return err;
953     } else if (target == self) {
954       target_is_self = true;
955     }
956   }
957   if (target_is_self) {
958     return SuspendSelf(self);
959   } else {
960     return SuspendOther(self, thread);
961   }
962 }
963 
ResumeThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)964 jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
965                                     jthread thread) {
966   if (thread == nullptr) {
967     return ERR(NULL_POINTER);
968   }
969   art::Thread* self = art::Thread::Current();
970   art::Thread* target;
971 
972   // Make sure we won't get suspended ourselves while in the middle of resuming another thread.
973   ScopedNoUserCodeSuspension snucs(self);
974   // From now on we know we cannot get suspended by user-code.
975   {
976     // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
977     // have the 'suspend_lock' locked here.
978     art::ScopedObjectAccess soa(self);
979     art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
980     jvmtiError err = ERR(INTERNAL);
981     if (!GetAliveNativeThread(thread, soa, &target, &err)) {
982       return err;
983     } else if (target == self) {
984       // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
985       // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
986       // about current state since it's all concurrent.
987       return ERR(THREAD_NOT_SUSPENDED);
988     }
989     // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
990     // cannot tell why resume failed.
991     {
992       art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
993       if (target->GetUserCodeSuspendCount() == 0) {
994         return ERR(THREAD_NOT_SUSPENDED);
995       }
996     }
997   }
998   // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
999   // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
1000   DCHECK(target != self);
1001   if (!art::Runtime::Current()->GetThreadList()->Resume(target,
1002                                                         art::SuspendReason::kForUserCode)) {
1003     // TODO Give a better error.
1004     // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
1005     return ERR(INTERNAL);
1006   } else {
1007     return OK;
1008   }
1009 }
1010 
IsCurrentThread(jthread thr)1011 static bool IsCurrentThread(jthread thr) {
1012   if (thr == nullptr) {
1013     return true;
1014   }
1015   art::Thread* self = art::Thread::Current();
1016   art::ScopedObjectAccess soa(self);
1017   art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1018   art::Thread* target = nullptr;
1019   jvmtiError err_unused = ERR(INTERNAL);
1020   if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1021     return target == self;
1022   } else {
1023     return false;
1024   }
1025 }
1026 
1027 // Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1028 // since we can have threads in the list multiple times. This generally doesn't matter unless the
1029 // current thread is present multiple times. In that case we need to suspend only once and either
1030 // return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1031 // it didn't. We also want to handle the current thread last to make the behavior of the code
1032 // simpler to understand.
SuspendThreadList(jvmtiEnv * env,jint request_count,const jthread * threads,jvmtiError * results)1033 jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1034                                          jint request_count,
1035                                          const jthread* threads,
1036                                          jvmtiError* results) {
1037   if (request_count == 0) {
1038     return ERR(ILLEGAL_ARGUMENT);
1039   } else if (results == nullptr || threads == nullptr) {
1040     return ERR(NULL_POINTER);
1041   }
1042   // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1043   // running thread. These indexes we need to handle specially since we need to only actually
1044   // suspend a single time.
1045   std::vector<jint> current_thread_indexes;
1046   for (jint i = 0; i < request_count; i++) {
1047     if (IsCurrentThread(threads[i])) {
1048       current_thread_indexes.push_back(i);
1049     } else {
1050       results[i] = env->SuspendThread(threads[i]);
1051     }
1052   }
1053   if (!current_thread_indexes.empty()) {
1054     jint first_current_thread_index = current_thread_indexes[0];
1055     // Suspend self.
1056     jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1057     results[first_current_thread_index] = res;
1058     // Fill in the rest of the error values as appropriate.
1059     jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1060     for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1061       results[*it] = other_results;
1062     }
1063   }
1064   return OK;
1065 }
1066 
ResumeThreadList(jvmtiEnv * env,jint request_count,const jthread * threads,jvmtiError * results)1067 jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1068                                         jint request_count,
1069                                         const jthread* threads,
1070                                         jvmtiError* results) {
1071   if (request_count == 0) {
1072     return ERR(ILLEGAL_ARGUMENT);
1073   } else if (results == nullptr || threads == nullptr) {
1074     return ERR(NULL_POINTER);
1075   }
1076   for (jint i = 0; i < request_count; i++) {
1077     results[i] = env->ResumeThread(threads[i]);
1078   }
1079   return OK;
1080 }
1081 
StopThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread,jobject exception)1082 jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1083                                   jthread thread,
1084                                   jobject exception) {
1085   art::Thread* self = art::Thread::Current();
1086   art::ScopedObjectAccess soa(self);
1087   art::StackHandleScope<1> hs(self);
1088   if (exception == nullptr) {
1089     return ERR(INVALID_OBJECT);
1090   }
1091   art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1092   if (!obj->GetClass()->IsThrowableClass()) {
1093     return ERR(INVALID_OBJECT);
1094   }
1095   art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
1096   art::Locks::thread_list_lock_->ExclusiveLock(self);
1097   art::Thread* target = nullptr;
1098   jvmtiError err = ERR(INTERNAL);
1099   if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1100     art::Locks::thread_list_lock_->ExclusiveUnlock(self);
1101     return err;
1102   } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1103     art::Locks::thread_list_lock_->ExclusiveUnlock(self);
1104     return ERR(THREAD_NOT_ALIVE);
1105   }
1106   struct StopThreadClosure : public art::Closure {
1107    public:
1108     explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1109 
1110     void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
1111       // Make sure the thread is prepared to notice the exception.
1112       DeoptManager::Get()->DeoptimizeThread(me);
1113       me->SetAsyncException(exception_.Get());
1114       // Wake up the thread if it is sleeping.
1115       me->Notify();
1116     }
1117 
1118    private:
1119     art::Handle<art::mirror::Throwable> exception_;
1120   };
1121   StopThreadClosure c(exc);
1122   // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
1123   if (target->RequestSynchronousCheckpoint(&c)) {
1124     return OK;
1125   } else {
1126     // Something went wrong, probably the thread died.
1127     return ERR(THREAD_NOT_ALIVE);
1128   }
1129 }
1130 
InterruptThread(jvmtiEnv * env ATTRIBUTE_UNUSED,jthread thread)1131 jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1132   art::Thread* self = art::Thread::Current();
1133   art::ScopedObjectAccess soa(self);
1134   art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1135   art::Thread* target = nullptr;
1136   jvmtiError err = ERR(INTERNAL);
1137   if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1138     return err;
1139   } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1140     return ERR(THREAD_NOT_ALIVE);
1141   }
1142   target->Interrupt(self);
1143   return OK;
1144 }
1145 
1146 }  // namespace openjdkjvmti
1147