blob: 6d075a6b7be8fd9c6f86a33a32ebb7e44f1cc396 [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"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080050#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080051#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080052#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080053#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070054#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080055#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070056#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080057#include "well_known_classes.h"
58
59namespace openjdkjvmti {
60
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070061art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
62
Alex Light1d8a9742017-08-17 11:12:06 -070063struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080064 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
65 if (self->GetPeer() == nullptr) {
66 return nullptr;
67 }
68 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
69 }
Alex Light1d8a9742017-08-17 11:12:06 -070070
Andreas Gampe983c1752017-01-23 19:46:56 -080071 template <ArtJvmtiEvent kEvent>
72 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080073 DCHECK_EQ(self, art::Thread::Current());
74 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080075 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080076 event_handler->DispatchEvent<kEvent>(self,
77 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
78 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080079 }
80
81 void ThreadStart(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
82 if (!started) {
83 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
84 // started here.
85 if (art::kIsDebugBuild) {
86 std::string name;
87 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080088 if (name != "JDWP" &&
89 name != "Signal Catcher" &&
90 !android::base::StartsWith(name, "Jit thread pool")) {
Alex Light23aa7482017-08-16 10:01:13 -070091 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
92 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080093 }
94 }
95 return;
96 }
Andreas Gampe983c1752017-01-23 19:46:56 -080097 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080098 }
99
100 void ThreadDeath(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -0800101 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800102 }
103
Andreas Gampeeafaf572017-01-20 12:34:15 -0800104 EventHandler* event_handler = nullptr;
105 bool started = false;
106};
107
108ThreadCallback gThreadCallback;
109
110void ThreadUtil::Register(EventHandler* handler) {
111 art::Runtime* runtime = art::Runtime::Current();
112
113 gThreadCallback.started = runtime->IsStarted();
114 gThreadCallback.event_handler = handler;
115
116 art::ScopedThreadStateChange stsc(art::Thread::Current(),
117 art::ThreadState::kWaitingForDebuggerToAttach);
118 art::ScopedSuspendAll ssa("Add thread callback");
119 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700120}
121
122void ThreadUtil::VMInitEventSent() {
123 // We should have already started.
124 DCHECK(gThreadCallback.started);
125 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
126 // reported until Init.
127 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800128}
129
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700130void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700131 // We must have started since it is now safe to cache our data;
132 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700133 art::ScopedObjectAccess soa(art::Thread::Current());
134 art::ObjPtr<art::mirror::Class> thread_class =
135 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
136 CHECK(thread_class != nullptr);
137 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
138 "Ljava/lang/ClassLoader;");
139 CHECK(context_class_loader_ != nullptr);
140}
141
Andreas Gampeeafaf572017-01-20 12:34:15 -0800142void ThreadUtil::Unregister() {
143 art::ScopedThreadStateChange stsc(art::Thread::Current(),
144 art::ThreadState::kWaitingForDebuggerToAttach);
145 art::ScopedSuspendAll ssa("Remove thread callback");
146 art::Runtime* runtime = art::Runtime::Current();
147 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800148}
149
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800150jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
151 art::Thread* self = art::Thread::Current();
152
153 art::ScopedObjectAccess soa(self);
154
155 jthread thread_peer;
156 if (self->IsStillStarting()) {
157 thread_peer = nullptr;
158 } else {
159 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
160 }
161
162 *thread_ptr = thread_peer;
163 return ERR(NONE);
164}
165
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800166// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700167bool ThreadUtil::GetNativeThread(jthread thread,
168 const art::ScopedObjectAccessAlreadyRunnable& soa,
169 /*out*/ art::Thread** thr,
170 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800171 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700172 *thr = art::Thread::Current();
173 return true;
174 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
175 *err = ERR(INVALID_THREAD);
176 return false;
177 } else {
178 *thr = art::Thread::FromManagedThread(soa, thread);
179 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800180 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700181}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800182
Alex Light7ddc23d2017-09-22 15:33:41 -0700183bool ThreadUtil::GetAliveNativeThread(jthread thread,
184 const art::ScopedObjectAccessAlreadyRunnable& soa,
185 /*out*/ art::Thread** thr,
186 /*out*/ jvmtiError* err) {
187 if (!GetNativeThread(thread, soa, thr, err)) {
188 return false;
189 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
190 *err = ERR(THREAD_NOT_ALIVE);
191 return false;
192 } else {
193 return true;
194 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800195}
196
197jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
198 if (info_ptr == nullptr) {
199 return ERR(NULL_POINTER);
200 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700201 if (!PhaseUtil::IsLivePhase()) {
202 return JVMTI_ERROR_WRONG_PHASE;
203 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800204
Alex Light3ae82532017-07-26 13:59:07 -0700205 art::Thread* self = art::Thread::Current();
206 art::ScopedObjectAccess soa(self);
207 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800208
Alex Light7ddc23d2017-09-22 15:33:41 -0700209 art::Thread* target;
210 jvmtiError err = ERR(INTERNAL);
211 if (!GetNativeThread(thread, soa, &target, &err)) {
212 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800213 }
214
Andreas Gampe54711412017-02-21 12:41:43 -0800215 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700216 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800217 // Have a native thread object, this thread is alive.
218 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700219 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800220 jvmtiError name_result;
221 name_uptr = CopyString(env, name.c_str(), &name_result);
222 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800223 return name_result;
224 }
Andreas Gampe54711412017-02-21 12:41:43 -0800225 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800226
Alex Light3ae82532017-07-26 13:59:07 -0700227 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800228
Alex Light3ae82532017-07-26 13:59:07 -0700229 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800230
Alex Light3ae82532017-07-26 13:59:07 -0700231 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800232
233 // ThreadGroup.
234 if (peer != nullptr) {
235 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
236 CHECK(f != nullptr);
237 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
238 info_ptr->thread_group = group == nullptr
239 ? nullptr
240 : soa.AddLocalReference<jthreadGroup>(group);
241 } else {
242 info_ptr->thread_group = nullptr;
243 }
244
245 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700246 DCHECK(context_class_loader_ != nullptr);
247 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
248 ? context_class_loader_->GetObject(peer)
249 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800250 info_ptr->context_class_loader = ccl == nullptr
251 ? nullptr
252 : soa.AddLocalReference<jobject>(ccl);
253 } else {
254 // Only the peer. This thread has either not been started, or is dead. Read things from
255 // the Java side.
256 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
257
258 // Name.
259 {
260 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
261 CHECK(f != nullptr);
262 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
263 std::string name_cpp;
264 const char* name_cstr;
265 if (name != nullptr) {
266 name_cpp = name->AsString()->ToModifiedUtf8();
267 name_cstr = name_cpp.c_str();
268 } else {
269 name_cstr = "";
270 }
Andreas Gampe54711412017-02-21 12:41:43 -0800271 jvmtiError name_result;
272 name_uptr = CopyString(env, name_cstr, &name_result);
273 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800274 return name_result;
275 }
Andreas Gampe54711412017-02-21 12:41:43 -0800276 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800277 }
278
279 // Priority.
280 {
281 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
282 CHECK(f != nullptr);
283 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
284 }
285
286 // Daemon.
287 {
288 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
289 CHECK(f != nullptr);
290 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
291 }
292
293 // ThreadGroup.
294 {
295 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
296 CHECK(f != nullptr);
297 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
298 info_ptr->thread_group = group == nullptr
299 ? nullptr
300 : soa.AddLocalReference<jthreadGroup>(group);
301 }
302
303 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700304 DCHECK(context_class_loader_ != nullptr);
305 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
306 ? context_class_loader_->GetObject(peer)
307 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800308 info_ptr->context_class_loader = ccl == nullptr
309 ? nullptr
310 : soa.AddLocalReference<jobject>(ccl);
311 }
312
313 name_uptr.release();
314
315 return ERR(NONE);
316}
317
Alex Light1f0a22f2017-07-17 12:55:59 -0700318struct InternalThreadState {
319 art::Thread* native_thread;
320 art::ThreadState art_state;
321 int thread_user_code_suspend_count;
322};
323
324// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700325static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700326 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700327 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700328 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700329 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
330 thread_state.native_thread = target;
331 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700332 thread_state.art_state = art::ThreadState::kStarting;
333 thread_state.thread_user_code_suspend_count = 0;
334 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700335 thread_state.art_state = target->GetState();
336 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800337 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700338 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800339}
340
Alex Light1f0a22f2017-07-17 12:55:59 -0700341static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
342 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800343 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
344
Alex Light1f0a22f2017-07-17 12:55:59 -0700345 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700346 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
347 // 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 -0800348 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
349 // Note: We do not have data about the previous state. Otherwise we should load the previous
350 // state here.
351 }
352
Alex Light1f0a22f2017-07-17 12:55:59 -0700353 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700354 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700355 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
356 }
357
Alex Light597adad2017-10-16 16:11:42 -0700358 // Enumerate all the thread states and fill in the other bits. This contains the results of
359 // following the decision tree in the JVMTI spec GetThreadState documentation.
360 switch (internal_thread_state) {
361 case art::ThreadState::kRunnable:
362 case art::ThreadState::kWaitingWeakGcRootRead:
363 case art::ThreadState::kSuspended:
364 // These are all simply runnable.
365 // kRunnable is self-explanatory.
366 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
367 // so we want to keep it marked as runnable.
368 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
369 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
370 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
371 break;
372 case art::ThreadState::kNative:
373 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
374 // state but we don't have the information to know if it should be present for any but the
375 // kNative state.
376 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
377 JVMTI_THREAD_STATE_RUNNABLE);
378 break;
379 case art::ThreadState::kBlocked:
380 // Blocked is one of the top level states so it sits alone.
381 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
382 break;
383 case art::ThreadState::kWaiting:
384 // Object.wait() so waiting, indefinitely, in object.wait.
385 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
386 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
387 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
388 break;
389 case art::ThreadState::kTimedWaiting:
390 // Object.wait(long) so waiting, with timeout, in object.wait.
391 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
392 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
393 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
394 break;
395 case art::ThreadState::kSleeping:
396 // In object.sleep. This is a timed wait caused by sleep.
397 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
398 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
399 JVMTI_THREAD_STATE_SLEEPING);
400 break;
401 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
402 // attached.
403 case art::ThreadState::kWaitingForDebuggerSend:
404 case art::ThreadState::kWaitingForDebuggerToAttach:
405 case art::ThreadState::kWaitingInMainDebuggerLoop:
406 case art::ThreadState::kWaitingForDebuggerSuspension:
407 case art::ThreadState::kWaitingForLockInflation:
408 case art::ThreadState::kWaitingForTaskProcessor:
409 case art::ThreadState::kWaitingForGcToComplete:
410 case art::ThreadState::kWaitingForCheckPointsToRun:
411 case art::ThreadState::kWaitingPerformingGc:
412 case art::ThreadState::kWaitingForJniOnLoad:
413 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
414 case art::ThreadState::kWaitingForSignalCatcherOutput:
415 case art::ThreadState::kWaitingForDeoptimization:
416 case art::ThreadState::kWaitingForMethodTracingStart:
417 case art::ThreadState::kWaitingForVisitObjects:
418 case art::ThreadState::kWaitingForGetObjectsAllocated:
419 case art::ThreadState::kWaitingForGcThreadFlip:
420 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
421 // caused by sleep, park, or object#wait.
422 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
423 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
424 break;
425 case art::ThreadState::kStarting:
426 case art::ThreadState::kTerminated:
427 // We only call this if we are alive so we shouldn't see either of these states.
428 LOG(FATAL) << "Should not be in state " << internal_thread_state;
429 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800430 }
Alex Light597adad2017-10-16 16:11:42 -0700431 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800432
433 return jvmti_state;
434}
435
Alex Light1f0a22f2017-07-17 12:55:59 -0700436static jint GetJavaStateFromInternal(const InternalThreadState& state) {
437 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800438 case art::ThreadState::kTerminated:
439 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
440
441 case art::ThreadState::kRunnable:
442 case art::ThreadState::kNative:
443 case art::ThreadState::kWaitingWeakGcRootRead:
444 case art::ThreadState::kSuspended:
445 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
446
447 case art::ThreadState::kTimedWaiting:
448 case art::ThreadState::kSleeping:
449 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
450
451 case art::ThreadState::kBlocked:
452 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
453
454 case art::ThreadState::kStarting:
455 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
456
457 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700458 case art::ThreadState::kWaitingForTaskProcessor:
459 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800460 case art::ThreadState::kWaitingForGcToComplete:
461 case art::ThreadState::kWaitingPerformingGc:
462 case art::ThreadState::kWaitingForCheckPointsToRun:
463 case art::ThreadState::kWaitingForDebuggerSend:
464 case art::ThreadState::kWaitingForDebuggerToAttach:
465 case art::ThreadState::kWaitingInMainDebuggerLoop:
466 case art::ThreadState::kWaitingForDebuggerSuspension:
467 case art::ThreadState::kWaitingForDeoptimization:
468 case art::ThreadState::kWaitingForGetObjectsAllocated:
469 case art::ThreadState::kWaitingForJniOnLoad:
470 case art::ThreadState::kWaitingForSignalCatcherOutput:
471 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
472 case art::ThreadState::kWaitingForMethodTracingStart:
473 case art::ThreadState::kWaitingForVisitObjects:
474 case art::ThreadState::kWaitingForGcThreadFlip:
475 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
476 }
477 LOG(FATAL) << "Unreachable";
478 UNREACHABLE();
479}
480
Alex Light1f0a22f2017-07-17 12:55:59 -0700481// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700482void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700483 art::ScopedObjectAccess soa(self);
484 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
485 self->FullSuspendCheck();
486}
487
Alex Light23aa7482017-08-16 10:01:13 -0700488bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
489 DCHECK(self == art::Thread::Current());
490 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
491 return self->GetUserCodeSuspendCount() != 0;
492}
493
494bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
495 DCHECK(self == art::Thread::Current());
496 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
497 return WouldSuspendForUserCodeLocked(self);
498}
499
Andreas Gampe72c19832017-01-12 13:22:16 -0800500jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
501 jthread thread,
502 jint* thread_state_ptr) {
503 if (thread_state_ptr == nullptr) {
504 return ERR(NULL_POINTER);
505 }
506
Alex Light1f0a22f2017-07-17 12:55:59 -0700507 art::Thread* self = art::Thread::Current();
508 InternalThreadState state = {};
509 // Loop since we need to bail out and try again if we would end up getting suspended while holding
510 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
511 // release the lock, wait to get resumed and try again.
512 do {
513 SuspendCheck(self);
514 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700515 if (WouldSuspendForUserCodeLocked(self)) {
516 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
517 // a user-code suspension. We retry and do another SuspendCheck to clear this.
518 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700519 }
520 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700521 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700522 jvmtiError err = ERR(INTERNAL);
523 art::Thread* target = nullptr;
524 if (!GetNativeThread(thread, soa, &target, &err)) {
525 return err;
526 }
527 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700528 if (state.art_state == art::ThreadState::kStarting) {
529 break;
530 }
531 DCHECK(state.native_thread != nullptr);
532
533 // Translate internal thread state to JVMTI and Java state.
534 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
535
536 // Java state is derived from nativeGetState.
537 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
538 // different mask if a thread got suspended due to user-code. However, this is for
539 // consistency with the Java view.
540 jint java_state = GetJavaStateFromInternal(state);
541
542 *thread_state_ptr = jvmti_state | java_state;
543
544 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700545 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800546
Alex Light3ae82532017-07-26 13:59:07 -0700547 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800548
Alex Light3ae82532017-07-26 13:59:07 -0700549 if (thread == nullptr) {
550 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
551 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800552 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800553
Alex Light3ae82532017-07-26 13:59:07 -0700554 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700555 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800556
Alex Light3ae82532017-07-26 13:59:07 -0700557 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700558 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
559 art::ObjPtr<art::mirror::Class> thread_klass =
560 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
561 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
562 return ERR(INVALID_THREAD);
563 }
564 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700565 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700566 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700567 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
568 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
569 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
570 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800571 return ERR(NONE);
572}
573
Andreas Gampe85807442017-01-13 14:40:58 -0800574jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
575 jint* threads_count_ptr,
576 jthread** threads_ptr) {
577 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
578 return ERR(NULL_POINTER);
579 }
580
581 art::Thread* current = art::Thread::Current();
582
583 art::ScopedObjectAccess soa(current);
584
585 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
586 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
587
588 std::vector<art::ObjPtr<art::mirror::Object>> peers;
589
590 for (art::Thread* thread : thread_list) {
591 // Skip threads that are still starting.
592 if (thread->IsStillStarting()) {
593 continue;
594 }
595
Andreas Gampe202f85a2017-02-06 10:23:26 -0800596 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800597 if (peer != nullptr) {
598 peers.push_back(peer);
599 }
600 }
601
602 if (peers.empty()) {
603 *threads_count_ptr = 0;
604 *threads_ptr = nullptr;
605 } else {
606 unsigned char* data;
607 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
608 if (data_result != ERR(NONE)) {
609 return data_result;
610 }
611 jthread* threads = reinterpret_cast<jthread*>(data);
612 for (size_t i = 0; i != peers.size(); ++i) {
613 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
614 }
615
616 *threads_count_ptr = static_cast<jint>(peers.size());
617 *threads_ptr = threads;
618 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800619 return ERR(NONE);
620}
Andreas Gampe85807442017-01-13 14:40:58 -0800621
Alex Light092a4042017-07-12 08:46:44 -0700622// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
623// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
624// data but we only have a single slot in Thread objects to store data.
625struct JvmtiGlobalTLSData {
626 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
627};
628
629static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
630 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
631 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
632 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
633 if (global_tls != nullptr) {
634 global_tls->data.erase(env);
635 }
636}
637
638void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
639 art::Thread* self = art::Thread::Current();
640 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
641 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
642 list->ForEach(RemoveTLSData, env);
643}
644
645jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
646 art::Thread* self = art::Thread::Current();
647 art::ScopedObjectAccess soa(self);
648 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700649 art::Thread* target = nullptr;
650 jvmtiError err = ERR(INTERNAL);
651 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
652 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800653 }
654
Alex Light092a4042017-07-12 08:46:44 -0700655 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
656 if (global_tls == nullptr) {
657 target->SetCustomTLS(new JvmtiGlobalTLSData);
658 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
659 }
660
661 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800662
663 return ERR(NONE);
664}
665
Alex Light092a4042017-07-12 08:46:44 -0700666jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800667 jthread thread,
668 void** data_ptr) {
669 if (data_ptr == nullptr) {
670 return ERR(NULL_POINTER);
671 }
672
Alex Light092a4042017-07-12 08:46:44 -0700673 art::Thread* self = art::Thread::Current();
674 art::ScopedObjectAccess soa(self);
675 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700676 art::Thread* target = nullptr;
677 jvmtiError err = ERR(INTERNAL);
678 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
679 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800680 }
681
Alex Light092a4042017-07-12 08:46:44 -0700682 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
683 if (global_tls == nullptr) {
684 *data_ptr = nullptr;
685 return OK;
686 }
687 auto it = global_tls->data.find(env);
688 if (it != global_tls->data.end()) {
689 *data_ptr = const_cast<void*>(it->second);
690 } else {
691 *data_ptr = nullptr;
692 }
693
Andreas Gampe85807442017-01-13 14:40:58 -0800694 return ERR(NONE);
695}
696
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800697struct AgentData {
698 const void* arg;
699 jvmtiStartFunction proc;
700 jthread thread;
701 JavaVM* java_vm;
702 jvmtiEnv* jvmti_env;
703 jint priority;
704};
705
706static void* AgentCallback(void* arg) {
707 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
708 CHECK(data->thread != nullptr);
709
710 // We already have a peer. So call our special Attach function.
711 art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700712 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800713 // The name in Attach() is only for logging. Set the thread name. This is important so
714 // that the thread is no longer seen as starting up.
715 {
716 art::ScopedObjectAccess soa(self);
717 self->SetThreadName("JVMTI Agent thread");
718 }
719
720 // Release the peer.
721 JNIEnv* env = self->GetJniEnv();
722 env->DeleteGlobalRef(data->thread);
723 data->thread = nullptr;
724
Alex Light739bf722017-10-20 13:14:24 -0700725 {
726 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
727 // before going into the provided code.
728 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
729 art::Runtime::Current()->EndThreadBirth();
730 }
731
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800732 // Run the agent code.
733 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
734
735 // Detach the thread.
736 int detach_result = data->java_vm->DetachCurrentThread();
737 CHECK_EQ(detach_result, 0);
738
739 return nullptr;
740}
741
742jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
743 jthread thread,
744 jvmtiStartFunction proc,
745 const void* arg,
746 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700747 if (!PhaseUtil::IsLivePhase()) {
748 return ERR(WRONG_PHASE);
749 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800750 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
751 return ERR(INVALID_PRIORITY);
752 }
753 JNIEnv* env = art::Thread::Current()->GetJniEnv();
754 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
755 return ERR(INVALID_THREAD);
756 }
757 if (proc == nullptr) {
758 return ERR(NULL_POINTER);
759 }
760
Alex Light739bf722017-10-20 13:14:24 -0700761 {
762 art::Runtime* runtime = art::Runtime::Current();
763 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
764 if (runtime->IsShuttingDownLocked()) {
765 // The runtime is shutting down so we cannot create new threads.
766 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
767 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
768 // impossible. Existing agents don't seem to generally do anything with this return value so
769 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
770 // even though code is never actually run.
771 return ERR(INTERNAL);
772 }
773 runtime->StartThreadBirth();
774 }
775
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800776 std::unique_ptr<AgentData> data(new AgentData);
777 data->arg = arg;
778 data->proc = proc;
779 // We need a global ref for Java objects, as local refs will be invalid.
780 data->thread = env->NewGlobalRef(thread);
781 data->java_vm = art::Runtime::Current()->GetJavaVM();
782 data->jvmti_env = jvmti_env;
783 data->priority = priority;
784
785 pthread_t pthread;
786 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700787 nullptr,
788 &AgentCallback,
789 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800790 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700791 // If the create succeeded the other thread will call EndThreadBirth.
792 art::Runtime* runtime = art::Runtime::Current();
793 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
794 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800795 return ERR(INTERNAL);
796 }
797 data.release();
798
799 return ERR(NONE);
800}
801
Alex Light88fd7202017-06-30 08:31:59 -0700802jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700803 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700804 // Loop since we need to bail out and try again if we would end up getting suspended while holding
805 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
806 // release the lock, wait to get resumed and try again.
807 do {
808 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
809 // another SuspendThread in the middle of suspending something else potentially causing a
810 // deadlock. We need to do this in the loop because if we ended up back here then we had
811 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
812 // before continuing.
813 SuspendCheck(self);
814 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700815 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700816 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
817 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700818 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700819 }
Alex Light23aa7482017-08-16 10:01:13 -0700820 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700821 {
822 art::ScopedObjectAccess soa(self);
823 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700824 art::Thread* target = nullptr;
825 jvmtiError err = ERR(INTERNAL);
826 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
827 return err;
828 }
Alex Light88fd7202017-06-30 08:31:59 -0700829 art::ThreadState state = target->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700830 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Light88fd7202017-06-30 08:31:59 -0700831 return ERR(THREAD_NOT_ALIVE);
Alex Light3ae82532017-07-26 13:59:07 -0700832 } else {
833 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
834 if (target->GetUserCodeSuspendCount() != 0) {
835 return ERR(THREAD_SUSPENDED);
836 }
Alex Light88fd7202017-06-30 08:31:59 -0700837 }
838 }
Alex Light3ae82532017-07-26 13:59:07 -0700839 bool timeout = true;
840 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
841 target_jthread,
842 /* request_suspension */ true,
843 art::SuspendReason::kForUserCode,
844 &timeout);
845 if (ret_target == nullptr && !timeout) {
846 // TODO It would be good to get more information about why exactly the thread failed to
847 // suspend.
848 return ERR(INTERNAL);
849 } else if (!timeout) {
850 // we didn't time out and got a result.
851 return OK;
852 }
853 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700854 } while (true);
855 UNREACHABLE();
856}
857
858jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
859 CHECK(self == art::Thread::Current());
860 {
861 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
862 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
863 if (self->GetUserCodeSuspendCount() != 0) {
864 // This can only happen if we race with another thread to suspend 'self' and we lose.
865 return ERR(THREAD_SUSPENDED);
866 }
867 // We shouldn't be able to fail this.
868 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
869 // TODO More specific error would be nice.
870 return ERR(INTERNAL);
871 }
872 }
873 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
874 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
875 // to go to sleep until we are resumed.
876 SuspendCheck(self);
877 return OK;
878}
879
880jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
881 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700882 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700883 {
884 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700885 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700886 art::Thread* target = nullptr;
887 jvmtiError err = ERR(INTERNAL);
888 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
889 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700890 } else if (target == self) {
891 target_is_self = true;
892 }
Alex Light88fd7202017-06-30 08:31:59 -0700893 }
Alex Light3ae82532017-07-26 13:59:07 -0700894 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700895 return SuspendSelf(self);
896 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700897 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700898 }
899}
900
901jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
902 jthread thread) {
903 if (thread == nullptr) {
904 return ERR(NULL_POINTER);
905 }
906 art::Thread* self = art::Thread::Current();
907 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700908 // Retry until we know we won't get suspended by user code while resuming something.
909 do {
910 SuspendCheck(self);
911 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700912 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700913 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
914 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700915 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700916 }
Alex Light3ae82532017-07-26 13:59:07 -0700917 // From now on we know we cannot get suspended by user-code.
918 {
919 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
920 // have the 'suspend_lock' locked here.
921 art::ScopedObjectAccess soa(self);
922 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700923 jvmtiError err = ERR(INTERNAL);
924 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
925 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700926 } else if (target == self) {
927 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
928 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
929 // about current state since it's all concurrent.
930 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700931 }
932 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
933 // cannot tell why resume failed.
934 {
935 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
936 if (target->GetUserCodeSuspendCount() == 0) {
937 return ERR(THREAD_NOT_SUSPENDED);
938 }
939 }
940 }
941 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
942 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
943 DCHECK(target != self);
944 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
945 art::SuspendReason::kForUserCode)) {
946 // TODO Give a better error.
947 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
948 return ERR(INTERNAL);
949 } else {
950 return OK;
951 }
952 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700953}
954
Alex Light7ddc23d2017-09-22 15:33:41 -0700955static bool IsCurrentThread(jthread thr) {
956 if (thr == nullptr) {
957 return true;
958 }
959 art::Thread* self = art::Thread::Current();
960 art::ScopedObjectAccess soa(self);
961 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
962 art::Thread* target = nullptr;
963 jvmtiError err_unused = ERR(INTERNAL);
964 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
965 return target == self;
966 } else {
967 return false;
968 }
969}
970
Alex Light88fd7202017-06-30 08:31:59 -0700971// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
972// since we can have threads in the list multiple times. This generally doesn't matter unless the
973// current thread is present multiple times. In that case we need to suspend only once and either
974// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
975// it didn't. We also want to handle the current thread last to make the behavior of the code
976// simpler to understand.
977jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
978 jint request_count,
979 const jthread* threads,
980 jvmtiError* results) {
981 if (request_count == 0) {
982 return ERR(ILLEGAL_ARGUMENT);
983 } else if (results == nullptr || threads == nullptr) {
984 return ERR(NULL_POINTER);
985 }
986 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
987 // running thread. These indexes we need to handle specially since we need to only actually
988 // suspend a single time.
989 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -0700990 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700991 if (IsCurrentThread(threads[i])) {
992 current_thread_indexes.push_back(i);
993 } else {
994 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -0700995 }
Alex Light88fd7202017-06-30 08:31:59 -0700996 }
997 if (!current_thread_indexes.empty()) {
998 jint first_current_thread_index = current_thread_indexes[0];
999 // Suspend self.
1000 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
1001 results[first_current_thread_index] = res;
1002 // Fill in the rest of the error values as appropriate.
1003 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1004 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1005 results[*it] = other_results;
1006 }
1007 }
1008 return OK;
1009}
1010
1011jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1012 jint request_count,
1013 const jthread* threads,
1014 jvmtiError* results) {
1015 if (request_count == 0) {
1016 return ERR(ILLEGAL_ARGUMENT);
1017 } else if (results == nullptr || threads == nullptr) {
1018 return ERR(NULL_POINTER);
1019 }
1020 for (jint i = 0; i < request_count; i++) {
1021 results[i] = env->ResumeThread(threads[i]);
1022 }
1023 return OK;
1024}
1025
Alex Light54d39dc2017-09-25 17:00:16 -07001026jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1027 jthread thread,
1028 jobject exception) {
1029 art::Thread* self = art::Thread::Current();
1030 art::ScopedObjectAccess soa(self);
1031 art::StackHandleScope<1> hs(self);
1032 if (exception == nullptr) {
1033 return ERR(INVALID_OBJECT);
1034 }
1035 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1036 if (!obj->GetClass()->IsThrowableClass()) {
1037 return ERR(INVALID_OBJECT);
1038 }
1039 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001040 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001041 art::Thread* target = nullptr;
1042 jvmtiError err = ERR(INTERNAL);
1043 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001044 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001045 return err;
1046 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001047 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001048 return ERR(THREAD_NOT_ALIVE);
1049 }
1050 struct StopThreadClosure : public art::Closure {
1051 public:
1052 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1053
1054 void Run(art::Thread* me) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1055 // Make sure the thread is prepared to notice the exception.
1056 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1057 me->SetAsyncException(exception_.Get());
1058 // Wake up the thread if it is sleeping.
1059 me->Notify();
1060 }
1061
1062 private:
1063 art::Handle<art::mirror::Throwable> exception_;
1064 };
1065 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001066 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +00001067 if (RequestGCSafeSynchronousCheckpoint(target, &c)) {
Alex Light54d39dc2017-09-25 17:00:16 -07001068 return OK;
1069 } else {
1070 // Something went wrong, probably the thread died.
1071 return ERR(THREAD_NOT_ALIVE);
1072 }
1073}
1074
1075jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1076 art::Thread* self = art::Thread::Current();
1077 art::ScopedObjectAccess soa(self);
1078 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1079 art::Thread* target = nullptr;
1080 jvmtiError err = ERR(INTERNAL);
1081 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1082 return err;
1083 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1084 return ERR(THREAD_NOT_ALIVE);
1085 }
1086 target->Interrupt(self);
1087 return OK;
1088}
1089
Alex Lightd9aff132017-10-31 22:30:05 +00001090class GcCriticalSectionClosure : public art::Closure {
1091 public:
1092 explicit GcCriticalSectionClosure(art::Closure* wrapped) : wrapped_(wrapped) {}
1093
1094 void Run(art::Thread* self) OVERRIDE {
1095 if (art::kIsDebugBuild) {
1096 art::Locks::thread_list_lock_->AssertNotHeld(art::Thread::Current());
1097 }
1098 // This might block as it waits for any in-progress GCs to finish but this is fine since we
1099 // released the Thread-list-lock prior to calling this in RequestSynchronousCheckpoint.
1100 art::gc::ScopedGCCriticalSection sgccs(art::Thread::Current(),
1101 art::gc::kGcCauseDebugger,
1102 art::gc::kCollectorTypeDebugger);
1103 wrapped_->Run(self);
1104 }
1105
1106 private:
1107 art::Closure* wrapped_;
1108};
1109
1110bool ThreadUtil::RequestGCSafeSynchronousCheckpoint(art::Thread* thr, art::Closure* function) {
1111 GcCriticalSectionClosure gccsc(function);
1112 return thr->RequestSynchronousCheckpoint(&gccsc);
1113}
1114
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001115} // namespace openjdkjvmti