blob: 687fda7ca5114d4e8d80071429827f74aeac9338 [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"
Steven Morelande431e272017-07-18 16:53:49 -070046#include "nativehelper/ScopedLocalRef.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) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800343 jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED;
344 // Note: We do not have data about the previous state. Otherwise we should load the previous
345 // state here.
346 }
347
Alex Light1f0a22f2017-07-17 12:55:59 -0700348 if (state.native_thread->IsInterrupted()) {
349 jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
350 }
351
Andreas Gampe72c19832017-01-12 13:22:16 -0800352 if (internal_thread_state == art::ThreadState::kNative) {
353 jvmti_state |= JVMTI_THREAD_STATE_IN_NATIVE;
354 }
355
356 if (internal_thread_state == art::ThreadState::kRunnable ||
357 internal_thread_state == art::ThreadState::kWaitingWeakGcRootRead ||
358 internal_thread_state == art::ThreadState::kSuspended) {
359 jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE;
360 } else if (internal_thread_state == art::ThreadState::kBlocked) {
361 jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
362 } else {
363 // Should be in waiting state.
364 jvmti_state |= JVMTI_THREAD_STATE_WAITING;
365
366 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
367 internal_thread_state == art::ThreadState::kSleeping) {
368 jvmti_state |= JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT;
369 } else {
370 jvmti_state |= JVMTI_THREAD_STATE_WAITING_INDEFINITELY;
371 }
372
373 if (internal_thread_state == art::ThreadState::kSleeping) {
374 jvmti_state |= JVMTI_THREAD_STATE_SLEEPING;
375 }
376
377 if (internal_thread_state == art::ThreadState::kTimedWaiting ||
378 internal_thread_state == art::ThreadState::kWaiting) {
379 jvmti_state |= JVMTI_THREAD_STATE_IN_OBJECT_WAIT;
380 }
381
382 // TODO: PARKED. We'll have to inspect the stack.
383 }
384
385 return jvmti_state;
386}
387
Alex Light1f0a22f2017-07-17 12:55:59 -0700388static jint GetJavaStateFromInternal(const InternalThreadState& state) {
389 switch (state.art_state) {
Andreas Gampe72c19832017-01-12 13:22:16 -0800390 case art::ThreadState::kTerminated:
391 return JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
392
393 case art::ThreadState::kRunnable:
394 case art::ThreadState::kNative:
395 case art::ThreadState::kWaitingWeakGcRootRead:
396 case art::ThreadState::kSuspended:
397 return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
398
399 case art::ThreadState::kTimedWaiting:
400 case art::ThreadState::kSleeping:
401 return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
402
403 case art::ThreadState::kBlocked:
404 return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
405
406 case art::ThreadState::kStarting:
407 return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
408
409 case art::ThreadState::kWaiting:
Alex Light77fee872017-09-05 14:51:49 -0700410 case art::ThreadState::kWaitingForTaskProcessor:
411 case art::ThreadState::kWaitingForLockInflation:
Andreas Gampe72c19832017-01-12 13:22:16 -0800412 case art::ThreadState::kWaitingForGcToComplete:
413 case art::ThreadState::kWaitingPerformingGc:
414 case art::ThreadState::kWaitingForCheckPointsToRun:
415 case art::ThreadState::kWaitingForDebuggerSend:
416 case art::ThreadState::kWaitingForDebuggerToAttach:
417 case art::ThreadState::kWaitingInMainDebuggerLoop:
418 case art::ThreadState::kWaitingForDebuggerSuspension:
419 case art::ThreadState::kWaitingForDeoptimization:
420 case art::ThreadState::kWaitingForGetObjectsAllocated:
421 case art::ThreadState::kWaitingForJniOnLoad:
422 case art::ThreadState::kWaitingForSignalCatcherOutput:
423 case art::ThreadState::kWaitingInMainSignalCatcherLoop:
424 case art::ThreadState::kWaitingForMethodTracingStart:
425 case art::ThreadState::kWaitingForVisitObjects:
426 case art::ThreadState::kWaitingForGcThreadFlip:
427 return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
428 }
429 LOG(FATAL) << "Unreachable";
430 UNREACHABLE();
431}
432
Alex Light1f0a22f2017-07-17 12:55:59 -0700433// Suspends the current thread if it has any suspend requests on it.
Alex Light23aa7482017-08-16 10:01:13 -0700434void ThreadUtil::SuspendCheck(art::Thread* self) {
Alex Light1f0a22f2017-07-17 12:55:59 -0700435 art::ScopedObjectAccess soa(self);
436 // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
437 self->FullSuspendCheck();
438}
439
Alex Light23aa7482017-08-16 10:01:13 -0700440bool ThreadUtil::WouldSuspendForUserCodeLocked(art::Thread* self) {
441 DCHECK(self == art::Thread::Current());
442 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
443 return self->GetUserCodeSuspendCount() != 0;
444}
445
446bool ThreadUtil::WouldSuspendForUserCode(art::Thread* self) {
447 DCHECK(self == art::Thread::Current());
448 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
449 return WouldSuspendForUserCodeLocked(self);
450}
451
Andreas Gampe72c19832017-01-12 13:22:16 -0800452jvmtiError ThreadUtil::GetThreadState(jvmtiEnv* env ATTRIBUTE_UNUSED,
453 jthread thread,
454 jint* thread_state_ptr) {
455 if (thread_state_ptr == nullptr) {
456 return ERR(NULL_POINTER);
457 }
458
Alex Light1f0a22f2017-07-17 12:55:59 -0700459 art::Thread* self = art::Thread::Current();
460 InternalThreadState state = {};
461 // Loop since we need to bail out and try again if we would end up getting suspended while holding
462 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
463 // release the lock, wait to get resumed and try again.
464 do {
465 SuspendCheck(self);
466 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700467 if (WouldSuspendForUserCodeLocked(self)) {
468 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
469 // a user-code suspension. We retry and do another SuspendCheck to clear this.
470 continue;
Alex Light1f0a22f2017-07-17 12:55:59 -0700471 }
472 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700473 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700474 jvmtiError err = ERR(INTERNAL);
475 art::Thread* target = nullptr;
476 if (!GetNativeThread(thread, soa, &target, &err)) {
477 return err;
478 }
479 state = GetNativeThreadState(target);
Alex Light3ae82532017-07-26 13:59:07 -0700480 if (state.art_state == art::ThreadState::kStarting) {
481 break;
482 }
483 DCHECK(state.native_thread != nullptr);
484
485 // Translate internal thread state to JVMTI and Java state.
486 jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
487
488 // Java state is derived from nativeGetState.
489 // 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);
493
494 *thread_state_ptr = jvmti_state | java_state;
495
496 return ERR(NONE);
Alex Light1f0a22f2017-07-17 12:55:59 -0700497 } while (true);
Andreas Gampe72c19832017-01-12 13:22:16 -0800498
Alex Light3ae82532017-07-26 13:59:07 -0700499 DCHECK_EQ(state.art_state, art::ThreadState::kStarting);
Andreas Gampe72c19832017-01-12 13:22:16 -0800500
Alex Light3ae82532017-07-26 13:59:07 -0700501 if (thread == nullptr) {
502 // No native thread, and no Java thread? We must be starting up. Report as wrong phase.
503 return ERR(WRONG_PHASE);
Andreas Gampe72c19832017-01-12 13:22:16 -0800504 }
Andreas Gampe72c19832017-01-12 13:22:16 -0800505
Alex Light3ae82532017-07-26 13:59:07 -0700506 art::ScopedObjectAccess soa(self);
Alex Lightba461c32017-09-22 14:19:18 -0700507 art::StackHandleScope<1> hs(self);
Andreas Gampe72c19832017-01-12 13:22:16 -0800508
Alex Light3ae82532017-07-26 13:59:07 -0700509 // Need to read the Java "started" field to know whether this is starting or terminated.
Alex Lightba461c32017-09-22 14:19:18 -0700510 art::Handle<art::mirror::Object> peer(hs.NewHandle(soa.Decode<art::mirror::Object>(thread)));
511 art::ObjPtr<art::mirror::Class> thread_klass =
512 soa.Decode<art::mirror::Class>(art::WellKnownClasses::java_lang_Thread);
513 if (!thread_klass->IsAssignableFrom(peer->GetClass())) {
514 return ERR(INVALID_THREAD);
515 }
516 art::ArtField* started_field = thread_klass->FindDeclaredInstanceField("started", "Z");
Alex Light3ae82532017-07-26 13:59:07 -0700517 CHECK(started_field != nullptr);
Alex Lightba461c32017-09-22 14:19:18 -0700518 bool started = started_field->GetBoolean(peer.Get()) != 0;
Alex Light3ae82532017-07-26 13:59:07 -0700519 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
520 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
521 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
522 *thread_state_ptr = started ? kTerminatedState : kStartedState;
Andreas Gampe72c19832017-01-12 13:22:16 -0800523 return ERR(NONE);
524}
525
Andreas Gampe85807442017-01-13 14:40:58 -0800526jvmtiError ThreadUtil::GetAllThreads(jvmtiEnv* env,
527 jint* threads_count_ptr,
528 jthread** threads_ptr) {
529 if (threads_count_ptr == nullptr || threads_ptr == nullptr) {
530 return ERR(NULL_POINTER);
531 }
532
533 art::Thread* current = art::Thread::Current();
534
535 art::ScopedObjectAccess soa(current);
536
537 art::MutexLock mu(current, *art::Locks::thread_list_lock_);
538 std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList();
539
540 std::vector<art::ObjPtr<art::mirror::Object>> peers;
541
542 for (art::Thread* thread : thread_list) {
543 // Skip threads that are still starting.
544 if (thread->IsStillStarting()) {
545 continue;
546 }
547
Andreas Gampe202f85a2017-02-06 10:23:26 -0800548 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
Andreas Gampe85807442017-01-13 14:40:58 -0800549 if (peer != nullptr) {
550 peers.push_back(peer);
551 }
552 }
553
554 if (peers.empty()) {
555 *threads_count_ptr = 0;
556 *threads_ptr = nullptr;
557 } else {
558 unsigned char* data;
559 jvmtiError data_result = env->Allocate(peers.size() * sizeof(jthread), &data);
560 if (data_result != ERR(NONE)) {
561 return data_result;
562 }
563 jthread* threads = reinterpret_cast<jthread*>(data);
564 for (size_t i = 0; i != peers.size(); ++i) {
565 threads[i] = soa.AddLocalReference<jthread>(peers[i]);
566 }
567
568 *threads_count_ptr = static_cast<jint>(peers.size());
569 *threads_ptr = threads;
570 }
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800571 return ERR(NONE);
572}
Andreas Gampe85807442017-01-13 14:40:58 -0800573
Alex Light092a4042017-07-12 08:46:44 -0700574// The struct that we store in the art::Thread::custom_tls_ that maps the jvmtiEnvs to the data
575// stored with that thread. This is needed since different jvmtiEnvs are not supposed to share TLS
576// data but we only have a single slot in Thread objects to store data.
577struct JvmtiGlobalTLSData {
578 std::unordered_map<jvmtiEnv*, const void*> data GUARDED_BY(art::Locks::thread_list_lock_);
579};
580
581static void RemoveTLSData(art::Thread* target, void* ctx) REQUIRES(art::Locks::thread_list_lock_) {
582 jvmtiEnv* env = reinterpret_cast<jvmtiEnv*>(ctx);
583 art::Locks::thread_list_lock_->AssertHeld(art::Thread::Current());
584 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
585 if (global_tls != nullptr) {
586 global_tls->data.erase(env);
587 }
588}
589
590void ThreadUtil::RemoveEnvironment(jvmtiEnv* env) {
591 art::Thread* self = art::Thread::Current();
592 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
593 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
594 list->ForEach(RemoveTLSData, env);
595}
596
597jvmtiError ThreadUtil::SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) {
598 art::Thread* self = art::Thread::Current();
599 art::ScopedObjectAccess soa(self);
600 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700601 art::Thread* target = nullptr;
602 jvmtiError err = ERR(INTERNAL);
603 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
604 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800605 }
606
Alex Light092a4042017-07-12 08:46:44 -0700607 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
608 if (global_tls == nullptr) {
609 target->SetCustomTLS(new JvmtiGlobalTLSData);
610 global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
611 }
612
613 global_tls->data[env] = data;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800614
615 return ERR(NONE);
616}
617
Alex Light092a4042017-07-12 08:46:44 -0700618jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env,
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800619 jthread thread,
620 void** data_ptr) {
621 if (data_ptr == nullptr) {
622 return ERR(NULL_POINTER);
623 }
624
Alex Light092a4042017-07-12 08:46:44 -0700625 art::Thread* self = art::Thread::Current();
626 art::ScopedObjectAccess soa(self);
627 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700628 art::Thread* target = nullptr;
629 jvmtiError err = ERR(INTERNAL);
630 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
631 return err;
Andreas Gampef26bf2d2017-01-13 16:47:14 -0800632 }
633
Alex Light092a4042017-07-12 08:46:44 -0700634 JvmtiGlobalTLSData* global_tls = reinterpret_cast<JvmtiGlobalTLSData*>(target->GetCustomTLS());
635 if (global_tls == nullptr) {
636 *data_ptr = nullptr;
637 return OK;
638 }
639 auto it = global_tls->data.find(env);
640 if (it != global_tls->data.end()) {
641 *data_ptr = const_cast<void*>(it->second);
642 } else {
643 *data_ptr = nullptr;
644 }
645
Andreas Gampe85807442017-01-13 14:40:58 -0800646 return ERR(NONE);
647}
648
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800649struct AgentData {
650 const void* arg;
651 jvmtiStartFunction proc;
652 jthread thread;
653 JavaVM* java_vm;
654 jvmtiEnv* jvmti_env;
655 jint priority;
656};
657
658static void* AgentCallback(void* arg) {
659 std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg));
660 CHECK(data->thread != nullptr);
661
662 // We already have a peer. So call our special Attach function.
663 art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread);
664 CHECK(self != nullptr);
665 // The name in Attach() is only for logging. Set the thread name. This is important so
666 // that the thread is no longer seen as starting up.
667 {
668 art::ScopedObjectAccess soa(self);
669 self->SetThreadName("JVMTI Agent thread");
670 }
671
672 // Release the peer.
673 JNIEnv* env = self->GetJniEnv();
674 env->DeleteGlobalRef(data->thread);
675 data->thread = nullptr;
676
677 // Run the agent code.
678 data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
679
680 // Detach the thread.
681 int detach_result = data->java_vm->DetachCurrentThread();
682 CHECK_EQ(detach_result, 0);
683
684 return nullptr;
685}
686
687jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env,
688 jthread thread,
689 jvmtiStartFunction proc,
690 const void* arg,
691 jint priority) {
Alex Light23aa7482017-08-16 10:01:13 -0700692 if (!PhaseUtil::IsLivePhase()) {
693 return ERR(WRONG_PHASE);
694 }
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800695 if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
696 return ERR(INVALID_PRIORITY);
697 }
698 JNIEnv* env = art::Thread::Current()->GetJniEnv();
699 if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) {
700 return ERR(INVALID_THREAD);
701 }
702 if (proc == nullptr) {
703 return ERR(NULL_POINTER);
704 }
705
706 std::unique_ptr<AgentData> data(new AgentData);
707 data->arg = arg;
708 data->proc = proc;
709 // We need a global ref for Java objects, as local refs will be invalid.
710 data->thread = env->NewGlobalRef(thread);
711 data->java_vm = art::Runtime::Current()->GetJavaVM();
712 data->jvmti_env = jvmti_env;
713 data->priority = priority;
714
715 pthread_t pthread;
716 int pthread_create_result = pthread_create(&pthread,
717 nullptr,
718 &AgentCallback,
719 reinterpret_cast<void*>(data.get()));
720 if (pthread_create_result != 0) {
721 return ERR(INTERNAL);
722 }
723 data.release();
724
725 return ERR(NONE);
726}
727
Alex Light88fd7202017-06-30 08:31:59 -0700728jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
Alex Light3ae82532017-07-26 13:59:07 -0700729 jthread target_jthread) {
Alex Light88fd7202017-06-30 08:31:59 -0700730 // Loop since we need to bail out and try again if we would end up getting suspended while holding
731 // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we
732 // release the lock, wait to get resumed and try again.
733 do {
734 // Suspend ourself if we have any outstanding suspends. This is so we won't suspend due to
735 // another SuspendThread in the middle of suspending something else potentially causing a
736 // deadlock. We need to do this in the loop because if we ended up back here then we had
737 // outstanding SuspendReason::kForUserCode suspensions and we should wait for them to be cleared
738 // before continuing.
739 SuspendCheck(self);
740 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700741 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light88fd7202017-06-30 08:31:59 -0700742 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
743 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700744 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700745 }
Alex Light23aa7482017-08-16 10:01:13 -0700746 // We are not going to be suspended by user code from now on.
Alex Light3ae82532017-07-26 13:59:07 -0700747 {
748 art::ScopedObjectAccess soa(self);
749 art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700750 art::Thread* target = nullptr;
751 jvmtiError err = ERR(INTERNAL);
752 if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) {
753 return err;
754 }
Alex Light88fd7202017-06-30 08:31:59 -0700755 art::ThreadState state = target->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700756 if (state == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Light88fd7202017-06-30 08:31:59 -0700757 return ERR(THREAD_NOT_ALIVE);
Alex Light3ae82532017-07-26 13:59:07 -0700758 } else {
759 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
760 if (target->GetUserCodeSuspendCount() != 0) {
761 return ERR(THREAD_SUSPENDED);
762 }
Alex Light88fd7202017-06-30 08:31:59 -0700763 }
764 }
Alex Light3ae82532017-07-26 13:59:07 -0700765 bool timeout = true;
766 art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
767 target_jthread,
768 /* request_suspension */ true,
769 art::SuspendReason::kForUserCode,
770 &timeout);
771 if (ret_target == nullptr && !timeout) {
772 // TODO It would be good to get more information about why exactly the thread failed to
773 // suspend.
774 return ERR(INTERNAL);
775 } else if (!timeout) {
776 // we didn't time out and got a result.
777 return OK;
778 }
779 // We timed out. Just go around and try again.
Alex Light88fd7202017-06-30 08:31:59 -0700780 } while (true);
781 UNREACHABLE();
782}
783
784jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
785 CHECK(self == art::Thread::Current());
786 {
787 art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_);
788 art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_);
789 if (self->GetUserCodeSuspendCount() != 0) {
790 // This can only happen if we race with another thread to suspend 'self' and we lose.
791 return ERR(THREAD_SUSPENDED);
792 }
793 // We shouldn't be able to fail this.
794 if (!self->ModifySuspendCount(self, +1, nullptr, art::SuspendReason::kForUserCode)) {
795 // TODO More specific error would be nice.
796 return ERR(INTERNAL);
797 }
798 }
799 // Once we have requested the suspend we actually go to sleep. We need to do this after releasing
800 // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us
801 // to go to sleep until we are resumed.
802 SuspendCheck(self);
803 return OK;
804}
805
806jvmtiError ThreadUtil::SuspendThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
807 art::Thread* self = art::Thread::Current();
Alex Light3ae82532017-07-26 13:59:07 -0700808 bool target_is_self = false;
Alex Light88fd7202017-06-30 08:31:59 -0700809 {
810 art::ScopedObjectAccess soa(self);
Alex Light3ae82532017-07-26 13:59:07 -0700811 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700812 art::Thread* target = nullptr;
813 jvmtiError err = ERR(INTERNAL);
814 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
815 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700816 } else if (target == self) {
817 target_is_self = true;
818 }
Alex Light88fd7202017-06-30 08:31:59 -0700819 }
Alex Light3ae82532017-07-26 13:59:07 -0700820 if (target_is_self) {
Alex Light88fd7202017-06-30 08:31:59 -0700821 return SuspendSelf(self);
822 } else {
Alex Light3ae82532017-07-26 13:59:07 -0700823 return SuspendOther(self, thread);
Alex Light88fd7202017-06-30 08:31:59 -0700824 }
825}
826
827jvmtiError ThreadUtil::ResumeThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
828 jthread thread) {
829 if (thread == nullptr) {
830 return ERR(NULL_POINTER);
831 }
832 art::Thread* self = art::Thread::Current();
833 art::Thread* target;
Alex Light3ae82532017-07-26 13:59:07 -0700834 // Retry until we know we won't get suspended by user code while resuming something.
835 do {
836 SuspendCheck(self);
837 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
Alex Light23aa7482017-08-16 10:01:13 -0700838 if (WouldSuspendForUserCodeLocked(self)) {
Alex Light3ae82532017-07-26 13:59:07 -0700839 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by
840 // a user-code suspension. We retry and do another SuspendCheck to clear this.
Alex Light23aa7482017-08-16 10:01:13 -0700841 continue;
Alex Light88fd7202017-06-30 08:31:59 -0700842 }
Alex Light3ae82532017-07-26 13:59:07 -0700843 // From now on we know we cannot get suspended by user-code.
844 {
845 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
846 // have the 'suspend_lock' locked here.
847 art::ScopedObjectAccess soa(self);
848 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -0700849 jvmtiError err = ERR(INTERNAL);
850 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
851 return err;
Alex Light3ae82532017-07-26 13:59:07 -0700852 } else if (target == self) {
853 // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so
854 // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs
855 // about current state since it's all concurrent.
856 return ERR(THREAD_NOT_SUSPENDED);
Alex Light3ae82532017-07-26 13:59:07 -0700857 }
858 // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really
859 // cannot tell why resume failed.
860 {
861 art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_);
862 if (target->GetUserCodeSuspendCount() == 0) {
863 return ERR(THREAD_NOT_SUSPENDED);
864 }
865 }
866 }
867 // It is okay that we don't have a thread_list_lock here since we know that the thread cannot
868 // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
869 DCHECK(target != self);
870 if (!art::Runtime::Current()->GetThreadList()->Resume(target,
871 art::SuspendReason::kForUserCode)) {
872 // TODO Give a better error.
873 // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure.
874 return ERR(INTERNAL);
875 } else {
876 return OK;
877 }
878 } while (true);
Alex Light88fd7202017-06-30 08:31:59 -0700879}
880
Alex Light7ddc23d2017-09-22 15:33:41 -0700881static bool IsCurrentThread(jthread thr) {
882 if (thr == nullptr) {
883 return true;
884 }
885 art::Thread* self = art::Thread::Current();
886 art::ScopedObjectAccess soa(self);
887 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
888 art::Thread* target = nullptr;
889 jvmtiError err_unused = ERR(INTERNAL);
890 if (ThreadUtil::GetNativeThread(thr, soa, &target, &err_unused)) {
891 return target == self;
892 } else {
893 return false;
894 }
895}
896
Alex Light88fd7202017-06-30 08:31:59 -0700897// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky
898// since we can have threads in the list multiple times. This generally doesn't matter unless the
899// current thread is present multiple times. In that case we need to suspend only once and either
900// return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if
901// it didn't. We also want to handle the current thread last to make the behavior of the code
902// simpler to understand.
903jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
904 jint request_count,
905 const jthread* threads,
906 jvmtiError* results) {
907 if (request_count == 0) {
908 return ERR(ILLEGAL_ARGUMENT);
909 } else if (results == nullptr || threads == nullptr) {
910 return ERR(NULL_POINTER);
911 }
912 // This is the list of the indexes in 'threads' and 'results' that correspond to the currently
913 // running thread. These indexes we need to handle specially since we need to only actually
914 // suspend a single time.
915 std::vector<jint> current_thread_indexes;
Alex Light88fd7202017-06-30 08:31:59 -0700916 for (jint i = 0; i < request_count; i++) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700917 if (IsCurrentThread(threads[i])) {
918 current_thread_indexes.push_back(i);
919 } else {
920 results[i] = env->SuspendThread(threads[i]);
Alex Light88fd7202017-06-30 08:31:59 -0700921 }
Alex Light88fd7202017-06-30 08:31:59 -0700922 }
923 if (!current_thread_indexes.empty()) {
924 jint first_current_thread_index = current_thread_indexes[0];
925 // Suspend self.
926 jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
927 results[first_current_thread_index] = res;
928 // Fill in the rest of the error values as appropriate.
929 jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED);
930 for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
931 results[*it] = other_results;
932 }
933 }
934 return OK;
935}
936
937jvmtiError ThreadUtil::ResumeThreadList(jvmtiEnv* env,
938 jint request_count,
939 const jthread* threads,
940 jvmtiError* results) {
941 if (request_count == 0) {
942 return ERR(ILLEGAL_ARGUMENT);
943 } else if (results == nullptr || threads == nullptr) {
944 return ERR(NULL_POINTER);
945 }
946 for (jint i = 0; i < request_count; i++) {
947 results[i] = env->ResumeThread(threads[i]);
948 }
949 return OK;
950}
951
Alex Light54d39dc2017-09-25 17:00:16 -0700952jvmtiError ThreadUtil::StopThread(jvmtiEnv* env ATTRIBUTE_UNUSED,
953 jthread thread,
954 jobject exception) {
955 art::Thread* self = art::Thread::Current();
956 art::ScopedObjectAccess soa(self);
957 art::StackHandleScope<1> hs(self);
958 if (exception == nullptr) {
959 return ERR(INVALID_OBJECT);
960 }
961 art::ObjPtr<art::mirror::Object> obj(soa.Decode<art::mirror::Object>(exception));
962 if (!obj->GetClass()->IsThrowableClass()) {
963 return ERR(INVALID_OBJECT);
964 }
965 art::Handle<art::mirror::Throwable> exc(hs.NewHandle(obj->AsThrowable()));
Alex Lightb1e31a82017-10-04 16:57:36 -0700966 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light54d39dc2017-09-25 17:00:16 -0700967 art::Thread* target = nullptr;
968 jvmtiError err = ERR(INTERNAL);
969 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700970 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -0700971 return err;
972 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700973 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light54d39dc2017-09-25 17:00:16 -0700974 return ERR(THREAD_NOT_ALIVE);
975 }
976 struct StopThreadClosure : public art::Closure {
977 public:
978 explicit StopThreadClosure(art::Handle<art::mirror::Throwable> except) : exception_(except) { }
979
980 void Run(art::Thread* me) REQUIRES_SHARED(art::Locks::mutator_lock_) {
981 // Make sure the thread is prepared to notice the exception.
982 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(me);
983 me->SetAsyncException(exception_.Get());
984 // Wake up the thread if it is sleeping.
985 me->Notify();
986 }
987
988 private:
989 art::Handle<art::mirror::Throwable> exception_;
990 };
991 StopThreadClosure c(exc);
Alex Lightb1e31a82017-10-04 16:57:36 -0700992 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light54d39dc2017-09-25 17:00:16 -0700993 if (target->RequestSynchronousCheckpoint(&c)) {
994 return OK;
995 } else {
996 // Something went wrong, probably the thread died.
997 return ERR(THREAD_NOT_ALIVE);
998 }
999}
1000
1001jvmtiError ThreadUtil::InterruptThread(jvmtiEnv* env ATTRIBUTE_UNUSED, jthread thread) {
1002 art::Thread* self = art::Thread::Current();
1003 art::ScopedObjectAccess soa(self);
1004 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
1005 art::Thread* target = nullptr;
1006 jvmtiError err = ERR(INTERNAL);
1007 if (!GetAliveNativeThread(thread, soa, &target, &err)) {
1008 return err;
1009 } else if (target->GetState() == art::ThreadState::kStarting || target->IsStillStarting()) {
1010 return ERR(THREAD_NOT_ALIVE);
1011 }
1012 target->Interrupt(self);
1013 return OK;
1014}
1015
Andreas Gampeaf13ab92017-01-11 20:57:40 -08001016} // namespace openjdkjvmti