blob: bb8fa3b6943dd5c4e4684774c0202814b6f9c740 [file] [log] [blame]
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001/* 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
Andreas Gampe57943812017-12-06 21:39:13 -080034#include <android-base/logging.h>
35#include <android-base/strings.h>
36
Andreas Gampea1d2f952017-04-20 22:53:58 -070037#include "art_field-inl.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080038#include "art_jvmti.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080039#include "base/mutex.h"
Alex Lighta4cdd362019-04-18 09:17:10 -070040#include "deopt_manager.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080041#include "events-inl.h"
Alex Lightd9aff132017-10-31 22:30:05 +000042#include "gc/collector_type.h"
43#include "gc/gc_cause.h"
44#include "gc/scoped_gc_critical_section.h"
Eric Holk0b986f72021-01-20 22:24:06 +000045#include "gc/system_weak.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080046#include "gc_root-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010047#include "jni/jni_internal.h"
Eric Holk39d529f2021-02-17 12:48:53 -080048#include "metrics/reporter.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080049#include "mirror/class.h"
50#include "mirror/object-inl.h"
51#include "mirror/string.h"
Alex Lighte0b2ce42019-02-21 19:23:42 +000052#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070053#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080054#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080055#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080056#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080057#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080058#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070059#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080060#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070061#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080062#include "well_known_classes.h"
63
64namespace openjdkjvmti {
65
Alex Light184f0752018-07-13 11:18:22 -070066static const char* kJvmtiTlsKey = "JvmtiTlsKey";
67
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070068art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
69
Alex Light679dec12019-04-08 16:30:14 +000070ScopedNoUserCodeSuspension::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
90ScopedNoUserCodeSuspension::~ScopedNoUserCodeSuspension() {
91 art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_);
92}
93
Alex Light1d8a9742017-08-17 11:12:06 -070094struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080095 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 }
Alex Light1d8a9742017-08-17 11:12:06 -0700101
Andreas Gampe983c1752017-01-23 19:46:56 -0800102 template <ArtJvmtiEvent kEvent>
103 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -0800104 DCHECK_EQ(self, art::Thread::Current());
105 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -0800106 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800107 event_handler->DispatchEvent<kEvent>(self,
108 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
109 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800110 }
111
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100112 void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lighte0b2ce42019-02-21 19:23:42 +0000113 // 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 }
Andreas Gampeeafaf572017-01-20 12:34:15 -0800124 if (!started) {
125 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
Florian Mayer516745b2020-01-27 14:29:57 +0000126 // started here; this includes the perfetto_hprof_listener signal handler thread for
Eric Holk0b986f72021-01-20 22:24:06 +0000127 // perfetto_hprof, as well as the metrics background reporting thread.
Andreas Gampeeafaf572017-01-20 12:34:15 -0800128 if (art::kIsDebugBuild) {
129 std::string name;
130 self->GetThreadName(name);
Eric Holk0b986f72021-01-20 22:24:06 +0000131 if (name != "JDWP" && name != "Signal Catcher" && name != "perfetto_hprof_listener" &&
132 name != art::metrics::MetricsReporter::kBackgroundThreadName &&
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800133 !android::base::StartsWith(name, "Jit thread pool") &&
134 !android::base::StartsWith(name, "Runtime worker thread")) {
Alex Light23aa7482017-08-16 10:01:13 -0700135 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
136 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -0800137 }
138 }
139 return;
140 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800141 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800142 }
143
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100144 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800145 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800146 }
147
Andreas Gampeeafaf572017-01-20 12:34:15 -0800148 EventHandler* event_handler = nullptr;
149 bool started = false;
150};
151
152ThreadCallback gThreadCallback;
153
154void 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);
Alex Light1d8a9742017-08-17 11:12:06 -0700164}
165
166void 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());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800172}
173
Alex Lighte0b2ce42019-02-21 19:23:42 +0000174
175static 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
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700189void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700190 // We must have started since it is now safe to cache our data;
191 gThreadCallback.started = true;
Alex Lighte0b2ce42019-02-21 19:23:42 +0000192 art::Thread* self = art::Thread::Current();
193 art::ScopedObjectAccess soa(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700194 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);
Alex Lighte0b2ce42019-02-21 19:23:42 +0000200 // Now wait for all required system threads to come up before allowing the rest of loading to
201 // continue.
202 WaitForSystemDaemonStart(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700203}
204
Andreas Gampeeafaf572017-01-20 12:34:15 -0800205void 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);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800211}
212
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800213jvmtiError 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
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800229// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700230bool ThreadUtil::GetNativeThread(jthread thread,
231 const art::ScopedObjectAccessAlreadyRunnable& soa,
232 /*out*/ art::Thread** thr,
233 /*out*/ jvmtiError* err) {
Alex Lightb7c640d2019-03-20 15:52:13 -0700234 art::ScopedExceptionStorage sse(soa.Self());
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800235 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700236 *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;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800244 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700245}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800246
Alex Light7ddc23d2017-09-22 15:33:41 -0700247bool 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 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800259}
260
261jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
262 if (info_ptr == nullptr) {
263 return ERR(NULL_POINTER);
264 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700265 if (!PhaseUtil::IsLivePhase()) {
266 return JVMTI_ERROR_WRONG_PHASE;
267 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800268
Alex Light3ae82532017-07-26 13:59:07 -0700269 art::Thread* self = art::Thread::Current();
270 art::ScopedObjectAccess soa(self);
271 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800272
Alex Light7ddc23d2017-09-22 15:33:41 -0700273 art::Thread* target;
274 jvmtiError err = ERR(INTERNAL);
275 if (!GetNativeThread(thread, soa, &target, &err)) {
276 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800277 }
278
Andreas Gampe54711412017-02-21 12:41:43 -0800279 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700280 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800281 // Have a native thread object, this thread is alive.
282 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700283 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800284 jvmtiError name_result;
285 name_uptr = CopyString(env, name.c_str(), &name_result);
286 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800287 return name_result;
288 }
Andreas Gampe54711412017-02-21 12:41:43 -0800289 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800290
Alex Light3ae82532017-07-26 13:59:07 -0700291 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800292
Alex Light3ae82532017-07-26 13:59:07 -0700293 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800294
Alex Light3ae82532017-07-26 13:59:07 -0700295 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800296
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.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700310 DCHECK(context_class_loader_ != nullptr);
311 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
312 ? context_class_loader_->GetObject(peer)
313 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800314 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 }
Andreas Gampe54711412017-02-21 12:41:43 -0800335 jvmtiError name_result;
336 name_uptr = CopyString(env, name_cstr, &name_result);
337 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800338 return name_result;
339 }
Andreas Gampe54711412017-02-21 12:41:43 -0800340 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800341 }
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.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700368 DCHECK(context_class_loader_ != nullptr);
369 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
370 ? context_class_loader_->GetObject(peer)
371 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800372 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
Alex Light1f0a22f2017-07-17 12:55:59 -0700382struct 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.
Alex Light7ddc23d2017-09-22 15:33:41 -0700389static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700390 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700391 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700392 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700393 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()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700396 thread_state.art_state = art::ThreadState::kStarting;
397 thread_state.thread_user_code_suspend_count = 0;
398 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700399 thread_state.art_state = target->GetState();
400 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800401 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700402 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800403}
404
Alex Light1f0a22f2017-07-17 12:55:59 -0700405static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
406 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800407 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
408
Alex Light1f0a22f2017-07-17 12:55:59 -0700409 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700410 // 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.
Andreas Gampe72c19832017-01-12 13:22:16 -0800412 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
Alex Light1f0a22f2017-07-17 12:55:59 -0700417 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700418 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700419 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
420 }
421
Alex Light597adad2017-10-16 16:11:42 -0700422 // 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:
Koji Fukui34857b52019-03-20 19:13:00 +0900484 case art::ThreadState::kNativeForAbort:
Alex Light597adad2017-10-16 16:11:42 -0700485 // 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();
Andreas Gampe72c19832017-01-12 13:22:16 -0800495 }
Alex Light597adad2017-10-16 16:11:42 -0700496 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800497
498 return jvmti_state;
499}
500
Alex Light1f0a22f2017-07-17 12:55:59 -0700501static jint GetJavaStateFromInternal(const InternalThreadState& state) {
502 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800503 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:
Alex Light77fee872017-09-05 14:51:49 -0700523 case art::ThreadState::kWaitingForTaskProcessor:
524 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800525 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:
Koji Fukui34857b52019-03-20 19:13:00 +0900540 case art::ThreadState::kNativeForAbort:
Andreas Gampe72c19832017-01-12 13:22:16 -0800541 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
542 }
543 LOG(FATAL) << "Unreachable";
544 UNREACHABLE();
545}
546
Alex Light1f0a22f2017-07-17 12:55:59 -0700547// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700548void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700549 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
Alex Light23aa7482017-08-16 10:01:13 -0700554bool 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
560bool 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
Andreas Gampe72c19832017-01-12 13:22:16 -0800566jvmtiError 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
Alex Light1f0a22f2017-07-17 12:55:59 -0700573 art::Thread* self = art::Thread::Current();
574 InternalThreadState state = {};
Alex Light679dec12019-04-08 16:30:14 +0000575 {
576 ScopedNoUserCodeSuspension snucs(self);
Alex Light1f0a22f2017-07-17 12:55:59 -0700577 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700578 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700579 jvmtiError err = ERR(INTERNAL);
580 art::Thread* target = nullptr;
581 if (!GetNativeThread(thread, soa, &target, &err)) {
582 return err;
583 }
584 state = GetNativeThreadState(target);
Alex Light679dec12019-04-08 16:30:14 +0000585 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);
Alex Light3ae82532017-07-26 13:59:07 -0700600 }
Alex Light679dec12019-04-08 16:30:14 +0000601 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800602
Alex Light3ae82532017-07-26 13:59:07 -0700603 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800604
Alex Light3ae82532017-07-26 13:59:07 -0700605 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);
Andreas Gampe72c19832017-01-12 13:22:16 -0800608 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800609
Alex Light3ae82532017-07-26 13:59:07 -0700610 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700611 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800612
Alex Light3ae82532017-07-26 13:59:07 -0700613 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700614 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");
Alex Light3ae82532017-07-26 13:59:07 -0700621 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700622 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700623 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;
Andreas Gampe72c19832017-01-12 13:22:16 -0800627 return ERR(NONE);
628}
629
Andreas Gampe85807442017-01-13 14:40:58 -0800630jvmtiError 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
Andreas Gampe202f85a2017-02-06 10:23:26 -0800652 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800653 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 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800675 return ERR(NONE);
676}
Andreas Gampe85807442017-01-13 14:40:58 -0800677
Alex Light092a4042017-07-12 08:46:44 -0700678static 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());
Alex Light0aa7a5a2018-10-10 15:58:14 +0000681 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700682 if (global_tls != nullptr) {
683 global_tls->data.erase(env);
684 }
685}
686
687void 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
694jvmtiError 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_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700698 art::Thread* target = nullptr;
699 jvmtiError err = ERR(INTERNAL);
700 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
701 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800702 }
703
Alex Light0aa7a5a2018-10-10 15:58:14 +0000704 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700705
706 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800707
708 return ERR(NONE);
709}
710
Alex Light0aa7a5a2018-10-10 15:58:14 +0000711JvmtiGlobalTLSData* 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
721JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
722 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
723}
724
Alex Light092a4042017-07-12 08:46:44 -0700725jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800726 jthread thread,
727 void** data_ptr) {
728 if (data_ptr == nullptr) {
729 return ERR(NULL_POINTER);
730 }
731
Alex Light092a4042017-07-12 08:46:44 -0700732 art::Thread* self = art::Thread::Current();
733 art::ScopedObjectAccess soa(self);
734 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700735 art::Thread* target = nullptr;
736 jvmtiError err = ERR(INTERNAL);
737 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
738 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800739 }
740
Alex Light0aa7a5a2018-10-10 15:58:14 +0000741 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700742 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
Andreas Gampe85807442017-01-13 14:40:58 -0800753 return ERR(NONE);
754}
755
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800756struct AgentData {
757 const void* arg;
758 jvmtiStartFunction proc;
759 jthread thread;
760 JavaVM* java_vm;
761 jvmtiEnv* jvmti_env;
762 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800763 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800764};
765
766static 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.
Alex Light93112972017-11-13 10:38:59 -0800771 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700772 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800773 // 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);
Alex Light93112972017-11-13 10:38:59 -0800777 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800778 }
779
780 // Release the peer.
781 JNIEnv* env = self->GetJniEnv();
782 env->DeleteGlobalRef(data->thread);
783 data->thread = nullptr;
784
Alex Light739bf722017-10-20 13:14:24 -0700785 {
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
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800792 // 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
802jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
803 jthread thread,
804 jvmtiStartFunction proc,
805 const void* arg,
806 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700807 if (!PhaseUtil::IsLivePhase()) {
808 return ERR(WRONG_PHASE);
809 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800810 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
Alex Light739bf722017-10-20 13:14:24 -0700821 {
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
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800836 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;
Alex Light93112972017-11-13 10:38:59 -0800844 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 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800854
855 pthread_t pthread;
856 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700857 nullptr,
858 &AgentCallback,
859 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800860 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700861 // 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();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800865 return ERR(INTERNAL);
866 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700867 data.release(); // NOLINT pthreads API.
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800868
869 return ERR(NONE);
870}
871
Alex Light88fd7202017-06-30 08:31:59 -0700872jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700873 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700874 // 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 {
Alex Light679dec12019-04-08 16:30:14 +0000878 ScopedNoUserCodeSuspension snucs(self);
Alex Light23aa7482017-08-16 10:01:13 -0700879 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700880 {
881 art::ScopedObjectAccess soa(self);
882 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700883 art::Thread* target = nullptr;
884 jvmtiError err = ERR(INTERNAL);
885 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
886 return err;
887 }
Alex Lightcea42152018-09-18 22:51:55 +0000888 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 }
Alex Light88fd7202017-06-30 08:31:59 -0700897 }
Alex Lightcea42152018-09-18 22:51:55 +0000898 bool timeout = true;
899 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
900 target_jthread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700901 /* request_suspension= */ true,
Alex Lightcea42152018-09-18 22:51:55 +0000902 art::SuspendReason::kForUserCode,
903 &timeout);
904 if (ret_target == nullptr && !timeout) {
Alex Light3ae82532017-07-26 13:59:07 -0700905 // TODO It would be good to get more information about why exactly the thread failed to
906 // suspend.
907 return ERR(INTERNAL);
Alex Lightcea42152018-09-18 22:51:55 +0000908 } else if (!timeout) {
909 // we didn't time out and got a result.
910 return OK;
Alex Light3ae82532017-07-26 13:59:07 -0700911 }
912 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700913 } while (true);
914 UNREACHABLE();
915}
916
917jvmtiError 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
939jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
940 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700941 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700942 {
943 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700944 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700945 art::Thread* target = nullptr;
946 jvmtiError err = ERR(INTERNAL);
947 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
948 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700949 } else if (target == self) {
950 target_is_self = true;
951 }
Alex Light88fd7202017-06-30 08:31:59 -0700952 }
Alex Light3ae82532017-07-26 13:59:07 -0700953 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700954 return SuspendSelf(self);
955 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700956 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700957 }
958}
959
960jvmtiError 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();
Alex Lightcea42152018-09-18 22:51:55 +0000966 art::Thread* target;
Alex Light679dec12019-04-08 16:30:14 +0000967
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);
Alex Light88fd7202017-06-30 08:31:59 -0700984 }
Alex Light679dec12019-04-08 16:30:14 +0000985 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
986 // cannot tell why resume failed.
Alex Lightcea42152018-09-18 22:51:55 +0000987 {
Alex Light679dec12019-04-08 16:30:14 +0000988 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
989 if (target->GetUserCodeSuspendCount() == 0) {
Alex Lightcea42152018-09-18 22:51:55 +0000990 return ERR(THREAD_NOT_SUSPENDED);
991 }
Alex Light3ae82532017-07-26 13:59:07 -0700992 }
Alex Light679dec12019-04-08 16:30:14 +0000993 }
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 }
Alex Light88fd7202017-06-30 08:31:59 -07001005}
1006
Alex Light7ddc23d2017-09-22 15:33:41 -07001007static 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
Alex Light88fd7202017-06-30 08:31:59 -07001023// 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.
1029jvmtiError 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;
Alex Light88fd7202017-06-30 08:31:59 -07001042 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001043 if (IsCurrentThread(threads[i])) {
1044 current_thread_indexes.push_back(i);
1045 } else {
1046 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001047 }
Alex Light88fd7202017-06-30 08:31:59 -07001048 }
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
1063jvmtiError 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
Alex Light54d39dc2017-09-25 17:00:16 -07001078jvmtiError 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()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001092 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001093 art::Thread* target = nullptr;
1094 jvmtiError err = ERR(INTERNAL);
1095 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001096 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001097 return err;
1098 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001099 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001100 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
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001106 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001107 // Make sure the thread is prepared to notice the exception.
Alex Lighta4cdd362019-04-18 09:17:10 -07001108 DeoptManager::Get()->DeoptimizeThread(me);
Alex Light54d39dc2017-09-25 17:00:16 -07001109 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);
Alex Lightb1e31a82017-10-04 16:57:36 -07001118 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001119 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001120 return OK;
1121 } else {
1122 // Something went wrong, probably the thread died.
1123 return ERR(THREAD_NOT_ALIVE);
1124 }
1125}
1126
1127jvmtiError 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
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001142} // namespace openjdkjvmti