blob: b7b81ce358fb7580ce8ca6ccdad8e0fd0f1a99f2 [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 Gampeeafaf572017-01-20 12:34:15 -080034#include "android-base/strings.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070035#include "art_field-inl.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080036#include "art_jvmti.h"
37#include "base/logging.h"
38#include "base/mutex.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080039#include "events-inl.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080040#include "gc/system_weak.h"
Alex Lightd9aff132017-10-31 22:30:05 +000041#include "gc/collector_type.h"
42#include "gc/gc_cause.h"
43#include "gc/scoped_gc_critical_section.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080044#include "gc_root-inl.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080045#include "jni_internal.h"
46#include "mirror/class.h"
47#include "mirror/object-inl.h"
48#include "mirror/string.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070049#include "nativehelper/scoped_local_ref.h"
Alex Light93112972017-11-13 10:38:59 -080050#include "nativehelper/scoped_utf_chars.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080051#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080052#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080053#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080054#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070055#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080056#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070057#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080058#include "well_known_classes.h"
59
60namespace openjdkjvmti {
61
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070062art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
63
Alex Light1d8a9742017-08-17 11:12:06 -070064struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080065 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
66 if (self->GetPeer() == nullptr) {
67 return nullptr;
68 }
69 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
70 }
Alex Light1d8a9742017-08-17 11:12:06 -070071
Andreas Gampe983c1752017-01-23 19:46:56 -080072 template <ArtJvmtiEvent kEvent>
73 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080074 DCHECK_EQ(self, art::Thread::Current());
75 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080076 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080077 event_handler->DispatchEvent<kEvent>(self,
78 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
79 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080080 }
81
82 void ThreadStart(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
83 if (!started) {
84 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
85 // started here.
86 if (art::kIsDebugBuild) {
87 std::string name;
88 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080089 if (name != "JDWP" &&
90 name != "Signal Catcher" &&
91 !android::base::StartsWith(name, "Jit thread pool")) {
Alex Light23aa7482017-08-16 10:01:13 -070092 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
93 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080094 }
95 }
96 return;
97 }
Andreas Gampe983c1752017-01-23 19:46:56 -080098 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080099 }
100
101 void ThreadDeath(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800102 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800103 }
104
Andreas Gampeeafaf572017-01-20 12:34:15 -0800105 EventHandler* event_handler = nullptr;
106 bool started = false;
107};
108
109ThreadCallback gThreadCallback;
110
111void ThreadUtil::Register(EventHandler* handler) {
112 art::Runtime* runtime = art::Runtime::Current();
113
114 gThreadCallback.started = runtime->IsStarted();
115 gThreadCallback.event_handler = handler;
116
117 art::ScopedThreadStateChange stsc(art::Thread::Current(),
118 art::ThreadState::kWaitingForDebuggerToAttach);
119 art::ScopedSuspendAll ssa("Add thread callback");
120 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700121}
122
123void ThreadUtil::VMInitEventSent() {
124 // We should have already started.
125 DCHECK(gThreadCallback.started);
126 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
127 // reported until Init.
128 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800129}
130
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700131void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700132 // We must have started since it is now safe to cache our data;
133 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700134 art::ScopedObjectAccess soa(art::Thread::Current());
135 art::ObjPtr<art::mirror::Class> thread_class =
136 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
137 CHECK(thread_class != nullptr);
138 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
139 "Ljava/lang/ClassLoader;");
140 CHECK(context_class_loader_ != nullptr);
141}
142
Andreas Gampeeafaf572017-01-20 12:34:15 -0800143void ThreadUtil::Unregister() {
144 art::ScopedThreadStateChange stsc(art::Thread::Current(),
145 art::ThreadState::kWaitingForDebuggerToAttach);
146 art::ScopedSuspendAll ssa("Remove thread callback");
147 art::Runtime* runtime = art::Runtime::Current();
148 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800149}
150
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800151jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
152 art::Thread* self = art::Thread::Current();
153
154 art::ScopedObjectAccess soa(self);
155
156 jthread thread_peer;
157 if (self->IsStillStarting()) {
158 thread_peer = nullptr;
159 } else {
160 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
161 }
162
163 *thread_ptr = thread_peer;
164 return ERR(NONE);
165}
166
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800167// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700168bool ThreadUtil::GetNativeThread(jthread thread,
169 const art::ScopedObjectAccessAlreadyRunnable& soa,
170 /*out*/ art::Thread** thr,
171 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800172 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700173 *thr = art::Thread::Current();
174 return true;
175 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
176 *err = ERR(INVALID_THREAD);
177 return false;
178 } else {
179 *thr = art::Thread::FromManagedThread(soa, thread);
180 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800181 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700182}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800183
Alex Light7ddc23d2017-09-22 15:33:41 -0700184bool ThreadUtil::GetAliveNativeThread(jthread thread,
185 const art::ScopedObjectAccessAlreadyRunnable& soa,
186 /*out*/ art::Thread** thr,
187 /*out*/ jvmtiError* err) {
188 if (!GetNativeThread(thread, soa, thr, err)) {
189 return false;
190 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
191 *err = ERR(THREAD_NOT_ALIVE);
192 return false;
193 } else {
194 return true;
195 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800196}
197
198jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
199 if (info_ptr == nullptr) {
200 return ERR(NULL_POINTER);
201 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700202 if (!PhaseUtil::IsLivePhase()) {
203 return JVMTI_ERROR_WRONG_PHASE;
204 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800205
Alex Light3ae82532017-07-26 13:59:07 -0700206 art::Thread* self = art::Thread::Current();
207 art::ScopedObjectAccess soa(self);
208 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800209
Alex Light7ddc23d2017-09-22 15:33:41 -0700210 art::Thread* target;
211 jvmtiError err = ERR(INTERNAL);
212 if (!GetNativeThread(thread, soa, &target, &err)) {
213 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800214 }
215
Andreas Gampe54711412017-02-21 12:41:43 -0800216 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700217 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800218 // Have a native thread object, this thread is alive.
219 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700220 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800221 jvmtiError name_result;
222 name_uptr = CopyString(env, name.c_str(), &name_result);
223 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800224 return name_result;
225 }
Andreas Gampe54711412017-02-21 12:41:43 -0800226 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800227
Alex Light3ae82532017-07-26 13:59:07 -0700228 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800229
Alex Light3ae82532017-07-26 13:59:07 -0700230 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800231
Alex Light3ae82532017-07-26 13:59:07 -0700232 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800233
234 // ThreadGroup.
235 if (peer != nullptr) {
236 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
237 CHECK(f != nullptr);
238 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
239 info_ptr->thread_group = group == nullptr
240 ? nullptr
241 : soa.AddLocalReference<jthreadGroup>(group);
242 } else {
243 info_ptr->thread_group = nullptr;
244 }
245
246 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700247 DCHECK(context_class_loader_ != nullptr);
248 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
249 ? context_class_loader_->GetObject(peer)
250 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800251 info_ptr->context_class_loader = ccl == nullptr
252 ? nullptr
253 : soa.AddLocalReference<jobject>(ccl);
254 } else {
255 // Only the peer. This thread has either not been started, or is dead. Read things from
256 // the Java side.
257 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
258
259 // Name.
260 {
261 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
262 CHECK(f != nullptr);
263 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
264 std::string name_cpp;
265 const char* name_cstr;
266 if (name != nullptr) {
267 name_cpp = name->AsString()->ToModifiedUtf8();
268 name_cstr = name_cpp.c_str();
269 } else {
270 name_cstr = "";
271 }
Andreas Gampe54711412017-02-21 12:41:43 -0800272 jvmtiError name_result;
273 name_uptr = CopyString(env, name_cstr, &name_result);
274 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800275 return name_result;
276 }
Andreas Gampe54711412017-02-21 12:41:43 -0800277 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800278 }
279
280 // Priority.
281 {
282 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
283 CHECK(f != nullptr);
284 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
285 }
286
287 // Daemon.
288 {
289 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
290 CHECK(f != nullptr);
291 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
292 }
293
294 // ThreadGroup.
295 {
296 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
297 CHECK(f != nullptr);
298 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
299 info_ptr->thread_group = group == nullptr
300 ? nullptr
301 : soa.AddLocalReference<jthreadGroup>(group);
302 }
303
304 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700305 DCHECK(context_class_loader_ != nullptr);
306 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
307 ? context_class_loader_->GetObject(peer)
308 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800309 info_ptr->context_class_loader = ccl == nullptr
310 ? nullptr
311 : soa.AddLocalReference<jobject>(ccl);
312 }
313
314 name_uptr.release();
315
316 return ERR(NONE);
317}
318
Alex Light1f0a22f2017-07-17 12:55:59 -0700319struct InternalThreadState {
320 art::Thread* native_thread;
321 art::ThreadState art_state;
322 int thread_user_code_suspend_count;
323};
324
325// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700326static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700327 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700328 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700329 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700330 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
331 thread_state.native_thread = target;
332 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700333 thread_state.art_state = art::ThreadState::kStarting;
334 thread_state.thread_user_code_suspend_count = 0;
335 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700336 thread_state.art_state = target->GetState();
337 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800338 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700339 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800340}
341
Alex Light1f0a22f2017-07-17 12:55:59 -0700342static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
343 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800344 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
345
Alex Light1f0a22f2017-07-17 12:55:59 -0700346 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700347 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
348 // 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 -0800349 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
350 // Note: We do not have data about the previous state. Otherwise we should load the previous
351 // state here.
352 }
353
Alex Light1f0a22f2017-07-17 12:55:59 -0700354 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700355 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700356 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
357 }
358
Alex Light597adad2017-10-16 16:11:42 -0700359 // Enumerate all the thread states and fill in the other bits. This contains the results of
360 // following the decision tree in the JVMTI spec GetThreadState documentation.
361 switch (internal_thread_state) {
362 case art::ThreadState::kRunnable:
363 case art::ThreadState::kWaitingWeakGcRootRead:
364 case art::ThreadState::kSuspended:
365 // These are all simply runnable.
366 // kRunnable is self-explanatory.
367 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
368 // so we want to keep it marked as runnable.
369 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
370 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
371 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
372 break;
373 case art::ThreadState::kNative:
374 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
375 // state but we don't have the information to know if it should be present for any but the
376 // kNative state.
377 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
378 JVMTI_THREAD_STATE_RUNNABLE);
379 break;
380 case art::ThreadState::kBlocked:
381 // Blocked is one of the top level states so it sits alone.
382 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
383 break;
384 case art::ThreadState::kWaiting:
385 // Object.wait() so waiting, indefinitely, in object.wait.
386 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
387 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
388 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
389 break;
390 case art::ThreadState::kTimedWaiting:
391 // Object.wait(long) so waiting, with timeout, in object.wait.
392 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
393 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
394 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
395 break;
396 case art::ThreadState::kSleeping:
397 // In object.sleep. This is a timed wait caused by sleep.
398 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
399 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
400 JVMTI_THREAD_STATE_SLEEPING);
401 break;
402 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
403 // attached.
404 case art::ThreadState::kWaitingForDebuggerSend:
405 case art::ThreadState::kWaitingForDebuggerToAttach:
406 case art::ThreadState::kWaitingInMainDebuggerLoop:
407 case art::ThreadState::kWaitingForDebuggerSuspension:
408 case art::ThreadState::kWaitingForLockInflation:
409 case art::ThreadState::kWaitingForTaskProcessor:
410 case art::ThreadState::kWaitingForGcToComplete:
411 case art::ThreadState::kWaitingForCheckPointsToRun:
412 case art::ThreadState::kWaitingPerformingGc:
413 case art::ThreadState::kWaitingForJniOnLoad:
414 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
415 case art::ThreadState::kWaitingForSignalCatcherOutput:
416 case art::ThreadState::kWaitingForDeoptimization:
417 case art::ThreadState::kWaitingForMethodTracingStart:
418 case art::ThreadState::kWaitingForVisitObjects:
419 case art::ThreadState::kWaitingForGetObjectsAllocated:
420 case art::ThreadState::kWaitingForGcThreadFlip:
421 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
422 // caused by sleep, park, or object#wait.
423 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
424 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
425 break;
426 case art::ThreadState::kStarting:
427 case art::ThreadState::kTerminated:
428 // We only call this if we are alive so we shouldn't see either of these states.
429 LOG(FATAL) << "Should not be in state " << internal_thread_state;
430 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800431 }
Alex Light597adad2017-10-16 16:11:42 -0700432 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800433
434 return jvmti_state;
435}
436
Alex Light1f0a22f2017-07-17 12:55:59 -0700437static jint GetJavaStateFromInternal(const InternalThreadState& state) {
438 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800439 case art::ThreadState::kTerminated:
440 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
441
442 case art::ThreadState::kRunnable:
443 case art::ThreadState::kNative:
444 case art::ThreadState::kWaitingWeakGcRootRead:
445 case art::ThreadState::kSuspended:
446 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
447
448 case art::ThreadState::kTimedWaiting:
449 case art::ThreadState::kSleeping:
450 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
451
452 case art::ThreadState::kBlocked:
453 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
454
455 case art::ThreadState::kStarting:
456 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
457
458 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700459 case art::ThreadState::kWaitingForTaskProcessor:
460 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800461 case art::ThreadState::kWaitingForGcToComplete:
462 case art::ThreadState::kWaitingPerformingGc:
463 case art::ThreadState::kWaitingForCheckPointsToRun:
464 case art::ThreadState::kWaitingForDebuggerSend:
465 case art::ThreadState::kWaitingForDebuggerToAttach:
466 case art::ThreadState::kWaitingInMainDebuggerLoop:
467 case art::ThreadState::kWaitingForDebuggerSuspension:
468 case art::ThreadState::kWaitingForDeoptimization:
469 case art::ThreadState::kWaitingForGetObjectsAllocated:
470 case art::ThreadState::kWaitingForJniOnLoad:
471 case art::ThreadState::kWaitingForSignalCatcherOutput:
472 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
473 case art::ThreadState::kWaitingForMethodTracingStart:
474 case art::ThreadState::kWaitingForVisitObjects:
475 case art::ThreadState::kWaitingForGcThreadFlip:
476 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
477 }
478 LOG(FATAL) << "Unreachable";
479 UNREACHABLE();
480}
481
Alex Light1f0a22f2017-07-17 12:55:59 -0700482// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700483void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700484 art::ScopedObjectAccess soa(self);
485 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
486 self->FullSuspendCheck();
487}
488
Alex Light23aa7482017-08-16 10:01:13 -0700489bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
490 DCHECK(self == art::Thread::Current());
491 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
492 return self->GetUserCodeSuspendCount() != 0;
493}
494
495bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
496 DCHECK(self == art::Thread::Current());
497 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
498 return WouldSuspendForUserCodeLocked(self);
499}
500
Andreas Gampe72c19832017-01-12 13:22:16 -0800501jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
502 jthread thread,
503 jint* thread_state_ptr) {
504 if (thread_state_ptr == nullptr) {
505 return ERR(NULL_POINTER);
506 }
507
Alex Light1f0a22f2017-07-17 12:55:59 -0700508 art::Thread* self = art::Thread::Current();
509 InternalThreadState state = {};
510 // Loop since we need to bail out and try again if we would end up getting suspended while holding
511 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
512 // release the lock, wait to get resumed and try again.
513 do {
514 SuspendCheck(self);
515 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700516 if (WouldSuspendForUserCodeLocked(self)) {
517 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
518 // a user-code suspension. We retry and do another SuspendCheck to clear this.
519 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700520 }
521 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700522 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700523 jvmtiError err = ERR(INTERNAL);
524 art::Thread* target = nullptr;
525 if (!GetNativeThread(thread, soa, &target, &err)) {
526 return err;
527 }
528 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700529 if (state.art_state == art::ThreadState::kStarting) {
530 break;
531 }
532 DCHECK(state.native_thread != nullptr);
533
534 // Translate internal thread state to JVMTI and Java state.
535 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
536
537 // Java state is derived from nativeGetState.
538 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
539 // different mask if a thread got suspended due to user-code. However, this is for
540 // consistency with the Java view.
541 jint java_state = GetJavaStateFromInternal(state);
542
543 *thread_state_ptr = jvmti_state | java_state;
544
545 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700546 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800547
Alex Light3ae82532017-07-26 13:59:07 -0700548 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800549
Alex Light3ae82532017-07-26 13:59:07 -0700550 if (thread == nullptr) {
551 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
552 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800553 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800554
Alex Light3ae82532017-07-26 13:59:07 -0700555 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700556 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800557
Alex Light3ae82532017-07-26 13:59:07 -0700558 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700559 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
560 art::ObjPtr<art::mirror::Class> thread_klass =
561 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
562 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
563 return ERR(INVALID_THREAD);
564 }
565 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700566 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700567 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700568 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
569 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
570 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
571 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800572 return ERR(NONE);
573}
574
Andreas Gampe85807442017-01-13 14:40:58 -0800575jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
576 jint* threads_count_ptr,
577 jthread** threads_ptr) {
578 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
579 return ERR(NULL_POINTER);
580 }
581
582 art::Thread* current = art::Thread::Current();
583
584 art::ScopedObjectAccess soa(current);
585
586 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
587 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
588
589 std::vector<art::ObjPtr<art::mirror::Object>> peers;
590
591 for (art::Thread* thread : thread_list) {
592 // Skip threads that are still starting.
593 if (thread->IsStillStarting()) {
594 continue;
595 }
596
Andreas Gampe202f85a2017-02-06 10:23:26 -0800597 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800598 if (peer != nullptr) {
599 peers.push_back(peer);
600 }
601 }
602
603 if (peers.empty()) {
604 *threads_count_ptr = 0;
605 *threads_ptr = nullptr;
606 } else {
607 unsigned char* data;
608 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
609 if (data_result != ERR(NONE)) {
610 return data_result;
611 }
612 jthread* threads = reinterpret_cast<jthread*>(data);
613 for (size_t i = 0; i != peers.size(); ++i) {
614 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
615 }
616
617 *threads_count_ptr = static_cast<jint>(peers.size());
618 *threads_ptr = threads;
619 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800620 return ERR(NONE);
621}
Andreas Gampe85807442017-01-13 14:40:58 -0800622
Alex Light092a4042017-07-12 08:46:44 -0700623// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
624// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
625// data but we only have a single slot in Thread objects to store data.
626struct JvmtiGlobalTLSData {
627 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
628};
629
630static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
631 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
632 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
633 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
634 if (global_tls != nullptr) {
635 global_tls->data.erase(env);
636 }
637}
638
639void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
640 art::Thread* self = art::Thread::Current();
641 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
642 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
643 list->ForEach(RemoveTLSData, env);
644}
645
646jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
647 art::Thread* self = art::Thread::Current();
648 art::ScopedObjectAccess soa(self);
649 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700650 art::Thread* target = nullptr;
651 jvmtiError err = ERR(INTERNAL);
652 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
653 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800654 }
655
Alex Light092a4042017-07-12 08:46:44 -0700656 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
657 if (global_tls == nullptr) {
658 target->SetCustomTLS(new JvmtiGlobalTLSData);
659 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
660 }
661
662 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800663
664 return ERR(NONE);
665}
666
Alex Light092a4042017-07-12 08:46:44 -0700667jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800668 jthread thread,
669 void** data_ptr) {
670 if (data_ptr == nullptr) {
671 return ERR(NULL_POINTER);
672 }
673
Alex Light092a4042017-07-12 08:46:44 -0700674 art::Thread* self = art::Thread::Current();
675 art::ScopedObjectAccess soa(self);
676 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700677 art::Thread* target = nullptr;
678 jvmtiError err = ERR(INTERNAL);
679 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
680 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800681 }
682
Alex Light092a4042017-07-12 08:46:44 -0700683 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
684 if (global_tls == nullptr) {
685 *data_ptr = nullptr;
686 return OK;
687 }
688 auto it = global_tls->data.find(env);
689 if (it != global_tls->data.end()) {
690 *data_ptr = const_cast<void*>(it->second);
691 } else {
692 *data_ptr = nullptr;
693 }
694
Andreas Gampe85807442017-01-13 14:40:58 -0800695 return ERR(NONE);
696}
697
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800698struct AgentData {
699 const void* arg;
700 jvmtiStartFunction proc;
701 jthread thread;
702 JavaVM* java_vm;
703 jvmtiEnv* jvmti_env;
704 jint priority;
Alex Light93112972017-11-13 10:38:59 -0800705 std::string name;
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800706};
707
708static void* AgentCallback(void* arg) {
709 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
710 CHECK(data->thread != nullptr);
711
712 // We already have a peer. So call our special Attach function.
Alex Light93112972017-11-13 10:38:59 -0800713 art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700714 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800715 // The name in Attach() is only for logging. Set the thread name. This is important so
716 // that the thread is no longer seen as starting up.
717 {
718 art::ScopedObjectAccess soa(self);
Alex Light93112972017-11-13 10:38:59 -0800719 self->SetThreadName(data->name.c_str());
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800720 }
721
722 // Release the peer.
723 JNIEnv* env = self->GetJniEnv();
724 env->DeleteGlobalRef(data->thread);
725 data->thread = nullptr;
726
Alex Light739bf722017-10-20 13:14:24 -0700727 {
728 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
729 // before going into the provided code.
730 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
731 art::Runtime::Current()->EndThreadBirth();
732 }
733
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800734 // Run the agent code.
735 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
736
737 // Detach the thread.
738 int detach_result = data->java_vm->DetachCurrentThread();
739 CHECK_EQ(detach_result, 0);
740
741 return nullptr;
742}
743
744jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
745 jthread thread,
746 jvmtiStartFunction proc,
747 const void* arg,
748 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700749 if (!PhaseUtil::IsLivePhase()) {
750 return ERR(WRONG_PHASE);
751 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800752 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
753 return ERR(INVALID_PRIORITY);
754 }
755 JNIEnv* env = art::Thread::Current()->GetJniEnv();
756 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
757 return ERR(INVALID_THREAD);
758 }
759 if (proc == nullptr) {
760 return ERR(NULL_POINTER);
761 }
762
Alex Light739bf722017-10-20 13:14:24 -0700763 {
764 art::Runtime* runtime = art::Runtime::Current();
765 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
766 if (runtime->IsShuttingDownLocked()) {
767 // The runtime is shutting down so we cannot create new threads.
768 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
769 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
770 // impossible. Existing agents don't seem to generally do anything with this return value so
771 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
772 // even though code is never actually run.
773 return ERR(INTERNAL);
774 }
775 runtime->StartThreadBirth();
776 }
777
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800778 std::unique_ptr<AgentData> data(new AgentData);
779 data->arg = arg;
780 data->proc = proc;
781 // We need a global ref for Java objects, as local refs will be invalid.
782 data->thread = env->NewGlobalRef(thread);
783 data->java_vm = art::Runtime::Current()->GetJavaVM();
784 data->jvmti_env = jvmti_env;
785 data->priority = priority;
Alex Light93112972017-11-13 10:38:59 -0800786 ScopedLocalRef<jstring> s(
787 env,
788 reinterpret_cast<jstring>(
789 env->GetObjectField(thread, art::WellKnownClasses::java_lang_Thread_name)));
790 if (s == nullptr) {
791 data->name = "JVMTI Agent Thread";
792 } else {
793 ScopedUtfChars name(env, s.get());
794 data->name = name.c_str();
795 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800796
797 pthread_t pthread;
798 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700799 nullptr,
800 &AgentCallback,
801 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800802 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700803 // If the create succeeded the other thread will call EndThreadBirth.
804 art::Runtime* runtime = art::Runtime::Current();
805 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
806 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800807 return ERR(INTERNAL);
808 }
809 data.release();
810
811 return ERR(NONE);
812}
813
Alex Light88fd7202017-06-30 08:31:59 -0700814jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700815 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700816 // Loop since we need to bail out and try again if we would end up getting suspended while holding
817 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
818 // release the lock, wait to get resumed and try again.
819 do {
820 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
821 // another SuspendThread in the middle of suspending something else potentially causing a
822 // deadlock. We need to do this in the loop because if we ended up back here then we had
823 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
824 // before continuing.
825 SuspendCheck(self);
826 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700827 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700828 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
829 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700830 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700831 }
Alex Light23aa7482017-08-16 10:01:13 -0700832 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700833 {
834 art::ScopedObjectAccess soa(self);
835 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700836 art::Thread* target = nullptr;
837 jvmtiError err = ERR(INTERNAL);
838 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
839 return err;
840 }
Alex Light88fd7202017-06-30 08:31:59 -0700841 art::ThreadState state = target->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700842 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Light88fd7202017-06-30 08:31:59 -0700843 return ERR(THREAD_NOT_ALIVE);
Alex Light3ae82532017-07-26 13:59:07 -0700844 } else {
845 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
846 if (target->GetUserCodeSuspendCount() != 0) {
847 return ERR(THREAD_SUSPENDED);
848 }
Alex Light88fd7202017-06-30 08:31:59 -0700849 }
850 }
Alex Light3ae82532017-07-26 13:59:07 -0700851 bool timeout = true;
852 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
853 target_jthread,
854 /* request_suspension */ true,
855 art::SuspendReason::kForUserCode,
856 &timeout);
857 if (ret_target == nullptr && !timeout) {
858 // TODO It would be good to get more information about why exactly the thread failed to
859 // suspend.
860 return ERR(INTERNAL);
861 } else if (!timeout) {
862 // we didn't time out and got a result.
863 return OK;
864 }
865 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700866 } while (true);
867 UNREACHABLE();
868}
869
870jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
871 CHECK(self == art::Thread::Current());
872 {
873 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
874 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
875 if (self->GetUserCodeSuspendCount() != 0) {
876 // This can only happen if we race with another thread to suspend 'self' and we lose.
877 return ERR(THREAD_SUSPENDED);
878 }
879 // We shouldn't be able to fail this.
880 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
881 // TODO More specific error would be nice.
882 return ERR(INTERNAL);
883 }
884 }
885 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
886 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
887 // to go to sleep until we are resumed.
888 SuspendCheck(self);
889 return OK;
890}
891
892jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
893 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700894 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700895 {
896 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700897 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700898 art::Thread* target = nullptr;
899 jvmtiError err = ERR(INTERNAL);
900 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
901 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700902 } else if (target == self) {
903 target_is_self = true;
904 }
Alex Light88fd7202017-06-30 08:31:59 -0700905 }
Alex Light3ae82532017-07-26 13:59:07 -0700906 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700907 return SuspendSelf(self);
908 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700909 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700910 }
911}
912
913jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
914 jthread thread) {
915 if (thread == nullptr) {
916 return ERR(NULL_POINTER);
917 }
918 art::Thread* self = art::Thread::Current();
919 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700920 // Retry until we know we won't get suspended by user code while resuming something.
921 do {
922 SuspendCheck(self);
923 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700924 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700925 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
926 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700927 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700928 }
Alex Light3ae82532017-07-26 13:59:07 -0700929 // From now on we know we cannot get suspended by user-code.
930 {
931 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
932 // have the 'suspend_lock' locked here.
933 art::ScopedObjectAccess soa(self);
934 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700935 jvmtiError err = ERR(INTERNAL);
936 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
937 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700938 } else if (target == self) {
939 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
940 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
941 // about current state since it's all concurrent.
942 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700943 }
944 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
945 // cannot tell why resume failed.
946 {
947 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
948 if (target->GetUserCodeSuspendCount() == 0) {
949 return ERR(THREAD_NOT_SUSPENDED);
950 }
951 }
952 }
953 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
954 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
955 DCHECK(target != self);
956 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
957 art::SuspendReason::kForUserCode)) {
958 // TODO Give a better error.
959 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
960 return ERR(INTERNAL);
961 } else {
962 return OK;
963 }
964 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700965}
966
Alex Light7ddc23d2017-09-22 15:33:41 -0700967static bool IsCurrentThread(jthread thr) {
968 if (thr == nullptr) {
969 return true;
970 }
971 art::Thread* self = art::Thread::Current();
972 art::ScopedObjectAccess soa(self);
973 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
974 art::Thread* target = nullptr;
975 jvmtiError err_unused = ERR(INTERNAL);
976 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
977 return target == self;
978 } else {
979 return false;
980 }
981}
982
Alex Light88fd7202017-06-30 08:31:59 -0700983// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
984// since we can have threads in the list multiple times. This generally doesn't matter unless the
985// current thread is present multiple times. In that case we need to suspend only once and either
986// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
987// it didn't. We also want to handle the current thread last to make the behavior of the code
988// simpler to understand.
989jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
990 jint request_count,
991 const jthread* threads,
992 jvmtiError* results) {
993 if (request_count == 0) {
994 return ERR(ILLEGAL_ARGUMENT);
995 } else if (results == nullptr || threads == nullptr) {
996 return ERR(NULL_POINTER);
997 }
998 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
999 // running thread. These indexes we need to handle specially since we need to only actually
1000 // suspend a single time.
1001 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -07001002 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -07001003 if (IsCurrentThread(threads[i])) {
1004 current_thread_indexes.push_back(i);
1005 } else {
1006 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -07001007 }
Alex Light88fd7202017-06-30 08:31:59 -07001008 }
1009 if (!current_thread_indexes.empty()) {
1010 jint first_current_thread_index = current_thread_indexes[0];
1011 // Suspend self.
1012 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1013 results[first_current_thread_index] = res;
1014 // Fill in the rest of the error values as appropriate.
1015 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1016 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1017 results[*it] = other_results;
1018 }
1019 }
1020 return OK;
1021}
1022
1023jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1024 jint request_count,
1025 const jthread* threads,
1026 jvmtiError* results) {
1027 if (request_count == 0) {
1028 return ERR(ILLEGAL_ARGUMENT);
1029 } else if (results == nullptr || threads == nullptr) {
1030 return ERR(NULL_POINTER);
1031 }
1032 for (jint i = 0; i < request_count; i++) {
1033 results[i] = env->ResumeThread(threads[i]);
1034 }
1035 return OK;
1036}
1037
Alex Light54d39dc2017-09-25 17:00:16 -07001038jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1039 jthread thread,
1040 jobject exception) {
1041 art::Thread* self = art::Thread::Current();
1042 art::ScopedObjectAccess soa(self);
1043 art::StackHandleScope<1> hs(self);
1044 if (exception == nullptr) {
1045 return ERR(INVALID_OBJECT);
1046 }
1047 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1048 if (!obj->GetClass()->IsThrowableClass()) {
1049 return ERR(INVALID_OBJECT);
1050 }
1051 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001052 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001053 art::Thread* target = nullptr;
1054 jvmtiError err = ERR(INTERNAL);
1055 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001056 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001057 return err;
1058 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001059 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001060 return ERR(THREAD_NOT_ALIVE);
1061 }
1062 struct StopThreadClosure : public art::Closure {
1063 public:
1064 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1065
1066 void Run(art::Thread* me) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1067 // Make sure the thread is prepared to notice the exception.
1068 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1069 me->SetAsyncException(exception_.Get());
1070 // Wake up the thread if it is sleeping.
1071 me->Notify();
1072 }
1073
1074 private:
1075 art::Handle<art::mirror::Throwable> exception_;
1076 };
1077 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001078 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +00001079 if (RequestGCSafeSynchronousCheckpoint(target, &c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001080 return OK;
1081 } else {
1082 // Something went wrong, probably the thread died.
1083 return ERR(THREAD_NOT_ALIVE);
1084 }
1085}
1086
1087jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1088 art::Thread* self = art::Thread::Current();
1089 art::ScopedObjectAccess soa(self);
1090 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1091 art::Thread* target = nullptr;
1092 jvmtiError err = ERR(INTERNAL);
1093 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1094 return err;
1095 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1096 return ERR(THREAD_NOT_ALIVE);
1097 }
1098 target->Interrupt(self);
1099 return OK;
1100}
1101
Alex Lightd9aff132017-10-31 22:30:05 +00001102class GcCriticalSectionClosure : public art::Closure {
1103 public:
1104 explicit GcCriticalSectionClosure(art::Closure* wrapped) : wrapped_(wrapped) {}
1105
1106 void Run(art::Thread* self) OVERRIDE {
1107 if (art::kIsDebugBuild) {
1108 art::Locks::thread_list_lock_->AssertNotHeld(art::Thread::Current());
1109 }
1110 // This might block as it waits for any in-progress GCs to finish but this is fine since we
1111 // released the Thread-list-lock prior to calling this in RequestSynchronousCheckpoint.
1112 art::gc::ScopedGCCriticalSection sgccs(art::Thread::Current(),
1113 art::gc::kGcCauseDebugger,
1114 art::gc::kCollectorTypeDebugger);
1115 wrapped_->Run(self);
1116 }
1117
1118 private:
1119 art::Closure* wrapped_;
1120};
1121
1122bool ThreadUtil::RequestGCSafeSynchronousCheckpoint(art::Thread* thr, art::Closure* function) {
1123 GcCriticalSectionClosure gccsc(function);
1124 return thr->RequestSynchronousCheckpoint(&gccsc);
1125}
1126
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001127} // namespace openjdkjvmti