blob: 051db4c67e53cd37413c65411ce2d78a4b3fbae0 [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"
Andreas Gampe373a9b52017-10-18 09:01:57 -070050#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080051#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080052#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080053#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080054#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080055#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070056#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080057#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070058#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080059#include "well_known_classes.h"
60
61namespace openjdkjvmti {
62
Alex Light184f0752018-07-13 11:18:22 -070063static const char* kJvmtiTlsKey = "JvmtiTlsKey";
64
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070065art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
66
Alex Light1d8a9742017-08-17 11:12:06 -070067struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080068 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
69 if (self->GetPeer() == nullptr) {
70 return nullptr;
71 }
72 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
73 }
Alex Light1d8a9742017-08-17 11:12:06 -070074
Andreas Gampe983c1752017-01-23 19:46:56 -080075 template <ArtJvmtiEvent kEvent>
76 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080077 DCHECK_EQ(self, art::Thread::Current());
78 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080079 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080080 event_handler->DispatchEvent<kEvent>(self,
81 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
82 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080083 }
84
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010085 void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080086 if (!started) {
87 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
88 // started here.
89 if (art::kIsDebugBuild) {
90 std::string name;
91 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080092 if (name != "JDWP" &&
93 name != "Signal Catcher" &&
Mathieu Chartierc6068c72018-11-13 16:00:58 -080094 !android::base::StartsWith(name, "Jit thread pool") &&
95 !android::base::StartsWith(name, "Runtime worker thread")) {
Alex Light23aa7482017-08-16 10:01:13 -070096 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
97 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080098 }
99 }
100 return;
101 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800102 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800103 }
104
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100105 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800106 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800107 }
108
Andreas Gampeeafaf572017-01-20 12:34:15 -0800109 EventHandler* event_handler = nullptr;
110 bool started = false;
111};
112
113ThreadCallback gThreadCallback;
114
115void ThreadUtil::Register(EventHandler* handler) {
116 art::Runtime* runtime = art::Runtime::Current();
117
118 gThreadCallback.started = runtime->IsStarted();
119 gThreadCallback.event_handler = handler;
120
121 art::ScopedThreadStateChange stsc(art::Thread::Current(),
122 art::ThreadState::kWaitingForDebuggerToAttach);
123 art::ScopedSuspendAll ssa("Add thread callback");
124 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700125}
126
127void ThreadUtil::VMInitEventSent() {
128 // We should have already started.
129 DCHECK(gThreadCallback.started);
130 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
131 // reported until Init.
132 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800133}
134
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700135void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700136 // We must have started since it is now safe to cache our data;
137 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700138 art::ScopedObjectAccess soa(art::Thread::Current());
139 art::ObjPtr<art::mirror::Class> thread_class =
140 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
141 CHECK(thread_class != nullptr);
142 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
143 "Ljava/lang/ClassLoader;");
144 CHECK(context_class_loader_ != nullptr);
145}
146
Andreas Gampeeafaf572017-01-20 12:34:15 -0800147void ThreadUtil::Unregister() {
148 art::ScopedThreadStateChange stsc(art::Thread::Current(),
149 art::ThreadState::kWaitingForDebuggerToAttach);
150 art::ScopedSuspendAll ssa("Remove thread callback");
151 art::Runtime* runtime = art::Runtime::Current();
152 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800153}
154
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800155jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
156 art::Thread* self = art::Thread::Current();
157
158 art::ScopedObjectAccess soa(self);
159
160 jthread thread_peer;
161 if (self->IsStillStarting()) {
162 thread_peer = nullptr;
163 } else {
164 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
165 }
166
167 *thread_ptr = thread_peer;
168 return ERR(NONE);
169}
170
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800171// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700172bool ThreadUtil::GetNativeThread(jthread thread,
173 const art::ScopedObjectAccessAlreadyRunnable& soa,
174 /*out*/ art::Thread** thr,
175 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800176 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700177 *thr = art::Thread::Current();
178 return true;
179 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
180 *err = ERR(INVALID_THREAD);
181 return false;
182 } else {
183 *thr = art::Thread::FromManagedThread(soa, thread);
184 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800185 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700186}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800187
Alex Light7ddc23d2017-09-22 15:33:41 -0700188bool ThreadUtil::GetAliveNativeThread(jthread thread,
189 const art::ScopedObjectAccessAlreadyRunnable& soa,
190 /*out*/ art::Thread** thr,
191 /*out*/ jvmtiError* err) {
192 if (!GetNativeThread(thread, soa, thr, err)) {
193 return false;
194 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
195 *err = ERR(THREAD_NOT_ALIVE);
196 return false;
197 } else {
198 return true;
199 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800200}
201
202jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
203 if (info_ptr == nullptr) {
204 return ERR(NULL_POINTER);
205 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700206 if (!PhaseUtil::IsLivePhase()) {
207 return JVMTI_ERROR_WRONG_PHASE;
208 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800209
Alex Light3ae82532017-07-26 13:59:07 -0700210 art::Thread* self = art::Thread::Current();
211 art::ScopedObjectAccess soa(self);
212 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800213
Alex Light7ddc23d2017-09-22 15:33:41 -0700214 art::Thread* target;
215 jvmtiError err = ERR(INTERNAL);
216 if (!GetNativeThread(thread, soa, &target, &err)) {
217 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800218 }
219
Andreas Gampe54711412017-02-21 12:41:43 -0800220 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700221 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800222 // Have a native thread object, this thread is alive.
223 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700224 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800225 jvmtiError name_result;
226 name_uptr = CopyString(env, name.c_str(), &name_result);
227 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800228 return name_result;
229 }
Andreas Gampe54711412017-02-21 12:41:43 -0800230 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800231
Alex Light3ae82532017-07-26 13:59:07 -0700232 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800233
Alex Light3ae82532017-07-26 13:59:07 -0700234 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800235
Alex Light3ae82532017-07-26 13:59:07 -0700236 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800237
238 // ThreadGroup.
239 if (peer != nullptr) {
240 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
241 CHECK(f != nullptr);
242 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
243 info_ptr->thread_group = group == nullptr
244 ? nullptr
245 : soa.AddLocalReference<jthreadGroup>(group);
246 } else {
247 info_ptr->thread_group = nullptr;
248 }
249
250 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700251 DCHECK(context_class_loader_ != nullptr);
252 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
253 ? context_class_loader_->GetObject(peer)
254 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800255 info_ptr->context_class_loader = ccl == nullptr
256 ? nullptr
257 : soa.AddLocalReference<jobject>(ccl);
258 } else {
259 // Only the peer. This thread has either not been started, or is dead. Read things from
260 // the Java side.
261 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
262
263 // Name.
264 {
265 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
266 CHECK(f != nullptr);
267 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
268 std::string name_cpp;
269 const char* name_cstr;
270 if (name != nullptr) {
271 name_cpp = name->AsString()->ToModifiedUtf8();
272 name_cstr = name_cpp.c_str();
273 } else {
274 name_cstr = "";
275 }
Andreas Gampe54711412017-02-21 12:41:43 -0800276 jvmtiError name_result;
277 name_uptr = CopyString(env, name_cstr, &name_result);
278 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800279 return name_result;
280 }
Andreas Gampe54711412017-02-21 12:41:43 -0800281 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800282 }
283
284 // Priority.
285 {
286 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
287 CHECK(f != nullptr);
288 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
289 }
290
291 // Daemon.
292 {
293 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
294 CHECK(f != nullptr);
295 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
296 }
297
298 // ThreadGroup.
299 {
300 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
301 CHECK(f != nullptr);
302 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
303 info_ptr->thread_group = group == nullptr
304 ? nullptr
305 : soa.AddLocalReference<jthreadGroup>(group);
306 }
307
308 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700309 DCHECK(context_class_loader_ != nullptr);
310 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
311 ? context_class_loader_->GetObject(peer)
312 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800313 info_ptr->context_class_loader = ccl == nullptr
314 ? nullptr
315 : soa.AddLocalReference<jobject>(ccl);
316 }
317
318 name_uptr.release();
319
320 return ERR(NONE);
321}
322
Alex Light1f0a22f2017-07-17 12:55:59 -0700323struct InternalThreadState {
324 art::Thread* native_thread;
325 art::ThreadState art_state;
326 int thread_user_code_suspend_count;
327};
328
329// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700330static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700331 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700332 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700333 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700334 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
335 thread_state.native_thread = target;
336 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700337 thread_state.art_state = art::ThreadState::kStarting;
338 thread_state.thread_user_code_suspend_count = 0;
339 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700340 thread_state.art_state = target->GetState();
341 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800342 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700343 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800344}
345
Alex Light1f0a22f2017-07-17 12:55:59 -0700346static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
347 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800348 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
349
Alex Light1f0a22f2017-07-17 12:55:59 -0700350 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700351 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
352 // 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 -0800353 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
354 // Note: We do not have data about the previous state. Otherwise we should load the previous
355 // state here.
356 }
357
Alex Light1f0a22f2017-07-17 12:55:59 -0700358 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700359 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700360 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
361 }
362
Alex Light597adad2017-10-16 16:11:42 -0700363 // Enumerate all the thread states and fill in the other bits. This contains the results of
364 // following the decision tree in the JVMTI spec GetThreadState documentation.
365 switch (internal_thread_state) {
366 case art::ThreadState::kRunnable:
367 case art::ThreadState::kWaitingWeakGcRootRead:
368 case art::ThreadState::kSuspended:
369 // These are all simply runnable.
370 // kRunnable is self-explanatory.
371 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
372 // so we want to keep it marked as runnable.
373 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
374 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
375 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
376 break;
377 case art::ThreadState::kNative:
378 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
379 // state but we don't have the information to know if it should be present for any but the
380 // kNative state.
381 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
382 JVMTI_THREAD_STATE_RUNNABLE);
383 break;
384 case art::ThreadState::kBlocked:
385 // Blocked is one of the top level states so it sits alone.
386 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
387 break;
388 case art::ThreadState::kWaiting:
389 // Object.wait() so waiting, indefinitely, in object.wait.
390 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
391 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
392 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
393 break;
394 case art::ThreadState::kTimedWaiting:
395 // Object.wait(long) so waiting, with timeout, in object.wait.
396 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
397 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
398 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
399 break;
400 case art::ThreadState::kSleeping:
401 // In object.sleep. This is a timed wait caused by sleep.
402 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
403 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
404 JVMTI_THREAD_STATE_SLEEPING);
405 break;
406 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
407 // attached.
408 case art::ThreadState::kWaitingForDebuggerSend:
409 case art::ThreadState::kWaitingForDebuggerToAttach:
410 case art::ThreadState::kWaitingInMainDebuggerLoop:
411 case art::ThreadState::kWaitingForDebuggerSuspension:
412 case art::ThreadState::kWaitingForLockInflation:
413 case art::ThreadState::kWaitingForTaskProcessor:
414 case art::ThreadState::kWaitingForGcToComplete:
415 case art::ThreadState::kWaitingForCheckPointsToRun:
416 case art::ThreadState::kWaitingPerformingGc:
417 case art::ThreadState::kWaitingForJniOnLoad:
418 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
419 case art::ThreadState::kWaitingForSignalCatcherOutput:
420 case art::ThreadState::kWaitingForDeoptimization:
421 case art::ThreadState::kWaitingForMethodTracingStart:
422 case art::ThreadState::kWaitingForVisitObjects:
423 case art::ThreadState::kWaitingForGetObjectsAllocated:
424 case art::ThreadState::kWaitingForGcThreadFlip:
425 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
426 // caused by sleep, park, or object#wait.
427 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
428 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
429 break;
430 case art::ThreadState::kStarting:
431 case art::ThreadState::kTerminated:
432 // We only call this if we are alive so we shouldn't see either of these states.
433 LOG(FATAL) << "Should not be in state " << internal_thread_state;
434 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800435 }
Alex Light597adad2017-10-16 16:11:42 -0700436 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800437
438 return jvmti_state;
439}
440
Alex Light1f0a22f2017-07-17 12:55:59 -0700441static jint GetJavaStateFromInternal(const InternalThreadState& state) {
442 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800443 case art::ThreadState::kTerminated:
444 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
445
446 case art::ThreadState::kRunnable:
447 case art::ThreadState::kNative:
448 case art::ThreadState::kWaitingWeakGcRootRead:
449 case art::ThreadState::kSuspended:
450 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
451
452 case art::ThreadState::kTimedWaiting:
453 case art::ThreadState::kSleeping:
454 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
455
456 case art::ThreadState::kBlocked:
457 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
458
459 case art::ThreadState::kStarting:
460 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
461
462 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700463 case art::ThreadState::kWaitingForTaskProcessor:
464 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800465 case art::ThreadState::kWaitingForGcToComplete:
466 case art::ThreadState::kWaitingPerformingGc:
467 case art::ThreadState::kWaitingForCheckPointsToRun:
468 case art::ThreadState::kWaitingForDebuggerSend:
469 case art::ThreadState::kWaitingForDebuggerToAttach:
470 case art::ThreadState::kWaitingInMainDebuggerLoop:
471 case art::ThreadState::kWaitingForDebuggerSuspension:
472 case art::ThreadState::kWaitingForDeoptimization:
473 case art::ThreadState::kWaitingForGetObjectsAllocated:
474 case art::ThreadState::kWaitingForJniOnLoad:
475 case art::ThreadState::kWaitingForSignalCatcherOutput:
476 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
477 case art::ThreadState::kWaitingForMethodTracingStart:
478 case art::ThreadState::kWaitingForVisitObjects:
479 case art::ThreadState::kWaitingForGcThreadFlip:
480 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
481 }
482 LOG(FATAL) << "Unreachable";
483 UNREACHABLE();
484}
485
Alex Light1f0a22f2017-07-17 12:55:59 -0700486// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700487void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700488 art::ScopedObjectAccess soa(self);
489 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
490 self->FullSuspendCheck();
491}
492
Alex Light23aa7482017-08-16 10:01:13 -0700493bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
494 DCHECK(self == art::Thread::Current());
495 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
496 return self->GetUserCodeSuspendCount() != 0;
497}
498
499bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
500 DCHECK(self == art::Thread::Current());
501 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
502 return WouldSuspendForUserCodeLocked(self);
503}
504
Andreas Gampe72c19832017-01-12 13:22:16 -0800505jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
506 jthread thread,
507 jint* thread_state_ptr) {
508 if (thread_state_ptr == nullptr) {
509 return ERR(NULL_POINTER);
510 }
511
Alex Light1f0a22f2017-07-17 12:55:59 -0700512 art::Thread* self = art::Thread::Current();
513 InternalThreadState state = {};
514 // Loop since we need to bail out and try again if we would end up getting suspended while holding
515 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
516 // release the lock, wait to get resumed and try again.
517 do {
518 SuspendCheck(self);
519 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700520 if (WouldSuspendForUserCodeLocked(self)) {
521 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
522 // a user-code suspension. We retry and do another SuspendCheck to clear this.
523 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700524 }
525 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700526 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700527 jvmtiError err = ERR(INTERNAL);
528 art::Thread* target = nullptr;
529 if (!GetNativeThread(thread, soa, &target, &err)) {
530 return err;
531 }
532 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700533 if (state.art_state == art::ThreadState::kStarting) {
534 break;
535 }
536 DCHECK(state.native_thread != nullptr);
537
538 // Translate internal thread state to JVMTI and Java state.
539 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
540
541 // Java state is derived from nativeGetState.
542 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
543 // different mask if a thread got suspended due to user-code. However, this is for
544 // consistency with the Java view.
545 jint java_state = GetJavaStateFromInternal(state);
546
547 *thread_state_ptr = jvmti_state | java_state;
548
549 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700550 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800551
Alex Light3ae82532017-07-26 13:59:07 -0700552 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800553
Alex Light3ae82532017-07-26 13:59:07 -0700554 if (thread == nullptr) {
555 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
556 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800557 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800558
Alex Light3ae82532017-07-26 13:59:07 -0700559 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700560 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800561
Alex Light3ae82532017-07-26 13:59:07 -0700562 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700563 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
564 art::ObjPtr<art::mirror::Class> thread_klass =
565 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
566 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
567 return ERR(INVALID_THREAD);
568 }
569 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700570 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700571 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700572 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
573 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
574 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
575 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800576 return ERR(NONE);
577}
578
Andreas Gampe85807442017-01-13 14:40:58 -0800579jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
580 jint* threads_count_ptr,
581 jthread** threads_ptr) {
582 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
583 return ERR(NULL_POINTER);
584 }
585
586 art::Thread* current = art::Thread::Current();
587
588 art::ScopedObjectAccess soa(current);
589
590 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
591 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
592
593 std::vector<art::ObjPtr<art::mirror::Object>> peers;
594
595 for (art::Thread* thread : thread_list) {
596 // Skip threads that are still starting.
597 if (thread->IsStillStarting()) {
598 continue;
599 }
600
Andreas Gampe202f85a2017-02-06 10:23:26 -0800601 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800602 if (peer != nullptr) {
603 peers.push_back(peer);
604 }
605 }
606
607 if (peers.empty()) {
608 *threads_count_ptr = 0;
609 *threads_ptr = nullptr;
610 } else {
611 unsigned char* data;
612 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
613 if (data_result != ERR(NONE)) {
614 return data_result;
615 }
616 jthread* threads = reinterpret_cast<jthread*>(data);
617 for (size_t i = 0; i != peers.size(); ++i) {
618 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
619 }
620
621 *threads_count_ptr = static_cast<jint>(peers.size());
622 *threads_ptr = threads;
623 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800624 return ERR(NONE);
625}
Andreas Gampe85807442017-01-13 14:40:58 -0800626
Alex Light092a4042017-07-12 08:46:44 -0700627static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
628 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
629 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
Alex Light0aa7a5a2018-10-10 15:58:14 +0000630 JvmtiGlobalTLSData* global_tls = ThreadUtil::GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700631 if (global_tls != nullptr) {
632 global_tls->data.erase(env);
633 }
634}
635
636void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
637 art::Thread* self = art::Thread::Current();
638 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
639 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
640 list->ForEach(RemoveTLSData, env);
641}
642
643jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
644 art::Thread* self = art::Thread::Current();
645 art::ScopedObjectAccess soa(self);
646 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700647 art::Thread* target = nullptr;
648 jvmtiError err = ERR(INTERNAL);
649 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
650 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800651 }
652
Alex Light0aa7a5a2018-10-10 15:58:14 +0000653 JvmtiGlobalTLSData* global_tls = GetOrCreateGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700654
655 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800656
657 return ERR(NONE);
658}
659
Alex Light0aa7a5a2018-10-10 15:58:14 +0000660JvmtiGlobalTLSData* ThreadUtil::GetOrCreateGlobalTLSData(art::Thread* thread) {
661 JvmtiGlobalTLSData* data = GetGlobalTLSData(thread);
662 if (data != nullptr) {
663 return data;
664 } else {
665 thread->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
666 return GetGlobalTLSData(thread);
667 }
668}
669
670JvmtiGlobalTLSData* ThreadUtil::GetGlobalTLSData(art::Thread* thread) {
671 return reinterpret_cast<JvmtiGlobalTLSData*>(thread->GetCustomTLS(kJvmtiTlsKey));
672}
673
Alex Light092a4042017-07-12 08:46:44 -0700674jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800675 jthread thread,
676 void** data_ptr) {
677 if (data_ptr == nullptr) {
678 return ERR(NULL_POINTER);
679 }
680
Alex Light092a4042017-07-12 08:46:44 -0700681 art::Thread* self = art::Thread::Current();
682 art::ScopedObjectAccess soa(self);
683 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700684 art::Thread* target = nullptr;
685 jvmtiError err = ERR(INTERNAL);
686 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
687 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800688 }
689
Alex Light0aa7a5a2018-10-10 15:58:14 +0000690 JvmtiGlobalTLSData* global_tls = GetGlobalTLSData(target);
Alex Light092a4042017-07-12 08:46:44 -0700691 if (global_tls == nullptr) {
692 *data_ptr = nullptr;
693 return OK;
694 }
695 auto it = global_tls->data.find(env);
696 if (it != global_tls->data.end()) {
697 *data_ptr = const_cast<void*>(it->second);
698 } else {
699 *data_ptr = nullptr;
700 }
701
Andreas Gampe85807442017-01-13 14:40:58 -0800702 return ERR(NONE);
703}
704
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800705struct AgentData {
706 const void* arg;
707 jvmtiStartFunction proc;
708 jthread thread;
709 JavaVM* java_vm;
710 jvmtiEnv* jvmti_env;
711 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800712 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800713};
714
715static void* AgentCallback(void* arg) {
716 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
717 CHECK(data->thread != nullptr);
718
719 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800720 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700721 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800722 // The name in Attach() is only for logging. Set the thread name. This is important so
723 // that the thread is no longer seen as starting up.
724 {
725 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800726 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800727 }
728
729 // Release the peer.
730 JNIEnv* env = self->GetJniEnv();
731 env->DeleteGlobalRef(data->thread);
732 data->thread = nullptr;
733
Alex Light739bf722017-10-20 13:14:24 -0700734 {
735 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
736 // before going into the provided code.
737 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
738 art::Runtime::Current()->EndThreadBirth();
739 }
740
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800741 // Run the agent code.
742 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
743
744 // Detach the thread.
745 int detach_result = data->java_vm->DetachCurrentThread();
746 CHECK_EQ(detach_result, 0);
747
748 return nullptr;
749}
750
751jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
752 jthread thread,
753 jvmtiStartFunction proc,
754 const void* arg,
755 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700756 if (!PhaseUtil::IsLivePhase()) {
757 return ERR(WRONG_PHASE);
758 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800759 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
760 return ERR(INVALID_PRIORITY);
761 }
762 JNIEnv* env = art::Thread::Current()->GetJniEnv();
763 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
764 return ERR(INVALID_THREAD);
765 }
766 if (proc == nullptr) {
767 return ERR(NULL_POINTER);
768 }
769
Alex Light739bf722017-10-20 13:14:24 -0700770 {
771 art::Runtime* runtime = art::Runtime::Current();
772 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
773 if (runtime->IsShuttingDownLocked()) {
774 // The runtime is shutting down so we cannot create new threads.
775 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
776 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
777 // impossible. Existing agents don't seem to generally do anything with this return value so
778 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
779 // even though code is never actually run.
780 return ERR(INTERNAL);
781 }
782 runtime->StartThreadBirth();
783 }
784
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800785 std::unique_ptr<AgentData> data(new AgentData);
786 data->arg = arg;
787 data->proc = proc;
788 // We need a global ref for Java objects, as local refs will be invalid.
789 data->thread = env->NewGlobalRef(thread);
790 data->java_vm = art::Runtime::Current()->GetJavaVM();
791 data->jvmti_env = jvmti_env;
792 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800793 ScopedLocalRef<jstring> s(
794 env,
795 reinterpret_cast<jstring>(
796 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
797 if (s == nullptr) {
798 data->name = "JVMTI Agent Thread";
799 } else {
800 ScopedUtfChars name(env, s.get());
801 data->name = name.c_str();
802 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800803
804 pthread_t pthread;
805 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700806 nullptr,
807 &AgentCallback,
808 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800809 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700810 // If the create succeeded the other thread will call EndThreadBirth.
811 art::Runtime* runtime = art::Runtime::Current();
812 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
813 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800814 return ERR(INTERNAL);
815 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700816 data.release(); // NOLINT pthreads API.
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800817
818 return ERR(NONE);
819}
820
Alex Light88fd7202017-06-30 08:31:59 -0700821jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700822 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700823 // Loop since we need to bail out and try again if we would end up getting suspended while holding
824 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
825 // release the lock, wait to get resumed and try again.
826 do {
827 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
828 // another SuspendThread in the middle of suspending something else potentially causing a
829 // deadlock. We need to do this in the loop because if we ended up back here then we had
830 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
831 // before continuing.
832 SuspendCheck(self);
833 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700834 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700835 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
836 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700837 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700838 }
Alex Light23aa7482017-08-16 10:01:13 -0700839 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700840 {
841 art::ScopedObjectAccess soa(self);
842 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700843 art::Thread* target = nullptr;
844 jvmtiError err = ERR(INTERNAL);
845 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
846 return err;
847 }
Alex Lightcea42152018-09-18 22:51:55 +0000848 art::ThreadState state = target->GetState();
849 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
850 return ERR(THREAD_NOT_ALIVE);
851 } else {
852 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
853 if (target->GetUserCodeSuspendCount() != 0) {
854 return ERR(THREAD_SUSPENDED);
855 }
856 }
Alex Light88fd7202017-06-30 08:31:59 -0700857 }
Alex Lightcea42152018-09-18 22:51:55 +0000858 bool timeout = true;
859 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
860 target_jthread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700861 /* request_suspension= */ true,
Alex Lightcea42152018-09-18 22:51:55 +0000862 art::SuspendReason::kForUserCode,
863 &timeout);
864 if (ret_target == nullptr && !timeout) {
Alex Light3ae82532017-07-26 13:59:07 -0700865 // TODO It would be good to get more information about why exactly the thread failed to
866 // suspend.
867 return ERR(INTERNAL);
Alex Lightcea42152018-09-18 22:51:55 +0000868 } else if (!timeout) {
869 // we didn't time out and got a result.
870 return OK;
Alex Light3ae82532017-07-26 13:59:07 -0700871 }
872 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700873 } while (true);
874 UNREACHABLE();
875}
876
877jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
878 CHECK(self == art::Thread::Current());
879 {
880 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
881 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
882 if (self->GetUserCodeSuspendCount() != 0) {
883 // This can only happen if we race with another thread to suspend 'self' and we lose.
884 return ERR(THREAD_SUSPENDED);
885 }
886 // We shouldn't be able to fail this.
887 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
888 // TODO More specific error would be nice.
889 return ERR(INTERNAL);
890 }
891 }
892 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
893 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
894 // to go to sleep until we are resumed.
895 SuspendCheck(self);
896 return OK;
897}
898
899jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
900 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700901 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700902 {
903 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700904 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700905 art::Thread* target = nullptr;
906 jvmtiError err = ERR(INTERNAL);
907 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
908 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700909 } else if (target == self) {
910 target_is_self = true;
911 }
Alex Light88fd7202017-06-30 08:31:59 -0700912 }
Alex Light3ae82532017-07-26 13:59:07 -0700913 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700914 return SuspendSelf(self);
915 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700916 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700917 }
918}
919
920jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
921 jthread thread) {
922 if (thread == nullptr) {
923 return ERR(NULL_POINTER);
924 }
925 art::Thread* self = art::Thread::Current();
Alex Lightcea42152018-09-18 22:51:55 +0000926 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700927 // Retry until we know we won't get suspended by user code while resuming something.
928 do {
929 SuspendCheck(self);
930 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700931 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700932 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
933 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700934 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700935 }
Alex Light3ae82532017-07-26 13:59:07 -0700936 // From now on we know we cannot get suspended by user-code.
Alex Lightcea42152018-09-18 22:51:55 +0000937 {
938 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
939 // have the 'suspend_lock' locked here.
940 art::ScopedObjectAccess soa(self);
941 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
942 jvmtiError err = ERR(INTERNAL);
943 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
944 return err;
945 } else if (target == self) {
946 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
947 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
948 // about current state since it's all concurrent.
949 return ERR(THREAD_NOT_SUSPENDED);
950 }
951 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
952 // cannot tell why resume failed.
953 {
954 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
955 if (target->GetUserCodeSuspendCount() == 0) {
956 return ERR(THREAD_NOT_SUSPENDED);
957 }
958 }
Alex Light3ae82532017-07-26 13:59:07 -0700959 }
Alex Lightcea42152018-09-18 22:51:55 +0000960 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
961 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
962 DCHECK(target != self);
963 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
964 art::SuspendReason::kForUserCode)) {
Alex Light3ae82532017-07-26 13:59:07 -0700965 // TODO Give a better error.
Alex Lightcea42152018-09-18 22:51:55 +0000966 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
Alex Light3ae82532017-07-26 13:59:07 -0700967 return ERR(INTERNAL);
968 } else {
969 return OK;
970 }
971 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700972}
973
Alex Light7ddc23d2017-09-22 15:33:41 -0700974static bool IsCurrentThread(jthread thr) {
975 if (thr == nullptr) {
976 return true;
977 }
978 art::Thread* self = art::Thread::Current();
979 art::ScopedObjectAccess soa(self);
980 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
981 art::Thread* target = nullptr;
982 jvmtiError err_unused = ERR(INTERNAL);
983 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
984 return target == self;
985 } else {
986 return false;
987 }
988}
989
Alex Light88fd7202017-06-30 08:31:59 -0700990// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
991// since we can have threads in the list multiple times. This generally doesn't matter unless the
992// current thread is present multiple times. In that case we need to suspend only once and either
993// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
994// it didn't. We also want to handle the current thread last to make the behavior of the code
995// simpler to understand.
996jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
997 jint request_count,
998 const jthread* threads,
999 jvmtiError* results) {
1000 if (request_count == 0) {
1001 return ERR(ILLEGAL_ARGUMENT);
1002 } else if (results == nullptr || threads == nullptr) {
1003 return ERR(NULL_POINTER);
1004 }
1005 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1006 // running thread. These indexes we need to handle specially since we need to only actually
1007 // suspend a single time.
1008 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001009 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001010 if (IsCurrentThread(threads[i])) {
1011 current_thread_indexes.push_back(i);
1012 } else {
1013 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001014 }
Alex Light88fd7202017-06-30 08:31:59 -07001015 }
1016 if (!current_thread_indexes.empty()) {
1017 jint first_current_thread_index = current_thread_indexes[0];
1018 // Suspend self.
1019 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1020 results[first_current_thread_index] = res;
1021 // Fill in the rest of the error values as appropriate.
1022 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1023 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1024 results[*it] = other_results;
1025 }
1026 }
1027 return OK;
1028}
1029
1030jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1031 jint request_count,
1032 const jthread* threads,
1033 jvmtiError* results) {
1034 if (request_count == 0) {
1035 return ERR(ILLEGAL_ARGUMENT);
1036 } else if (results == nullptr || threads == nullptr) {
1037 return ERR(NULL_POINTER);
1038 }
1039 for (jint i = 0; i < request_count; i++) {
1040 results[i] = env->ResumeThread(threads[i]);
1041 }
1042 return OK;
1043}
1044
Alex Light54d39dc2017-09-25 17:00:16 -07001045jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1046 jthread thread,
1047 jobject exception) {
1048 art::Thread* self = art::Thread::Current();
1049 art::ScopedObjectAccess soa(self);
1050 art::StackHandleScope<1> hs(self);
1051 if (exception == nullptr) {
1052 return ERR(INVALID_OBJECT);
1053 }
1054 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1055 if (!obj->GetClass()->IsThrowableClass()) {
1056 return ERR(INVALID_OBJECT);
1057 }
1058 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001059 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001060 art::Thread* target = nullptr;
1061 jvmtiError err = ERR(INTERNAL);
1062 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001063 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001064 return err;
1065 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001066 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001067 return ERR(THREAD_NOT_ALIVE);
1068 }
1069 struct StopThreadClosure : public art::Closure {
1070 public:
1071 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1072
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001073 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001074 // Make sure the thread is prepared to notice the exception.
1075 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1076 me->SetAsyncException(exception_.Get());
1077 // Wake up the thread if it is sleeping.
1078 me->Notify();
1079 }
1080
1081 private:
1082 art::Handle<art::mirror::Throwable> exception_;
1083 };
1084 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001085 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001086 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001087 return OK;
1088 } else {
1089 // Something went wrong, probably the thread died.
1090 return ERR(THREAD_NOT_ALIVE);
1091 }
1092}
1093
1094jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1095 art::Thread* self = art::Thread::Current();
1096 art::ScopedObjectAccess soa(self);
1097 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1098 art::Thread* target = nullptr;
1099 jvmtiError err = ERR(INTERNAL);
1100 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1101 return err;
1102 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1103 return ERR(THREAD_NOT_ALIVE);
1104 }
1105 target->Interrupt(self);
1106 return OK;
1107}
1108
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001109} // namespace openjdkjvmti