ScopedNoUserCodeSuspension::ScopedNoUserCodeSuspension(art::Thread* self) : self_(self) {
DCHECK_EQ(self, art::Thread::Current()); // Loop until we both have the user_code_suspension_locK_ and don't have any pending user_code // suspensions. do {
art::Locks::user_code_suspension_lock_->AssertNotHeld(self_);
ThreadUtil::SuspendCheck(self_);
art::Locks::user_code_suspension_lock_->ExclusiveLock(self_); if (ThreadUtil::WouldSuspendForUserCodeLocked(self_)) {
art::Locks::user_code_suspension_lock_->ExclusiveUnlock(self_); continue;
}
void ThreadStart(art::Thread* self) override REQUIRES_SHARED(art::Locks::mutator_lock_) { // Needs to be checked first because we might start these threads before we actually send the // VMInit event. if (self->IsSystemDaemon()) { // System daemon threads are things like the finalizer or gc thread. It would be dangerous to // allow agents to get in the way of these threads starting up. These threads include things // like the HeapTaskDaemon and the finalizer daemon. // // This event can happen during the time before VMInit or just after zygote fork. Since the // second is hard to distinguish we unfortunately cannot really check the state here. return;
} if (!started) { // Runtime isn't started. We only expect at most the signal handler or JIT threads to be // started here; this includes the perfetto_hprof_listener signal handler thread for // perfetto_hprof, as well as the metrics background reporting thread. if (art::kIsDebugBuild) {
std::string name;
self->GetThreadName(name); if (name != "JDWP" && name != "Signal Catcher" && name != "perfetto_hprof_listener" &&
name != art::metrics::MetricsReporter::kBackgroundThreadName &&
!name.starts_with("Jit thread pool") &&
!name.starts_with("Heap thread pool worker thread") &&
!name.starts_with("Runtime worker thread")) {
LOG(FATAL) << "Unexpected thread before start: " << name << " id: "
<< self->GetThreadId();
}
} return;
}
Post<ArtJvmtiEvent::kThreadStart>(self);
}
void ThreadUtil::VMInitEventSent() { // We should have already started.
DCHECK(gThreadCallback.started); // We moved to VMInit. Report the main thread as started (it was attached early, and must not be // reported until Init.
gThreadCallback.Post<ArtJvmtiEvent::kThreadStart>(art::Thread::Current());
}
staticvoid WaitForSystemDaemonStart(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_) {
art::WellKnownClasses::java_lang_Daemons_waitForDaemonStart->InvokeStatic<'V'>(self); if (self->IsExceptionPending()) {
LOG(WARNING) << "Exception occurred when waiting for system daemons to start: "
<< self->GetException()->Dump();
self->ClearException();
}
}
void ThreadUtil::CacheData() { // We must have started since it is now safe to cache our data;
gThreadCallback.started = true;
art::Thread* self = art::Thread::Current();
art::ScopedObjectAccess soa(self);
art::ObjPtr<art::mirror::Class> thread_class = art::WellKnownClasses::java_lang_Thread.Get();
CHECK(thread_class != nullptr);
context_class_loader_ = thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
CHECK(context_class_loader_ != nullptr); // Now wait for all required system threads to come up before allowing the rest of loading to // continue.
WaitForSystemDaemonStart(self);
}
JvmtiUniquePtr<char[]> name_uptr; if (target != nullptr) { // Have a native thread object, this thread is alive.
std::string name;
target->GetThreadName(name);
jvmtiError name_result;
name_uptr = CopyString(env, name.c_str(), &name_result); if (name_uptr == nullptr) { return name_result;
}
info_ptr->name = name_uptr.get();
info_ptr->priority = target->GetNativePriority();
info_ptr->is_daemon = target->IsDaemon();
art::ObjPtr<art::mirror::Object> peer = target->LockedGetPeerFromOtherThread(); // *target may be invalid here since we may have temporarily released thread_list_lock_.
target = nullptr; // Value should not be used.
// ThreadGroup. if (peer != nullptr) {
art::ArtField* f = art::WellKnownClasses::java_lang_Thread_group;
CHECK(f != nullptr);
art::ObjPtr<art::mirror::Object> group = f->GetObject(peer);
info_ptr->thread_group = group == nullptr
? nullptr
: soa.AddLocalReference<jthreadGroup>(group);
} else {
info_ptr->thread_group = nullptr;
}
// Context classloader.
DCHECK(context_class_loader_ != nullptr);
art::ObjPtr<art::mirror::Object> ccl = peer != nullptr
? context_class_loader_->GetObject(peer)
: nullptr;
info_ptr->context_class_loader = ccl == nullptr
? nullptr
: soa.AddLocalReference<jobject>(ccl);
} else { // Only the peer. This thread has either not been started, or is dead. Read things from // the Java side.
art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread);
if (state.thread_user_code_suspend_count != 0) { // Suspended can be set with any thread state so check it here. Even if the thread isn't in // kSuspended state it will move to that once it hits a checkpoint so we can still set this.
jvmti_state |= JVMTI_THREAD_STATE_SUSPENDED; // Note: We do not have data about the previous state. Otherwise we should load the previous // state here.
}
if (state.native_thread->IsInterrupted()) { // Interrupted can be set with any thread state so check it here.
jvmti_state |= JVMTI_THREAD_STATE_INTERRUPTED;
}
// Enumerate all the thread states and fill in the other bits. This contains the results of // following the decision tree in the JVMTI spec GetThreadState documentation. switch (internal_thread_state) { case art::ThreadState::kRunnable: case art::ThreadState::kWaitingWeakGcRootRead: case art::ThreadState::kSuspended: // These are all simply runnable. // kRunnable is self-explanatory. // kWaitingWeakGcRootRead is set during some operations with strings due to the intern-table // so we want to keep it marked as runnable. // kSuspended we don't mark since if we don't have a user_code_suspend_count then it is done // by the GC and not a JVMTI suspension, which means it cannot be removed by ResumeThread.
jvmti_state |= JVMTI_THREAD_STATE_RUNNABLE; break; case art::ThreadState::kNative: // kNative means native and runnable. Technically THREAD_STATE_IN_NATIVE can be set with any // state but we don't have the information to know if it should be present for any but the // kNative state.
jvmti_state |= (JVMTI_THREAD_STATE_IN_NATIVE |
JVMTI_THREAD_STATE_RUNNABLE); break; case art::ThreadState::kBlocked: // Blocked is one of the top level states so it sits alone.
jvmti_state |= JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER; break; case art::ThreadState::kWaiting: // Object.wait() so waiting, indefinitely, in object.wait.
jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
JVMTI_THREAD_STATE_WAITING_INDEFINITELY |
JVMTI_THREAD_STATE_IN_OBJECT_WAIT); break; case art::ThreadState::kTimedWaiting: // Object.wait(long) so waiting, with timeout, in object.wait.
jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
JVMTI_THREAD_STATE_IN_OBJECT_WAIT); break; case art::ThreadState::kSleeping: // In object.sleep. This is a timed wait caused by sleep.
jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT |
JVMTI_THREAD_STATE_SLEEPING); break; // TODO We might want to print warnings if we have the debugger running while JVMTI agents are // attached. case art::ThreadState::kWaitingForDebuggerSend: case art::ThreadState::kWaitingForDebuggerToAttach: case art::ThreadState::kWaitingInMainDebuggerLoop: case art::ThreadState::kWaitingForDebuggerSuspension: case art::ThreadState::kWaitingForLockInflation: case art::ThreadState::kWaitingForTaskProcessor: case art::ThreadState::kWaitingForGcToComplete: case art::ThreadState::kWaitingForCheckPointsToRun: case art::ThreadState::kWaitingPerformingGc: case art::ThreadState::kWaitingForJniOnLoad: case art::ThreadState::kWaitingInMainSignalCatcherLoop: case art::ThreadState::kWaitingForSignalCatcherOutput: case art::ThreadState::kWaitingForDeoptimization: case art::ThreadState::kWaitingForMethodTracingStart: case art::ThreadState::kWaitingForVisitObjects: case art::ThreadState::kWaitingForGetObjectsAllocated: case art::ThreadState::kWaitingForGcThreadFlip: case art::ThreadState::kNativeForAbort: // All of these are causing the thread to wait for an indeterminate amount of time but isn't // caused by sleep, park, or object#wait.
jvmti_state |= (JVMTI_THREAD_STATE_WAITING |
JVMTI_THREAD_STATE_WAITING_INDEFINITELY); break; case art::ThreadState::kObsoleteRunnable: // Obsolete value. case art::ThreadState::kStarting: case art::ThreadState::kTerminated: case art::ThreadState::kInvalidState: // We only call this if we are alive so we shouldn't see either of these states.
LOG(FATAL) << "Should not be in state " << internal_thread_state;
UNREACHABLE();
} // TODO: PARKED. We'll have to inspect the stack.
case art::ThreadState::kRunnable: case art::ThreadState::kNative: case art::ThreadState::kWaitingWeakGcRootRead: case art::ThreadState::kSuspended: return JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE;
case art::ThreadState::kTimedWaiting: case art::ThreadState::kSleeping: return JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING;
case art::ThreadState::kBlocked: return JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED;
case art::ThreadState::kStarting: return JVMTI_JAVA_LANG_THREAD_STATE_NEW;
case art::ThreadState::kWaiting: case art::ThreadState::kWaitingForTaskProcessor: case art::ThreadState::kWaitingForLockInflation: case art::ThreadState::kWaitingForGcToComplete: case art::ThreadState::kWaitingPerformingGc: case art::ThreadState::kWaitingForCheckPointsToRun: case art::ThreadState::kWaitingForDebuggerSend: case art::ThreadState::kWaitingForDebuggerToAttach: case art::ThreadState::kWaitingInMainDebuggerLoop: case art::ThreadState::kWaitingForDebuggerSuspension: case art::ThreadState::kWaitingForDeoptimization: case art::ThreadState::kWaitingForGetObjectsAllocated: case art::ThreadState::kWaitingForJniOnLoad: case art::ThreadState::kWaitingForSignalCatcherOutput: case art::ThreadState::kWaitingInMainSignalCatcherLoop: case art::ThreadState::kWaitingForMethodTracingStart: case art::ThreadState::kWaitingForVisitObjects: case art::ThreadState::kWaitingForGcThreadFlip: case art::ThreadState::kNativeForAbort: return JVMTI_JAVA_LANG_THREAD_STATE_WAITING;
case art::ThreadState::kObsoleteRunnable: case art::ThreadState::kInvalidState: break; // Obsolete or invalid value.
}
LOG(FATAL) << "Unreachable";
UNREACHABLE();
}
// Suspends the current thread if it has any suspend requests on it. void ThreadUtil::SuspendCheck(art::Thread* self) {
DCHECK(!self->ReadFlag(art::ThreadFlag::kSuspensionImmune, std::memory_order_relaxed));
art::ScopedObjectAccess soa(self); // Really this is only needed if we are in FastJNI and actually have the mutator_lock_ already.
self->FullSuspendCheck();
}
// Translate internal thread state to JVMTI and Java state.
jint jvmti_state = GetJvmtiThreadStateFromInternal(state);
// Java state is derived from nativeGetState. // TODO: Our implementation assigns "runnable" to suspended. As such, we will have slightly // different mask if a thread got suspended due to user-code. However, this is for // consistency with the Java view.
jint java_state = GetJavaStateFromInternal(state);
art::MutexLock mu(current, *art::Locks::thread_list_lock_);
std::list<art::Thread*> thread_list = art::Runtime::Current()->GetThreadList()->GetList(); // We have to be careful with threads exiting while we build this list.
std::vector<art::ThreadExitFlag> tefs(thread_list.size()); auto i = tefs.begin(); for (art::Thread* thd : thread_list) {
thd->NotifyOnThreadExit(&*i++);
}
DCHECK(i == tefs.end());
i = tefs.begin(); for (art::Thread* thread : thread_list) {
art::ThreadExitFlag* tef = &*i++; // Skip threads that have since exited or are still starting. We also don't need to report // runtime threads like jit worker threads. if (!tef->HasExited() && !thread->IsStillStarting() && !thread->IsRuntimeThread()) { // LockedGetPeerFromOtherThreads() may release lock!
art::ObjPtr<art::mirror::Object> peer = thread->LockedGetPeerFromOtherThread(tef); if (peer != nullptr) {
peers.push_back(peer);
}
}
thread->UnregisterThreadExitFlag(tef);
}
DCHECK(i == tefs.end());
// We already have a peer. So call our special Attach function.
art::Thread* self = art::Thread::Attach(data->name.c_str(), true, data->thread);
CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached."; // The name in Attach() is only for logging. Set the thread name. This is important so // that the thread is no longer seen as starting up.
{
art::ScopedObjectAccess soa(self);
self->SetThreadName(data->name.c_str());
}
{ // The StartThreadBirth was called in the parent thread. We let the runtime know we are up // before going into the provided code.
art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
art::Runtime::Current()->EndThreadBirth();
}
// Run the agent code.
data->proc(data->jvmti_env, env, const_cast<void*>(data->arg));
// Detach the thread. int detach_result = data->java_vm->DetachCurrentThread();
CHECK_EQ(detach_result, 0);
{
art::MutexLock mu(soa.Self(), *art::Locks::runtime_shutdown_lock_); if (runtime->IsShuttingDownLocked()) { // The runtime is shutting down so we cannot create new threads. // TODO It's not fully clear from the spec what we should do here. We aren't yet in // JVMTI_PHASE_DEAD so we cannot return ERR(WRONG_PHASE) but creating new threads is now // impossible. Existing agents don't seem to generally do anything with this return value so // it doesn't matter too much. We could do something like sending a fake ThreadStart event // even though code is never actually run. return ERR(INTERNAL);
}
runtime->StartThreadBirth();
}
data.reset(new AgentData);
data->arg = arg;
data->proc = proc; // We need a global ref for Java objects, as local refs will be invalid.
data->thread = runtime->GetJavaVM()->AddGlobalRef(soa.Self(), othread);
data->java_vm = runtime->GetJavaVM();
data->jvmti_env = jvmti_env;
data->priority = priority;
art::ObjPtr<art::mirror::Object> name =
art::WellKnownClasses::java_lang_Thread_name->GetObject(
soa.Decode<art::mirror::Object>(thread)); if (name == nullptr) {
data->name = "JVMTI Agent Thread";
} else {
data->name = name->AsString()->ToModifiedUtf8();
}
}
pthread_t pthread; int pthread_create_result = pthread_create(&pthread,
nullptr,
&AgentCallback, reinterpret_cast<void*>(data.get())); if (pthread_create_result != 0) { // If the create succeeded the other thread will call EndThreadBirth.
art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
runtime->EndThreadBirth(); return ERR(INTERNAL);
}
data.release(); // NOLINT pthreads API.
return ERR(NONE);
}
jvmtiError ThreadUtil::SuspendOther(art::Thread* self,
jthread target_jthread) { // Loop since we need to bail out and try again if we would end up getting suspended while holding // the user_code_suspension_lock_ due to a SuspendReason::kForUserCode. In this situation we // release the lock, wait to get resumed and try again. do {
ScopedNoUserCodeSuspension snucs(self); // We are not going to be suspended by user code from now on.
{
art::ScopedObjectAccess soa(self);
art::MutexLock thread_list_mu(self, *art::Locks::thread_list_lock_);
art::Thread* target = nullptr;
jvmtiError err = ERR(INTERNAL); if (!GetAliveNativeThread(target_jthread, soa, &target, &err)) { return err;
}
art::ThreadState state = target->GetState(); if (state == art::ThreadState::kStarting || target->IsStillStarting()) { return ERR(THREAD_NOT_ALIVE);
} else {
art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_); if (target->GetUserCodeSuspendCount() != 0) { return ERR(THREAD_SUSPENDED);
}
}
}
art::Thread* ret_target = art::Runtime::Current()->GetThreadList()->SuspendThreadByPeer(
target_jthread, art::SuspendReason::kForUserCode); if (ret_target == nullptr) { // TODO It would be good to get more information about why exactly the thread failed to // suspend. return ERR(INTERNAL);
} else { return OK;
} // We timed out. Just go around and try again.
} while (true);
}
jvmtiError ThreadUtil::SuspendSelf(art::Thread* self) {
CHECK(self == art::Thread::Current());
{
art::MutexLock mu(self, *art::Locks::user_code_suspension_lock_); // IncrementSuspendCount normally needs thread_list_lock_ to ensure the thread stays // around. In this case we are the target thread, so we fake it.
art::FakeMutexLock fmu(*art::Locks::thread_list_lock_);
art::MutexLock thread_list_mu(self, *art::Locks::thread_suspend_count_lock_); if (self->GetUserCodeSuspendCount() != 0) { // This can only happen if we race with another thread to suspend 'self' and we lose. return ERR(THREAD_SUSPENDED);
}
self->IncrementSuspendCount(self, nullptr, nullptr, art::SuspendReason::kForUserCode);
} // Once we have requested the suspend we actually go to sleep. We need to do this after releasing // the suspend_lock to make sure we can be woken up. This call gains the mutator lock causing us // to go to sleep until we are resumed.
SuspendCheck(self); return OK;
}
// Make sure we won't get suspended ourselves while in the middle of resuming another thread.
ScopedNoUserCodeSuspension snucs(self); // From now on we know we cannot get suspended by user-code.
{ // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't // have the 'suspend_lock' locked here.
art::ScopedObjectAccess soa(self);
art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
jvmtiError err = ERR(INTERNAL); if (!GetAliveNativeThread(thread, soa, &target, &err)) { return err;
} elseif (target == self) { // We would have paused until we aren't suspended anymore due to the ScopedObjectAccess so // we can just return THREAD_NOT_SUSPENDED. Unfortunately we cannot do any real DCHECKs // about current state since it's all concurrent. return ERR(THREAD_NOT_SUSPENDED);
} // The JVMTI spec requires us to return THREAD_NOT_SUSPENDED if it is alive but we really // cannot tell why resume failed.
{
art::MutexLock thread_suspend_count_mu(self, *art::Locks::thread_suspend_count_lock_); if (target->GetUserCodeSuspendCount() == 0) { return ERR(THREAD_NOT_SUSPENDED);
}
}
} // It is okay that we don't have a thread_list_lock here since we know that the thread cannot // die since it is currently held suspended by a SuspendReason::kForUserCode suspend.
DCHECK(target != self); if (!art::Runtime::Current()->GetThreadList()->Resume(target,
art::SuspendReason::kForUserCode)) { // TODO Give a better error. // This is most likely THREAD_NOT_SUSPENDED but we cannot really be sure. return ERR(INTERNAL);
} else { return OK;
}
}
// Suspends all the threads in the list at the same time. Getting this behavior is a little tricky // since we can have threads in the list multiple times. This generally doesn't matter unless the // current thread is present multiple times. In that case we need to suspend only once and either // return the same error code in all the other slots if it failed or return ERR(THREAD_SUSPENDED) if // it didn't. We also want to handle the current thread last to make the behavior of the code // simpler to understand.
jvmtiError ThreadUtil::SuspendThreadList(jvmtiEnv* env,
jint request_count, const jthread* threads,
jvmtiError* results) { if (request_count == 0) { return ERR(ILLEGAL_ARGUMENT);
} elseif (results == nullptr || threads == nullptr) { return ERR(NULL_POINTER);
} // This is the list of the indexes in 'threads' and 'results' that correspond to the currently // running thread. These indexes we need to handle specially since we need to only actually // suspend a single time.
std::vector<jint> current_thread_indexes; for (jint i = 0; i < request_count; i++) { if (IsCurrentThread(threads[i])) {
current_thread_indexes.push_back(i);
} else {
results[i] = env->SuspendThread(threads[i]);
}
} if (!current_thread_indexes.empty()) {
jint first_current_thread_index = current_thread_indexes[0]; // Suspend self.
jvmtiError res = env->SuspendThread(threads[first_current_thread_index]);
results[first_current_thread_index] = res; // Fill in the rest of the error values as appropriate.
jvmtiError other_results = (res != OK) ? res : ERR(THREAD_SUSPENDED); for (auto it = ++current_thread_indexes.begin(); it != current_thread_indexes.end(); ++it) {
results[*it] = other_results;
}
} return OK;
}
void Run(art::Thread* me) override REQUIRES_SHARED(art::Locks::mutator_lock_) { // Make sure the thread is prepared to notice the exception.
DeoptManager::Get()->DeoptimizeThread(me);
me->SetAsyncException(exception_.Get()); // Wake up the thread if it is sleeping.
me->Notify();
}
private:
art::Handle<art::mirror::Throwable> exception_;
};
StopThreadClosure c(exc); // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution. if (target->RequestSynchronousCheckpoint(&c)) { return OK;
} else { // Something went wrong, probably the thread died. return ERR(THREAD_NOT_ALIVE);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.