blob: 1021648a2ccfc9282e9a8657a0acf0a3c350970a [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"
Andreas Gampeeafaf572017-01-20 12:34:15 -080040#include "events-inl.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080041#include "gc/system_weak.h"
Alex Lightd9aff132017-10-31 22:30:05 +000042#include "gc/collector_type.h"
43#include "gc/gc_cause.h"
44#include "gc/scoped_gc_critical_section.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080045#include "gc_root-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010046#include "jni/jni_internal.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080047#include "mirror/class.h"
48#include "mirror/object-inl.h"
49#include "mirror/string.h"
Alex Light3611fdf2019-02-06 15:10:58 -080050#include "mirror/throwable.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070051#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080052#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080053#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080054#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080055#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080056#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070057#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080058#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070059#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080060#include "well_known_classes.h"
61
62namespace openjdkjvmti {
63
Alex Light184f0752018-07-13 11:18:22 -070064static const char* kJvmtiTlsKey = "JvmtiTlsKey";
65
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070066art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
67
Alex Light1d8a9742017-08-17 11:12:06 -070068struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080069 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
70 if (self->GetPeer() == nullptr) {
71 return nullptr;
72 }
73 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
74 }
Alex Light1d8a9742017-08-17 11:12:06 -070075
Andreas Gampe983c1752017-01-23 19:46:56 -080076 template <ArtJvmtiEvent kEvent>
77 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080078 DCHECK_EQ(self, art::Thread::Current());
79 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080080 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080081 event_handler->DispatchEvent<kEvent>(self,
82 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
83 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080084 }
85
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010086 void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light3611fdf2019-02-06 15:10:58 -080087 // Needs to be checked first because we might start these threads before we actually send the
88 // VMInit event.
89 if (self->IsSystemDaemon()) {
90 // System daemon threads are things like the finalizer or gc thread. It would be dangerous to
91 // allow agents to get in the way of these threads starting up. These threads include things
92 // like the HeapTaskDaemon and the finalizer daemon.
93 //
94 // This event can happen during the time before VMInit or just after zygote fork. Since the
95 // second is hard to distinguish we unfortunately cannot really check the state here.
96 return;
97 }
Andreas Gampeeafaf572017-01-20 12:34:15 -080098 if (!started) {
99 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
100 // started here.
101 if (art::kIsDebugBuild) {
102 std::string name;
103 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -0800104 if (name != "JDWP" &&
105 name != "Signal Catcher" &&
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800106 !android::base::StartsWith(name, "Jit thread pool") &&
107 !android::base::StartsWith(name, "Runtime worker thread")) {
Alex Light23aa7482017-08-16 10:01:13 -0700108 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
109 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -0800110 }
111 }
112 return;
113 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800114 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800115 }
116
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100117 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800118 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800119 }
120
Andreas Gampeeafaf572017-01-20 12:34:15 -0800121 EventHandler* event_handler = nullptr;
122 bool started = false;
123};
124
125ThreadCallback gThreadCallback;
126
127void ThreadUtil::Register(EventHandler* handler) {
128 art::Runtime* runtime = art::Runtime::Current();
129
130 gThreadCallback.started = runtime->IsStarted();
131 gThreadCallback.event_handler = handler;
132
133 art::ScopedThreadStateChange stsc(art::Thread::Current(),
134 art::ThreadState::kWaitingForDebuggerToAttach);
135 art::ScopedSuspendAll ssa("Add thread callback");
136 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700137}
138
139void ThreadUtil::VMInitEventSent() {
140 // We should have already started.
141 DCHECK(gThreadCallback.started);
142 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
143 // reported until Init.
144 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800145}
146
Alex Light3611fdf2019-02-06 15:10:58 -0800147
148static void WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
149 {
150 art::ScopedThreadStateChange strc(self, art::kNative);
151 JNIEnv* jni = self->GetJniEnv();
152 jni->CallStaticVoidMethod(art::WellKnownClasses::java_lang_Daemons,
153 art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart);
154 }
155 if (self->IsExceptionPending()) {
156 LOG(WARNING) << "Exception occured when waiting for system daemons to start: "
157 << self->GetException()->Dump();
158 self->ClearException();
159 }
160}
161
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700162void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700163 // We must have started since it is now safe to cache our data;
164 gThreadCallback.started = true;
Alex Light3611fdf2019-02-06 15:10:58 -0800165 art::Thread* self = art::Thread::Current();
166 art::ScopedObjectAccess soa(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700167 art::ObjPtr<art::mirror::Class> thread_class =
168 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
169 CHECK(thread_class != nullptr);
170 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
171 "Ljava/lang/ClassLoader;");
172 CHECK(context_class_loader_ != nullptr);
Alex Light3611fdf2019-02-06 15:10:58 -0800173 // Now wait for all required system threads to come up before allowing the rest of loading to
174 // continue.
175 WaitForSystemDaemonStart(self);
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700176}
177
Andreas Gampeeafaf572017-01-20 12:34:15 -0800178void ThreadUtil::Unregister() {
179 art::ScopedThreadStateChange stsc(art::Thread::Current(),
180 art::ThreadState::kWaitingForDebuggerToAttach);
181 art::ScopedSuspendAll ssa("Remove thread callback");
182 art::Runtime* runtime = art::Runtime::Current();
183 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800184}
185
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800186jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
187 art::Thread* self = art::Thread::Current();
188
189 art::ScopedObjectAccess soa(self);
190
191 jthread thread_peer;
192 if (self->IsStillStarting()) {
193 thread_peer = nullptr;
194 } else {
195 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
196 }
197
198 *thread_ptr = thread_peer;
199 return ERR(NONE);
200}
201
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800202// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700203bool ThreadUtil::GetNativeThread(jthread thread,
204 const art::ScopedObjectAccessAlreadyRunnable& soa,
205 /*out*/ art::Thread** thr,
206 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800207 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700208 *thr = art::Thread::Current();
209 return true;
210 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
211 *err = ERR(INVALID_THREAD);
212 return false;
213 } else {
214 *thr = art::Thread::FromManagedThread(soa, thread);
215 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800216 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700217}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800218
Alex Light7ddc23d2017-09-22 15:33:41 -0700219bool ThreadUtil::GetAliveNativeThread(jthread thread,
220 const art::ScopedObjectAccessAlreadyRunnable& soa,
221 /*out*/ art::Thread** thr,
222 /*out*/ jvmtiError* err) {
223 if (!GetNativeThread(thread, soa, thr, err)) {
224 return false;
225 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
226 *err = ERR(THREAD_NOT_ALIVE);
227 return false;
228 } else {
229 return true;
230 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800231}
232
233jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
234 if (info_ptr == nullptr) {
235 return ERR(NULL_POINTER);
236 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700237 if (!PhaseUtil::IsLivePhase()) {
238 return JVMTI_ERROR_WRONG_PHASE;
239 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800240
Alex Light3ae82532017-07-26 13:59:07 -0700241 art::Thread* self = art::Thread::Current();
242 art::ScopedObjectAccess soa(self);
243 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800244
Alex Light7ddc23d2017-09-22 15:33:41 -0700245 art::Thread* target;
246 jvmtiError err = ERR(INTERNAL);
247 if (!GetNativeThread(thread, soa, &target, &err)) {
248 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800249 }
250
Andreas Gampe54711412017-02-21 12:41:43 -0800251 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700252 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800253 // Have a native thread object, this thread is alive.
254 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700255 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800256 jvmtiError name_result;
257 name_uptr = CopyString(env, name.c_str(), &name_result);
258 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800259 return name_result;
260 }
Andreas Gampe54711412017-02-21 12:41:43 -0800261 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800262
Alex Light3ae82532017-07-26 13:59:07 -0700263 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800264
Alex Light3ae82532017-07-26 13:59:07 -0700265 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800266
Alex Light3ae82532017-07-26 13:59:07 -0700267 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800268
269 // ThreadGroup.
270 if (peer != nullptr) {
271 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
272 CHECK(f != nullptr);
273 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
274 info_ptr->thread_group = group == nullptr
275 ? nullptr
276 : soa.AddLocalReference<jthreadGroup>(group);
277 } else {
278 info_ptr->thread_group = nullptr;
279 }
280
281 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700282 DCHECK(context_class_loader_ != nullptr);
283 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
284 ? context_class_loader_->GetObject(peer)
285 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800286 info_ptr->context_class_loader = ccl == nullptr
287 ? nullptr
288 : soa.AddLocalReference<jobject>(ccl);
289 } else {
290 // Only the peer. This thread has either not been started, or is dead. Read things from
291 // the Java side.
292 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
293
294 // Name.
295 {
296 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
297 CHECK(f != nullptr);
298 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
299 std::string name_cpp;
300 const char* name_cstr;
301 if (name != nullptr) {
302 name_cpp = name->AsString()->ToModifiedUtf8();
303 name_cstr = name_cpp.c_str();
304 } else {
305 name_cstr = "";
306 }
Andreas Gampe54711412017-02-21 12:41:43 -0800307 jvmtiError name_result;
308 name_uptr = CopyString(env, name_cstr, &name_result);
309 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800310 return name_result;
311 }
Andreas Gampe54711412017-02-21 12:41:43 -0800312 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800313 }
314
315 // Priority.
316 {
317 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
318 CHECK(f != nullptr);
319 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
320 }
321
322 // Daemon.
323 {
324 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
325 CHECK(f != nullptr);
326 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
327 }
328
329 // ThreadGroup.
330 {
331 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
332 CHECK(f != nullptr);
333 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
334 info_ptr->thread_group = group == nullptr
335 ? nullptr
336 : soa.AddLocalReference<jthreadGroup>(group);
337 }
338
339 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700340 DCHECK(context_class_loader_ != nullptr);
341 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
342 ? context_class_loader_->GetObject(peer)
343 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800344 info_ptr->context_class_loader = ccl == nullptr
345 ? nullptr
346 : soa.AddLocalReference<jobject>(ccl);
347 }
348
349 name_uptr.release();
350
351 return ERR(NONE);
352}
353
Alex Light1f0a22f2017-07-17 12:55:59 -0700354struct InternalThreadState {
355 art::Thread* native_thread;
356 art::ThreadState art_state;
357 int thread_user_code_suspend_count;
358};
359
360// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700361static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700362 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700363 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700364 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700365 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
366 thread_state.native_thread = target;
367 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700368 thread_state.art_state = art::ThreadState::kStarting;
369 thread_state.thread_user_code_suspend_count = 0;
370 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700371 thread_state.art_state = target->GetState();
372 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800373 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700374 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800375}
376
Alex Light1f0a22f2017-07-17 12:55:59 -0700377static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
378 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800379 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
380
Alex Light1f0a22f2017-07-17 12:55:59 -0700381 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700382 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
383 // 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 -0800384 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
385 // Note: We do not have data about the previous state. Otherwise we should load the previous
386 // state here.
387 }
388
Alex Light1f0a22f2017-07-17 12:55:59 -0700389 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700390 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700391 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
392 }
393
Alex Light597adad2017-10-16 16:11:42 -0700394 // Enumerate all the thread states and fill in the other bits. This contains the results of
395 // following the decision tree in the JVMTI spec GetThreadState documentation.
396 switch (internal_thread_state) {
397 case art::ThreadState::kRunnable:
398 case art::ThreadState::kWaitingWeakGcRootRead:
399 case art::ThreadState::kSuspended:
400 // These are all simply runnable.
401 // kRunnable is self-explanatory.
402 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
403 // so we want to keep it marked as runnable.
404 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
405 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
406 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
407 break;
408 case art::ThreadState::kNative:
409 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
410 // state but we don't have the information to know if it should be present for any but the
411 // kNative state.
412 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
413 JVMTI_THREAD_STATE_RUNNABLE);
414 break;
415 case art::ThreadState::kBlocked:
416 // Blocked is one of the top level states so it sits alone.
417 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
418 break;
419 case art::ThreadState::kWaiting:
420 // Object.wait() so waiting, indefinitely, in object.wait.
421 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
422 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
423 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
424 break;
425 case art::ThreadState::kTimedWaiting:
426 // Object.wait(long) so waiting, with timeout, in object.wait.
427 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
428 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
429 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
430 break;
431 case art::ThreadState::kSleeping:
432 // In object.sleep. This is a timed wait caused by sleep.
433 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
434 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
435 JVMTI_THREAD_STATE_SLEEPING);
436 break;
437 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
438 // attached.
439 case art::ThreadState::kWaitingForDebuggerSend:
440 case art::ThreadState::kWaitingForDebuggerToAttach:
441 case art::ThreadState::kWaitingInMainDebuggerLoop:
442 case art::ThreadState::kWaitingForDebuggerSuspension:
443 case art::ThreadState::kWaitingForLockInflation:
444 case art::ThreadState::kWaitingForTaskProcessor:
445 case art::ThreadState::kWaitingForGcToComplete:
446 case art::ThreadState::kWaitingForCheckPointsToRun:
447 case art::ThreadState::kWaitingPerformingGc:
448 case art::ThreadState::kWaitingForJniOnLoad:
449 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
450 case art::ThreadState::kWaitingForSignalCatcherOutput:
451 case art::ThreadState::kWaitingForDeoptimization:
452 case art::ThreadState::kWaitingForMethodTracingStart:
453 case art::ThreadState::kWaitingForVisitObjects:
454 case art::ThreadState::kWaitingForGetObjectsAllocated:
455 case art::ThreadState::kWaitingForGcThreadFlip:
456 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
457 // caused by sleep, park, or object#wait.
458 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
459 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
460 break;
461 case art::ThreadState::kStarting:
462 case art::ThreadState::kTerminated:
463 // We only call this if we are alive so we shouldn't see either of these states.
464 LOG(FATAL) << "Should not be in state " << internal_thread_state;
465 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800466 }
Alex Light597adad2017-10-16 16:11:42 -0700467 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800468
469 return jvmti_state;
470}
471
Alex Light1f0a22f2017-07-17 12:55:59 -0700472static jint GetJavaStateFromInternal(const InternalThreadState& state) {
473 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800474 case art::ThreadState::kTerminated:
475 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
476
477 case art::ThreadState::kRunnable:
478 case art::ThreadState::kNative:
479 case art::ThreadState::kWaitingWeakGcRootRead:
480 case art::ThreadState::kSuspended:
481 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
482
483 case art::ThreadState::kTimedWaiting:
484 case art::ThreadState::kSleeping:
485 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
486
487 case art::ThreadState::kBlocked:
488 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
489
490 case art::ThreadState::kStarting:
491 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
492
493 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700494 case art::ThreadState::kWaitingForTaskProcessor:
495 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800496 case art::ThreadState::kWaitingForGcToComplete:
497 case art::ThreadState::kWaitingPerformingGc:
498 case art::ThreadState::kWaitingForCheckPointsToRun:
499 case art::ThreadState::kWaitingForDebuggerSend:
500 case art::ThreadState::kWaitingForDebuggerToAttach:
501 case art::ThreadState::kWaitingInMainDebuggerLoop:
502 case art::ThreadState::kWaitingForDebuggerSuspension:
503 case art::ThreadState::kWaitingForDeoptimization:
504 case art::ThreadState::kWaitingForGetObjectsAllocated:
505 case art::ThreadState::kWaitingForJniOnLoad:
506 case art::ThreadState::kWaitingForSignalCatcherOutput:
507 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
508 case art::ThreadState::kWaitingForMethodTracingStart:
509 case art::ThreadState::kWaitingForVisitObjects:
510 case art::ThreadState::kWaitingForGcThreadFlip:
511 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
512 }
513 LOG(FATAL) << "Unreachable";
514 UNREACHABLE();
515}
516
Alex Light1f0a22f2017-07-17 12:55:59 -0700517// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700518void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700519 art::ScopedObjectAccess soa(self);
520 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
521 self->FullSuspendCheck();
522}
523
Alex Light23aa7482017-08-16 10:01:13 -0700524bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
525 DCHECK(self == art::Thread::Current());
526 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
527 return self->GetUserCodeSuspendCount() != 0;
528}
529
530bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
531 DCHECK(self == art::Thread::Current());
532 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
533 return WouldSuspendForUserCodeLocked(self);
534}
535
Andreas Gampe72c19832017-01-12 13:22:16 -0800536jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
537 jthread thread,
538 jint* thread_state_ptr) {
539 if (thread_state_ptr == nullptr) {
540 return ERR(NULL_POINTER);
541 }
542
Alex Light1f0a22f2017-07-17 12:55:59 -0700543 art::Thread* self = art::Thread::Current();
544 InternalThreadState state = {};
545 // Loop since we need to bail out and try again if we would end up getting suspended while holding
546 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
547 // release the lock, wait to get resumed and try again.
548 do {
549 SuspendCheck(self);
550 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700551 if (WouldSuspendForUserCodeLocked(self)) {
552 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
553 // a user-code suspension. We retry and do another SuspendCheck to clear this.
554 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700555 }
556 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700557 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700558 jvmtiError err = ERR(INTERNAL);
559 art::Thread* target = nullptr;
560 if (!GetNativeThread(thread, soa, &target, &err)) {
561 return err;
562 }
563 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700564 if (state.art_state == art::ThreadState::kStarting) {
565 break;
566 }
567 DCHECK(state.native_thread != nullptr);
568
569 // Translate internal thread state to JVMTI and Java state.
570 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
571
572 // Java state is derived from nativeGetState.
573 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
574 // different mask if a thread got suspended due to user-code. However, this is for
575 // consistency with the Java view.
576 jint java_state = GetJavaStateFromInternal(state);
577
578 *thread_state_ptr = jvmti_state | java_state;
579
580 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700581 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800582
Alex Light3ae82532017-07-26 13:59:07 -0700583 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800584
Alex Light3ae82532017-07-26 13:59:07 -0700585 if (thread == nullptr) {
586 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
587 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800588 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800589
Alex Light3ae82532017-07-26 13:59:07 -0700590 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700591 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800592
Alex Light3ae82532017-07-26 13:59:07 -0700593 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700594 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
595 art::ObjPtr<art::mirror::Class> thread_klass =
596 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
597 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
598 return ERR(INVALID_THREAD);
599 }
600 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700601 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700602 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700603 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
604 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
605 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
606 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800607 return ERR(NONE);
608}
609
Andreas Gampe85807442017-01-13 14:40:58 -0800610jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
611 jint* threads_count_ptr,
612 jthread** threads_ptr) {
613 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
614 return ERR(NULL_POINTER);
615 }
616
617 art::Thread* current = art::Thread::Current();
618
619 art::ScopedObjectAccess soa(current);
620
621 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
622 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
623
624 std::vector<art::ObjPtr<art::mirror::Object>> peers;
625
626 for (art::Thread* thread : thread_list) {
627 // Skip threads that are still starting.
628 if (thread->IsStillStarting()) {
629 continue;
630 }
631
Andreas Gampe202f85a2017-02-06 10:23:26 -0800632 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800633 if (peer != nullptr) {
634 peers.push_back(peer);
635 }
636 }
637
638 if (peers.empty()) {
639 *threads_count_ptr = 0;
640 *threads_ptr = nullptr;
641 } else {
642 unsigned char* data;
643 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
644 if (data_result != ERR(NONE)) {
645 return data_result;
646 }
647 jthread* threads = reinterpret_cast<jthread*>(data);
648 for (size_t i = 0; i != peers.size(); ++i) {
649 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
650 }
651
652 *threads_count_ptr = static_cast<jint>(peers.size());
653 *threads_ptr = threads;
654 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800655 return ERR(NONE);
656}
Andreas Gampe85807442017-01-13 14:40:58 -0800657
Alex Light092a4042017-07-12 08:46:44 -0700658static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
659 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
660 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
Alex Light0aa7a5a2018-10-10 15:58:14 +0000661 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700662 if (global_tls != nullptr) {
663 global_tls->data.erase(env);
664 }
665}
666
667void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
668 art::Thread* self = art::Thread::Current();
669 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
670 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
671 list->ForEach(RemoveTLSData, env);
672}
673
674jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
675 art::Thread* self = art::Thread::Current();
676 art::ScopedObjectAccess soa(self);
677 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700678 art::Thread* target = nullptr;
679 jvmtiError err = ERR(INTERNAL);
680 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
681 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800682 }
683
Alex Light0aa7a5a2018-10-10 15:58:14 +0000684 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700685
686 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800687
688 return ERR(NONE);
689}
690
Alex Light0aa7a5a2018-10-10 15:58:14 +0000691JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
692 JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
693 if (data != nullptr) {
694 return data;
695 } else {
696 thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
697 return GetGlobalTLSData(thread);
698 }
699}
700
701JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
702 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
703}
704
Alex Light092a4042017-07-12 08:46:44 -0700705jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800706 jthread thread,
707 void** data_ptr) {
708 if (data_ptr == nullptr) {
709 return ERR(NULL_POINTER);
710 }
711
Alex Light092a4042017-07-12 08:46:44 -0700712 art::Thread* self = art::Thread::Current();
713 art::ScopedObjectAccess soa(self);
714 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700715 art::Thread* target = nullptr;
716 jvmtiError err = ERR(INTERNAL);
717 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
718 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800719 }
720
Alex Light0aa7a5a2018-10-10 15:58:14 +0000721 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700722 if (global_tls == nullptr) {
723 *data_ptr = nullptr;
724 return OK;
725 }
726 auto it = global_tls->data.find(env);
727 if (it != global_tls->data.end()) {
728 *data_ptr = const_cast<void*>(it->second);
729 } else {
730 *data_ptr = nullptr;
731 }
732
Andreas Gampe85807442017-01-13 14:40:58 -0800733 return ERR(NONE);
734}
735
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800736struct AgentData {
737 const void* arg;
738 jvmtiStartFunction proc;
739 jthread thread;
740 JavaVM* java_vm;
741 jvmtiEnv* jvmti_env;
742 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800743 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800744};
745
746static void* AgentCallback(void* arg) {
747 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
748 CHECK(data->thread != nullptr);
749
750 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800751 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700752 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800753 // The name in Attach() is only for logging. Set the thread name. This is important so
754 // that the thread is no longer seen as starting up.
755 {
756 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800757 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800758 }
759
760 // Release the peer.
761 JNIEnv* env = self->GetJniEnv();
762 env->DeleteGlobalRef(data->thread);
763 data->thread = nullptr;
764
Alex Light739bf722017-10-20 13:14:24 -0700765 {
766 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
767 // before going into the provided code.
768 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
769 art::Runtime::Current()->EndThreadBirth();
770 }
771
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800772 // Run the agent code.
773 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
774
775 // Detach the thread.
776 int detach_result = data->java_vm->DetachCurrentThread();
777 CHECK_EQ(detach_result, 0);
778
779 return nullptr;
780}
781
782jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
783 jthread thread,
784 jvmtiStartFunction proc,
785 const void* arg,
786 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700787 if (!PhaseUtil::IsLivePhase()) {
788 return ERR(WRONG_PHASE);
789 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800790 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
791 return ERR(INVALID_PRIORITY);
792 }
793 JNIEnv* env = art::Thread::Current()->GetJniEnv();
794 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
795 return ERR(INVALID_THREAD);
796 }
797 if (proc == nullptr) {
798 return ERR(NULL_POINTER);
799 }
800
Alex Light739bf722017-10-20 13:14:24 -0700801 {
802 art::Runtime* runtime = art::Runtime::Current();
803 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
804 if (runtime->IsShuttingDownLocked()) {
805 // The runtime is shutting down so we cannot create new threads.
806 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
807 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
808 // impossible. Existing agents don't seem to generally do anything with this return value so
809 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
810 // even though code is never actually run.
811 return ERR(INTERNAL);
812 }
813 runtime->StartThreadBirth();
814 }
815
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800816 std::unique_ptr<AgentData> data(new AgentData);
817 data->arg = arg;
818 data->proc = proc;
819 // We need a global ref for Java objects, as local refs will be invalid.
820 data->thread = env->NewGlobalRef(thread);
821 data->java_vm = art::Runtime::Current()->GetJavaVM();
822 data->jvmti_env = jvmti_env;
823 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800824 ScopedLocalRef<jstring> s(
825 env,
826 reinterpret_cast<jstring>(
827 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
828 if (s == nullptr) {
829 data->name = "JVMTI Agent Thread";
830 } else {
831 ScopedUtfChars name(env, s.get());
832 data->name = name.c_str();
833 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800834
835 pthread_t pthread;
836 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700837 nullptr,
838 &AgentCallback,
839 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800840 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700841 // If the create succeeded the other thread will call EndThreadBirth.
842 art::Runtime* runtime = art::Runtime::Current();
843 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
844 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800845 return ERR(INTERNAL);
846 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700847 data.release(); // NOLINT pthreads API.
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800848
849 return ERR(NONE);
850}
851
Alex Light88fd7202017-06-30 08:31:59 -0700852jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700853 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700854 // Loop since we need to bail out and try again if we would end up getting suspended while holding
855 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
856 // release the lock, wait to get resumed and try again.
857 do {
858 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
859 // another SuspendThread in the middle of suspending something else potentially causing a
860 // deadlock. We need to do this in the loop because if we ended up back here then we had
861 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
862 // before continuing.
863 SuspendCheck(self);
864 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700865 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700866 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
867 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700868 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700869 }
Alex Light23aa7482017-08-16 10:01:13 -0700870 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700871 {
872 art::ScopedObjectAccess soa(self);
873 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700874 art::Thread* target = nullptr;
875 jvmtiError err = ERR(INTERNAL);
876 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
877 return err;
878 }
Alex Lightcea42152018-09-18 22:51:55 +0000879 art::ThreadState state = target->GetState();
880 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
881 return ERR(THREAD_NOT_ALIVE);
882 } else {
883 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
884 if (target->GetUserCodeSuspendCount() != 0) {
885 return ERR(THREAD_SUSPENDED);
886 }
887 }
Alex Light88fd7202017-06-30 08:31:59 -0700888 }
Alex Lightcea42152018-09-18 22:51:55 +0000889 bool timeout = true;
890 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
891 target_jthread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700892 /* request_suspension= */ true,
Alex Lightcea42152018-09-18 22:51:55 +0000893 art::SuspendReason::kForUserCode,
894 &timeout);
895 if (ret_target == nullptr && !timeout) {
Alex Light3ae82532017-07-26 13:59:07 -0700896 // TODO It would be good to get more information about why exactly the thread failed to
897 // suspend.
898 return ERR(INTERNAL);
Alex Lightcea42152018-09-18 22:51:55 +0000899 } else if (!timeout) {
900 // we didn't time out and got a result.
901 return OK;
Alex Light3ae82532017-07-26 13:59:07 -0700902 }
903 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700904 } while (true);
905 UNREACHABLE();
906}
907
908jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
909 CHECK(self == art::Thread::Current());
910 {
911 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
912 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
913 if (self->GetUserCodeSuspendCount() != 0) {
914 // This can only happen if we race with another thread to suspend 'self' and we lose.
915 return ERR(THREAD_SUSPENDED);
916 }
917 // We shouldn't be able to fail this.
918 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
919 // TODO More specific error would be nice.
920 return ERR(INTERNAL);
921 }
922 }
923 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
924 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
925 // to go to sleep until we are resumed.
926 SuspendCheck(self);
927 return OK;
928}
929
930jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
931 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700932 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700933 {
934 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700935 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700936 art::Thread* target = nullptr;
937 jvmtiError err = ERR(INTERNAL);
938 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
939 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700940 } else if (target == self) {
941 target_is_self = true;
942 }
Alex Light88fd7202017-06-30 08:31:59 -0700943 }
Alex Light3ae82532017-07-26 13:59:07 -0700944 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700945 return SuspendSelf(self);
946 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700947 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700948 }
949}
950
951jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
952 jthread thread) {
953 if (thread == nullptr) {
954 return ERR(NULL_POINTER);
955 }
956 art::Thread* self = art::Thread::Current();
Alex Lightcea42152018-09-18 22:51:55 +0000957 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700958 // Retry until we know we won't get suspended by user code while resuming something.
959 do {
960 SuspendCheck(self);
961 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700962 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700963 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
964 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700965 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700966 }
Alex Light3ae82532017-07-26 13:59:07 -0700967 // From now on we know we cannot get suspended by user-code.
Alex Lightcea42152018-09-18 22:51:55 +0000968 {
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);
981 }
982 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
983 // cannot tell why resume failed.
984 {
985 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
986 if (target->GetUserCodeSuspendCount() == 0) {
987 return ERR(THREAD_NOT_SUSPENDED);
988 }
989 }
Alex Light3ae82532017-07-26 13:59:07 -0700990 }
Alex Lightcea42152018-09-18 22:51:55 +0000991 // 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)) {
Alex Light3ae82532017-07-26 13:59:07 -0700996 // TODO Give a better error.
Alex Lightcea42152018-09-18 22:51:55 +0000997 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
Alex Light3ae82532017-07-26 13:59:07 -0700998 return ERR(INTERNAL);
999 } else {
1000 return OK;
1001 }
1002 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -07001003}
1004
Alex Light7ddc23d2017-09-22 15:33:41 -07001005static bool IsCurrentThread(jthread thr) {
1006 if (thr == nullptr) {
1007 return true;
1008 }
1009 art::Thread* self = art::Thread::Current();
1010 art::ScopedObjectAccess soa(self);
1011 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1012 art::Thread* target = nullptr;
1013 jvmtiError err_unused = ERR(INTERNAL);
1014 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1015 return target == self;
1016 } else {
1017 return false;
1018 }
1019}
1020
Alex Light88fd7202017-06-30 08:31:59 -07001021// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1022// since we can have threads in the list multiple times. This generally doesn't matter unless the
1023// current thread is present multiple times. In that case we need to suspend only once and either
1024// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1025// it didn't. We also want to handle the current thread last to make the behavior of the code
1026// simpler to understand.
1027jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1028 jint request_count,
1029 const jthread* threads,
1030 jvmtiError* results) {
1031 if (request_count == 0) {
1032 return ERR(ILLEGAL_ARGUMENT);
1033 } else if (results == nullptr || threads == nullptr) {
1034 return ERR(NULL_POINTER);
1035 }
1036 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1037 // running thread. These indexes we need to handle specially since we need to only actually
1038 // suspend a single time.
1039 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001040 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001041 if (IsCurrentThread(threads[i])) {
1042 current_thread_indexes.push_back(i);
1043 } else {
1044 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001045 }
Alex Light88fd7202017-06-30 08:31:59 -07001046 }
1047 if (!current_thread_indexes.empty()) {
1048 jint first_current_thread_index = current_thread_indexes[0];
1049 // Suspend self.
1050 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1051 results[first_current_thread_index] = res;
1052 // Fill in the rest of the error values as appropriate.
1053 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1054 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1055 results[*it] = other_results;
1056 }
1057 }
1058 return OK;
1059}
1060
1061jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1062 jint request_count,
1063 const jthread* threads,
1064 jvmtiError* results) {
1065 if (request_count == 0) {
1066 return ERR(ILLEGAL_ARGUMENT);
1067 } else if (results == nullptr || threads == nullptr) {
1068 return ERR(NULL_POINTER);
1069 }
1070 for (jint i = 0; i < request_count; i++) {
1071 results[i] = env->ResumeThread(threads[i]);
1072 }
1073 return OK;
1074}
1075
Alex Light54d39dc2017-09-25 17:00:16 -07001076jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1077 jthread thread,
1078 jobject exception) {
1079 art::Thread* self = art::Thread::Current();
1080 art::ScopedObjectAccess soa(self);
1081 art::StackHandleScope<1> hs(self);
1082 if (exception == nullptr) {
1083 return ERR(INVALID_OBJECT);
1084 }
1085 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1086 if (!obj->GetClass()->IsThrowableClass()) {
1087 return ERR(INVALID_OBJECT);
1088 }
1089 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001090 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001091 art::Thread* target = nullptr;
1092 jvmtiError err = ERR(INTERNAL);
1093 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001094 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001095 return err;
1096 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001097 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001098 return ERR(THREAD_NOT_ALIVE);
1099 }
1100 struct StopThreadClosure : public art::Closure {
1101 public:
1102 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1103
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001104 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001105 // Make sure the thread is prepared to notice the exception.
1106 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1107 me->SetAsyncException(exception_.Get());
1108 // Wake up the thread if it is sleeping.
1109 me->Notify();
1110 }
1111
1112 private:
1113 art::Handle<art::mirror::Throwable> exception_;
1114 };
1115 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001116 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001117 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001118 return OK;
1119 } else {
1120 // Something went wrong, probably the thread died.
1121 return ERR(THREAD_NOT_ALIVE);
1122 }
1123}
1124
1125jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1126 art::Thread* self = art::Thread::Current();
1127 art::ScopedObjectAccess soa(self);
1128 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1129 art::Thread* target = nullptr;
1130 jvmtiError err = ERR(INTERNAL);
1131 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1132 return err;
1133 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1134 return ERR(THREAD_NOT_ALIVE);
1135 }
1136 target->Interrupt(self);
1137 return OK;
1138}
1139
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001140} // namespace openjdkjvmti