blob: 6c50a2039c646cf8b061fa95842121a19864ff15 [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
125 // started here.
126 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" &&
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800131 !android::base::StartsWith(name, "Jit thread pool") &&
132 !android::base::StartsWith(name, "Runtime worker thread")) {
Alex Light23aa7482017-08-16 10:01:13 -0700133 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
134 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -0800135 }
136 }
137 return;
138 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800139 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800140 }
141
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100142 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800143 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800144 }
145
Andreas Gampeeafaf572017-01-20 12:34:15 -0800146 EventHandler* event_handler = nullptr;
147 bool started = false;
148};
149
150ThreadCallback gThreadCallback;
151
152void ThreadUtil::Register(EventHandler* handler) {
153 art::Runtime* runtime = art::Runtime::Current();
154
155 gThreadCallback.started = runtime->IsStarted();
156 gThreadCallback.event_handler = handler;
157
158 art::ScopedThreadStateChange stsc(art::Thread::Current(),
159 art::ThreadState::kWaitingForDebuggerToAttach);
160 art::ScopedSuspendAll ssa("Add thread callback");
161 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700162}
163
164void ThreadUtil::VMInitEventSent() {
165 // We should have already started.
166 DCHECK(gThreadCallback.started);
167 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
168 // reported until Init.
169 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800170}
171
Alex Lighte0b2ce42019-02-21 19:23:42 +0000172
173static void WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
174 {
175 art::ScopedThreadStateChange strc(self, art::kNative);
176 JNIEnv* jni = self->GetJniEnv();
177 jni->CallStaticVoidMethod(art::WellKnownClasses::java_lang_Daemons,
178 art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart);
179 }
180 if (self->IsExceptionPending()) {
181 LOG(WARNING) << "Exception occurred when waiting for system daemons to start: "
182 << self->GetException()->Dump();
183 self->ClearException();
184 }
185}
186
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700187void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700188 // We must have started since it is now safe to cache our data;
189 gThreadCallback.started = true;
Alex Lighte0b2ce42019-02-21 19:23:42 +0000190 art::Thread* self = art::Thread::Current();
191 art::ScopedObjectAccess soa(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700192 art::ObjPtr<art::mirror::Class> thread_class =
193 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
194 CHECK(thread_class != nullptr);
195 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
196 "Ljava/lang/ClassLoader;");
197 CHECK(context_class_loader_ != nullptr);
Alex Lighte0b2ce42019-02-21 19:23:42 +0000198 // Now wait for all required system threads to come up before allowing the rest of loading to
199 // continue.
200 WaitForSystemDaemonStart(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700201}
202
Andreas Gampeeafaf572017-01-20 12:34:15 -0800203void ThreadUtil::Unregister() {
204 art::ScopedThreadStateChange stsc(art::Thread::Current(),
205 art::ThreadState::kWaitingForDebuggerToAttach);
206 art::ScopedSuspendAll ssa("Remove thread callback");
207 art::Runtime* runtime = art::Runtime::Current();
208 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800209}
210
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800211jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
212 art::Thread* self = art::Thread::Current();
213
214 art::ScopedObjectAccess soa(self);
215
216 jthread thread_peer;
217 if (self->IsStillStarting()) {
218 thread_peer = nullptr;
219 } else {
220 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
221 }
222
223 *thread_ptr = thread_peer;
224 return ERR(NONE);
225}
226
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800227// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700228bool ThreadUtil::GetNativeThread(jthread thread,
229 const art::ScopedObjectAccessAlreadyRunnable& soa,
230 /*out*/ art::Thread** thr,
231 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800232 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700233 *thr = art::Thread::Current();
234 return true;
235 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
236 *err = ERR(INVALID_THREAD);
237 return false;
238 } else {
239 *thr = art::Thread::FromManagedThread(soa, thread);
240 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800241 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700242}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800243
Alex Light7ddc23d2017-09-22 15:33:41 -0700244bool ThreadUtil::GetAliveNativeThread(jthread thread,
245 const art::ScopedObjectAccessAlreadyRunnable& soa,
246 /*out*/ art::Thread** thr,
247 /*out*/ jvmtiError* err) {
248 if (!GetNativeThread(thread, soa, thr, err)) {
249 return false;
250 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
251 *err = ERR(THREAD_NOT_ALIVE);
252 return false;
253 } else {
254 return true;
255 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800256}
257
258jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
259 if (info_ptr == nullptr) {
260 return ERR(NULL_POINTER);
261 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700262 if (!PhaseUtil::IsLivePhase()) {
263 return JVMTI_ERROR_WRONG_PHASE;
264 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800265
Alex Light3ae82532017-07-26 13:59:07 -0700266 art::Thread* self = art::Thread::Current();
267 art::ScopedObjectAccess soa(self);
268 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800269
Alex Light7ddc23d2017-09-22 15:33:41 -0700270 art::Thread* target;
271 jvmtiError err = ERR(INTERNAL);
272 if (!GetNativeThread(thread, soa, &target, &err)) {
273 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800274 }
275
Andreas Gampe54711412017-02-21 12:41:43 -0800276 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700277 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800278 // Have a native thread object, this thread is alive.
279 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700280 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800281 jvmtiError name_result;
282 name_uptr = CopyString(env, name.c_str(), &name_result);
283 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800284 return name_result;
285 }
Andreas Gampe54711412017-02-21 12:41:43 -0800286 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800287
Alex Light3ae82532017-07-26 13:59:07 -0700288 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800289
Alex Light3ae82532017-07-26 13:59:07 -0700290 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800291
Alex Light3ae82532017-07-26 13:59:07 -0700292 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800293
294 // ThreadGroup.
295 if (peer != nullptr) {
296 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
297 CHECK(f != nullptr);
298 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
299 info_ptr->thread_group = group == nullptr
300 ? nullptr
301 : soa.AddLocalReference<jthreadGroup>(group);
302 } else {
303 info_ptr->thread_group = nullptr;
304 }
305
306 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700307 DCHECK(context_class_loader_ != nullptr);
308 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
309 ? context_class_loader_->GetObject(peer)
310 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800311 info_ptr->context_class_loader = ccl == nullptr
312 ? nullptr
313 : soa.AddLocalReference<jobject>(ccl);
314 } else {
315 // Only the peer. This thread has either not been started, or is dead. Read things from
316 // the Java side.
317 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
318
319 // Name.
320 {
321 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
322 CHECK(f != nullptr);
323 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
324 std::string name_cpp;
325 const char* name_cstr;
326 if (name != nullptr) {
327 name_cpp = name->AsString()->ToModifiedUtf8();
328 name_cstr = name_cpp.c_str();
329 } else {
330 name_cstr = "";
331 }
Andreas Gampe54711412017-02-21 12:41:43 -0800332 jvmtiError name_result;
333 name_uptr = CopyString(env, name_cstr, &name_result);
334 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800335 return name_result;
336 }
Andreas Gampe54711412017-02-21 12:41:43 -0800337 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800338 }
339
340 // Priority.
341 {
342 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
343 CHECK(f != nullptr);
344 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
345 }
346
347 // Daemon.
348 {
349 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
350 CHECK(f != nullptr);
351 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
352 }
353
354 // ThreadGroup.
355 {
356 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
357 CHECK(f != nullptr);
358 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
359 info_ptr->thread_group = group == nullptr
360 ? nullptr
361 : soa.AddLocalReference<jthreadGroup>(group);
362 }
363
364 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700365 DCHECK(context_class_loader_ != nullptr);
366 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
367 ? context_class_loader_->GetObject(peer)
368 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800369 info_ptr->context_class_loader = ccl == nullptr
370 ? nullptr
371 : soa.AddLocalReference<jobject>(ccl);
372 }
373
374 name_uptr.release();
375
376 return ERR(NONE);
377}
378
Alex Light1f0a22f2017-07-17 12:55:59 -0700379struct InternalThreadState {
380 art::Thread* native_thread;
381 art::ThreadState art_state;
382 int thread_user_code_suspend_count;
383};
384
385// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700386static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700387 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700388 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700389 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700390 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
391 thread_state.native_thread = target;
392 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700393 thread_state.art_state = art::ThreadState::kStarting;
394 thread_state.thread_user_code_suspend_count = 0;
395 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700396 thread_state.art_state = target->GetState();
397 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800398 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700399 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800400}
401
Alex Light1f0a22f2017-07-17 12:55:59 -0700402static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
403 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800404 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
405
Alex Light1f0a22f2017-07-17 12:55:59 -0700406 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700407 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
408 // kSuspended state it will move to that once it hits a checkpoint so we can still set this.
Andreas Gampe72c19832017-01-12 13:22:16 -0800409 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
410 // Note: We do not have data about the previous state. Otherwise we should load the previous
411 // state here.
412 }
413
Alex Light1f0a22f2017-07-17 12:55:59 -0700414 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700415 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700416 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
417 }
418
Alex Light597adad2017-10-16 16:11:42 -0700419 // Enumerate all the thread states and fill in the other bits. This contains the results of
420 // following the decision tree in the JVMTI spec GetThreadState documentation.
421 switch (internal_thread_state) {
422 case art::ThreadState::kRunnable:
423 case art::ThreadState::kWaitingWeakGcRootRead:
424 case art::ThreadState::kSuspended:
425 // These are all simply runnable.
426 // kRunnable is self-explanatory.
427 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
428 // so we want to keep it marked as runnable.
429 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
430 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
431 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
432 break;
433 case art::ThreadState::kNative:
434 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
435 // state but we don't have the information to know if it should be present for any but the
436 // kNative state.
437 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
438 JVMTI_THREAD_STATE_RUNNABLE);
439 break;
440 case art::ThreadState::kBlocked:
441 // Blocked is one of the top level states so it sits alone.
442 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
443 break;
444 case art::ThreadState::kWaiting:
445 // Object.wait() so waiting, indefinitely, in object.wait.
446 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
447 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
448 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
449 break;
450 case art::ThreadState::kTimedWaiting:
451 // Object.wait(long) so waiting, with timeout, in object.wait.
452 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
453 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
454 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
455 break;
456 case art::ThreadState::kSleeping:
457 // In object.sleep. This is a timed wait caused by sleep.
458 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
459 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
460 JVMTI_THREAD_STATE_SLEEPING);
461 break;
462 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
463 // attached.
464 case art::ThreadState::kWaitingForDebuggerSend:
465 case art::ThreadState::kWaitingForDebuggerToAttach:
466 case art::ThreadState::kWaitingInMainDebuggerLoop:
467 case art::ThreadState::kWaitingForDebuggerSuspension:
468 case art::ThreadState::kWaitingForLockInflation:
469 case art::ThreadState::kWaitingForTaskProcessor:
470 case art::ThreadState::kWaitingForGcToComplete:
471 case art::ThreadState::kWaitingForCheckPointsToRun:
472 case art::ThreadState::kWaitingPerformingGc:
473 case art::ThreadState::kWaitingForJniOnLoad:
474 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
475 case art::ThreadState::kWaitingForSignalCatcherOutput:
476 case art::ThreadState::kWaitingForDeoptimization:
477 case art::ThreadState::kWaitingForMethodTracingStart:
478 case art::ThreadState::kWaitingForVisitObjects:
479 case art::ThreadState::kWaitingForGetObjectsAllocated:
480 case art::ThreadState::kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +0900481 case art::ThreadState::kNativeForAbort:
Alex Light597adad2017-10-16 16:11:42 -0700482 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
483 // caused by sleep, park, or object#wait.
484 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
485 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
486 break;
487 case art::ThreadState::kStarting:
488 case art::ThreadState::kTerminated:
489 // We only call this if we are alive so we shouldn't see either of these states.
490 LOG(FATAL) << "Should not be in state " << internal_thread_state;
491 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800492 }
Alex Light597adad2017-10-16 16:11:42 -0700493 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800494
495 return jvmti_state;
496}
497
Alex Light1f0a22f2017-07-17 12:55:59 -0700498static jint GetJavaStateFromInternal(const InternalThreadState& state) {
499 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800500 case art::ThreadState::kTerminated:
501 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
502
503 case art::ThreadState::kRunnable:
504 case art::ThreadState::kNative:
505 case art::ThreadState::kWaitingWeakGcRootRead:
506 case art::ThreadState::kSuspended:
507 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
508
509 case art::ThreadState::kTimedWaiting:
510 case art::ThreadState::kSleeping:
511 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
512
513 case art::ThreadState::kBlocked:
514 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
515
516 case art::ThreadState::kStarting:
517 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
518
519 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700520 case art::ThreadState::kWaitingForTaskProcessor:
521 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800522 case art::ThreadState::kWaitingForGcToComplete:
523 case art::ThreadState::kWaitingPerformingGc:
524 case art::ThreadState::kWaitingForCheckPointsToRun:
525 case art::ThreadState::kWaitingForDebuggerSend:
526 case art::ThreadState::kWaitingForDebuggerToAttach:
527 case art::ThreadState::kWaitingInMainDebuggerLoop:
528 case art::ThreadState::kWaitingForDebuggerSuspension:
529 case art::ThreadState::kWaitingForDeoptimization:
530 case art::ThreadState::kWaitingForGetObjectsAllocated:
531 case art::ThreadState::kWaitingForJniOnLoad:
532 case art::ThreadState::kWaitingForSignalCatcherOutput:
533 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
534 case art::ThreadState::kWaitingForMethodTracingStart:
535 case art::ThreadState::kWaitingForVisitObjects:
536 case art::ThreadState::kWaitingForGcThreadFlip:
Koji Fukui34857b52019-03-20 19:13:00 +0900537 case art::ThreadState::kNativeForAbort:
Andreas Gampe72c19832017-01-12 13:22:16 -0800538 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
539 }
540 LOG(FATAL) << "Unreachable";
541 UNREACHABLE();
542}
543
Alex Light1f0a22f2017-07-17 12:55:59 -0700544// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700545void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700546 art::ScopedObjectAccess soa(self);
547 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
548 self->FullSuspendCheck();
549}
550
Alex Light23aa7482017-08-16 10:01:13 -0700551bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
552 DCHECK(self == art::Thread::Current());
553 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
554 return self->GetUserCodeSuspendCount() != 0;
555}
556
557bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
558 DCHECK(self == art::Thread::Current());
559 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
560 return WouldSuspendForUserCodeLocked(self);
561}
562
Andreas Gampe72c19832017-01-12 13:22:16 -0800563jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
564 jthread thread,
565 jint* thread_state_ptr) {
566 if (thread_state_ptr == nullptr) {
567 return ERR(NULL_POINTER);
568 }
569
Alex Light1f0a22f2017-07-17 12:55:59 -0700570 art::Thread* self = art::Thread::Current();
571 InternalThreadState state = {};
Alex Light679dec12019-04-08 16:30:14 +0000572 {
573 ScopedNoUserCodeSuspension snucs(self);
Alex Light1f0a22f2017-07-17 12:55:59 -0700574 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700575 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700576 jvmtiError err = ERR(INTERNAL);
577 art::Thread* target = nullptr;
578 if (!GetNativeThread(thread, soa, &target, &err)) {
579 return err;
580 }
581 state = GetNativeThreadState(target);
Alex Light679dec12019-04-08 16:30:14 +0000582 if (state.art_state != art::ThreadState::kStarting) {
583 DCHECK(state.native_thread != nullptr);
584
585 // Translate internal thread state to JVMTI and Java state.
586 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
587
588 // Java state is derived from nativeGetState.
589 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
590 // different mask if a thread got suspended due to user-code. However, this is for
591 // consistency with the Java view.
592 jint java_state = GetJavaStateFromInternal(state);
593
594 *thread_state_ptr = jvmti_state | java_state;
595
596 return ERR(NONE);
Alex Light3ae82532017-07-26 13:59:07 -0700597 }
Alex Light679dec12019-04-08 16:30:14 +0000598 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800599
Alex Light3ae82532017-07-26 13:59:07 -0700600 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800601
Alex Light3ae82532017-07-26 13:59:07 -0700602 if (thread == nullptr) {
603 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
604 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800605 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800606
Alex Light3ae82532017-07-26 13:59:07 -0700607 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700608 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800609
Alex Light3ae82532017-07-26 13:59:07 -0700610 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700611 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
612 art::ObjPtr<art::mirror::Class> thread_klass =
613 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
614 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
615 return ERR(INVALID_THREAD);
616 }
617 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700618 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700619 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700620 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
621 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
622 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
623 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800624 return ERR(NONE);
625}
626
Andreas Gampe85807442017-01-13 14:40:58 -0800627jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
628 jint* threads_count_ptr,
629 jthread** threads_ptr) {
630 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
631 return ERR(NULL_POINTER);
632 }
633
634 art::Thread* current = art::Thread::Current();
635
636 art::ScopedObjectAccess soa(current);
637
638 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
639 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
640
641 std::vector<art::ObjPtr<art::mirror::Object>> peers;
642
643 for (art::Thread* thread : thread_list) {
644 // Skip threads that are still starting.
645 if (thread->IsStillStarting()) {
646 continue;
647 }
648
Andreas Gampe202f85a2017-02-06 10:23:26 -0800649 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800650 if (peer != nullptr) {
651 peers.push_back(peer);
652 }
653 }
654
655 if (peers.empty()) {
656 *threads_count_ptr = 0;
657 *threads_ptr = nullptr;
658 } else {
659 unsigned char* data;
660 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
661 if (data_result != ERR(NONE)) {
662 return data_result;
663 }
664 jthread* threads = reinterpret_cast<jthread*>(data);
665 for (size_t i = 0; i != peers.size(); ++i) {
666 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
667 }
668
669 *threads_count_ptr = static_cast<jint>(peers.size());
670 *threads_ptr = threads;
671 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800672 return ERR(NONE);
673}
Andreas Gampe85807442017-01-13 14:40:58 -0800674
Alex Light092a4042017-07-12 08:46:44 -0700675static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
676 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
677 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
Alex Light0aa7a5a2018-10-10 15:58:14 +0000678 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700679 if (global_tls != nullptr) {
680 global_tls->data.erase(env);
681 }
682}
683
684void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
685 art::Thread* self = art::Thread::Current();
686 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
687 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
688 list->ForEach(RemoveTLSData, env);
689}
690
691jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
692 art::Thread* self = art::Thread::Current();
693 art::ScopedObjectAccess soa(self);
694 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700695 art::Thread* target = nullptr;
696 jvmtiError err = ERR(INTERNAL);
697 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
698 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800699 }
700
Alex Light0aa7a5a2018-10-10 15:58:14 +0000701 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700702
703 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800704
705 return ERR(NONE);
706}
707
Alex Light0aa7a5a2018-10-10 15:58:14 +0000708JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
709 JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
710 if (data != nullptr) {
711 return data;
712 } else {
713 thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
714 return GetGlobalTLSData(thread);
715 }
716}
717
718JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
719 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
720}
721
Alex Light092a4042017-07-12 08:46:44 -0700722jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800723 jthread thread,
724 void** data_ptr) {
725 if (data_ptr == nullptr) {
726 return ERR(NULL_POINTER);
727 }
728
Alex Light092a4042017-07-12 08:46:44 -0700729 art::Thread* self = art::Thread::Current();
730 art::ScopedObjectAccess soa(self);
731 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700732 art::Thread* target = nullptr;
733 jvmtiError err = ERR(INTERNAL);
734 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
735 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800736 }
737
Alex Light0aa7a5a2018-10-10 15:58:14 +0000738 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700739 if (global_tls == nullptr) {
740 *data_ptr = nullptr;
741 return OK;
742 }
743 auto it = global_tls->data.find(env);
744 if (it != global_tls->data.end()) {
745 *data_ptr = const_cast<void*>(it->second);
746 } else {
747 *data_ptr = nullptr;
748 }
749
Andreas Gampe85807442017-01-13 14:40:58 -0800750 return ERR(NONE);
751}
752
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800753struct AgentData {
754 const void* arg;
755 jvmtiStartFunction proc;
756 jthread thread;
757 JavaVM* java_vm;
758 jvmtiEnv* jvmti_env;
759 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800760 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800761};
762
763static void* AgentCallback(void* arg) {
764 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
765 CHECK(data->thread != nullptr);
766
767 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800768 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700769 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800770 // The name in Attach() is only for logging. Set the thread name. This is important so
771 // that the thread is no longer seen as starting up.
772 {
773 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800774 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800775 }
776
777 // Release the peer.
778 JNIEnv* env = self->GetJniEnv();
779 env->DeleteGlobalRef(data->thread);
780 data->thread = nullptr;
781
Alex Light739bf722017-10-20 13:14:24 -0700782 {
783 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
784 // before going into the provided code.
785 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
786 art::Runtime::Current()->EndThreadBirth();
787 }
788
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800789 // Run the agent code.
790 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
791
792 // Detach the thread.
793 int detach_result = data->java_vm->DetachCurrentThread();
794 CHECK_EQ(detach_result, 0);
795
796 return nullptr;
797}
798
799jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
800 jthread thread,
801 jvmtiStartFunction proc,
802 const void* arg,
803 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700804 if (!PhaseUtil::IsLivePhase()) {
805 return ERR(WRONG_PHASE);
806 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800807 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
808 return ERR(INVALID_PRIORITY);
809 }
810 JNIEnv* env = art::Thread::Current()->GetJniEnv();
811 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
812 return ERR(INVALID_THREAD);
813 }
814 if (proc == nullptr) {
815 return ERR(NULL_POINTER);
816 }
817
Alex Light739bf722017-10-20 13:14:24 -0700818 {
819 art::Runtime* runtime = art::Runtime::Current();
820 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
821 if (runtime->IsShuttingDownLocked()) {
822 // The runtime is shutting down so we cannot create new threads.
823 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
824 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
825 // impossible. Existing agents don't seem to generally do anything with this return value so
826 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
827 // even though code is never actually run.
828 return ERR(INTERNAL);
829 }
830 runtime->StartThreadBirth();
831 }
832
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800833 std::unique_ptr<AgentData> data(new AgentData);
834 data->arg = arg;
835 data->proc = proc;
836 // We need a global ref for Java objects, as local refs will be invalid.
837 data->thread = env->NewGlobalRef(thread);
838 data->java_vm = art::Runtime::Current()->GetJavaVM();
839 data->jvmti_env = jvmti_env;
840 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800841 ScopedLocalRef<jstring> s(
842 env,
843 reinterpret_cast<jstring>(
844 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
845 if (s == nullptr) {
846 data->name = "JVMTI Agent Thread";
847 } else {
848 ScopedUtfChars name(env, s.get());
849 data->name = name.c_str();
850 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800851
852 pthread_t pthread;
853 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700854 nullptr,
855 &AgentCallback,
856 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800857 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700858 // If the create succeeded the other thread will call EndThreadBirth.
859 art::Runtime* runtime = art::Runtime::Current();
860 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
861 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800862 return ERR(INTERNAL);
863 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700864 data.release(); // NOLINT pthreads API.
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800865
866 return ERR(NONE);
867}
868
Alex Light88fd7202017-06-30 08:31:59 -0700869jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700870 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700871 // Loop since we need to bail out and try again if we would end up getting suspended while holding
872 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
873 // release the lock, wait to get resumed and try again.
874 do {
Alex Light679dec12019-04-08 16:30:14 +0000875 ScopedNoUserCodeSuspension snucs(self);
Alex Light23aa7482017-08-16 10:01:13 -0700876 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700877 {
878 art::ScopedObjectAccess soa(self);
879 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700880 art::Thread* target = nullptr;
881 jvmtiError err = ERR(INTERNAL);
882 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
883 return err;
884 }
Alex Lightcea42152018-09-18 22:51:55 +0000885 art::ThreadState state = target->GetState();
886 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
887 return ERR(THREAD_NOT_ALIVE);
888 } else {
889 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
890 if (target->GetUserCodeSuspendCount() != 0) {
891 return ERR(THREAD_SUSPENDED);
892 }
893 }
Alex Light88fd7202017-06-30 08:31:59 -0700894 }
Alex Lightcea42152018-09-18 22:51:55 +0000895 bool timeout = true;
896 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
897 target_jthread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700898 /* request_suspension= */ true,
Alex Lightcea42152018-09-18 22:51:55 +0000899 art::SuspendReason::kForUserCode,
900 &timeout);
901 if (ret_target == nullptr && !timeout) {
Alex Light3ae82532017-07-26 13:59:07 -0700902 // TODO It would be good to get more information about why exactly the thread failed to
903 // suspend.
904 return ERR(INTERNAL);
Alex Lightcea42152018-09-18 22:51:55 +0000905 } else if (!timeout) {
906 // we didn't time out and got a result.
907 return OK;
Alex Light3ae82532017-07-26 13:59:07 -0700908 }
909 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700910 } while (true);
911 UNREACHABLE();
912}
913
914jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
915 CHECK(self == art::Thread::Current());
916 {
917 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
918 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
919 if (self->GetUserCodeSuspendCount() != 0) {
920 // This can only happen if we race with another thread to suspend 'self' and we lose.
921 return ERR(THREAD_SUSPENDED);
922 }
923 // We shouldn't be able to fail this.
924 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
925 // TODO More specific error would be nice.
926 return ERR(INTERNAL);
927 }
928 }
929 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
930 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
931 // to go to sleep until we are resumed.
932 SuspendCheck(self);
933 return OK;
934}
935
936jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
937 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700938 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700939 {
940 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700941 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700942 art::Thread* target = nullptr;
943 jvmtiError err = ERR(INTERNAL);
944 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
945 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700946 } else if (target == self) {
947 target_is_self = true;
948 }
Alex Light88fd7202017-06-30 08:31:59 -0700949 }
Alex Light3ae82532017-07-26 13:59:07 -0700950 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700951 return SuspendSelf(self);
952 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700953 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700954 }
955}
956
957jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
958 jthread thread) {
959 if (thread == nullptr) {
960 return ERR(NULL_POINTER);
961 }
962 art::Thread* self = art::Thread::Current();
Alex Lightcea42152018-09-18 22:51:55 +0000963 art::Thread* target;
Alex Light679dec12019-04-08 16:30:14 +0000964
965 // Make sure we won't get suspended ourselves while in the middle of resuming another thread.
966 ScopedNoUserCodeSuspension snucs(self);
967 // From now on we know we cannot get suspended by user-code.
968 {
969 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
970 // have the 'suspend_lock' locked here.
971 art::ScopedObjectAccess soa(self);
972 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
973 jvmtiError err = ERR(INTERNAL);
974 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
975 return err;
976 } else if (target == self) {
977 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
978 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
979 // about current state since it's all concurrent.
980 return ERR(THREAD_NOT_SUSPENDED);
Alex Light88fd7202017-06-30 08:31:59 -0700981 }
Alex Light679dec12019-04-08 16:30:14 +0000982 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
983 // cannot tell why resume failed.
Alex Lightcea42152018-09-18 22:51:55 +0000984 {
Alex Light679dec12019-04-08 16:30:14 +0000985 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
986 if (target->GetUserCodeSuspendCount() == 0) {
Alex Lightcea42152018-09-18 22:51:55 +0000987 return ERR(THREAD_NOT_SUSPENDED);
988 }
Alex Light3ae82532017-07-26 13:59:07 -0700989 }
Alex Light679dec12019-04-08 16:30:14 +0000990 }
991 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
992 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
993 DCHECK(target != self);
994 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
995 art::SuspendReason::kForUserCode)) {
996 // TODO Give a better error.
997 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
998 return ERR(INTERNAL);
999 } else {
1000 return OK;
1001 }
Alex Light88fd7202017-06-30 08:31:59 -07001002}
1003
Alex Light7ddc23d2017-09-22 15:33:41 -07001004static bool IsCurrentThread(jthread thr) {
1005 if (thr == nullptr) {
1006 return true;
1007 }
1008 art::Thread* self = art::Thread::Current();
1009 art::ScopedObjectAccess soa(self);
1010 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1011 art::Thread* target = nullptr;
1012 jvmtiError err_unused = ERR(INTERNAL);
1013 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1014 return target == self;
1015 } else {
1016 return false;
1017 }
1018}
1019
Alex Light88fd7202017-06-30 08:31:59 -07001020// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1021// since we can have threads in the list multiple times. This generally doesn't matter unless the
1022// current thread is present multiple times. In that case we need to suspend only once and either
1023// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1024// it didn't. We also want to handle the current thread last to make the behavior of the code
1025// simpler to understand.
1026jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1027 jint request_count,
1028 const jthread* threads,
1029 jvmtiError* results) {
1030 if (request_count == 0) {
1031 return ERR(ILLEGAL_ARGUMENT);
1032 } else if (results == nullptr || threads == nullptr) {
1033 return ERR(NULL_POINTER);
1034 }
1035 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1036 // running thread. These indexes we need to handle specially since we need to only actually
1037 // suspend a single time.
1038 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001039 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001040 if (IsCurrentThread(threads[i])) {
1041 current_thread_indexes.push_back(i);
1042 } else {
1043 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001044 }
Alex Light88fd7202017-06-30 08:31:59 -07001045 }
1046 if (!current_thread_indexes.empty()) {
1047 jint first_current_thread_index = current_thread_indexes[0];
1048 // Suspend self.
1049 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1050 results[first_current_thread_index] = res;
1051 // Fill in the rest of the error values as appropriate.
1052 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1053 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1054 results[*it] = other_results;
1055 }
1056 }
1057 return OK;
1058}
1059
1060jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1061 jint request_count,
1062 const jthread* threads,
1063 jvmtiError* results) {
1064 if (request_count == 0) {
1065 return ERR(ILLEGAL_ARGUMENT);
1066 } else if (results == nullptr || threads == nullptr) {
1067 return ERR(NULL_POINTER);
1068 }
1069 for (jint i = 0; i < request_count; i++) {
1070 results[i] = env->ResumeThread(threads[i]);
1071 }
1072 return OK;
1073}
1074
Alex Light54d39dc2017-09-25 17:00:16 -07001075jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1076 jthread thread,
1077 jobject exception) {
1078 art::Thread* self = art::Thread::Current();
1079 art::ScopedObjectAccess soa(self);
1080 art::StackHandleScope<1> hs(self);
1081 if (exception == nullptr) {
1082 return ERR(INVALID_OBJECT);
1083 }
1084 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1085 if (!obj->GetClass()->IsThrowableClass()) {
1086 return ERR(INVALID_OBJECT);
1087 }
1088 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001089 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001090 art::Thread* target = nullptr;
1091 jvmtiError err = ERR(INTERNAL);
1092 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001093 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001094 return err;
1095 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
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(THREAD_NOT_ALIVE);
1098 }
1099 struct StopThreadClosure : public art::Closure {
1100 public:
1101 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1102
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001103 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001104 // Make sure the thread is prepared to notice the exception.
Alex Lighta4cdd362019-04-18 09:17:10 -07001105 DeoptManager::Get()->DeoptimizeThread(me);
Alex Light54d39dc2017-09-25 17:00:16 -07001106 me->SetAsyncException(exception_.Get());
1107 // Wake up the thread if it is sleeping.
1108 me->Notify();
1109 }
1110
1111 private:
1112 art::Handle<art::mirror::Throwable> exception_;
1113 };
1114 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001115 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001116 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001117 return OK;
1118 } else {
1119 // Something went wrong, probably the thread died.
1120 return ERR(THREAD_NOT_ALIVE);
1121 }
1122}
1123
1124jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1125 art::Thread* self = art::Thread::Current();
1126 art::ScopedObjectAccess soa(self);
1127 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1128 art::Thread* target = nullptr;
1129 jvmtiError err = ERR(INTERNAL);
1130 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1131 return err;
1132 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1133 return ERR(THREAD_NOT_ALIVE);
1134 }
1135 target->Interrupt(self);
1136 return OK;
1137}
1138
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001139} // namespace openjdkjvmti