blob: b0a7f1f3f7d3efbed104119adc0c27f2f8affcce [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"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080042#include "gc/system_weak.h"
Alex Lightd9aff132017-10-31 22:30:05 +000043#include "gc/collector_type.h"
44#include "gc/gc_cause.h"
45#include "gc/scoped_gc_critical_section.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"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080048#include "mirror/class.h"
49#include "mirror/object-inl.h"
50#include "mirror/string.h"
Alex Lighte0b2ce42019-02-21 19:23:42 +000051#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070052#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080053#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080054#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080055#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080056#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080057#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070058#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080059#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070060#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080061#include "well_known_classes.h"
62
63namespace openjdkjvmti {
64
Alex Light184f0752018-07-13 11:18:22 -070065static const char* kJvmtiTlsKey = "JvmtiTlsKey";
66
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070067art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
68
Alex Light679dec12019-04-08 16:30:14 +000069ScopedNoUserCodeSuspension::ScopedNoUserCodeSuspension(art::Thread* self) : self_(self) {
70 DCHECK_EQ(self, art::Thread::Current());
71 // Loop until we both have the user_code_suspension_locK_ and don't have any pending user_code
72 // suspensions.
73 do {
74 art::Locks::user_code_suspension_lock_->AssertNotHeld(self_);
75 ThreadUtil::SuspendCheck(self_);
76
77 art::Locks::user_code_suspension_lock_->ExclusiveLock(self_);
78 if (ThreadUtil::WouldSuspendForUserCodeLocked(self_)) {
79 art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_);
80 continue;
81 }
82
83 art::Locks::user_code_suspension_lock_->AssertHeld(self_);
84
85 return;
86 } while (true);
87}
88
89ScopedNoUserCodeSuspension::~ScopedNoUserCodeSuspension() {
90 art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_);
91}
92
Alex Light1d8a9742017-08-17 11:12:06 -070093struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080094 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
95 if (self->GetPeer() == nullptr) {
96 return nullptr;
97 }
98 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
99 }
Alex Light1d8a9742017-08-17 11:12:06 -0700100
Andreas Gampe983c1752017-01-23 19:46:56 -0800101 template <ArtJvmtiEvent kEvent>
102 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -0800103 DCHECK_EQ(self, art::Thread::Current());
104 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -0800105 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800106 event_handler->DispatchEvent<kEvent>(self,
107 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
108 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800109 }
110
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100111 void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lighte0b2ce42019-02-21 19:23:42 +0000112 // Needs to be checked first because we might start these threads before we actually send the
113 // VMInit event.
114 if (self->IsSystemDaemon()) {
115 // System daemon threads are things like the finalizer or gc thread. It would be dangerous to
116 // allow agents to get in the way of these threads starting up. These threads include things
117 // like the HeapTaskDaemon and the finalizer daemon.
118 //
119 // This event can happen during the time before VMInit or just after zygote fork. Since the
120 // second is hard to distinguish we unfortunately cannot really check the state here.
121 return;
122 }
Andreas Gampeeafaf572017-01-20 12:34:15 -0800123 if (!started) {
124 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
Florian Mayer07710c52019-09-16 15:53:38 +0000125 // started here; this includes the hprof_listener signal handler thread for perfetto_hprof.
Andreas Gampeeafaf572017-01-20 12:34:15 -0800126 if (art::kIsDebugBuild) {
127 std::string name;
128 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -0800129 if (name != "JDWP" &&
130 name != "Signal Catcher" &&
Florian Mayer07710c52019-09-16 15:53:38 +0000131 name != "hprof_listener" &&
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800132 !android::base::StartsWith(name, "Jit thread pool") &&
133 !android::base::StartsWith(name, "Runtime worker thread")) {
Alex Light23aa7482017-08-16 10:01:13 -0700134 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
135 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -0800136 }
137 }
138 return;
139 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800140 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800141 }
142
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100143 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800144 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800145 }
146
Andreas Gampeeafaf572017-01-20 12:34:15 -0800147 EventHandler* event_handler = nullptr;
148 bool started = false;
149};
150
151ThreadCallback gThreadCallback;
152
153void ThreadUtil::Register(EventHandler* handler) {
154 art::Runtime* runtime = art::Runtime::Current();
155
156 gThreadCallback.started = runtime->IsStarted();
157 gThreadCallback.event_handler = handler;
158
159 art::ScopedThreadStateChange stsc(art::Thread::Current(),
160 art::ThreadState::kWaitingForDebuggerToAttach);
161 art::ScopedSuspendAll ssa("Add thread callback");
162 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700163}
164
165void ThreadUtil::VMInitEventSent() {
166 // We should have already started.
167 DCHECK(gThreadCallback.started);
168 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
169 // reported until Init.
170 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800171}
172
Alex Lighte0b2ce42019-02-21 19:23:42 +0000173
174static void WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
175 {
176 art::ScopedThreadStateChange strc(self, art::kNative);
177 JNIEnv* jni = self->GetJniEnv();
178 jni->CallStaticVoidMethod(art::WellKnownClasses::java_lang_Daemons,
179 art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart);
180 }
181 if (self->IsExceptionPending()) {
182 LOG(WARNING) << "Exception occurred when waiting for system daemons to start: "
183 << self->GetException()->Dump();
184 self->ClearException();
185 }
186}
187
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700188void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700189 // We must have started since it is now safe to cache our data;
190 gThreadCallback.started = true;
Alex Lighte0b2ce42019-02-21 19:23:42 +0000191 art::Thread* self = art::Thread::Current();
192 art::ScopedObjectAccess soa(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700193 art::ObjPtr<art::mirror::Class> thread_class =
194 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
195 CHECK(thread_class != nullptr);
196 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
197 "Ljava/lang/ClassLoader;");
198 CHECK(context_class_loader_ != nullptr);
Alex Lighte0b2ce42019-02-21 19:23:42 +0000199 // Now wait for all required system threads to come up before allowing the rest of loading to
200 // continue.
201 WaitForSystemDaemonStart(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700202}
203
Andreas Gampeeafaf572017-01-20 12:34:15 -0800204void ThreadUtil::Unregister() {
205 art::ScopedThreadStateChange stsc(art::Thread::Current(),
206 art::ThreadState::kWaitingForDebuggerToAttach);
207 art::ScopedSuspendAll ssa("Remove thread callback");
208 art::Runtime* runtime = art::Runtime::Current();
209 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800210}
211
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800212jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
213 art::Thread* self = art::Thread::Current();
214
215 art::ScopedObjectAccess soa(self);
216
217 jthread thread_peer;
218 if (self->IsStillStarting()) {
219 thread_peer = nullptr;
220 } else {
221 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
222 }
223
224 *thread_ptr = thread_peer;
225 return ERR(NONE);
226}
227
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800228// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700229bool ThreadUtil::GetNativeThread(jthread thread,
230 const art::ScopedObjectAccessAlreadyRunnable& soa,
231 /*out*/ art::Thread** thr,
232 /*out*/ jvmtiError* err) {
Alex Lightb7c640d2019-03-20 15:52:13 -0700233 art::ScopedExceptionStorage sse(soa.Self());
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800234 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700235 *thr = art::Thread::Current();
236 return true;
237 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
238 *err = ERR(INVALID_THREAD);
239 return false;
240 } else {
241 *thr = art::Thread::FromManagedThread(soa, thread);
242 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800243 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700244}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800245
Alex Light7ddc23d2017-09-22 15:33:41 -0700246bool ThreadUtil::GetAliveNativeThread(jthread thread,
247 const art::ScopedObjectAccessAlreadyRunnable& soa,
248 /*out*/ art::Thread** thr,
249 /*out*/ jvmtiError* err) {
250 if (!GetNativeThread(thread, soa, thr, err)) {
251 return false;
252 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
253 *err = ERR(THREAD_NOT_ALIVE);
254 return false;
255 } else {
256 return true;
257 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800258}
259
260jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
261 if (info_ptr == nullptr) {
262 return ERR(NULL_POINTER);
263 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700264 if (!PhaseUtil::IsLivePhase()) {
265 return JVMTI_ERROR_WRONG_PHASE;
266 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800267
Alex Light3ae82532017-07-26 13:59:07 -0700268 art::Thread* self = art::Thread::Current();
269 art::ScopedObjectAccess soa(self);
270 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800271
Alex Light7ddc23d2017-09-22 15:33:41 -0700272 art::Thread* target;
273 jvmtiError err = ERR(INTERNAL);
274 if (!GetNativeThread(thread, soa, &target, &err)) {
275 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800276 }
277
Andreas Gampe54711412017-02-21 12:41:43 -0800278 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700279 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800280 // Have a native thread object, this thread is alive.
281 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700282 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800283 jvmtiError name_result;
284 name_uptr = CopyString(env, name.c_str(), &name_result);
285 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800286 return name_result;
287 }
Andreas Gampe54711412017-02-21 12:41:43 -0800288 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800289
Alex Light3ae82532017-07-26 13:59:07 -0700290 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800291
Alex Light3ae82532017-07-26 13:59:07 -0700292 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800293
Alex Light3ae82532017-07-26 13:59:07 -0700294 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800295
296 // ThreadGroup.
297 if (peer != nullptr) {
298 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
299 CHECK(f != nullptr);
300 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
301 info_ptr->thread_group = group == nullptr
302 ? nullptr
303 : soa.AddLocalReference<jthreadGroup>(group);
304 } else {
305 info_ptr->thread_group = nullptr;
306 }
307
308 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700309 DCHECK(context_class_loader_ != nullptr);
310 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
311 ? context_class_loader_->GetObject(peer)
312 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800313 info_ptr->context_class_loader = ccl == nullptr
314 ? nullptr
315 : soa.AddLocalReference<jobject>(ccl);
316 } else {
317 // Only the peer. This thread has either not been started, or is dead. Read things from
318 // the Java side.
319 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
320
321 // Name.
322 {
323 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
324 CHECK(f != nullptr);
325 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
326 std::string name_cpp;
327 const char* name_cstr;
328 if (name != nullptr) {
329 name_cpp = name->AsString()->ToModifiedUtf8();
330 name_cstr = name_cpp.c_str();
331 } else {
332 name_cstr = "";
333 }
Andreas Gampe54711412017-02-21 12:41:43 -0800334 jvmtiError name_result;
335 name_uptr = CopyString(env, name_cstr, &name_result);
336 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800337 return name_result;
338 }
Andreas Gampe54711412017-02-21 12:41:43 -0800339 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800340 }
341
342 // Priority.
343 {
344 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
345 CHECK(f != nullptr);
346 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
347 }
348
349 // Daemon.
350 {
351 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
352 CHECK(f != nullptr);
353 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
354 }
355
356 // ThreadGroup.
357 {
358 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
359 CHECK(f != nullptr);
360 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
361 info_ptr->thread_group = group == nullptr
362 ? nullptr
363 : soa.AddLocalReference<jthreadGroup>(group);
364 }
365
366 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700367 DCHECK(context_class_loader_ != nullptr);
368 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
369 ? context_class_loader_->GetObject(peer)
370 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800371 info_ptr->context_class_loader = ccl == nullptr
372 ? nullptr
373 : soa.AddLocalReference<jobject>(ccl);
374 }
375
376 name_uptr.release();
377
378 return ERR(NONE);
379}
380
Alex Light1f0a22f2017-07-17 12:55:59 -0700381struct InternalThreadState {
382 art::Thread* native_thread;
383 art::ThreadState art_state;
384 int thread_user_code_suspend_count;
385};
386
387// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700388static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700389 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700390 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700391 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700392 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
393 thread_state.native_thread = target;
394 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700395 thread_state.art_state = art::ThreadState::kStarting;
396 thread_state.thread_user_code_suspend_count = 0;
397 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700398 thread_state.art_state = target->GetState();
399 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800400 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700401 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800402}
403
Alex Light1f0a22f2017-07-17 12:55:59 -0700404static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
405 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800406 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
407
Alex Light1f0a22f2017-07-17 12:55:59 -0700408 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700409 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
410 // 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 -0800411 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
412 // Note: We do not have data about the previous state. Otherwise we should load the previous
413 // state here.
414 }
415
Alex Light1f0a22f2017-07-17 12:55:59 -0700416 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700417 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700418 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
419 }
420
Alex Light597adad2017-10-16 16:11:42 -0700421 // Enumerate all the thread states and fill in the other bits. This contains the results of
422 // following the decision tree in the JVMTI spec GetThreadState documentation.
423 switch (internal_thread_state) {
424 case art::ThreadState::kRunnable:
425 case art::ThreadState::kWaitingWeakGcRootRead:
426 case art::ThreadState::kSuspended:
427 // These are all simply runnable.
428 // kRunnable is self-explanatory.
429 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
430 // so we want to keep it marked as runnable.
431 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
432 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
433 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
434 break;
435 case art::ThreadState::kNative:
436 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
437 // state but we don't have the information to know if it should be present for any but the
438 // kNative state.
439 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
440 JVMTI_THREAD_STATE_RUNNABLE);
441 break;
442 case art::ThreadState::kBlocked:
443 // Blocked is one of the top level states so it sits alone.
444 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
445 break;
446 case art::ThreadState::kWaiting:
447 // Object.wait() so waiting, indefinitely, in object.wait.
448 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
449 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
450 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
451 break;
452 case art::ThreadState::kTimedWaiting:
453 // Object.wait(long) so waiting, with timeout, in object.wait.
454 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
455 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
456 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
457 break;
458 case art::ThreadState::kSleeping:
459 // In object.sleep. This is a timed wait caused by sleep.
460 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
461 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
462 JVMTI_THREAD_STATE_SLEEPING);
463 break;
464 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
465 // attached.
466 case art::ThreadState::kWaitingForDebuggerSend:
467 case art::ThreadState::kWaitingForDebuggerToAttach:
468 case art::ThreadState::kWaitingInMainDebuggerLoop:
469 case art::ThreadState::kWaitingForDebuggerSuspension:
470 case art::ThreadState::kWaitingForLockInflation:
471 case art::ThreadState::kWaitingForTaskProcessor:
472 case art::ThreadState::kWaitingForGcToComplete:
473 case art::ThreadState::kWaitingForCheckPointsToRun:
474 case art::ThreadState::kWaitingPerformingGc:
475 case art::ThreadState::kWaitingForJniOnLoad:
476 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
477 case art::ThreadState::kWaitingForSignalCatcherOutput:
478 case art::ThreadState::kWaitingForDeoptimization:
479 case art::ThreadState::kWaitingForMethodTracingStart:
480 case art::ThreadState::kWaitingForVisitObjects:
481 case art::ThreadState::kWaitingForGetObjectsAllocated:
482 case art::ThreadState::kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +0900483 case art::ThreadState::kNativeForAbort:
Alex Light597adad2017-10-16 16:11:42 -0700484 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
485 // caused by sleep, park, or object#wait.
486 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
487 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
488 break;
489 case art::ThreadState::kStarting:
490 case art::ThreadState::kTerminated:
491 // We only call this if we are alive so we shouldn't see either of these states.
492 LOG(FATAL) << "Should not be in state " << internal_thread_state;
493 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800494 }
Alex Light597adad2017-10-16 16:11:42 -0700495 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800496
497 return jvmti_state;
498}
499
Alex Light1f0a22f2017-07-17 12:55:59 -0700500static jint GetJavaStateFromInternal(const InternalThreadState& state) {
501 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800502 case art::ThreadState::kTerminated:
503 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
504
505 case art::ThreadState::kRunnable:
506 case art::ThreadState::kNative:
507 case art::ThreadState::kWaitingWeakGcRootRead:
508 case art::ThreadState::kSuspended:
509 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
510
511 case art::ThreadState::kTimedWaiting:
512 case art::ThreadState::kSleeping:
513 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
514
515 case art::ThreadState::kBlocked:
516 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
517
518 case art::ThreadState::kStarting:
519 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
520
521 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700522 case art::ThreadState::kWaitingForTaskProcessor:
523 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800524 case art::ThreadState::kWaitingForGcToComplete:
525 case art::ThreadState::kWaitingPerformingGc:
526 case art::ThreadState::kWaitingForCheckPointsToRun:
527 case art::ThreadState::kWaitingForDebuggerSend:
528 case art::ThreadState::kWaitingForDebuggerToAttach:
529 case art::ThreadState::kWaitingInMainDebuggerLoop:
530 case art::ThreadState::kWaitingForDebuggerSuspension:
531 case art::ThreadState::kWaitingForDeoptimization:
532 case art::ThreadState::kWaitingForGetObjectsAllocated:
533 case art::ThreadState::kWaitingForJniOnLoad:
534 case art::ThreadState::kWaitingForSignalCatcherOutput:
535 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
536 case art::ThreadState::kWaitingForMethodTracingStart:
537 case art::ThreadState::kWaitingForVisitObjects:
538 case art::ThreadState::kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +0900539 case art::ThreadState::kNativeForAbort:
Andreas Gampe72c19832017-01-12 13:22:16 -0800540 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
541 }
542 LOG(FATAL) << "Unreachable";
543 UNREACHABLE();
544}
545
Alex Light1f0a22f2017-07-17 12:55:59 -0700546// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700547void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700548 art::ScopedObjectAccess soa(self);
549 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
550 self->FullSuspendCheck();
551}
552
Alex Light23aa7482017-08-16 10:01:13 -0700553bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
554 DCHECK(self == art::Thread::Current());
555 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
556 return self->GetUserCodeSuspendCount() != 0;
557}
558
559bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
560 DCHECK(self == art::Thread::Current());
561 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
562 return WouldSuspendForUserCodeLocked(self);
563}
564
Andreas Gampe72c19832017-01-12 13:22:16 -0800565jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
566 jthread thread,
567 jint* thread_state_ptr) {
568 if (thread_state_ptr == nullptr) {
569 return ERR(NULL_POINTER);
570 }
571
Alex Light1f0a22f2017-07-17 12:55:59 -0700572 art::Thread* self = art::Thread::Current();
573 InternalThreadState state = {};
Alex Light679dec12019-04-08 16:30:14 +0000574 {
575 ScopedNoUserCodeSuspension snucs(self);
Alex Light1f0a22f2017-07-17 12:55:59 -0700576 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700577 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700578 jvmtiError err = ERR(INTERNAL);
579 art::Thread* target = nullptr;
580 if (!GetNativeThread(thread, soa, &target, &err)) {
581 return err;
582 }
583 state = GetNativeThreadState(target);
Alex Light679dec12019-04-08 16:30:14 +0000584 if (state.art_state != art::ThreadState::kStarting) {
585 DCHECK(state.native_thread != nullptr);
586
587 // Translate internal thread state to JVMTI and Java state.
588 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
589
590 // Java state is derived from nativeGetState.
591 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
592 // different mask if a thread got suspended due to user-code. However, this is for
593 // consistency with the Java view.
594 jint java_state = GetJavaStateFromInternal(state);
595
596 *thread_state_ptr = jvmti_state | java_state;
597
598 return ERR(NONE);
Alex Light3ae82532017-07-26 13:59:07 -0700599 }
Alex Light679dec12019-04-08 16:30:14 +0000600 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800601
Alex Light3ae82532017-07-26 13:59:07 -0700602 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800603
Alex Light3ae82532017-07-26 13:59:07 -0700604 if (thread == nullptr) {
605 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
606 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800607 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800608
Alex Light3ae82532017-07-26 13:59:07 -0700609 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700610 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800611
Alex Light3ae82532017-07-26 13:59:07 -0700612 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700613 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
614 art::ObjPtr<art::mirror::Class> thread_klass =
615 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
616 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
617 return ERR(INVALID_THREAD);
618 }
619 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700620 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700621 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700622 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
623 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
624 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
625 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800626 return ERR(NONE);
627}
628
Andreas Gampe85807442017-01-13 14:40:58 -0800629jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
630 jint* threads_count_ptr,
631 jthread** threads_ptr) {
632 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
633 return ERR(NULL_POINTER);
634 }
635
636 art::Thread* current = art::Thread::Current();
637
638 art::ScopedObjectAccess soa(current);
639
640 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
641 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
642
643 std::vector<art::ObjPtr<art::mirror::Object>> peers;
644
645 for (art::Thread* thread : thread_list) {
646 // Skip threads that are still starting.
647 if (thread->IsStillStarting()) {
648 continue;
649 }
650
Andreas Gampe202f85a2017-02-06 10:23:26 -0800651 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800652 if (peer != nullptr) {
653 peers.push_back(peer);
654 }
655 }
656
657 if (peers.empty()) {
658 *threads_count_ptr = 0;
659 *threads_ptr = nullptr;
660 } else {
661 unsigned char* data;
662 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
663 if (data_result != ERR(NONE)) {
664 return data_result;
665 }
666 jthread* threads = reinterpret_cast<jthread*>(data);
667 for (size_t i = 0; i != peers.size(); ++i) {
668 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
669 }
670
671 *threads_count_ptr = static_cast<jint>(peers.size());
672 *threads_ptr = threads;
673 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800674 return ERR(NONE);
675}
Andreas Gampe85807442017-01-13 14:40:58 -0800676
Alex Light092a4042017-07-12 08:46:44 -0700677static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
678 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
679 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
Alex Light0aa7a5a2018-10-10 15:58:14 +0000680 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700681 if (global_tls != nullptr) {
682 global_tls->data.erase(env);
683 }
684}
685
686void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
687 art::Thread* self = art::Thread::Current();
688 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
689 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
690 list->ForEach(RemoveTLSData, env);
691}
692
693jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
694 art::Thread* self = art::Thread::Current();
695 art::ScopedObjectAccess soa(self);
696 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700697 art::Thread* target = nullptr;
698 jvmtiError err = ERR(INTERNAL);
699 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
700 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800701 }
702
Alex Light0aa7a5a2018-10-10 15:58:14 +0000703 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700704
705 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800706
707 return ERR(NONE);
708}
709
Alex Light0aa7a5a2018-10-10 15:58:14 +0000710JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
711 JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
712 if (data != nullptr) {
713 return data;
714 } else {
715 thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
716 return GetGlobalTLSData(thread);
717 }
718}
719
720JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
721 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
722}
723
Alex Light092a4042017-07-12 08:46:44 -0700724jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800725 jthread thread,
726 void** data_ptr) {
727 if (data_ptr == nullptr) {
728 return ERR(NULL_POINTER);
729 }
730
Alex Light092a4042017-07-12 08:46:44 -0700731 art::Thread* self = art::Thread::Current();
732 art::ScopedObjectAccess soa(self);
733 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700734 art::Thread* target = nullptr;
735 jvmtiError err = ERR(INTERNAL);
736 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
737 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800738 }
739
Alex Light0aa7a5a2018-10-10 15:58:14 +0000740 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700741 if (global_tls == nullptr) {
742 *data_ptr = nullptr;
743 return OK;
744 }
745 auto it = global_tls->data.find(env);
746 if (it != global_tls->data.end()) {
747 *data_ptr = const_cast<void*>(it->second);
748 } else {
749 *data_ptr = nullptr;
750 }
751
Andreas Gampe85807442017-01-13 14:40:58 -0800752 return ERR(NONE);
753}
754
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800755struct AgentData {
756 const void* arg;
757 jvmtiStartFunction proc;
758 jthread thread;
759 JavaVM* java_vm;
760 jvmtiEnv* jvmti_env;
761 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800762 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800763};
764
765static void* AgentCallback(void* arg) {
766 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
767 CHECK(data->thread != nullptr);
768
769 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800770 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700771 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800772 // The name in Attach() is only for logging. Set the thread name. This is important so
773 // that the thread is no longer seen as starting up.
774 {
775 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800776 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800777 }
778
779 // Release the peer.
780 JNIEnv* env = self->GetJniEnv();
781 env->DeleteGlobalRef(data->thread);
782 data->thread = nullptr;
783
Alex Light739bf722017-10-20 13:14:24 -0700784 {
785 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
786 // before going into the provided code.
787 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
788 art::Runtime::Current()->EndThreadBirth();
789 }
790
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800791 // Run the agent code.
792 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
793
794 // Detach the thread.
795 int detach_result = data->java_vm->DetachCurrentThread();
796 CHECK_EQ(detach_result, 0);
797
798 return nullptr;
799}
800
801jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
802 jthread thread,
803 jvmtiStartFunction proc,
804 const void* arg,
805 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700806 if (!PhaseUtil::IsLivePhase()) {
807 return ERR(WRONG_PHASE);
808 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800809 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
810 return ERR(INVALID_PRIORITY);
811 }
812 JNIEnv* env = art::Thread::Current()->GetJniEnv();
813 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
814 return ERR(INVALID_THREAD);
815 }
816 if (proc == nullptr) {
817 return ERR(NULL_POINTER);
818 }
819
Alex Light739bf722017-10-20 13:14:24 -0700820 {
821 art::Runtime* runtime = art::Runtime::Current();
822 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
823 if (runtime->IsShuttingDownLocked()) {
824 // The runtime is shutting down so we cannot create new threads.
825 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
826 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
827 // impossible. Existing agents don't seem to generally do anything with this return value so
828 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
829 // even though code is never actually run.
830 return ERR(INTERNAL);
831 }
832 runtime->StartThreadBirth();
833 }
834
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800835 std::unique_ptr<AgentData> data(new AgentData);
836 data->arg = arg;
837 data->proc = proc;
838 // We need a global ref for Java objects, as local refs will be invalid.
839 data->thread = env->NewGlobalRef(thread);
840 data->java_vm = art::Runtime::Current()->GetJavaVM();
841 data->jvmti_env = jvmti_env;
842 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800843 ScopedLocalRef<jstring> s(
844 env,
845 reinterpret_cast<jstring>(
846 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
847 if (s == nullptr) {
848 data->name = "JVMTI Agent Thread";
849 } else {
850 ScopedUtfChars name(env, s.get());
851 data->name = name.c_str();
852 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800853
854 pthread_t pthread;
855 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700856 nullptr,
857 &AgentCallback,
858 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800859 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700860 // If the create succeeded the other thread will call EndThreadBirth.
861 art::Runtime* runtime = art::Runtime::Current();
862 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
863 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800864 return ERR(INTERNAL);
865 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700866 data.release(); // NOLINT pthreads API.
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800867
868 return ERR(NONE);
869}
870
Alex Light88fd7202017-06-30 08:31:59 -0700871jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700872 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700873 // Loop since we need to bail out and try again if we would end up getting suspended while holding
874 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
875 // release the lock, wait to get resumed and try again.
876 do {
Alex Light679dec12019-04-08 16:30:14 +0000877 ScopedNoUserCodeSuspension snucs(self);
Alex Light23aa7482017-08-16 10:01:13 -0700878 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700879 {
880 art::ScopedObjectAccess soa(self);
881 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700882 art::Thread* target = nullptr;
883 jvmtiError err = ERR(INTERNAL);
884 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
885 return err;
886 }
Alex Lightcea42152018-09-18 22:51:55 +0000887 art::ThreadState state = target->GetState();
888 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
889 return ERR(THREAD_NOT_ALIVE);
890 } else {
891 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
892 if (target->GetUserCodeSuspendCount() != 0) {
893 return ERR(THREAD_SUSPENDED);
894 }
895 }
Alex Light88fd7202017-06-30 08:31:59 -0700896 }
Alex Lightcea42152018-09-18 22:51:55 +0000897 bool timeout = true;
898 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
899 target_jthread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700900 /* request_suspension= */ true,
Alex Lightcea42152018-09-18 22:51:55 +0000901 art::SuspendReason::kForUserCode,
902 &timeout);
903 if (ret_target == nullptr && !timeout) {
Alex Light3ae82532017-07-26 13:59:07 -0700904 // TODO It would be good to get more information about why exactly the thread failed to
905 // suspend.
906 return ERR(INTERNAL);
Alex Lightcea42152018-09-18 22:51:55 +0000907 } else if (!timeout) {
908 // we didn't time out and got a result.
909 return OK;
Alex Light3ae82532017-07-26 13:59:07 -0700910 }
911 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700912 } while (true);
913 UNREACHABLE();
914}
915
916jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
917 CHECK(self == art::Thread::Current());
918 {
919 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
920 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
921 if (self->GetUserCodeSuspendCount() != 0) {
922 // This can only happen if we race with another thread to suspend 'self' and we lose.
923 return ERR(THREAD_SUSPENDED);
924 }
925 // We shouldn't be able to fail this.
926 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
927 // TODO More specific error would be nice.
928 return ERR(INTERNAL);
929 }
930 }
931 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
932 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
933 // to go to sleep until we are resumed.
934 SuspendCheck(self);
935 return OK;
936}
937
938jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
939 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700940 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700941 {
942 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700943 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700944 art::Thread* target = nullptr;
945 jvmtiError err = ERR(INTERNAL);
946 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
947 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700948 } else if (target == self) {
949 target_is_self = true;
950 }
Alex Light88fd7202017-06-30 08:31:59 -0700951 }
Alex Light3ae82532017-07-26 13:59:07 -0700952 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700953 return SuspendSelf(self);
954 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700955 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700956 }
957}
958
959jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
960 jthread thread) {
961 if (thread == nullptr) {
962 return ERR(NULL_POINTER);
963 }
964 art::Thread* self = art::Thread::Current();
Alex Lightcea42152018-09-18 22:51:55 +0000965 art::Thread* target;
Alex Light679dec12019-04-08 16:30:14 +0000966
967 // Make sure we won't get suspended ourselves while in the middle of resuming another thread.
968 ScopedNoUserCodeSuspension snucs(self);
969 // From now on we know we cannot get suspended by user-code.
970 {
971 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
972 // have the 'suspend_lock' locked here.
973 art::ScopedObjectAccess soa(self);
974 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
975 jvmtiError err = ERR(INTERNAL);
976 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
977 return err;
978 } else if (target == self) {
979 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
980 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
981 // about current state since it's all concurrent.
982 return ERR(THREAD_NOT_SUSPENDED);
Alex Light88fd7202017-06-30 08:31:59 -0700983 }
Alex Light679dec12019-04-08 16:30:14 +0000984 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
985 // cannot tell why resume failed.
Alex Lightcea42152018-09-18 22:51:55 +0000986 {
Alex Light679dec12019-04-08 16:30:14 +0000987 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
988 if (target->GetUserCodeSuspendCount() == 0) {
Alex Lightcea42152018-09-18 22:51:55 +0000989 return ERR(THREAD_NOT_SUSPENDED);
990 }
Alex Light3ae82532017-07-26 13:59:07 -0700991 }
Alex Light679dec12019-04-08 16:30:14 +0000992 }
993 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
994 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
995 DCHECK(target != self);
996 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
997 art::SuspendReason::kForUserCode)) {
998 // TODO Give a better error.
999 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
1000 return ERR(INTERNAL);
1001 } else {
1002 return OK;
1003 }
Alex Light88fd7202017-06-30 08:31:59 -07001004}
1005
Alex Light7ddc23d2017-09-22 15:33:41 -07001006static bool IsCurrentThread(jthread thr) {
1007 if (thr == nullptr) {
1008 return true;
1009 }
1010 art::Thread* self = art::Thread::Current();
1011 art::ScopedObjectAccess soa(self);
1012 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1013 art::Thread* target = nullptr;
1014 jvmtiError err_unused = ERR(INTERNAL);
1015 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1016 return target == self;
1017 } else {
1018 return false;
1019 }
1020}
1021
Alex Light88fd7202017-06-30 08:31:59 -07001022// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1023// since we can have threads in the list multiple times. This generally doesn't matter unless the
1024// current thread is present multiple times. In that case we need to suspend only once and either
1025// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1026// it didn't. We also want to handle the current thread last to make the behavior of the code
1027// simpler to understand.
1028jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1029 jint request_count,
1030 const jthread* threads,
1031 jvmtiError* results) {
1032 if (request_count == 0) {
1033 return ERR(ILLEGAL_ARGUMENT);
1034 } else if (results == nullptr || threads == nullptr) {
1035 return ERR(NULL_POINTER);
1036 }
1037 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1038 // running thread. These indexes we need to handle specially since we need to only actually
1039 // suspend a single time.
1040 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001041 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001042 if (IsCurrentThread(threads[i])) {
1043 current_thread_indexes.push_back(i);
1044 } else {
1045 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001046 }
Alex Light88fd7202017-06-30 08:31:59 -07001047 }
1048 if (!current_thread_indexes.empty()) {
1049 jint first_current_thread_index = current_thread_indexes[0];
1050 // Suspend self.
1051 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1052 results[first_current_thread_index] = res;
1053 // Fill in the rest of the error values as appropriate.
1054 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1055 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1056 results[*it] = other_results;
1057 }
1058 }
1059 return OK;
1060}
1061
1062jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1063 jint request_count,
1064 const jthread* threads,
1065 jvmtiError* results) {
1066 if (request_count == 0) {
1067 return ERR(ILLEGAL_ARGUMENT);
1068 } else if (results == nullptr || threads == nullptr) {
1069 return ERR(NULL_POINTER);
1070 }
1071 for (jint i = 0; i < request_count; i++) {
1072 results[i] = env->ResumeThread(threads[i]);
1073 }
1074 return OK;
1075}
1076
Alex Light54d39dc2017-09-25 17:00:16 -07001077jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1078 jthread thread,
1079 jobject exception) {
1080 art::Thread* self = art::Thread::Current();
1081 art::ScopedObjectAccess soa(self);
1082 art::StackHandleScope<1> hs(self);
1083 if (exception == nullptr) {
1084 return ERR(INVALID_OBJECT);
1085 }
1086 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1087 if (!obj->GetClass()->IsThrowableClass()) {
1088 return ERR(INVALID_OBJECT);
1089 }
1090 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001091 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001092 art::Thread* target = nullptr;
1093 jvmtiError err = ERR(INTERNAL);
1094 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001095 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001096 return err;
1097 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001098 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001099 return ERR(THREAD_NOT_ALIVE);
1100 }
1101 struct StopThreadClosure : public art::Closure {
1102 public:
1103 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1104
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001105 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001106 // Make sure the thread is prepared to notice the exception.
Alex Lighta4cdd362019-04-18 09:17:10 -07001107 DeoptManager::Get()->DeoptimizeThread(me);
Alex Light54d39dc2017-09-25 17:00:16 -07001108 me->SetAsyncException(exception_.Get());
1109 // Wake up the thread if it is sleeping.
1110 me->Notify();
1111 }
1112
1113 private:
1114 art::Handle<art::mirror::Throwable> exception_;
1115 };
1116 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001117 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001118 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001119 return OK;
1120 } else {
1121 // Something went wrong, probably the thread died.
1122 return ERR(THREAD_NOT_ALIVE);
1123 }
1124}
1125
1126jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1127 art::Thread* self = art::Thread::Current();
1128 art::ScopedObjectAccess soa(self);
1129 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1130 art::Thread* target = nullptr;
1131 jvmtiError err = ERR(INTERNAL);
1132 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1133 return err;
1134 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1135 return ERR(THREAD_NOT_ALIVE);
1136 }
1137 target->Interrupt(self);
1138 return OK;
1139}
1140
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001141} // namespace openjdkjvmti