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