blob: 3d447dc7ac756bc7b3273e4e22739983aeb40831 [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
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800162// Get the native thread. The spec says a null object denotes the current thread.
163static art::Thread* GetNativeThread(jthread thread,
164 const art::ScopedObjectAccessAlreadyRunnable& soa)
165 REQUIRES_SHARED(art::Locks::mutator_lock_) {
166 if (thread == nullptr) {
167 return art::Thread::Current();
168 }
169
170 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
171 return art::Thread::FromManagedThread(soa, thread);
172}
173
174jvmtiError ThreadUtil::GetThreadInfo(jvmtiEnv* env, jthread thread, jvmtiThreadInfo* info_ptr) {
175 if (info_ptr == nullptr) {
176 return ERR(NULL_POINTER);
177 }
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700178 if (!PhaseUtil::IsLivePhase()) {
179 return JVMTI_ERROR_WRONG_PHASE;
180 }
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800181
182 art::ScopedObjectAccess soa(art::Thread::Current());
183
184 art::Thread* self = GetNativeThread(thread, soa);
185 if (self == nullptr && thread == nullptr) {
186 return ERR(INVALID_THREAD);
187 }
188
Andreas Gampe54711412017-02-21 12:41:43 -0800189 JvmtiUniquePtr<char[]> name_uptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800190 if (self != nullptr) {
191 // Have a native thread object, this thread is alive.
192 std::string name;
193 self->GetThreadName(name);
Andreas Gampe54711412017-02-21 12:41:43 -0800194 jvmtiError name_result;
195 name_uptr = CopyString(env, name.c_str(), &name_result);
196 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800197 return name_result;
198 }
Andreas Gampe54711412017-02-21 12:41:43 -0800199 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800200
201 info_ptr->priority = self->GetNativePriority();
202
203 info_ptr->is_daemon = self->IsDaemon();
204
Andreas Gampe202f85a2017-02-06 10:23:26 -0800205 art::ObjPtr<art::mirror::Object> peer = self->GetPeerFromOtherThread();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800206
207 // ThreadGroup.
208 if (peer != nullptr) {
209 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
210 CHECK(f != nullptr);
211 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
212 info_ptr->thread_group = group == nullptr
213 ? nullptr
214 : soa.AddLocalReference<jthreadGroup>(group);
215 } else {
216 info_ptr->thread_group = nullptr;
217 }
218
219 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700220 DCHECK(context_class_loader_ != nullptr);
221 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
222 ? context_class_loader_->GetObject(peer)
223 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800224 info_ptr->context_class_loader = ccl == nullptr
225 ? nullptr
226 : soa.AddLocalReference<jobject>(ccl);
227 } else {
228 // Only the peer. This thread has either not been started, or is dead. Read things from
229 // the Java side.
230 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
231
232 // Name.
233 {
234 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_name);
235 CHECK(f != nullptr);
236 art::ObjPtr<art::mirror::Object> name = f->GetObject(peer);
237 std::string name_cpp;
238 const char* name_cstr;
239 if (name != nullptr) {
240 name_cpp = name->AsString()->ToModifiedUtf8();
241 name_cstr = name_cpp.c_str();
242 } else {
243 name_cstr = "";
244 }
Andreas Gampe54711412017-02-21 12:41:43 -0800245 jvmtiError name_result;
246 name_uptr = CopyString(env, name_cstr, &name_result);
247 if (name_uptr == nullptr) {
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800248 return name_result;
249 }
Andreas Gampe54711412017-02-21 12:41:43 -0800250 info_ptr->name = name_uptr.get();
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800251 }
252
253 // Priority.
254 {
255 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_priority);
256 CHECK(f != nullptr);
257 info_ptr->priority = static_cast<jint>(f->GetInt(peer));
258 }
259
260 // Daemon.
261 {
262 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_daemon);
263 CHECK(f != nullptr);
264 info_ptr->is_daemon = f->GetBoolean(peer) == 0 ? JNI_FALSE : JNI_TRUE;
265 }
266
267 // ThreadGroup.
268 {
269 art::ArtField* f = art::jni::DecodeArtField(art::WellKnownClasses::java_lang_Thread_group);
270 CHECK(f != nullptr);
271 art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
272 info_ptr->thread_group = group == nullptr
273 ? nullptr
274 : soa.AddLocalReference<jthreadGroup>(group);
275 }
276
277 // Context classloader.
Andreas Gampedb6c2ab2017-03-28 17:28:32 -0700278 DCHECK(context_class_loader_ != nullptr);
279 art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
280 ? context_class_loader_->GetObject(peer)
281 : nullptr;
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800282 info_ptr->context_class_loader = ccl == nullptr
283 ? nullptr
284 : soa.AddLocalReference<jobject>(ccl);
285 }
286
287 name_uptr.release();
288
289 return ERR(NONE);
290}
291
Andreas Gampe72c19832017-01-12 13:22:16 -0800292// Return the thread's (or current thread, if null) thread state. Return kStarting in case
293// there's no native counterpart (thread hasn't been started, yet, or is dead).
294static art::ThreadState GetNativeThreadState(jthread thread,
295 const art::ScopedObjectAccessAlreadyRunnable& soa,
296 art::Thread** native_thread)
297 REQUIRES_SHARED(art::Locks::mutator_lock_) {
298 art::Thread* self = nullptr;
299 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
300 if (thread == nullptr) {
301 self = art::Thread::Current();
302 } else {
303 self = art::Thread::FromManagedThread(soa, thread);
304 }
305 *native_thread = self;
306 if (self == nullptr || self->IsStillStarting()) {
307 return art::ThreadState::kStarting;
308 }
309 return self->GetState();
310}
311
312static jint GetJvmtiThreadStateFromInternal(art::ThreadState internal_thread_state) {
313 jint jvmti_state = JVMTI_THREAD_STATE_ALIVE;
314
315 if (internal_thread_state == art::ThreadState::kSuspended) {
316 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
317 // Note: We do not have data about the previous state. Otherwise we should load the previous
318 // state here.
319 }
320
321 if (internal_thread_state == art::ThreadState::kNative) {
322 jvmti_state |= JVMTI_THREAD_STATE_IN_NATIVE;
323 }
324
325 if (internal_thread_state == art::ThreadState::kRunnable ||
326 internal_thread_state == art::ThreadState::kWaitingWeakGcRootRead ||
327 internal_thread_state == art::ThreadState::kSuspended) {
328 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
329 } else if (internal_thread_state == art::ThreadState::kBlocked) {
330 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
331 } else {
332 // Should be in waiting state.
333 jvmti_state |= JVMTI_THREAD_STATE_WAITING;
334
335 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
336 internal_thread_state == art::ThreadState::kSleeping) {
337 jvmti_state |= JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT;
338 } else {
339 jvmti_state |= JVMTI_THREAD_STATE_WAITING_INDEFINITELY;
340 }
341
342 if (internal_thread_state == art::ThreadState::kSleeping) {
343 jvmti_state |= JVMTI_THREAD_STATE_SLEEPING;
344 }
345
346 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
347 internal_thread_state == art::ThreadState::kWaiting) {
348 jvmti_state |= JVMTI_THREAD_STATE_IN_OBJECT_WAIT;
349 }
350
351 // TODO: PARKED. We'll have to inspect the stack.
352 }
353
354 return jvmti_state;
355}
356
357static jint GetJavaStateFromInternal(art::ThreadState internal_thread_state) {
358 switch (internal_thread_state) {
359 case art::ThreadState::kTerminated:
360 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
361
362 case art::ThreadState::kRunnable:
363 case art::ThreadState::kNative:
364 case art::ThreadState::kWaitingWeakGcRootRead:
365 case art::ThreadState::kSuspended:
366 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
367
368 case art::ThreadState::kTimedWaiting:
369 case art::ThreadState::kSleeping:
370 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
371
372 case art::ThreadState::kBlocked:
373 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
374
375 case art::ThreadState::kStarting:
376 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
377
378 case art::ThreadState::kWaiting:
379 case art::ThreadState::kWaitingForGcToComplete:
380 case art::ThreadState::kWaitingPerformingGc:
381 case art::ThreadState::kWaitingForCheckPointsToRun:
382 case art::ThreadState::kWaitingForDebuggerSend:
383 case art::ThreadState::kWaitingForDebuggerToAttach:
384 case art::ThreadState::kWaitingInMainDebuggerLoop:
385 case art::ThreadState::kWaitingForDebuggerSuspension:
386 case art::ThreadState::kWaitingForDeoptimization:
387 case art::ThreadState::kWaitingForGetObjectsAllocated:
388 case art::ThreadState::kWaitingForJniOnLoad:
389 case art::ThreadState::kWaitingForSignalCatcherOutput:
390 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
391 case art::ThreadState::kWaitingForMethodTracingStart:
392 case art::ThreadState::kWaitingForVisitObjects:
393 case art::ThreadState::kWaitingForGcThreadFlip:
394 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
395 }
396 LOG(FATAL) << "Unreachable";
397 UNREACHABLE();
398}
399
400jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
401 jthread thread,
402 jint* thread_state_ptr) {
403 if (thread_state_ptr == nullptr) {
404 return ERR(NULL_POINTER);
405 }
406
407 art::ScopedObjectAccess soa(art::Thread::Current());
408 art::Thread* native_thread = nullptr;
409 art::ThreadState internal_thread_state = GetNativeThreadState(thread, soa, &native_thread);
410
411 if (internal_thread_state == art::ThreadState::kStarting) {
412 if (thread == nullptr) {
413 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
414 return ERR(WRONG_PHASE);
415 }
416
417 // Need to read the Java "started" field to know whether this is starting or terminated.
418 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
419 art::ObjPtr<art::mirror::Class> klass = peer->GetClass();
420 art::ArtField* started_field = klass->FindDeclaredInstanceField("started", "Z");
421 CHECK(started_field != nullptr);
422 bool started = started_field->GetBoolean(peer) != 0;
423 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
424 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
425 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
426 *thread_state_ptr = started ? kTerminatedState : kStartedState;
427 return ERR(NONE);
428 }
429 DCHECK(native_thread != nullptr);
430
431 // Translate internal thread state to JVMTI and Java state.
432 jint jvmti_state = GetJvmtiThreadStateFromInternal(internal_thread_state);
433 if (native_thread->IsInterrupted()) {
434 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
435 }
Alex Light88fd7202017-06-30 08:31:59 -0700436 if (native_thread->IsSuspended()) {
437 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
438 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800439
440 // Java state is derived from nativeGetState.
441 // Note: Our implementation assigns "runnable" to suspended. As such, we will have slightly
442 // different mask. However, this is for consistency with the Java view.
443 jint java_state = GetJavaStateFromInternal(internal_thread_state);
444
445 *thread_state_ptr = jvmti_state | java_state;
446
447 return ERR(NONE);
448}
449
Andreas Gampe85807442017-01-13 14:40:58 -0800450jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
451 jint* threads_count_ptr,
452 jthread** threads_ptr) {
453 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
454 return ERR(NULL_POINTER);
455 }
456
457 art::Thread* current = art::Thread::Current();
458
459 art::ScopedObjectAccess soa(current);
460
461 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
462 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
463
464 std::vector<art::ObjPtr<art::mirror::Object>> peers;
465
466 for (art::Thread* thread : thread_list) {
467 // Skip threads that are still starting.
468 if (thread->IsStillStarting()) {
469 continue;
470 }
471
Andreas Gampe202f85a2017-02-06 10:23:26 -0800472 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800473 if (peer != nullptr) {
474 peers.push_back(peer);
475 }
476 }
477
478 if (peers.empty()) {
479 *threads_count_ptr = 0;
480 *threads_ptr = nullptr;
481 } else {
482 unsigned char* data;
483 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
484 if (data_result != ERR(NONE)) {
485 return data_result;
486 }
487 jthread* threads = reinterpret_cast<jthread*>(data);
488 for (size_t i = 0; i != peers.size(); ++i) {
489 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
490 }
491
492 *threads_count_ptr = static_cast<jint>(peers.size());
493 *threads_ptr = threads;
494 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800495 return ERR(NONE);
496}
Andreas Gampe85807442017-01-13 14:40:58 -0800497
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800498jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env ATTRIBUTE_UNUSED,
499 jthread thread,
500 const void* data) {
501 art::ScopedObjectAccess soa(art::Thread::Current());
502 art::Thread* self = GetNativeThread(thread, soa);
503 if (self == nullptr && thread == nullptr) {
504 return ERR(INVALID_THREAD);
505 }
506 if (self == nullptr) {
507 return ERR(THREAD_NOT_ALIVE);
508 }
509
510 self->SetCustomTLS(data);
511
512 return ERR(NONE);
513}
514
515jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env ATTRIBUTE_UNUSED,
516 jthread thread,
517 void** data_ptr) {
518 if (data_ptr == nullptr) {
519 return ERR(NULL_POINTER);
520 }
521
522 art::ScopedObjectAccess soa(art::Thread::Current());
523 art::Thread* self = GetNativeThread(thread, soa);
524 if (self == nullptr && thread == nullptr) {
525 return ERR(INVALID_THREAD);
526 }
527 if (self == nullptr) {
528 return ERR(THREAD_NOT_ALIVE);
529 }
530
531 *data_ptr = const_cast<void*>(self->GetCustomTLS());
Andreas Gampe85807442017-01-13 14:40:58 -0800532 return ERR(NONE);
533}
534
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800535struct AgentData {
536 const void* arg;
537 jvmtiStartFunction proc;
538 jthread thread;
539 JavaVM* java_vm;
540 jvmtiEnv* jvmti_env;
541 jint priority;
542};
543
544static void* AgentCallback(void* arg) {
545 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
546 CHECK(data->thread != nullptr);
547
548 // We already have a peer. So call our special Attach function.
549 art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread);
550 CHECK(self != nullptr);
551 // The name in Attach() is only for logging. Set the thread name. This is important so
552 // that the thread is no longer seen as starting up.
553 {
554 art::ScopedObjectAccess soa(self);
555 self->SetThreadName("JVMTI Agent thread");
556 }
557
558 // Release the peer.
559 JNIEnv* env = self->GetJniEnv();
560 env->DeleteGlobalRef(data->thread);
561 data->thread = nullptr;
562
563 // Run the agent code.
564 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
565
566 // Detach the thread.
567 int detach_result = data->java_vm->DetachCurrentThread();
568 CHECK_EQ(detach_result, 0);
569
570 return nullptr;
571}
572
573jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
574 jthread thread,
575 jvmtiStartFunction proc,
576 const void* arg,
577 jint priority) {
578 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
579 return ERR(INVALID_PRIORITY);
580 }
581 JNIEnv* env = art::Thread::Current()->GetJniEnv();
582 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
583 return ERR(INVALID_THREAD);
584 }
585 if (proc == nullptr) {
586 return ERR(NULL_POINTER);
587 }
588
589 std::unique_ptr<AgentData> data(new AgentData);
590 data->arg = arg;
591 data->proc = proc;
592 // We need a global ref for Java objects, as local refs will be invalid.
593 data->thread = env->NewGlobalRef(thread);
594 data->java_vm = art::Runtime::Current()->GetJavaVM();
595 data->jvmti_env = jvmti_env;
596 data->priority = priority;
597
598 pthread_t pthread;
599 int pthread_create_result = pthread_create(&pthread,
600 nullptr,
601 &AgentCallback,
602 reinterpret_cast<void*>(data.get()));
603 if (pthread_create_result != 0) {
604 return ERR(INTERNAL);
605 }
606 data.release();
607
608 return ERR(NONE);
609}
610
Alex Light88fd7202017-06-30 08:31:59 -0700611// Suspends the current thread if it has any suspend requests on it.
612static void SuspendCheck(art::Thread* self)
613 REQUIRES(!art::Locks::mutator_lock_, !art::Locks::user_code_suspension_lock_) {
614 art::ScopedObjectAccess soa(self);
615 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
616 self->FullSuspendCheck();
617}
618
619jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
620 jthread target_jthread,
621 art::Thread* target) {
622 // Loop since we need to bail out and try again if we would end up getting suspended while holding
623 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
624 // release the lock, wait to get resumed and try again.
625 do {
626 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
627 // another SuspendThread in the middle of suspending something else potentially causing a
628 // deadlock. We need to do this in the loop because if we ended up back here then we had
629 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
630 // before continuing.
631 SuspendCheck(self);
632 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
633 {
634 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
635 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
636 // a user-code suspension. We retry and do another SuspendCheck to clear this.
637 if (self->GetUserCodeSuspendCount() != 0) {
638 continue;
639 } else if (target->GetUserCodeSuspendCount() != 0) {
640 return ERR(THREAD_SUSPENDED);
641 }
642 }
643 bool timeout = true;
644 while (timeout) {
645 art::ThreadState state = target->GetState();
646 if (state == art::ThreadState::kTerminated || state == art::ThreadState::kStarting) {
647 return ERR(THREAD_NOT_ALIVE);
648 }
649 target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
650 target_jthread,
651 /* request_suspension */ true,
652 art::SuspendReason::kForUserCode,
653 &timeout);
654 if (target == nullptr && !timeout) {
655 // TODO It would be good to get more information about why exactly the thread failed to
656 // suspend.
657 return ERR(INTERNAL);
658 }
659 }
660 return OK;
661 } while (true);
662 UNREACHABLE();
663}
664
665jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
666 CHECK(self == art::Thread::Current());
667 {
668 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
669 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
670 if (self->GetUserCodeSuspendCount() != 0) {
671 // This can only happen if we race with another thread to suspend 'self' and we lose.
672 return ERR(THREAD_SUSPENDED);
673 }
674 // We shouldn't be able to fail this.
675 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
676 // TODO More specific error would be nice.
677 return ERR(INTERNAL);
678 }
679 }
680 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
681 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
682 // to go to sleep until we are resumed.
683 SuspendCheck(self);
684 return OK;
685}
686
687jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
688 art::Thread* self = art::Thread::Current();
689 art::Thread* target;
690 {
691 art::ScopedObjectAccess soa(self);
692 target = GetNativeThread(thread, soa);
693 }
694 if (target == nullptr) {
695 return ERR(INVALID_THREAD);
696 }
697 if (target == self) {
698 return SuspendSelf(self);
699 } else {
700 return SuspendOther(self, thread, target);
701 }
702}
703
704jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
705 jthread thread) {
706 if (thread == nullptr) {
707 return ERR(NULL_POINTER);
708 }
709 art::Thread* self = art::Thread::Current();
710 art::Thread* target;
711 {
712 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
713 // have the 'suspend_lock' locked here.
714 art::ScopedObjectAccess soa(self);
715 target = GetNativeThread(thread, soa);
716 }
717 if (target == nullptr) {
718 return ERR(INVALID_THREAD);
719 } else if (target == self) {
720 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so we
721 // can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs about
722 // current state since it's all concurrent.
723 return ERR(THREAD_NOT_SUSPENDED);
724 }
725 // Now that we know we aren't getting suspended ourself (since we have a mutator lock) we lock the
726 // suspend_lock to start suspending.
727 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
728 {
729 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really cannot
730 // tell why resume failed.
731 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
732 if (target->GetUserCodeSuspendCount() == 0) {
733 return ERR(THREAD_NOT_SUSPENDED);
734 }
735 }
736 if (target->GetState() == art::ThreadState::kTerminated) {
737 return ERR(THREAD_NOT_ALIVE);
738 }
739 DCHECK(target != self);
740 if (!art::Runtime::Current()->GetThreadList()->Resume(target, art::SuspendReason::kForUserCode)) {
741 // TODO Give a better error.
742 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
743 return ERR(INTERNAL);
744 }
745 return OK;
746}
747
748// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
749// since we can have threads in the list multiple times. This generally doesn't matter unless the
750// current thread is present multiple times. In that case we need to suspend only once and either
751// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
752// it didn't. We also want to handle the current thread last to make the behavior of the code
753// simpler to understand.
754jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
755 jint request_count,
756 const jthread* threads,
757 jvmtiError* results) {
758 if (request_count == 0) {
759 return ERR(ILLEGAL_ARGUMENT);
760 } else if (results == nullptr || threads == nullptr) {
761 return ERR(NULL_POINTER);
762 }
763 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
764 // running thread. These indexes we need to handle specially since we need to only actually
765 // suspend a single time.
766 std::vector<jint> current_thread_indexes;
767 art::Thread* self = art::Thread::Current();
768 for (jint i = 0; i < request_count; i++) {
769 {
770 art::ScopedObjectAccess soa(self);
771 if (threads[i] == nullptr || GetNativeThread(threads[i], soa) == self) {
772 current_thread_indexes.push_back(i);
773 continue;
774 }
775 }
776 results[i] = env->SuspendThread(threads[i]);
777 }
778 if (!current_thread_indexes.empty()) {
779 jint first_current_thread_index = current_thread_indexes[0];
780 // Suspend self.
781 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
782 results[first_current_thread_index] = res;
783 // Fill in the rest of the error values as appropriate.
784 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
785 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
786 results[*it] = other_results;
787 }
788 }
789 return OK;
790}
791
792jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
793 jint request_count,
794 const jthread* threads,
795 jvmtiError* results) {
796 if (request_count == 0) {
797 return ERR(ILLEGAL_ARGUMENT);
798 } else if (results == nullptr || threads == nullptr) {
799 return ERR(NULL_POINTER);
800 }
801 for (jint i = 0; i < request_count; i++) {
802 results[i] = env->ResumeThread(threads[i]);
803 }
804 return OK;
805}
806
Andreas Gampeaf13ab92017-01-11 20:57:40 -0800807} // namespace openjdkjvmti