blob: 41ef6c281dcbb7971afd85a20be174584f1f02a9 [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" &&
94 !android::base::StartsWith(name, "Jit thread pool")) {
Alex Light23aa7482017-08-16 10:01:13 -070095 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
96 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080097 }
98 }
99 return;
100 }
Andreas Gampe983c1752017-01-23 19:46:56 -0800101 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800102 }
103
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100104 void ThreadDeath(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800105 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800106 }
107
Andreas Gampeeafaf572017-01-20 12:34:15 -0800108 EventHandler* event_handler = nullptr;
109 bool started = false;
110};
111
112ThreadCallback gThreadCallback;
113
114void ThreadUtil::Register(EventHandler* handler) {
115 art::Runtime* runtime = art::Runtime::Current();
116
117 gThreadCallback.started = runtime->IsStarted();
118 gThreadCallback.event_handler = handler;
119
120 art::ScopedThreadStateChange stsc(art::Thread::Current(),
121 art::ThreadState::kWaitingForDebuggerToAttach);
122 art::ScopedSuspendAll ssa("Add thread callback");
123 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700124}
125
126void ThreadUtil::VMInitEventSent() {
127 // We should have already started.
128 DCHECK(gThreadCallback.started);
129 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
130 // reported until Init.
131 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800132}
133
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700134void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700135 // We must have started since it is now safe to cache our data;
136 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700137 art::ScopedObjectAccess soa(art::Thread::Current());
138 art::ObjPtr<art::mirror::Class> thread_class =
139 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
140 CHECK(thread_class != nullptr);
141 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
142 "Ljava/lang/ClassLoader;");
143 CHECK(context_class_loader_ != nullptr);
144}
145
Andreas Gampeeafaf572017-01-20 12:34:15 -0800146void ThreadUtil::Unregister() {
147 art::ScopedThreadStateChange stsc(art::Thread::Current(),
148 art::ThreadState::kWaitingForDebuggerToAttach);
149 art::ScopedSuspendAll ssa("Remove thread callback");
150 art::Runtime* runtime = art::Runtime::Current();
151 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800152}
153
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800154jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
155 art::Thread* self = art::Thread::Current();
156
157 art::ScopedObjectAccess soa(self);
158
159 jthread thread_peer;
160 if (self->IsStillStarting()) {
161 thread_peer = nullptr;
162 } else {
163 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
164 }
165
166 *thread_ptr = thread_peer;
167 return ERR(NONE);
168}
169
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800170// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700171bool ThreadUtil::GetNativeThread(jthread thread,
172 const art::ScopedObjectAccessAlreadyRunnable& soa,
173 /*out*/ art::Thread** thr,
174 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800175 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700176 *thr = art::Thread::Current();
177 return true;
178 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
179 *err = ERR(INVALID_THREAD);
180 return false;
181 } else {
182 *thr = art::Thread::FromManagedThread(soa, thread);
183 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800184 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700185}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800186
Alex Light7ddc23d2017-09-22 15:33:41 -0700187bool ThreadUtil::GetAliveNativeThread(jthread thread,
188 const art::ScopedObjectAccessAlreadyRunnable& soa,
189 /*out*/ art::Thread** thr,
190 /*out*/ jvmtiError* err) {
191 if (!GetNativeThread(thread, soa, thr, err)) {
192 return false;
193 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
194 *err = ERR(THREAD_NOT_ALIVE);
195 return false;
196 } else {
197 return true;
198 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800199}
200
201jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
202 if (info_ptr == nullptr) {
203 return ERR(NULL_POINTER);
204 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700205 if (!PhaseUtil::IsLivePhase()) {
206 return JVMTI_ERROR_WRONG_PHASE;
207 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800208
Alex Light3ae82532017-07-26 13:59:07 -0700209 art::Thread* self = art::Thread::Current();
210 art::ScopedObjectAccess soa(self);
211 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800212
Alex Light7ddc23d2017-09-22 15:33:41 -0700213 art::Thread* target;
214 jvmtiError err = ERR(INTERNAL);
215 if (!GetNativeThread(thread, soa, &target, &err)) {
216 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800217 }
218
Andreas Gampe54711412017-02-21 12:41:43 -0800219 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700220 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800221 // Have a native thread object, this thread is alive.
222 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700223 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800224 jvmtiError name_result;
225 name_uptr = CopyString(env, name.c_str(), &name_result);
226 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800227 return name_result;
228 }
Andreas Gampe54711412017-02-21 12:41:43 -0800229 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800230
Alex Light3ae82532017-07-26 13:59:07 -0700231 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800232
Alex Light3ae82532017-07-26 13:59:07 -0700233 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800234
Alex Light3ae82532017-07-26 13:59:07 -0700235 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800236
237 // ThreadGroup.
238 if (peer != nullptr) {
239 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
240 CHECK(f != nullptr);
241 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
242 info_ptr->thread_group = group == nullptr
243 ? nullptr
244 : soa.AddLocalReference<jthreadGroup>(group);
245 } else {
246 info_ptr->thread_group = nullptr;
247 }
248
249 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700250 DCHECK(context_class_loader_ != nullptr);
251 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
252 ? context_class_loader_->GetObject(peer)
253 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800254 info_ptr->context_class_loader = ccl == nullptr
255 ? nullptr
256 : soa.AddLocalReference<jobject>(ccl);
257 } else {
258 // Only the peer. This thread has either not been started, or is dead. Read things from
259 // the Java side.
260 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
261
262 // Name.
263 {
264 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
265 CHECK(f != nullptr);
266 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
267 std::string name_cpp;
268 const char* name_cstr;
269 if (name != nullptr) {
270 name_cpp = name->AsString()->ToModifiedUtf8();
271 name_cstr = name_cpp.c_str();
272 } else {
273 name_cstr = "";
274 }
Andreas Gampe54711412017-02-21 12:41:43 -0800275 jvmtiError name_result;
276 name_uptr = CopyString(env, name_cstr, &name_result);
277 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800278 return name_result;
279 }
Andreas Gampe54711412017-02-21 12:41:43 -0800280 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800281 }
282
283 // Priority.
284 {
285 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
286 CHECK(f != nullptr);
287 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
288 }
289
290 // Daemon.
291 {
292 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
293 CHECK(f != nullptr);
294 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
295 }
296
297 // ThreadGroup.
298 {
299 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
300 CHECK(f != nullptr);
301 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
302 info_ptr->thread_group = group == nullptr
303 ? nullptr
304 : soa.AddLocalReference<jthreadGroup>(group);
305 }
306
307 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700308 DCHECK(context_class_loader_ != nullptr);
309 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
310 ? context_class_loader_->GetObject(peer)
311 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800312 info_ptr->context_class_loader = ccl == nullptr
313 ? nullptr
314 : soa.AddLocalReference<jobject>(ccl);
315 }
316
317 name_uptr.release();
318
319 return ERR(NONE);
320}
321
Alex Light1f0a22f2017-07-17 12:55:59 -0700322struct InternalThreadState {
323 art::Thread* native_thread;
324 art::ThreadState art_state;
325 int thread_user_code_suspend_count;
326};
327
328// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700329static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700330 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700331 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700332 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700333 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
334 thread_state.native_thread = target;
335 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700336 thread_state.art_state = art::ThreadState::kStarting;
337 thread_state.thread_user_code_suspend_count = 0;
338 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700339 thread_state.art_state = target->GetState();
340 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800341 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700342 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800343}
344
Alex Light1f0a22f2017-07-17 12:55:59 -0700345static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
346 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800347 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
348
Alex Light1f0a22f2017-07-17 12:55:59 -0700349 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700350 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
351 // 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 -0800352 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
353 // Note: We do not have data about the previous state. Otherwise we should load the previous
354 // state here.
355 }
356
Alex Light1f0a22f2017-07-17 12:55:59 -0700357 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700358 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700359 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
360 }
361
Alex Light597adad2017-10-16 16:11:42 -0700362 // Enumerate all the thread states and fill in the other bits. This contains the results of
363 // following the decision tree in the JVMTI spec GetThreadState documentation.
364 switch (internal_thread_state) {
365 case art::ThreadState::kRunnable:
366 case art::ThreadState::kWaitingWeakGcRootRead:
367 case art::ThreadState::kSuspended:
368 // These are all simply runnable.
369 // kRunnable is self-explanatory.
370 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
371 // so we want to keep it marked as runnable.
372 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
373 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
374 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
375 break;
376 case art::ThreadState::kNative:
377 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
378 // state but we don't have the information to know if it should be present for any but the
379 // kNative state.
380 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
381 JVMTI_THREAD_STATE_RUNNABLE);
382 break;
383 case art::ThreadState::kBlocked:
384 // Blocked is one of the top level states so it sits alone.
385 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
386 break;
387 case art::ThreadState::kWaiting:
388 // Object.wait() so waiting, indefinitely, in object.wait.
389 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
390 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
391 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
392 break;
393 case art::ThreadState::kTimedWaiting:
394 // Object.wait(long) so waiting, with timeout, in object.wait.
395 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
396 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
397 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
398 break;
399 case art::ThreadState::kSleeping:
400 // In object.sleep. This is a timed wait caused by sleep.
401 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
402 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
403 JVMTI_THREAD_STATE_SLEEPING);
404 break;
405 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
406 // attached.
407 case art::ThreadState::kWaitingForDebuggerSend:
408 case art::ThreadState::kWaitingForDebuggerToAttach:
409 case art::ThreadState::kWaitingInMainDebuggerLoop:
410 case art::ThreadState::kWaitingForDebuggerSuspension:
411 case art::ThreadState::kWaitingForLockInflation:
412 case art::ThreadState::kWaitingForTaskProcessor:
413 case art::ThreadState::kWaitingForGcToComplete:
414 case art::ThreadState::kWaitingForCheckPointsToRun:
415 case art::ThreadState::kWaitingPerformingGc:
416 case art::ThreadState::kWaitingForJniOnLoad:
417 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
418 case art::ThreadState::kWaitingForSignalCatcherOutput:
419 case art::ThreadState::kWaitingForDeoptimization:
420 case art::ThreadState::kWaitingForMethodTracingStart:
421 case art::ThreadState::kWaitingForVisitObjects:
422 case art::ThreadState::kWaitingForGetObjectsAllocated:
423 case art::ThreadState::kWaitingForGcThreadFlip:
424 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
425 // caused by sleep, park, or object#wait.
426 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
427 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
428 break;
429 case art::ThreadState::kStarting:
430 case art::ThreadState::kTerminated:
431 // We only call this if we are alive so we shouldn't see either of these states.
432 LOG(FATAL) << "Should not be in state " << internal_thread_state;
433 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800434 }
Alex Light597adad2017-10-16 16:11:42 -0700435 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800436
437 return jvmti_state;
438}
439
Alex Light1f0a22f2017-07-17 12:55:59 -0700440static jint GetJavaStateFromInternal(const InternalThreadState& state) {
441 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800442 case art::ThreadState::kTerminated:
443 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
444
445 case art::ThreadState::kRunnable:
446 case art::ThreadState::kNative:
447 case art::ThreadState::kWaitingWeakGcRootRead:
448 case art::ThreadState::kSuspended:
449 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
450
451 case art::ThreadState::kTimedWaiting:
452 case art::ThreadState::kSleeping:
453 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
454
455 case art::ThreadState::kBlocked:
456 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
457
458 case art::ThreadState::kStarting:
459 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
460
461 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700462 case art::ThreadState::kWaitingForTaskProcessor:
463 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800464 case art::ThreadState::kWaitingForGcToComplete:
465 case art::ThreadState::kWaitingPerformingGc:
466 case art::ThreadState::kWaitingForCheckPointsToRun:
467 case art::ThreadState::kWaitingForDebuggerSend:
468 case art::ThreadState::kWaitingForDebuggerToAttach:
469 case art::ThreadState::kWaitingInMainDebuggerLoop:
470 case art::ThreadState::kWaitingForDebuggerSuspension:
471 case art::ThreadState::kWaitingForDeoptimization:
472 case art::ThreadState::kWaitingForGetObjectsAllocated:
473 case art::ThreadState::kWaitingForJniOnLoad:
474 case art::ThreadState::kWaitingForSignalCatcherOutput:
475 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
476 case art::ThreadState::kWaitingForMethodTracingStart:
477 case art::ThreadState::kWaitingForVisitObjects:
478 case art::ThreadState::kWaitingForGcThreadFlip:
479 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
480 }
481 LOG(FATAL) << "Unreachable";
482 UNREACHABLE();
483}
484
Alex Light1f0a22f2017-07-17 12:55:59 -0700485// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700486void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700487 art::ScopedObjectAccess soa(self);
488 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
489 self->FullSuspendCheck();
490}
491
Alex Light23aa7482017-08-16 10:01:13 -0700492bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
493 DCHECK(self == art::Thread::Current());
494 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
495 return self->GetUserCodeSuspendCount() != 0;
496}
497
498bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
499 DCHECK(self == art::Thread::Current());
500 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
501 return WouldSuspendForUserCodeLocked(self);
502}
503
Andreas Gampe72c19832017-01-12 13:22:16 -0800504jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
505 jthread thread,
506 jint* thread_state_ptr) {
507 if (thread_state_ptr == nullptr) {
508 return ERR(NULL_POINTER);
509 }
510
Alex Light1f0a22f2017-07-17 12:55:59 -0700511 art::Thread* self = art::Thread::Current();
512 InternalThreadState state = {};
513 // Loop since we need to bail out and try again if we would end up getting suspended while holding
514 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
515 // release the lock, wait to get resumed and try again.
516 do {
517 SuspendCheck(self);
518 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700519 if (WouldSuspendForUserCodeLocked(self)) {
520 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
521 // a user-code suspension. We retry and do another SuspendCheck to clear this.
522 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700523 }
524 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700525 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700526 jvmtiError err = ERR(INTERNAL);
527 art::Thread* target = nullptr;
528 if (!GetNativeThread(thread, soa, &target, &err)) {
529 return err;
530 }
531 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700532 if (state.art_state == art::ThreadState::kStarting) {
533 break;
534 }
535 DCHECK(state.native_thread != nullptr);
536
537 // Translate internal thread state to JVMTI and Java state.
538 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
539
540 // Java state is derived from nativeGetState.
541 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
542 // different mask if a thread got suspended due to user-code. However, this is for
543 // consistency with the Java view.
544 jint java_state = GetJavaStateFromInternal(state);
545
546 *thread_state_ptr = jvmti_state | java_state;
547
548 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700549 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800550
Alex Light3ae82532017-07-26 13:59:07 -0700551 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800552
Alex Light3ae82532017-07-26 13:59:07 -0700553 if (thread == nullptr) {
554 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
555 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800556 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800557
Alex Light3ae82532017-07-26 13:59:07 -0700558 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700559 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800560
Alex Light3ae82532017-07-26 13:59:07 -0700561 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700562 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
563 art::ObjPtr<art::mirror::Class> thread_klass =
564 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
565 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
566 return ERR(INVALID_THREAD);
567 }
568 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700569 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700570 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700571 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
572 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
573 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
574 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800575 return ERR(NONE);
576}
577
Andreas Gampe85807442017-01-13 14:40:58 -0800578jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
579 jint* threads_count_ptr,
580 jthread** threads_ptr) {
581 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
582 return ERR(NULL_POINTER);
583 }
584
585 art::Thread* current = art::Thread::Current();
586
587 art::ScopedObjectAccess soa(current);
588
589 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
590 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
591
592 std::vector<art::ObjPtr<art::mirror::Object>> peers;
593
594 for (art::Thread* thread : thread_list) {
595 // Skip threads that are still starting.
596 if (thread->IsStillStarting()) {
597 continue;
598 }
599
Andreas Gampe202f85a2017-02-06 10:23:26 -0800600 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800601 if (peer != nullptr) {
602 peers.push_back(peer);
603 }
604 }
605
606 if (peers.empty()) {
607 *threads_count_ptr = 0;
608 *threads_ptr = nullptr;
609 } else {
610 unsigned char* data;
611 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
612 if (data_result != ERR(NONE)) {
613 return data_result;
614 }
615 jthread* threads = reinterpret_cast<jthread*>(data);
616 for (size_t i = 0; i != peers.size(); ++i) {
617 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
618 }
619
620 *threads_count_ptr = static_cast<jint>(peers.size());
621 *threads_ptr = threads;
622 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800623 return ERR(NONE);
624}
Andreas Gampe85807442017-01-13 14:40:58 -0800625
Alex Light092a4042017-07-12 08:46:44 -0700626// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
627// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
628// data but we only have a single slot in Thread objects to store data.
Alex Light184f0752018-07-13 11:18:22 -0700629struct JvmtiGlobalTLSData : public art::TLSData {
Alex Light092a4042017-07-12 08:46:44 -0700630 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
631};
632
633static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
634 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
635 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
Alex Light184f0752018-07-13 11:18:22 -0700636 JvmtiGlobalTLSData* global_tls =
637 reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS(kJvmtiTlsKey));
Alex Light092a4042017-07-12 08:46:44 -0700638 if (global_tls != nullptr) {
639 global_tls->data.erase(env);
640 }
641}
642
643void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
644 art::Thread* self = art::Thread::Current();
645 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
646 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
647 list->ForEach(RemoveTLSData, env);
648}
649
650jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
651 art::Thread* self = art::Thread::Current();
652 art::ScopedObjectAccess soa(self);
653 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700654 art::Thread* target = nullptr;
655 jvmtiError err = ERR(INTERNAL);
656 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
657 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800658 }
659
Alex Light184f0752018-07-13 11:18:22 -0700660 JvmtiGlobalTLSData* global_tls =
661 reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS(kJvmtiTlsKey));
Alex Light092a4042017-07-12 08:46:44 -0700662 if (global_tls == nullptr) {
Alex Light184f0752018-07-13 11:18:22 -0700663 // Synchronized using thread_list_lock_ to prevent racing sets.
664 target->SetCustomTLS(kJvmtiTlsKey, new JvmtiGlobalTLSData);
665 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS(kJvmtiTlsKey));
Alex Light092a4042017-07-12 08:46:44 -0700666 }
667
668 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800669
670 return ERR(NONE);
671}
672
Alex Light092a4042017-07-12 08:46:44 -0700673jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800674 jthread thread,
675 void** data_ptr) {
676 if (data_ptr == nullptr) {
677 return ERR(NULL_POINTER);
678 }
679
Alex Light092a4042017-07-12 08:46:44 -0700680 art::Thread* self = art::Thread::Current();
681 art::ScopedObjectAccess soa(self);
682 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700683 art::Thread* target = nullptr;
684 jvmtiError err = ERR(INTERNAL);
685 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
686 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800687 }
688
Alex Light184f0752018-07-13 11:18:22 -0700689 JvmtiGlobalTLSData* global_tls =
690 reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS(kJvmtiTlsKey));
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 }
816 data.release();
817
818 return ERR(NONE);
819}
820
Alex Light53570672018-07-12 11:09:59 -0700821class ScopedSuspendByPeer {
822 public:
823 explicit ScopedSuspendByPeer(jthread jtarget)
824 : thread_list_(art::Runtime::Current()->GetThreadList()),
825 timeout_(false),
826 target_(thread_list_->SuspendThreadByPeer(jtarget,
827 /* suspend_thread */ true,
828 art::SuspendReason::kInternal,
829 &timeout_)) { }
830 ~ScopedSuspendByPeer() {
831 if (target_ != nullptr) {
832 if (!thread_list_->Resume(target_, art::SuspendReason::kInternal)) {
833 LOG(ERROR) << "Failed to resume " << target_ << "!";
834 }
835 }
836 }
837
838 art::Thread* GetTargetThread() const {
839 return target_;
840 }
841
842 bool TimedOut() const {
843 return timeout_;
844 }
845
846 private:
847 art::ThreadList* thread_list_;
848 bool timeout_;
849 art::Thread* target_;
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 Light88fd7202017-06-30 08:31:59 -0700879 }
Alex Light53570672018-07-12 11:09:59 -0700880 // Get the actual thread in a suspended state so we can change the user-code suspend count.
881 ScopedSuspendByPeer ssbp(target_jthread);
882 if (ssbp.GetTargetThread() == nullptr && !ssbp.TimedOut()) {
Alex Light3ae82532017-07-26 13:59:07 -0700883 // TODO It would be good to get more information about why exactly the thread failed to
884 // suspend.
885 return ERR(INTERNAL);
Alex Light53570672018-07-12 11:09:59 -0700886 } else if (!ssbp.TimedOut()) {
887 art::ThreadState state = ssbp.GetTargetThread()->GetState();
888 if (state == art::ThreadState::kStarting || ssbp.GetTargetThread()->IsStillStarting()) {
889 return ERR(THREAD_NOT_ALIVE);
890 }
891 // we didn't time out and got a result. Suspend the thread by usercode and return. It's
892 // already suspended internal so we don't need to do anything but increment the count.
893 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
894 if (ssbp.GetTargetThread()->GetUserCodeSuspendCount() != 0) {
895 return ERR(THREAD_SUSPENDED);
896 }
897 bool res = ssbp.GetTargetThread()->ModifySuspendCount(
898 self, +1, nullptr, art::SuspendReason::kForUserCode);
899 return res ? OK : ERR(INTERNAL);
Alex Light3ae82532017-07-26 13:59:07 -0700900 }
901 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700902 } while (true);
903 UNREACHABLE();
904}
905
906jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
907 CHECK(self == art::Thread::Current());
Alex Light53570672018-07-12 11:09:59 -0700908 if (!self->CanBeSuspendedByUserCode()) {
909 // TODO This is really undesirable. As far as I can tell this is can only come about because of
910 // class-loads in the jit-threads (through either VMObjectAlloc or the ClassLoad/ClassPrepare
911 // events that we send). It's unlikely that anyone would be suspending themselves there since
912 // it's almost guaranteed to cause a deadlock but it is technically allowed. Ideally we'd want
913 // to put a CHECK here (or in the event-dispatch code) that we are only in this situation when
914 // sending the GC callbacks but the jit causing events means we cannot do this.
915 LOG(WARNING) << "Attempt to self-suspend on a thread without suspension enabled. Thread is "
916 << *self;
917 return ERR(INTERNAL);
918 }
Alex Light88fd7202017-06-30 08:31:59 -0700919 {
920 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
921 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
922 if (self->GetUserCodeSuspendCount() != 0) {
923 // This can only happen if we race with another thread to suspend 'self' and we lose.
924 return ERR(THREAD_SUSPENDED);
925 }
926 // We shouldn't be able to fail this.
927 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
928 // TODO More specific error would be nice.
929 return ERR(INTERNAL);
930 }
931 }
932 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
933 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
934 // to go to sleep until we are resumed.
935 SuspendCheck(self);
936 return OK;
937}
938
939jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
940 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700941 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700942 {
943 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700944 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700945 art::Thread* target = nullptr;
946 jvmtiError err = ERR(INTERNAL);
947 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
948 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700949 } else if (target == self) {
950 target_is_self = true;
951 }
Alex Light88fd7202017-06-30 08:31:59 -0700952 }
Alex Light3ae82532017-07-26 13:59:07 -0700953 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700954 return SuspendSelf(self);
955 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700956 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700957 }
958}
959
960jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
961 jthread thread) {
962 if (thread == nullptr) {
963 return ERR(NULL_POINTER);
964 }
965 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700966 // Retry until we know we won't get suspended by user code while resuming something.
967 do {
968 SuspendCheck(self);
969 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700970 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700971 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
972 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700973 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700974 }
Alex Light3ae82532017-07-26 13:59:07 -0700975 // From now on we know we cannot get suspended by user-code.
Alex Light53570672018-07-12 11:09:59 -0700976 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
977 // have the 'suspend_lock' locked here.
978 art::ScopedObjectAccess soa(self);
979 if (thread == nullptr) {
980 // The thread is the current thread.
981 return ERR(THREAD_NOT_SUSPENDED);
982 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
983 // Not a thread object.
984 return ERR(INVALID_THREAD);
985 } else if (self->GetPeer() == soa.Decode<art::mirror::Object>(thread)) {
986 // The thread is the current thread.
987 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700988 }
Alex Light53570672018-07-12 11:09:59 -0700989 ScopedSuspendByPeer ssbp(thread);
990 if (ssbp.TimedOut()) {
991 // Unknown error. Couldn't suspend thread!
992 return ERR(INTERNAL);
993 } else if (ssbp.GetTargetThread() == nullptr) {
994 // Thread must not be alive.
995 return ERR(THREAD_NOT_ALIVE);
996 }
997 // We didn't time out and got a result. Check the thread is suspended by usercode, unsuspend it
998 // and return. It's already suspended internal so we don't need to do anything but decrement the
999 // count.
1000 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
1001 if (ssbp.GetTargetThread()->GetUserCodeSuspendCount() == 0) {
1002 return ERR(THREAD_NOT_SUSPENDED);
1003 } else if (!ssbp.GetTargetThread()->ModifySuspendCount(
1004 self, -1, nullptr, art::SuspendReason::kForUserCode)) {
Alex Light3ae82532017-07-26 13:59:07 -07001005 // TODO Give a better error.
Alex Light53570672018-07-12 11:09:59 -07001006 // This should not really be possible and is probably some race.
Alex Light3ae82532017-07-26 13:59:07 -07001007 return ERR(INTERNAL);
1008 } else {
1009 return OK;
1010 }
1011 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -07001012}
1013
Alex Light7ddc23d2017-09-22 15:33:41 -07001014static bool IsCurrentThread(jthread thr) {
1015 if (thr == nullptr) {
1016 return true;
1017 }
1018 art::Thread* self = art::Thread::Current();
1019 art::ScopedObjectAccess soa(self);
1020 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1021 art::Thread* target = nullptr;
1022 jvmtiError err_unused = ERR(INTERNAL);
1023 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
1024 return target == self;
1025 } else {
1026 return false;
1027 }
1028}
1029
Alex Light88fd7202017-06-30 08:31:59 -07001030// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
1031// since we can have threads in the list multiple times. This generally doesn't matter unless the
1032// current thread is present multiple times. In that case we need to suspend only once and either
1033// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
1034// it didn't. We also want to handle the current thread last to make the behavior of the code
1035// simpler to understand.
1036jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
1037 jint request_count,
1038 const jthread* threads,
1039 jvmtiError* results) {
1040 if (request_count == 0) {
1041 return ERR(ILLEGAL_ARGUMENT);
1042 } else if (results == nullptr || threads == nullptr) {
1043 return ERR(NULL_POINTER);
1044 }
1045 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
1046 // running thread. These indexes we need to handle specially since we need to only actually
1047 // suspend a single time.
1048 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001049 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001050 if (IsCurrentThread(threads[i])) {
1051 current_thread_indexes.push_back(i);
1052 } else {
1053 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001054 }
Alex Light88fd7202017-06-30 08:31:59 -07001055 }
1056 if (!current_thread_indexes.empty()) {
1057 jint first_current_thread_index = current_thread_indexes[0];
1058 // Suspend self.
1059 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1060 results[first_current_thread_index] = res;
1061 // Fill in the rest of the error values as appropriate.
1062 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1063 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1064 results[*it] = other_results;
1065 }
1066 }
1067 return OK;
1068}
1069
1070jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1071 jint request_count,
1072 const jthread* threads,
1073 jvmtiError* results) {
1074 if (request_count == 0) {
1075 return ERR(ILLEGAL_ARGUMENT);
1076 } else if (results == nullptr || threads == nullptr) {
1077 return ERR(NULL_POINTER);
1078 }
1079 for (jint i = 0; i < request_count; i++) {
1080 results[i] = env->ResumeThread(threads[i]);
1081 }
1082 return OK;
1083}
1084
Alex Light54d39dc2017-09-25 17:00:16 -07001085jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1086 jthread thread,
1087 jobject exception) {
1088 art::Thread* self = art::Thread::Current();
1089 art::ScopedObjectAccess soa(self);
1090 art::StackHandleScope<1> hs(self);
1091 if (exception == nullptr) {
1092 return ERR(INVALID_OBJECT);
1093 }
1094 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1095 if (!obj->GetClass()->IsThrowableClass()) {
1096 return ERR(INVALID_OBJECT);
1097 }
1098 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001099 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001100 art::Thread* target = nullptr;
1101 jvmtiError err = ERR(INTERNAL);
1102 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001103 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001104 return err;
1105 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001106 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001107 return ERR(THREAD_NOT_ALIVE);
1108 }
1109 struct StopThreadClosure : public art::Closure {
1110 public:
1111 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1112
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001113 void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light54d39dc2017-09-25 17:00:16 -07001114 // Make sure the thread is prepared to notice the exception.
1115 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1116 me->SetAsyncException(exception_.Get());
1117 // Wake up the thread if it is sleeping.
1118 me->Notify();
1119 }
1120
1121 private:
1122 art::Handle<art::mirror::Throwable> exception_;
1123 };
1124 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001125 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001126 if (target->RequestSynchronousCheckpoint(&c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001127 return OK;
1128 } else {
1129 // Something went wrong, probably the thread died.
1130 return ERR(THREAD_NOT_ALIVE);
1131 }
1132}
1133
1134jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1135 art::Thread* self = art::Thread::Current();
1136 art::ScopedObjectAccess soa(self);
1137 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1138 art::Thread* target = nullptr;
1139 jvmtiError err = ERR(INTERNAL);
1140 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1141 return err;
1142 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1143 return ERR(THREAD_NOT_ALIVE);
1144 }
1145 target->Interrupt(self);
1146 return OK;
1147}
1148
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001149} // namespace openjdkjvmti