blob: 99dea540e523a2822d4f61370da0941ad3dce7fc [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"
41#include "gc_root-inl.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080042#include "jni_internal.h"
43#include "mirror/class.h"
44#include "mirror/object-inl.h"
45#include "mirror/string.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070046#include "nativehelper/scoped_local_ref.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080047#include "obj_ptr.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080048#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080049#include "runtime_callbacks.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080050#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070051#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080052#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070053#include "ti_phase.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080054#include "well_known_classes.h"
55
56namespace openjdkjvmti {
57
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070058art::ArtField* ThreadUtil::context_class_loader_ = nullptr;
59
Alex Light1d8a9742017-08-17 11:12:06 -070060struct ThreadCallback : public art::ThreadLifecycleCallback {
Andreas Gampeeafaf572017-01-20 12:34:15 -080061 jthread GetThreadObject(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
62 if (self->GetPeer() == nullptr) {
63 return nullptr;
64 }
65 return self->GetJniEnv()->AddLocalReference<jthread>(self->GetPeer());
66 }
Alex Light1d8a9742017-08-17 11:12:06 -070067
Andreas Gampe983c1752017-01-23 19:46:56 -080068 template <ArtJvmtiEvent kEvent>
69 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080070 DCHECK_EQ(self, art::Thread::Current());
71 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080072 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080073 event_handler->DispatchEvent<kEvent>(self,
74 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
75 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080076 }
77
78 void ThreadStart(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
79 if (!started) {
80 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
81 // started here.
82 if (art::kIsDebugBuild) {
83 std::string name;
84 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080085 if (name != "JDWP" &&
86 name != "Signal Catcher" &&
87 !android::base::StartsWith(name, "Jit thread pool")) {
Alex Light23aa7482017-08-16 10:01:13 -070088 LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
89 << self->GetThreadId();
Andreas Gampeeafaf572017-01-20 12:34:15 -080090 }
91 }
92 return;
93 }
Andreas Gampe983c1752017-01-23 19:46:56 -080094 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080095 }
96
97 void ThreadDeath(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -080098 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080099 }
100
Andreas Gampeeafaf572017-01-20 12:34:15 -0800101 EventHandler* event_handler = nullptr;
102 bool started = false;
103};
104
105ThreadCallback gThreadCallback;
106
107void ThreadUtil::Register(EventHandler* handler) {
108 art::Runtime* runtime = art::Runtime::Current();
109
110 gThreadCallback.started = runtime->IsStarted();
111 gThreadCallback.event_handler = handler;
112
113 art::ScopedThreadStateChange stsc(art::Thread::Current(),
114 art::ThreadState::kWaitingForDebuggerToAttach);
115 art::ScopedSuspendAll ssa("Add thread callback");
116 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
Alex Light1d8a9742017-08-17 11:12:06 -0700117}
118
119void ThreadUtil::VMInitEventSent() {
120 // We should have already started.
121 DCHECK(gThreadCallback.started);
122 // We moved to VMInit. Report the main thread as started (it was attached early, and must not be
123 // reported until Init.
124 gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800125}
126
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700127void ThreadUtil::CacheData() {
Alex Light1d8a9742017-08-17 11:12:06 -0700128 // We must have started since it is now safe to cache our data;
129 gThreadCallback.started = true;
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700130 art::ScopedObjectAccess soa(art::Thread::Current());
131 art::ObjPtr<art::mirror::Class> thread_class =
132 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
133 CHECK(thread_class != nullptr);
134 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
135 "Ljava/lang/ClassLoader;");
136 CHECK(context_class_loader_ != nullptr);
137}
138
Andreas Gampeeafaf572017-01-20 12:34:15 -0800139void ThreadUtil::Unregister() {
140 art::ScopedThreadStateChange stsc(art::Thread::Current(),
141 art::ThreadState::kWaitingForDebuggerToAttach);
142 art::ScopedSuspendAll ssa("Remove thread callback");
143 art::Runtime* runtime = art::Runtime::Current();
144 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
Andreas Gampeeafaf572017-01-20 12:34:15 -0800145}
146
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800147jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
148 art::Thread* self = art::Thread::Current();
149
150 art::ScopedObjectAccess soa(self);
151
152 jthread thread_peer;
153 if (self->IsStillStarting()) {
154 thread_peer = nullptr;
155 } else {
156 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
157 }
158
159 *thread_ptr = thread_peer;
160 return ERR(NONE);
161}
162
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800163// Get the native thread. The spec says a null object denotes the current thread.
Alex Light7ddc23d2017-09-22 15:33:41 -0700164bool ThreadUtil::GetNativeThread(jthread thread,
165 const art::ScopedObjectAccessAlreadyRunnable& soa,
166 /*out*/ art::Thread** thr,
167 /*out*/ jvmtiError* err) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800168 if (thread == nullptr) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700169 *thr = art::Thread::Current();
170 return true;
171 } else if (!soa.Env()->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
172 *err = ERR(INVALID_THREAD);
173 return false;
174 } else {
175 *thr = art::Thread::FromManagedThread(soa, thread);
176 return true;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800177 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700178}
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800179
Alex Light7ddc23d2017-09-22 15:33:41 -0700180bool ThreadUtil::GetAliveNativeThread(jthread thread,
181 const art::ScopedObjectAccessAlreadyRunnable& soa,
182 /*out*/ art::Thread** thr,
183 /*out*/ jvmtiError* err) {
184 if (!GetNativeThread(thread, soa, thr, err)) {
185 return false;
186 } else if (*thr == nullptr || (*thr)->GetState() == art::ThreadState::kTerminated) {
187 *err = ERR(THREAD_NOT_ALIVE);
188 return false;
189 } else {
190 return true;
191 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800192}
193
194jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
195 if (info_ptr == nullptr) {
196 return ERR(NULL_POINTER);
197 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700198 if (!PhaseUtil::IsLivePhase()) {
199 return JVMTI_ERROR_WRONG_PHASE;
200 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800201
Alex Light3ae82532017-07-26 13:59:07 -0700202 art::Thread* self = art::Thread::Current();
203 art::ScopedObjectAccess soa(self);
204 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800205
Alex Light7ddc23d2017-09-22 15:33:41 -0700206 art::Thread* target;
207 jvmtiError err = ERR(INTERNAL);
208 if (!GetNativeThread(thread, soa, &target, &err)) {
209 return err;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800210 }
211
Andreas Gampe54711412017-02-21 12:41:43 -0800212 JvmtiUniquePtr<char[]> name_uptr;
Alex Light3ae82532017-07-26 13:59:07 -0700213 if (target != nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800214 // Have a native thread object, this thread is alive.
215 std::string name;
Alex Light3ae82532017-07-26 13:59:07 -0700216 target->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800217 jvmtiError name_result;
218 name_uptr = CopyString(env, name.c_str(), &name_result);
219 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800220 return name_result;
221 }
Andreas Gampe54711412017-02-21 12:41:43 -0800222 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800223
Alex Light3ae82532017-07-26 13:59:07 -0700224 info_ptr->priority = target->GetNativePriority();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800225
Alex Light3ae82532017-07-26 13:59:07 -0700226 info_ptr->is_daemon = target->IsDaemon();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800227
Alex Light3ae82532017-07-26 13:59:07 -0700228 art::ObjPtr<art::mirror::Object> peer = target->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800229
230 // ThreadGroup.
231 if (peer != nullptr) {
232 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
233 CHECK(f != nullptr);
234 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
235 info_ptr->thread_group = group == nullptr
236 ? nullptr
237 : soa.AddLocalReference<jthreadGroup>(group);
238 } else {
239 info_ptr->thread_group = nullptr;
240 }
241
242 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700243 DCHECK(context_class_loader_ != nullptr);
244 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
245 ? context_class_loader_->GetObject(peer)
246 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800247 info_ptr->context_class_loader = ccl == nullptr
248 ? nullptr
249 : soa.AddLocalReference<jobject>(ccl);
250 } else {
251 // Only the peer. This thread has either not been started, or is dead. Read things from
252 // the Java side.
253 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
254
255 // Name.
256 {
257 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
258 CHECK(f != nullptr);
259 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
260 std::string name_cpp;
261 const char* name_cstr;
262 if (name != nullptr) {
263 name_cpp = name->AsString()->ToModifiedUtf8();
264 name_cstr = name_cpp.c_str();
265 } else {
266 name_cstr = "";
267 }
Andreas Gampe54711412017-02-21 12:41:43 -0800268 jvmtiError name_result;
269 name_uptr = CopyString(env, name_cstr, &name_result);
270 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800271 return name_result;
272 }
Andreas Gampe54711412017-02-21 12:41:43 -0800273 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800274 }
275
276 // Priority.
277 {
278 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
279 CHECK(f != nullptr);
280 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
281 }
282
283 // Daemon.
284 {
285 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
286 CHECK(f != nullptr);
287 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
288 }
289
290 // ThreadGroup.
291 {
292 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
293 CHECK(f != nullptr);
294 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
295 info_ptr->thread_group = group == nullptr
296 ? nullptr
297 : soa.AddLocalReference<jthreadGroup>(group);
298 }
299
300 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700301 DCHECK(context_class_loader_ != nullptr);
302 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
303 ? context_class_loader_->GetObject(peer)
304 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800305 info_ptr->context_class_loader = ccl == nullptr
306 ? nullptr
307 : soa.AddLocalReference<jobject>(ccl);
308 }
309
310 name_uptr.release();
311
312 return ERR(NONE);
313}
314
Alex Light1f0a22f2017-07-17 12:55:59 -0700315struct InternalThreadState {
316 art::Thread* native_thread;
317 art::ThreadState art_state;
318 int thread_user_code_suspend_count;
319};
320
321// Return the thread's (or current thread, if null) thread state.
Alex Light7ddc23d2017-09-22 15:33:41 -0700322static InternalThreadState GetNativeThreadState(art::Thread* target)
Alex Light1f0a22f2017-07-17 12:55:59 -0700323 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Light3ae82532017-07-26 13:59:07 -0700324 REQUIRES(art::Locks::thread_list_lock_, art::Locks::user_code_suspension_lock_) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700325 InternalThreadState thread_state = {};
Alex Light7ddc23d2017-09-22 15:33:41 -0700326 art::MutexLock tscl_mu(art::Thread::Current(), *art::Locks::thread_suspend_count_lock_);
327 thread_state.native_thread = target;
328 if (target == nullptr || target->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700329 thread_state.art_state = art::ThreadState::kStarting;
330 thread_state.thread_user_code_suspend_count = 0;
331 } else {
Alex Light7ddc23d2017-09-22 15:33:41 -0700332 thread_state.art_state = target->GetState();
333 thread_state.thread_user_code_suspend_count = target->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800334 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700335 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800336}
337
Alex Light1f0a22f2017-07-17 12:55:59 -0700338static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
339 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800340 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
341
Alex Light1f0a22f2017-07-17 12:55:59 -0700342 if (state.thread_user_code_suspend_count != 0) {
Alex Light597adad2017-10-16 16:11:42 -0700343 // Suspended can be set with any thread state so check it here. Even if the thread isn't in
344 // 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 -0800345 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
346 // Note: We do not have data about the previous state. Otherwise we should load the previous
347 // state here.
348 }
349
Alex Light1f0a22f2017-07-17 12:55:59 -0700350 if (state.native_thread->IsInterrupted()) {
Alex Light597adad2017-10-16 16:11:42 -0700351 // Interrupted can be set with any thread state so check it here.
Alex Light1f0a22f2017-07-17 12:55:59 -0700352 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
353 }
354
Alex Light597adad2017-10-16 16:11:42 -0700355 // Enumerate all the thread states and fill in the other bits. This contains the results of
356 // following the decision tree in the JVMTI spec GetThreadState documentation.
357 switch (internal_thread_state) {
358 case art::ThreadState::kRunnable:
359 case art::ThreadState::kWaitingWeakGcRootRead:
360 case art::ThreadState::kSuspended:
361 // These are all simply runnable.
362 // kRunnable is self-explanatory.
363 // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table
364 // so we want to keep it marked as runnable.
365 // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done
366 // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
367 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
368 break;
369 case art::ThreadState::kNative:
370 // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any
371 // state but we don't have the information to know if it should be present for any but the
372 // kNative state.
373 jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
374 JVMTI_THREAD_STATE_RUNNABLE);
375 break;
376 case art::ThreadState::kBlocked:
377 // Blocked is one of the top level states so it sits alone.
378 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
379 break;
380 case art::ThreadState::kWaiting:
381 // Object.wait() so waiting, indefinitely, in object.wait.
382 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
383 JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
384 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
385 break;
386 case art::ThreadState::kTimedWaiting:
387 // Object.wait(long) so waiting, with timeout, in object.wait.
388 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
389 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
390 JVMTI_THREAD_STATE_IN_OBJECT_WAIT);
391 break;
392 case art::ThreadState::kSleeping:
393 // In object.sleep. This is a timed wait caused by sleep.
394 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
395 JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
396 JVMTI_THREAD_STATE_SLEEPING);
397 break;
398 // TODO We might want to print warnings if we have the debugger running while JVMTI agents are
399 // attached.
400 case art::ThreadState::kWaitingForDebuggerSend:
401 case art::ThreadState::kWaitingForDebuggerToAttach:
402 case art::ThreadState::kWaitingInMainDebuggerLoop:
403 case art::ThreadState::kWaitingForDebuggerSuspension:
404 case art::ThreadState::kWaitingForLockInflation:
405 case art::ThreadState::kWaitingForTaskProcessor:
406 case art::ThreadState::kWaitingForGcToComplete:
407 case art::ThreadState::kWaitingForCheckPointsToRun:
408 case art::ThreadState::kWaitingPerformingGc:
409 case art::ThreadState::kWaitingForJniOnLoad:
410 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
411 case art::ThreadState::kWaitingForSignalCatcherOutput:
412 case art::ThreadState::kWaitingForDeoptimization:
413 case art::ThreadState::kWaitingForMethodTracingStart:
414 case art::ThreadState::kWaitingForVisitObjects:
415 case art::ThreadState::kWaitingForGetObjectsAllocated:
416 case art::ThreadState::kWaitingForGcThreadFlip:
417 // All of these are causing the thread to wait for an indeterminate amount of time but isn't
418 // caused by sleep, park, or object#wait.
419 jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
420 JVMTI_THREAD_STATE_WAITING_INDEFINITELY);
421 break;
422 case art::ThreadState::kStarting:
423 case art::ThreadState::kTerminated:
424 // We only call this if we are alive so we shouldn't see either of these states.
425 LOG(FATAL) << "Should not be in state " << internal_thread_state;
426 UNREACHABLE();
Andreas Gampe72c19832017-01-12 13:22:16 -0800427 }
Alex Light597adad2017-10-16 16:11:42 -0700428 // TODO: PARKED. We'll have to inspect the stack.
Andreas Gampe72c19832017-01-12 13:22:16 -0800429
430 return jvmti_state;
431}
432
Alex Light1f0a22f2017-07-17 12:55:59 -0700433static jint GetJavaStateFromInternal(const InternalThreadState& state) {
434 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800435 case art::ThreadState::kTerminated:
436 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
437
438 case art::ThreadState::kRunnable:
439 case art::ThreadState::kNative:
440 case art::ThreadState::kWaitingWeakGcRootRead:
441 case art::ThreadState::kSuspended:
442 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
443
444 case art::ThreadState::kTimedWaiting:
445 case art::ThreadState::kSleeping:
446 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
447
448 case art::ThreadState::kBlocked:
449 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
450
451 case art::ThreadState::kStarting:
452 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
453
454 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700455 case art::ThreadState::kWaitingForTaskProcessor:
456 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800457 case art::ThreadState::kWaitingForGcToComplete:
458 case art::ThreadState::kWaitingPerformingGc:
459 case art::ThreadState::kWaitingForCheckPointsToRun:
460 case art::ThreadState::kWaitingForDebuggerSend:
461 case art::ThreadState::kWaitingForDebuggerToAttach:
462 case art::ThreadState::kWaitingInMainDebuggerLoop:
463 case art::ThreadState::kWaitingForDebuggerSuspension:
464 case art::ThreadState::kWaitingForDeoptimization:
465 case art::ThreadState::kWaitingForGetObjectsAllocated:
466 case art::ThreadState::kWaitingForJniOnLoad:
467 case art::ThreadState::kWaitingForSignalCatcherOutput:
468 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
469 case art::ThreadState::kWaitingForMethodTracingStart:
470 case art::ThreadState::kWaitingForVisitObjects:
471 case art::ThreadState::kWaitingForGcThreadFlip:
472 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
473 }
474 LOG(FATAL) << "Unreachable";
475 UNREACHABLE();
476}
477
Alex Light1f0a22f2017-07-17 12:55:59 -0700478// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700479void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700480 art::ScopedObjectAccess soa(self);
481 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
482 self->FullSuspendCheck();
483}
484
Alex Light23aa7482017-08-16 10:01:13 -0700485bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
486 DCHECK(self == art::Thread::Current());
487 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
488 return self->GetUserCodeSuspendCount() != 0;
489}
490
491bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
492 DCHECK(self == art::Thread::Current());
493 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
494 return WouldSuspendForUserCodeLocked(self);
495}
496
Andreas Gampe72c19832017-01-12 13:22:16 -0800497jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
498 jthread thread,
499 jint* thread_state_ptr) {
500 if (thread_state_ptr == nullptr) {
501 return ERR(NULL_POINTER);
502 }
503
Alex Light1f0a22f2017-07-17 12:55:59 -0700504 art::Thread* self = art::Thread::Current();
505 InternalThreadState state = {};
506 // Loop since we need to bail out and try again if we would end up getting suspended while holding
507 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
508 // release the lock, wait to get resumed and try again.
509 do {
510 SuspendCheck(self);
511 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700512 if (WouldSuspendForUserCodeLocked(self)) {
513 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
514 // a user-code suspension. We retry and do another SuspendCheck to clear this.
515 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700516 }
517 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700518 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700519 jvmtiError err = ERR(INTERNAL);
520 art::Thread* target = nullptr;
521 if (!GetNativeThread(thread, soa, &target, &err)) {
522 return err;
523 }
524 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700525 if (state.art_state == art::ThreadState::kStarting) {
526 break;
527 }
528 DCHECK(state.native_thread != nullptr);
529
530 // Translate internal thread state to JVMTI and Java state.
531 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
532
533 // Java state is derived from nativeGetState.
534 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
535 // different mask if a thread got suspended due to user-code. However, this is for
536 // consistency with the Java view.
537 jint java_state = GetJavaStateFromInternal(state);
538
539 *thread_state_ptr = jvmti_state | java_state;
540
541 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700542 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800543
Alex Light3ae82532017-07-26 13:59:07 -0700544 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800545
Alex Light3ae82532017-07-26 13:59:07 -0700546 if (thread == nullptr) {
547 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
548 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800549 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800550
Alex Light3ae82532017-07-26 13:59:07 -0700551 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700552 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800553
Alex Light3ae82532017-07-26 13:59:07 -0700554 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700555 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
556 art::ObjPtr<art::mirror::Class> thread_klass =
557 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
558 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
559 return ERR(INVALID_THREAD);
560 }
561 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700562 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700563 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700564 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
565 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
566 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
567 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800568 return ERR(NONE);
569}
570
Andreas Gampe85807442017-01-13 14:40:58 -0800571jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
572 jint* threads_count_ptr,
573 jthread** threads_ptr) {
574 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
575 return ERR(NULL_POINTER);
576 }
577
578 art::Thread* current = art::Thread::Current();
579
580 art::ScopedObjectAccess soa(current);
581
582 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
583 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
584
585 std::vector<art::ObjPtr<art::mirror::Object>> peers;
586
587 for (art::Thread* thread : thread_list) {
588 // Skip threads that are still starting.
589 if (thread->IsStillStarting()) {
590 continue;
591 }
592
Andreas Gampe202f85a2017-02-06 10:23:26 -0800593 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800594 if (peer != nullptr) {
595 peers.push_back(peer);
596 }
597 }
598
599 if (peers.empty()) {
600 *threads_count_ptr = 0;
601 *threads_ptr = nullptr;
602 } else {
603 unsigned char* data;
604 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
605 if (data_result != ERR(NONE)) {
606 return data_result;
607 }
608 jthread* threads = reinterpret_cast<jthread*>(data);
609 for (size_t i = 0; i != peers.size(); ++i) {
610 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
611 }
612
613 *threads_count_ptr = static_cast<jint>(peers.size());
614 *threads_ptr = threads;
615 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800616 return ERR(NONE);
617}
Andreas Gampe85807442017-01-13 14:40:58 -0800618
Alex Light092a4042017-07-12 08:46:44 -0700619// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
620// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
621// data but we only have a single slot in Thread objects to store data.
622struct JvmtiGlobalTLSData {
623 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
624};
625
626static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
627 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
628 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
629 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
630 if (global_tls != nullptr) {
631 global_tls->data.erase(env);
632 }
633}
634
635void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
636 art::Thread* self = art::Thread::Current();
637 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
638 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
639 list->ForEach(RemoveTLSData, env);
640}
641
642jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
643 art::Thread* self = art::Thread::Current();
644 art::ScopedObjectAccess soa(self);
645 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700646 art::Thread* target = nullptr;
647 jvmtiError err = ERR(INTERNAL);
648 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
649 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800650 }
651
Alex Light092a4042017-07-12 08:46:44 -0700652 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
653 if (global_tls == nullptr) {
654 target->SetCustomTLS(new JvmtiGlobalTLSData);
655 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
656 }
657
658 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800659
660 return ERR(NONE);
661}
662
Alex Light092a4042017-07-12 08:46:44 -0700663jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800664 jthread thread,
665 void** data_ptr) {
666 if (data_ptr == nullptr) {
667 return ERR(NULL_POINTER);
668 }
669
Alex Light092a4042017-07-12 08:46:44 -0700670 art::Thread* self = art::Thread::Current();
671 art::ScopedObjectAccess soa(self);
672 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700673 art::Thread* target = nullptr;
674 jvmtiError err = ERR(INTERNAL);
675 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
676 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800677 }
678
Alex Light092a4042017-07-12 08:46:44 -0700679 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
680 if (global_tls == nullptr) {
681 *data_ptr = nullptr;
682 return OK;
683 }
684 auto it = global_tls->data.find(env);
685 if (it != global_tls->data.end()) {
686 *data_ptr = const_cast<void*>(it->second);
687 } else {
688 *data_ptr = nullptr;
689 }
690
Andreas Gampe85807442017-01-13 14:40:58 -0800691 return ERR(NONE);
692}
693
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800694struct AgentData {
695 const void* arg;
696 jvmtiStartFunction proc;
697 jthread thread;
698 JavaVM* java_vm;
699 jvmtiEnv* jvmti_env;
700 jint priority;
701};
702
703static void* AgentCallback(void* arg) {
704 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
705 CHECK(data->thread != nullptr);
706
707 // We already have a peer. So call our special Attach function.
708 art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread);
Alex Light739bf722017-10-20 13:14:24 -0700709 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800710 // The name in Attach() is only for logging. Set the thread name. This is important so
711 // that the thread is no longer seen as starting up.
712 {
713 art::ScopedObjectAccess soa(self);
714 self->SetThreadName("JVMTI Agent thread");
715 }
716
717 // Release the peer.
718 JNIEnv* env = self->GetJniEnv();
719 env->DeleteGlobalRef(data->thread);
720 data->thread = nullptr;
721
Alex Light739bf722017-10-20 13:14:24 -0700722 {
723 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
724 // before going into the provided code.
725 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
726 art::Runtime::Current()->EndThreadBirth();
727 }
728
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800729 // Run the agent code.
730 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
731
732 // Detach the thread.
733 int detach_result = data->java_vm->DetachCurrentThread();
734 CHECK_EQ(detach_result, 0);
735
736 return nullptr;
737}
738
739jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
740 jthread thread,
741 jvmtiStartFunction proc,
742 const void* arg,
743 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700744 if (!PhaseUtil::IsLivePhase()) {
745 return ERR(WRONG_PHASE);
746 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800747 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
748 return ERR(INVALID_PRIORITY);
749 }
750 JNIEnv* env = art::Thread::Current()->GetJniEnv();
751 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
752 return ERR(INVALID_THREAD);
753 }
754 if (proc == nullptr) {
755 return ERR(NULL_POINTER);
756 }
757
Alex Light739bf722017-10-20 13:14:24 -0700758 {
759 art::Runtime* runtime = art::Runtime::Current();
760 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
761 if (runtime->IsShuttingDownLocked()) {
762 // The runtime is shutting down so we cannot create new threads.
763 // TODO It's not fully clear from the spec what we should do here. We aren't yet in
764 // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now
765 // impossible. Existing agents don't seem to generally do anything with this return value so
766 // it doesn't matter too much. We could do something like sending a fake ThreadStart event
767 // even though code is never actually run.
768 return ERR(INTERNAL);
769 }
770 runtime->StartThreadBirth();
771 }
772
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800773 std::unique_ptr<AgentData> data(new AgentData);
774 data->arg = arg;
775 data->proc = proc;
776 // We need a global ref for Java objects, as local refs will be invalid.
777 data->thread = env->NewGlobalRef(thread);
778 data->java_vm = art::Runtime::Current()->GetJavaVM();
779 data->jvmti_env = jvmti_env;
780 data->priority = priority;
781
782 pthread_t pthread;
783 int pthread_create_result = pthread_create(&pthread,
Alex Light739bf722017-10-20 13:14:24 -0700784 nullptr,
785 &AgentCallback,
786 reinterpret_cast<void*>(data.get()));
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800787 if (pthread_create_result != 0) {
Alex Light739bf722017-10-20 13:14:24 -0700788 // If the create succeeded the other thread will call EndThreadBirth.
789 art::Runtime* runtime = art::Runtime::Current();
790 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
791 runtime->EndThreadBirth();
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800792 return ERR(INTERNAL);
793 }
794 data.release();
795
796 return ERR(NONE);
797}
798
Alex Light88fd7202017-06-30 08:31:59 -0700799jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700800 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700801 // Loop since we need to bail out and try again if we would end up getting suspended while holding
802 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
803 // release the lock, wait to get resumed and try again.
804 do {
805 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
806 // another SuspendThread in the middle of suspending something else potentially causing a
807 // deadlock. We need to do this in the loop because if we ended up back here then we had
808 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
809 // before continuing.
810 SuspendCheck(self);
811 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700812 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700813 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
814 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700815 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700816 }
Alex Light23aa7482017-08-16 10:01:13 -0700817 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700818 {
819 art::ScopedObjectAccess soa(self);
820 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700821 art::Thread* target = nullptr;
822 jvmtiError err = ERR(INTERNAL);
823 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
824 return err;
825 }
Alex Light88fd7202017-06-30 08:31:59 -0700826 art::ThreadState state = target->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700827 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Light88fd7202017-06-30 08:31:59 -0700828 return ERR(THREAD_NOT_ALIVE);
Alex Light3ae82532017-07-26 13:59:07 -0700829 } else {
830 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
831 if (target->GetUserCodeSuspendCount() != 0) {
832 return ERR(THREAD_SUSPENDED);
833 }
Alex Light88fd7202017-06-30 08:31:59 -0700834 }
835 }
Alex Light3ae82532017-07-26 13:59:07 -0700836 bool timeout = true;
837 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
838 target_jthread,
839 /* request_suspension */ true,
840 art::SuspendReason::kForUserCode,
841 &timeout);
842 if (ret_target == nullptr && !timeout) {
843 // TODO It would be good to get more information about why exactly the thread failed to
844 // suspend.
845 return ERR(INTERNAL);
846 } else if (!timeout) {
847 // we didn't time out and got a result.
848 return OK;
849 }
850 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700851 } while (true);
852 UNREACHABLE();
853}
854
855jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
856 CHECK(self == art::Thread::Current());
857 {
858 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
859 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
860 if (self->GetUserCodeSuspendCount() != 0) {
861 // This can only happen if we race with another thread to suspend 'self' and we lose.
862 return ERR(THREAD_SUSPENDED);
863 }
864 // We shouldn't be able to fail this.
865 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
866 // TODO More specific error would be nice.
867 return ERR(INTERNAL);
868 }
869 }
870 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
871 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
872 // to go to sleep until we are resumed.
873 SuspendCheck(self);
874 return OK;
875}
876
877jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
878 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700879 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700880 {
881 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700882 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700883 art::Thread* target = nullptr;
884 jvmtiError err = ERR(INTERNAL);
885 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
886 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700887 } else if (target == self) {
888 target_is_self = true;
889 }
Alex Light88fd7202017-06-30 08:31:59 -0700890 }
Alex Light3ae82532017-07-26 13:59:07 -0700891 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700892 return SuspendSelf(self);
893 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700894 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700895 }
896}
897
898jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
899 jthread thread) {
900 if (thread == nullptr) {
901 return ERR(NULL_POINTER);
902 }
903 art::Thread* self = art::Thread::Current();
904 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700905 // Retry until we know we won't get suspended by user code while resuming something.
906 do {
907 SuspendCheck(self);
908 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700909 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700910 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
911 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700912 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700913 }
Alex Light3ae82532017-07-26 13:59:07 -0700914 // From now on we know we cannot get suspended by user-code.
915 {
916 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
917 // have the 'suspend_lock' locked here.
918 art::ScopedObjectAccess soa(self);
919 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700920 jvmtiError err = ERR(INTERNAL);
921 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
922 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700923 } else if (target == self) {
924 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
925 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
926 // about current state since it's all concurrent.
927 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700928 }
929 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
930 // cannot tell why resume failed.
931 {
932 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
933 if (target->GetUserCodeSuspendCount() == 0) {
934 return ERR(THREAD_NOT_SUSPENDED);
935 }
936 }
937 }
938 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
939 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
940 DCHECK(target != self);
941 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
942 art::SuspendReason::kForUserCode)) {
943 // TODO Give a better error.
944 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
945 return ERR(INTERNAL);
946 } else {
947 return OK;
948 }
949 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700950}
951
Alex Light7ddc23d2017-09-22 15:33:41 -0700952static bool IsCurrentThread(jthread thr) {
953 if (thr == nullptr) {
954 return true;
955 }
956 art::Thread* self = art::Thread::Current();
957 art::ScopedObjectAccess soa(self);
958 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
959 art::Thread* target = nullptr;
960 jvmtiError err_unused = ERR(INTERNAL);
961 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
962 return target == self;
963 } else {
964 return false;
965 }
966}
967
Alex Light88fd7202017-06-30 08:31:59 -0700968// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
969// since we can have threads in the list multiple times. This generally doesn't matter unless the
970// current thread is present multiple times. In that case we need to suspend only once and either
971// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
972// it didn't. We also want to handle the current thread last to make the behavior of the code
973// simpler to understand.
974jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
975 jint request_count,
976 const jthread* threads,
977 jvmtiError* results) {
978 if (request_count == 0) {
979 return ERR(ILLEGAL_ARGUMENT);
980 } else if (results == nullptr || threads == nullptr) {
981 return ERR(NULL_POINTER);
982 }
983 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
984 // running thread. These indexes we need to handle specially since we need to only actually
985 // suspend a single time.
986 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -0700987 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700988 if (IsCurrentThread(threads[i])) {
989 current_thread_indexes.push_back(i);
990 } else {
991 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -0700992 }
Alex Light88fd7202017-06-30 08:31:59 -0700993 }
994 if (!current_thread_indexes.empty()) {
995 jint first_current_thread_index = current_thread_indexes[0];
996 // Suspend self.
997 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
998 results[first_current_thread_index] = res;
999 // Fill in the rest of the error values as appropriate.
1000 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
1001 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
1002 results[*it] = other_results;
1003 }
1004 }
1005 return OK;
1006}
1007
1008jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
1009 jint request_count,
1010 const jthread* threads,
1011 jvmtiError* results) {
1012 if (request_count == 0) {
1013 return ERR(ILLEGAL_ARGUMENT);
1014 } else if (results == nullptr || threads == nullptr) {
1015 return ERR(NULL_POINTER);
1016 }
1017 for (jint i = 0; i < request_count; i++) {
1018 results[i] = env->ResumeThread(threads[i]);
1019 }
1020 return OK;
1021}
1022
Alex Light54d39dc2017-09-25 17:00:16 -07001023jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
1024 jthread thread,
1025 jobject exception) {
1026 art::Thread* self = art::Thread::Current();
1027 art::ScopedObjectAccess soa(self);
1028 art::StackHandleScope<1> hs(self);
1029 if (exception == nullptr) {
1030 return ERR(INVALID_OBJECT);
1031 }
1032 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
1033 if (!obj->GetClass()->IsThrowableClass()) {
1034 return ERR(INVALID_OBJECT);
1035 }
1036 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -07001037 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001038 art::Thread* target = nullptr;
1039 jvmtiError err = ERR(INTERNAL);
1040 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001041 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -07001042 return err;
1043 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
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(THREAD_NOT_ALIVE);
1046 }
1047 struct StopThreadClosure : public art::Closure {
1048 public:
1049 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
1050
1051 void Run(art::Thread* me) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1052 // Make sure the thread is prepared to notice the exception.
1053 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
1054 me->SetAsyncException(exception_.Get());
1055 // Wake up the thread if it is sleeping.
1056 me->Notify();
1057 }
1058
1059 private:
1060 art::Handle<art::mirror::Throwable> exception_;
1061 };
1062 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -07001063 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light54d39dc2017-09-25 17:00:16 -07001064 if (target->RequestSynchronousCheckpoint(&c)) {
1065 return OK;
1066 } else {
1067 // Something went wrong, probably the thread died.
1068 return ERR(THREAD_NOT_ALIVE);
1069 }
1070}
1071
1072jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1073 art::Thread* self = art::Thread::Current();
1074 art::ScopedObjectAccess soa(self);
1075 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1076 art::Thread* target = nullptr;
1077 jvmtiError err = ERR(INTERNAL);
1078 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1079 return err;
1080 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1081 return ERR(THREAD_NOT_ALIVE);
1082 }
1083 target->Interrupt(self);
1084 return OK;
1085}
1086
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001087} // namespace openjdkjvmti