blob: fe0e3bbf44481c466bd98a413201dd13fb9ef774 [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"
46#include "obj_ptr.h"
Andreas Gampedb6c2ab2017-03-28 17:28:32 -070047#include "ti_phase.h"
Andreas Gampef26bf2d2017-01-13 16:47:14 -080048#include "runtime.h"
Andreas Gampeeafaf572017-01-20 12:34:15 -080049#include "runtime_callbacks.h"
50#include "ScopedLocalRef.h"
Andreas Gampeaf13ab92017-01-11 20:57:40 -080051#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070052#include "thread-current-inl.h"
Andreas Gampe85807442017-01-13 14:40:58 -080053#include "thread_list.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
Andreas Gampeeafaf572017-01-20 12:34:15 -080060struct ThreadCallback : public art::ThreadLifecycleCallback, public art::RuntimePhaseCallback {
61 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 }
Andreas Gampe983c1752017-01-23 19:46:56 -080067 template <ArtJvmtiEvent kEvent>
68 void Post(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080069 DCHECK_EQ(self, art::Thread::Current());
70 ScopedLocalRef<jthread> thread(self->GetJniEnv(), GetThreadObject(self));
Andreas Gampee6377462017-01-20 17:37:50 -080071 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -080072 event_handler->DispatchEvent<kEvent>(self,
73 reinterpret_cast<JNIEnv*>(self->GetJniEnv()),
74 thread.get());
Andreas Gampeeafaf572017-01-20 12:34:15 -080075 }
76
77 void ThreadStart(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
78 if (!started) {
79 // Runtime isn't started. We only expect at most the signal handler or JIT threads to be
80 // started here.
81 if (art::kIsDebugBuild) {
82 std::string name;
83 self->GetThreadName(name);
Alex Light5bd09542017-02-09 16:01:32 -080084 if (name != "JDWP" &&
85 name != "Signal Catcher" &&
86 !android::base::StartsWith(name, "Jit thread pool")) {
Andreas Gampeeafaf572017-01-20 12:34:15 -080087 LOG(FATAL) << "Unexpected thread before start: " << name;
88 }
89 }
90 return;
91 }
Andreas Gampe983c1752017-01-23 19:46:56 -080092 Post<ArtJvmtiEvent::kThreadStart>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080093 }
94
95 void ThreadDeath(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe983c1752017-01-23 19:46:56 -080096 Post<ArtJvmtiEvent::kThreadEnd>(self);
Andreas Gampeeafaf572017-01-20 12:34:15 -080097 }
98
99 void NextRuntimePhase(RuntimePhase phase) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
100 if (phase == RuntimePhase::kInit) {
101 // We moved to VMInit. Report the main thread as started (it was attached early, and must
102 // not be reported until Init.
103 started = true;
Andreas Gampe983c1752017-01-23 19:46:56 -0800104 Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
Andreas Gampeeafaf572017-01-20 12:34:15 -0800105 }
106 }
107
108 EventHandler* event_handler = nullptr;
109 bool started = false;
110};
111
112ThreadCallback gThreadCallback;
113
114void ThreadUtil::Register(EventHandler* handler) {
115 art::Runtime* runtime = art::Runtime::Current();
116
117 gThreadCallback.started = runtime->IsStarted();
118 gThreadCallback.event_handler = handler;
119
120 art::ScopedThreadStateChange stsc(art::Thread::Current(),
121 art::ThreadState::kWaitingForDebuggerToAttach);
122 art::ScopedSuspendAll ssa("Add thread callback");
123 runtime->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&gThreadCallback);
124 runtime->GetRuntimeCallbacks()->AddRuntimePhaseCallback(&gThreadCallback);
125}
126
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700127void ThreadUtil::CacheData() {
128 art::ScopedObjectAccess soa(art::Thread::Current());
129 art::ObjPtr<art::mirror::Class> thread_class =
130 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
131 CHECK(thread_class != nullptr);
132 context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader",
133 "Ljava/lang/ClassLoader;");
134 CHECK(context_class_loader_ != nullptr);
135}
136
Andreas Gampeeafaf572017-01-20 12:34:15 -0800137void ThreadUtil::Unregister() {
138 art::ScopedThreadStateChange stsc(art::Thread::Current(),
139 art::ThreadState::kWaitingForDebuggerToAttach);
140 art::ScopedSuspendAll ssa("Remove thread callback");
141 art::Runtime* runtime = art::Runtime::Current();
142 runtime->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&gThreadCallback);
143 runtime->GetRuntimeCallbacks()->RemoveRuntimePhaseCallback(&gThreadCallback);
144}
145
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800146jvmtiError ThreadUtil::GetCurrentThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread* thread_ptr) {
147 art::Thread* self = art::Thread::Current();
148
149 art::ScopedObjectAccess soa(self);
150
151 jthread thread_peer;
152 if (self->IsStillStarting()) {
153 thread_peer = nullptr;
154 } else {
155 thread_peer = soa.AddLocalReference<jthread>(self->GetPeer());
156 }
157
158 *thread_ptr = thread_peer;
159 return ERR(NONE);
160}
161
Alex Light092a4042017-07-12 08:46:44 -0700162static art::Thread* GetNativeThreadLocked(jthread thread,
163 const art::ScopedObjectAccessAlreadyRunnable& soa)
164 REQUIRES_SHARED(art::Locks::mutator_lock_)
165 REQUIRES(art::Locks::thread_list_lock_) {
166 if (thread == nullptr) {
167 return art::Thread::Current();
168 }
169
170 return art::Thread::FromManagedThread(soa, thread);
171}
172
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800173// Get the native thread. The spec says a null object denotes the current thread.
174static art::Thread* GetNativeThread(jthread thread,
175 const art::ScopedObjectAccessAlreadyRunnable& soa)
176 REQUIRES_SHARED(art::Locks::mutator_lock_) {
177 if (thread == nullptr) {
178 return art::Thread::Current();
179 }
180
181 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
182 return art::Thread::FromManagedThread(soa, thread);
183}
184
185jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
186 if (info_ptr == nullptr) {
187 return ERR(NULL_POINTER);
188 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700189 if (!PhaseUtil::IsLivePhase()) {
190 return JVMTI_ERROR_WRONG_PHASE;
191 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800192
193 art::ScopedObjectAccess soa(art::Thread::Current());
194
195 art::Thread* self = GetNativeThread(thread, soa);
196 if (self == nullptr && thread == nullptr) {
197 return ERR(INVALID_THREAD);
198 }
199
Andreas Gampe54711412017-02-21 12:41:43 -0800200 JvmtiUniquePtr<char[]> name_uptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800201 if (self != nullptr) {
202 // Have a native thread object, this thread is alive.
203 std::string name;
204 self->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800205 jvmtiError name_result;
206 name_uptr = CopyString(env, name.c_str(), &name_result);
207 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800208 return name_result;
209 }
Andreas Gampe54711412017-02-21 12:41:43 -0800210 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800211
212 info_ptr->priority = self->GetNativePriority();
213
214 info_ptr->is_daemon = self->IsDaemon();
215
Andreas Gampe202f85a2017-02-06 10:23:26 -0800216 art::ObjPtr<art::mirror::Object> peer = self->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800217
218 // ThreadGroup.
219 if (peer != nullptr) {
220 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
221 CHECK(f != nullptr);
222 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
223 info_ptr->thread_group = group == nullptr
224 ? nullptr
225 : soa.AddLocalReference<jthreadGroup>(group);
226 } else {
227 info_ptr->thread_group = nullptr;
228 }
229
230 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700231 DCHECK(context_class_loader_ != nullptr);
232 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
233 ? context_class_loader_->GetObject(peer)
234 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800235 info_ptr->context_class_loader = ccl == nullptr
236 ? nullptr
237 : soa.AddLocalReference<jobject>(ccl);
238 } else {
239 // Only the peer. This thread has either not been started, or is dead. Read things from
240 // the Java side.
241 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
242
243 // Name.
244 {
245 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
246 CHECK(f != nullptr);
247 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
248 std::string name_cpp;
249 const char* name_cstr;
250 if (name != nullptr) {
251 name_cpp = name->AsString()->ToModifiedUtf8();
252 name_cstr = name_cpp.c_str();
253 } else {
254 name_cstr = "";
255 }
Andreas Gampe54711412017-02-21 12:41:43 -0800256 jvmtiError name_result;
257 name_uptr = CopyString(env, name_cstr, &name_result);
258 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800259 return name_result;
260 }
Andreas Gampe54711412017-02-21 12:41:43 -0800261 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800262 }
263
264 // Priority.
265 {
266 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
267 CHECK(f != nullptr);
268 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
269 }
270
271 // Daemon.
272 {
273 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
274 CHECK(f != nullptr);
275 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
276 }
277
278 // ThreadGroup.
279 {
280 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
281 CHECK(f != nullptr);
282 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
283 info_ptr->thread_group = group == nullptr
284 ? nullptr
285 : soa.AddLocalReference<jthreadGroup>(group);
286 }
287
288 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700289 DCHECK(context_class_loader_ != nullptr);
290 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
291 ? context_class_loader_->GetObject(peer)
292 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800293 info_ptr->context_class_loader = ccl == nullptr
294 ? nullptr
295 : soa.AddLocalReference<jobject>(ccl);
296 }
297
298 name_uptr.release();
299
300 return ERR(NONE);
301}
302
Alex Light1f0a22f2017-07-17 12:55:59 -0700303struct InternalThreadState {
304 art::Thread* native_thread;
305 art::ThreadState art_state;
306 int thread_user_code_suspend_count;
307};
308
309// Return the thread's (or current thread, if null) thread state.
310static InternalThreadState GetNativeThreadState(jthread thread,
311 const art::ScopedObjectAccessAlreadyRunnable& soa)
312 REQUIRES_SHARED(art::Locks::mutator_lock_)
313 REQUIRES(art::Locks::user_code_suspension_lock_) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800314 art::Thread* self = nullptr;
Alex Light1f0a22f2017-07-17 12:55:59 -0700315 art::MutexLock tll_mu(soa.Self(), *art::Locks::thread_list_lock_);
Andreas Gampe72c19832017-01-12 13:22:16 -0800316 if (thread == nullptr) {
317 self = art::Thread::Current();
318 } else {
319 self = art::Thread::FromManagedThread(soa, thread);
320 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700321 InternalThreadState thread_state = {};
322 art::MutexLock tscl_mu(soa.Self(), *art::Locks::thread_suspend_count_lock_);
323 thread_state.native_thread = self;
Andreas Gampe72c19832017-01-12 13:22:16 -0800324 if (self == nullptr || self->IsStillStarting()) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700325 thread_state.art_state = art::ThreadState::kStarting;
326 thread_state.thread_user_code_suspend_count = 0;
327 } else {
328 thread_state.art_state = self->GetState();
329 thread_state.thread_user_code_suspend_count = self->GetUserCodeSuspendCount();
Andreas Gampe72c19832017-01-12 13:22:16 -0800330 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700331 return thread_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800332}
333
Alex Light1f0a22f2017-07-17 12:55:59 -0700334static jint GetJvmtiThreadStateFromInternal(const InternalThreadState& state) {
335 art::ThreadState internal_thread_state = state.art_state;
Andreas Gampe72c19832017-01-12 13:22:16 -0800336 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
337
Alex Light1f0a22f2017-07-17 12:55:59 -0700338 if (state.thread_user_code_suspend_count != 0) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800339 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
340 // Note: We do not have data about the previous state. Otherwise we should load the previous
341 // state here.
342 }
343
Alex Light1f0a22f2017-07-17 12:55:59 -0700344 if (state.native_thread->IsInterrupted()) {
345 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
346 }
347
Andreas Gampe72c19832017-01-12 13:22:16 -0800348 if (internal_thread_state == art::ThreadState::kNative) {
349 jvmti_state |= JVMTI_THREAD_STATE_IN_NATIVE;
350 }
351
352 if (internal_thread_state == art::ThreadState::kRunnable ||
353 internal_thread_state == art::ThreadState::kWaitingWeakGcRootRead ||
354 internal_thread_state == art::ThreadState::kSuspended) {
355 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
356 } else if (internal_thread_state == art::ThreadState::kBlocked) {
357 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
358 } else {
359 // Should be in waiting state.
360 jvmti_state |= JVMTI_THREAD_STATE_WAITING;
361
362 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
363 internal_thread_state == art::ThreadState::kSleeping) {
364 jvmti_state |= JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT;
365 } else {
366 jvmti_state |= JVMTI_THREAD_STATE_WAITING_INDEFINITELY;
367 }
368
369 if (internal_thread_state == art::ThreadState::kSleeping) {
370 jvmti_state |= JVMTI_THREAD_STATE_SLEEPING;
371 }
372
373 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
374 internal_thread_state == art::ThreadState::kWaiting) {
375 jvmti_state |= JVMTI_THREAD_STATE_IN_OBJECT_WAIT;
376 }
377
378 // TODO: PARKED. We'll have to inspect the stack.
379 }
380
381 return jvmti_state;
382}
383
Alex Light1f0a22f2017-07-17 12:55:59 -0700384static jint GetJavaStateFromInternal(const InternalThreadState& state) {
385 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800386 case art::ThreadState::kTerminated:
387 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
388
389 case art::ThreadState::kRunnable:
390 case art::ThreadState::kNative:
391 case art::ThreadState::kWaitingWeakGcRootRead:
392 case art::ThreadState::kSuspended:
393 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
394
395 case art::ThreadState::kTimedWaiting:
396 case art::ThreadState::kSleeping:
397 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
398
399 case art::ThreadState::kBlocked:
400 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
401
402 case art::ThreadState::kStarting:
403 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
404
405 case art::ThreadState::kWaiting:
406 case art::ThreadState::kWaitingForGcToComplete:
407 case art::ThreadState::kWaitingPerformingGc:
408 case art::ThreadState::kWaitingForCheckPointsToRun:
409 case art::ThreadState::kWaitingForDebuggerSend:
410 case art::ThreadState::kWaitingForDebuggerToAttach:
411 case art::ThreadState::kWaitingInMainDebuggerLoop:
412 case art::ThreadState::kWaitingForDebuggerSuspension:
413 case art::ThreadState::kWaitingForDeoptimization:
414 case art::ThreadState::kWaitingForGetObjectsAllocated:
415 case art::ThreadState::kWaitingForJniOnLoad:
416 case art::ThreadState::kWaitingForSignalCatcherOutput:
417 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
418 case art::ThreadState::kWaitingForMethodTracingStart:
419 case art::ThreadState::kWaitingForVisitObjects:
420 case art::ThreadState::kWaitingForGcThreadFlip:
421 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
422 }
423 LOG(FATAL) << "Unreachable";
424 UNREACHABLE();
425}
426
Alex Light1f0a22f2017-07-17 12:55:59 -0700427// Suspends the current thread if it has any suspend requests on it.
428static void SuspendCheck(art::Thread* self)
429 REQUIRES(!art::Locks::mutator_lock_, !art::Locks::user_code_suspension_lock_) {
430 art::ScopedObjectAccess soa(self);
431 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
432 self->FullSuspendCheck();
433}
434
Andreas Gampe72c19832017-01-12 13:22:16 -0800435jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
436 jthread thread,
437 jint* thread_state_ptr) {
438 if (thread_state_ptr == nullptr) {
439 return ERR(NULL_POINTER);
440 }
441
Alex Light1f0a22f2017-07-17 12:55:59 -0700442 art::Thread* self = art::Thread::Current();
443 InternalThreadState state = {};
444 // Loop since we need to bail out and try again if we would end up getting suspended while holding
445 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
446 // release the lock, wait to get resumed and try again.
447 do {
448 SuspendCheck(self);
449 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
450 {
451 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
452 if (self->GetUserCodeSuspendCount() != 0) {
453 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_
454 // by a user-code suspension. We retry and do another SuspendCheck to clear this.
455 continue;
456 }
457 }
458 art::ScopedObjectAccess soa(self);
459 state = GetNativeThreadState(thread, soa);
460 break;
461 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800462
Alex Light1f0a22f2017-07-17 12:55:59 -0700463 if (state.art_state == art::ThreadState::kStarting) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800464 if (thread == nullptr) {
465 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
466 return ERR(WRONG_PHASE);
467 }
468
Alex Light1f0a22f2017-07-17 12:55:59 -0700469 art::ScopedObjectAccess soa(self);
470
Andreas Gampe72c19832017-01-12 13:22:16 -0800471 // Need to read the Java "started" field to know whether this is starting or terminated.
472 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
473 art::ObjPtr<art::mirror::Class> klass = peer->GetClass();
474 art::ArtField* started_field = klass->FindDeclaredInstanceField("started", "Z");
475 CHECK(started_field != nullptr);
476 bool started = started_field->GetBoolean(peer) != 0;
477 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
478 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
479 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
480 *thread_state_ptr = started ? kTerminatedState : kStartedState;
481 return ERR(NONE);
482 }
Alex Light1f0a22f2017-07-17 12:55:59 -0700483 DCHECK(state.native_thread != nullptr);
Andreas Gampe72c19832017-01-12 13:22:16 -0800484
485 // Translate internal thread state to JVMTI and Java state.
Alex Light1f0a22f2017-07-17 12:55:59 -0700486 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
Andreas Gampe72c19832017-01-12 13:22:16 -0800487
488 // Java state is derived from nativeGetState.
Alex Light1f0a22f2017-07-17 12:55:59 -0700489 // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly
490 // different mask if a thread got suspended due to user-code. However, this is for
491 // consistency with the Java view.
492 jint java_state = GetJavaStateFromInternal(state);
Andreas Gampe72c19832017-01-12 13:22:16 -0800493
494 *thread_state_ptr = jvmti_state | java_state;
495
496 return ERR(NONE);
497}
498
Andreas Gampe85807442017-01-13 14:40:58 -0800499jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
500 jint* threads_count_ptr,
501 jthread** threads_ptr) {
502 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
503 return ERR(NULL_POINTER);
504 }
505
506 art::Thread* current = art::Thread::Current();
507
508 art::ScopedObjectAccess soa(current);
509
510 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
511 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
512
513 std::vector<art::ObjPtr<art::mirror::Object>> peers;
514
515 for (art::Thread* thread : thread_list) {
516 // Skip threads that are still starting.
517 if (thread->IsStillStarting()) {
518 continue;
519 }
520
Andreas Gampe202f85a2017-02-06 10:23:26 -0800521 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800522 if (peer != nullptr) {
523 peers.push_back(peer);
524 }
525 }
526
527 if (peers.empty()) {
528 *threads_count_ptr = 0;
529 *threads_ptr = nullptr;
530 } else {
531 unsigned char* data;
532 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
533 if (data_result != ERR(NONE)) {
534 return data_result;
535 }
536 jthread* threads = reinterpret_cast<jthread*>(data);
537 for (size_t i = 0; i != peers.size(); ++i) {
538 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
539 }
540
541 *threads_count_ptr = static_cast<jint>(peers.size());
542 *threads_ptr = threads;
543 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800544 return ERR(NONE);
545}
Andreas Gampe85807442017-01-13 14:40:58 -0800546
Alex Light092a4042017-07-12 08:46:44 -0700547// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
548// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
549// data but we only have a single slot in Thread objects to store data.
550struct JvmtiGlobalTLSData {
551 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
552};
553
554static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
555 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
556 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
557 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
558 if (global_tls != nullptr) {
559 global_tls->data.erase(env);
560 }
561}
562
563void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
564 art::Thread* self = art::Thread::Current();
565 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
566 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
567 list->ForEach(RemoveTLSData, env);
568}
569
570jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
571 art::Thread* self = art::Thread::Current();
572 art::ScopedObjectAccess soa(self);
573 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
574 art::Thread* target = GetNativeThreadLocked(thread, soa);
575 if (target == nullptr && thread == nullptr) {
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800576 return ERR(INVALID_THREAD);
577 }
Alex Light092a4042017-07-12 08:46:44 -0700578 if (target == nullptr) {
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800579 return ERR(THREAD_NOT_ALIVE);
580 }
581
Alex Light092a4042017-07-12 08:46:44 -0700582 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
583 if (global_tls == nullptr) {
584 target->SetCustomTLS(new JvmtiGlobalTLSData);
585 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
586 }
587
588 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800589
590 return ERR(NONE);
591}
592
Alex Light092a4042017-07-12 08:46:44 -0700593jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800594 jthread thread,
595 void** data_ptr) {
596 if (data_ptr == nullptr) {
597 return ERR(NULL_POINTER);
598 }
599
Alex Light092a4042017-07-12 08:46:44 -0700600 art::Thread* self = art::Thread::Current();
601 art::ScopedObjectAccess soa(self);
602 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
603 art::Thread* target = GetNativeThreadLocked(thread, soa);
604 if (target == nullptr && thread == nullptr) {
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800605 return ERR(INVALID_THREAD);
606 }
Alex Light092a4042017-07-12 08:46:44 -0700607 if (target == nullptr) {
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800608 return ERR(THREAD_NOT_ALIVE);
609 }
610
Alex Light092a4042017-07-12 08:46:44 -0700611 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
612 if (global_tls == nullptr) {
613 *data_ptr = nullptr;
614 return OK;
615 }
616 auto it = global_tls->data.find(env);
617 if (it != global_tls->data.end()) {
618 *data_ptr = const_cast<void*>(it->second);
619 } else {
620 *data_ptr = nullptr;
621 }
622
Andreas Gampe85807442017-01-13 14:40:58 -0800623 return ERR(NONE);
624}
625
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800626struct AgentData {
627 const void* arg;
628 jvmtiStartFunction proc;
629 jthread thread;
630 JavaVM* java_vm;
631 jvmtiEnv* jvmti_env;
632 jint priority;
633};
634
635static void* AgentCallback(void* arg) {
636 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
637 CHECK(data->thread != nullptr);
638
639 // We already have a peer. So call our special Attach function.
640 art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread);
641 CHECK(self != nullptr);
642 // The name in Attach() is only for logging. Set the thread name. This is important so
643 // that the thread is no longer seen as starting up.
644 {
645 art::ScopedObjectAccess soa(self);
646 self->SetThreadName("JVMTI Agent thread");
647 }
648
649 // Release the peer.
650 JNIEnv* env = self->GetJniEnv();
651 env->DeleteGlobalRef(data->thread);
652 data->thread = nullptr;
653
654 // Run the agent code.
655 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
656
657 // Detach the thread.
658 int detach_result = data->java_vm->DetachCurrentThread();
659 CHECK_EQ(detach_result, 0);
660
661 return nullptr;
662}
663
664jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
665 jthread thread,
666 jvmtiStartFunction proc,
667 const void* arg,
668 jint priority) {
669 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
670 return ERR(INVALID_PRIORITY);
671 }
672 JNIEnv* env = art::Thread::Current()->GetJniEnv();
673 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
674 return ERR(INVALID_THREAD);
675 }
676 if (proc == nullptr) {
677 return ERR(NULL_POINTER);
678 }
679
680 std::unique_ptr<AgentData> data(new AgentData);
681 data->arg = arg;
682 data->proc = proc;
683 // We need a global ref for Java objects, as local refs will be invalid.
684 data->thread = env->NewGlobalRef(thread);
685 data->java_vm = art::Runtime::Current()->GetJavaVM();
686 data->jvmti_env = jvmti_env;
687 data->priority = priority;
688
689 pthread_t pthread;
690 int pthread_create_result = pthread_create(&pthread,
691 nullptr,
692 &AgentCallback,
693 reinterpret_cast<void*>(data.get()));
694 if (pthread_create_result != 0) {
695 return ERR(INTERNAL);
696 }
697 data.release();
698
699 return ERR(NONE);
700}
701
Alex Light88fd7202017-06-30 08:31:59 -0700702jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
703 jthread target_jthread,
704 art::Thread* target) {
705 // Loop since we need to bail out and try again if we would end up getting suspended while holding
706 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
707 // release the lock, wait to get resumed and try again.
708 do {
709 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
710 // another SuspendThread in the middle of suspending something else potentially causing a
711 // deadlock. We need to do this in the loop because if we ended up back here then we had
712 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
713 // before continuing.
714 SuspendCheck(self);
715 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
716 {
717 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
718 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
719 // a user-code suspension. We retry and do another SuspendCheck to clear this.
720 if (self->GetUserCodeSuspendCount() != 0) {
721 continue;
722 } else if (target->GetUserCodeSuspendCount() != 0) {
723 return ERR(THREAD_SUSPENDED);
724 }
725 }
726 bool timeout = true;
727 while (timeout) {
728 art::ThreadState state = target->GetState();
729 if (state == art::ThreadState::kTerminated || state == art::ThreadState::kStarting) {
730 return ERR(THREAD_NOT_ALIVE);
731 }
732 target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
733 target_jthread,
734 /* request_suspension */ true,
735 art::SuspendReason::kForUserCode,
736 &timeout);
737 if (target == nullptr && !timeout) {
738 // TODO It would be good to get more information about why exactly the thread failed to
739 // suspend.
740 return ERR(INTERNAL);
741 }
742 }
743 return OK;
744 } while (true);
745 UNREACHABLE();
746}
747
748jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
749 CHECK(self == art::Thread::Current());
750 {
751 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
752 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
753 if (self->GetUserCodeSuspendCount() != 0) {
754 // This can only happen if we race with another thread to suspend 'self' and we lose.
755 return ERR(THREAD_SUSPENDED);
756 }
757 // We shouldn't be able to fail this.
758 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
759 // TODO More specific error would be nice.
760 return ERR(INTERNAL);
761 }
762 }
763 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
764 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
765 // to go to sleep until we are resumed.
766 SuspendCheck(self);
767 return OK;
768}
769
770jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
771 art::Thread* self = art::Thread::Current();
772 art::Thread* target;
773 {
774 art::ScopedObjectAccess soa(self);
775 target = GetNativeThread(thread, soa);
776 }
777 if (target == nullptr) {
778 return ERR(INVALID_THREAD);
779 }
780 if (target == self) {
781 return SuspendSelf(self);
782 } else {
783 return SuspendOther(self, thread, target);
784 }
785}
786
787jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
788 jthread thread) {
789 if (thread == nullptr) {
790 return ERR(NULL_POINTER);
791 }
792 art::Thread* self = art::Thread::Current();
793 art::Thread* target;
794 {
795 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
796 // have the 'suspend_lock' locked here.
797 art::ScopedObjectAccess soa(self);
798 target = GetNativeThread(thread, soa);
799 }
800 if (target == nullptr) {
801 return ERR(INVALID_THREAD);
802 } else if (target == self) {
803 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so we
804 // can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs about
805 // current state since it's all concurrent.
806 return ERR(THREAD_NOT_SUSPENDED);
807 }
808 // Now that we know we aren't getting suspended ourself (since we have a mutator lock) we lock the
809 // suspend_lock to start suspending.
810 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
811 {
812 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really cannot
813 // tell why resume failed.
814 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
815 if (target->GetUserCodeSuspendCount() == 0) {
816 return ERR(THREAD_NOT_SUSPENDED);
817 }
818 }
819 if (target->GetState() == art::ThreadState::kTerminated) {
820 return ERR(THREAD_NOT_ALIVE);
821 }
822 DCHECK(target != self);
823 if (!art::Runtime::Current()->GetThreadList()->Resume(target, art::SuspendReason::kForUserCode)) {
824 // TODO Give a better error.
825 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
826 return ERR(INTERNAL);
827 }
828 return OK;
829}
830
831// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
832// since we can have threads in the list multiple times. This generally doesn't matter unless the
833// current thread is present multiple times. In that case we need to suspend only once and either
834// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
835// it didn't. We also want to handle the current thread last to make the behavior of the code
836// simpler to understand.
837jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
838 jint request_count,
839 const jthread* threads,
840 jvmtiError* results) {
841 if (request_count == 0) {
842 return ERR(ILLEGAL_ARGUMENT);
843 } else if (results == nullptr || threads == nullptr) {
844 return ERR(NULL_POINTER);
845 }
846 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
847 // running thread. These indexes we need to handle specially since we need to only actually
848 // suspend a single time.
849 std::vector<jint> current_thread_indexes;
850 art::Thread* self = art::Thread::Current();
851 for (jint i = 0; i < request_count; i++) {
852 {
853 art::ScopedObjectAccess soa(self);
854 if (threads[i] == nullptr || GetNativeThread(threads[i], soa) == self) {
855 current_thread_indexes.push_back(i);
856 continue;
857 }
858 }
859 results[i] = env->SuspendThread(threads[i]);
860 }
861 if (!current_thread_indexes.empty()) {
862 jint first_current_thread_index = current_thread_indexes[0];
863 // Suspend self.
864 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
865 results[first_current_thread_index] = res;
866 // Fill in the rest of the error values as appropriate.
867 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
868 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
869 results[*it] = other_results;
870 }
871 }
872 return OK;
873}
874
875jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
876 jint request_count,
877 const jthread* threads,
878 jvmtiError* results) {
879 if (request_count == 0) {
880 return ERR(ILLEGAL_ARGUMENT);
881 } else if (results == nullptr || threads == nullptr) {
882 return ERR(NULL_POINTER);
883 }
884 for (jint i = 0; i < request_count; i++) {
885 results[i] = env->ResumeThread(threads[i]);
886 }
887 return OK;
888}
889
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800890} // namespace openjdkjvmti