1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "java_lang_Thread.h"
18 
19 #include "common_throws.h"
20 #include "jni/jni_internal.h"
21 #include "mirror/object.h"
22 #include "monitor.h"
23 #include "native_util.h"
24 #include "nativehelper/jni_macros.h"
25 #include "nativehelper/scoped_utf_chars.h"
26 #include "scoped_fast_native_object_access-inl.h"
27 #include "scoped_thread_state_change-inl.h"
28 #include "thread.h"
29 #include "thread_list.h"
30 #include "verify_object.h"
31 
32 namespace art {
33 
Thread_currentThread(JNIEnv * env,jclass)34 static jobject Thread_currentThread(JNIEnv* env, jclass) {
35   ScopedFastNativeObjectAccess soa(env);
36   return soa.AddLocalReference<jobject>(soa.Self()->GetPeer());
37 }
38 
Thread_interrupted(JNIEnv * env,jclass)39 static jboolean Thread_interrupted(JNIEnv* env, jclass) {
40   return static_cast<JNIEnvExt*>(env)->GetSelf()->Interrupted() ? JNI_TRUE : JNI_FALSE;
41 }
42 
Thread_isInterrupted(JNIEnv * env,jobject java_thread)43 static jboolean Thread_isInterrupted(JNIEnv* env, jobject java_thread) {
44   ScopedFastNativeObjectAccess soa(env);
45   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
46   Thread* thread = Thread::FromManagedThread(soa, java_thread);
47   return (thread != nullptr) ? thread->IsInterrupted() : JNI_FALSE;
48 }
49 
Thread_nativeCreate(JNIEnv * env,jclass,jobject java_thread,jlong stack_size,jboolean daemon)50 static void Thread_nativeCreate(JNIEnv* env, jclass, jobject java_thread, jlong stack_size,
51                                 jboolean daemon) {
52   // There are sections in the zygote that forbid thread creation.
53   Runtime* runtime = Runtime::Current();
54   if (runtime->IsZygote() && runtime->IsZygoteNoThreadSection()) {
55     jclass internal_error = env->FindClass("java/lang/InternalError");
56     CHECK(internal_error != nullptr);
57     env->ThrowNew(internal_error, "Cannot create threads in zygote");
58     return;
59   }
60 
61   Thread::CreateNativeThread(env, java_thread, stack_size, daemon == JNI_TRUE);
62 }
63 
Thread_nativeGetStatus(JNIEnv * env,jobject java_thread,jboolean has_been_started)64 static jint Thread_nativeGetStatus(JNIEnv* env, jobject java_thread, jboolean has_been_started) {
65   // Ordinals from Java's Thread.State.
66   const jint kJavaNew = 0;
67   const jint kJavaRunnable = 1;
68   const jint kJavaBlocked = 2;
69   const jint kJavaWaiting = 3;
70   const jint kJavaTimedWaiting = 4;
71   const jint kJavaTerminated = 5;
72 
73   ScopedObjectAccess soa(env);
74   ThreadState internal_thread_state = (has_been_started ? kTerminated : kStarting);
75   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
76   Thread* thread = Thread::FromManagedThread(soa, java_thread);
77   if (thread != nullptr) {
78     internal_thread_state = thread->GetState();
79   }
80   switch (internal_thread_state) {
81     case kTerminated:                     return kJavaTerminated;
82     case kRunnable:                       return kJavaRunnable;
83     case kTimedWaiting:                   return kJavaTimedWaiting;
84     case kSleeping:                       return kJavaTimedWaiting;
85     case kBlocked:                        return kJavaBlocked;
86     case kWaiting:                        return kJavaWaiting;
87     case kStarting:                       return kJavaNew;
88     case kNative:                         return kJavaRunnable;
89     case kWaitingForTaskProcessor:        return kJavaWaiting;
90     case kWaitingForLockInflation:        return kJavaWaiting;
91     case kWaitingForGcToComplete:         return kJavaWaiting;
92     case kWaitingPerformingGc:            return kJavaWaiting;
93     case kWaitingForCheckPointsToRun:     return kJavaWaiting;
94     case kWaitingForDebuggerSend:         return kJavaWaiting;
95     case kWaitingForDebuggerToAttach:     return kJavaWaiting;
96     case kWaitingInMainDebuggerLoop:      return kJavaWaiting;
97     case kWaitingForDebuggerSuspension:   return kJavaWaiting;
98     case kWaitingForDeoptimization:       return kJavaWaiting;
99     case kWaitingForGetObjectsAllocated:  return kJavaWaiting;
100     case kWaitingForJniOnLoad:            return kJavaWaiting;
101     case kWaitingForSignalCatcherOutput:  return kJavaWaiting;
102     case kWaitingInMainSignalCatcherLoop: return kJavaWaiting;
103     case kWaitingForMethodTracingStart:   return kJavaWaiting;
104     case kWaitingForVisitObjects:         return kJavaWaiting;
105     case kWaitingWeakGcRootRead:          return kJavaRunnable;
106     case kWaitingForGcThreadFlip:         return kJavaWaiting;
107     case kNativeForAbort:                 return kJavaWaiting;
108     case kSuspended:                      return kJavaRunnable;
109     // Don't add a 'default' here so the compiler can spot incompatible enum changes.
110   }
111   LOG(ERROR) << "Unexpected thread state: " << internal_thread_state;
112   return -1;  // Unreachable.
113 }
114 
Thread_getNativeTid(JNIEnv * env,jobject java_thread)115 static jint Thread_getNativeTid(JNIEnv* env, jobject java_thread) {
116   ScopedFastNativeObjectAccess soa(env);
117   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
118   Thread* thread = Thread::FromManagedThread(soa, java_thread);
119   return (thread != nullptr) ? thread->GetTid() : 0;
120 }
121 
Thread_holdsLock(JNIEnv * env,jclass,jobject java_object)122 static jboolean Thread_holdsLock(JNIEnv* env, jclass, jobject java_object) {
123   ScopedObjectAccess soa(env);
124   ObjPtr<mirror::Object> object = soa.Decode<mirror::Object>(java_object);
125   if (object == nullptr) {
126     ThrowNullPointerException("object == null");
127     return JNI_FALSE;
128   }
129   Thread* thread = soa.Self();
130   return thread->HoldsLock(object);
131 }
132 
Thread_interrupt0(JNIEnv * env,jobject java_thread)133 static void Thread_interrupt0(JNIEnv* env, jobject java_thread) {
134   ScopedFastNativeObjectAccess soa(env);
135   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
136   Thread* thread = Thread::FromManagedThread(soa, java_thread);
137   if (thread != nullptr) {
138     thread->Interrupt(soa.Self());
139   }
140 }
141 
Thread_setNativeName(JNIEnv * env,jobject peer,jstring java_name)142 static void Thread_setNativeName(JNIEnv* env, jobject peer, jstring java_name) {
143   ScopedUtfChars name(env, java_name);
144   {
145     ScopedObjectAccess soa(env);
146     if (soa.Decode<mirror::Object>(peer) == soa.Self()->GetPeer()) {
147       soa.Self()->SetThreadName(name.c_str());
148       return;
149     }
150   }
151   // Suspend thread to avoid it from killing itself while we set its name. We don't just hold the
152   // thread list lock to avoid this, as setting the thread name causes mutator to lock/unlock
153   // in the DDMS send code.
154   ThreadList* thread_list = Runtime::Current()->GetThreadList();
155   bool timed_out;
156   // Take suspend thread lock to avoid races with threads trying to suspend this one.
157   Thread* thread = thread_list->SuspendThreadByPeer(peer,
158                                                     /* request_suspension= */ true,
159                                                     SuspendReason::kInternal,
160                                                     &timed_out);
161   if (thread != nullptr) {
162     {
163       ScopedObjectAccess soa(env);
164       thread->SetThreadName(name.c_str());
165     }
166     bool resumed = thread_list->Resume(thread, SuspendReason::kInternal);
167     DCHECK(resumed);
168   } else if (timed_out) {
169     LOG(ERROR) << "Trying to set thread name to '" << name.c_str() << "' failed as the thread "
170         "failed to suspend within a generous timeout.";
171   }
172 }
173 
174 /*
175  * Alter the priority of the specified thread.  "new_priority" will range
176  * from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY (1-10), with "normal"
177  * threads at Thread.NORM_PRIORITY (5).
178  */
Thread_setPriority0(JNIEnv * env,jobject java_thread,jint new_priority)179 static void Thread_setPriority0(JNIEnv* env, jobject java_thread, jint new_priority) {
180   ScopedObjectAccess soa(env);
181   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
182   Thread* thread = Thread::FromManagedThread(soa, java_thread);
183   if (thread != nullptr) {
184     thread->SetNativePriority(new_priority);
185   }
186 }
187 
Thread_sleep(JNIEnv * env,jclass,jobject java_lock,jlong ms,jint ns)188 static void Thread_sleep(JNIEnv* env, jclass, jobject java_lock, jlong ms, jint ns) {
189   ScopedFastNativeObjectAccess soa(env);
190   ObjPtr<mirror::Object> lock = soa.Decode<mirror::Object>(java_lock);
191   Monitor::Wait(Thread::Current(), lock.Ptr(), ms, ns, true, kSleeping);
192 }
193 
194 /*
195  * Causes the thread to temporarily pause and allow other threads to execute.
196  *
197  * The exact behavior is poorly defined.  Some discussion here:
198  *   http://www.cs.umd.edu/~pugh/java/memoryModel/archive/0944.html
199  */
Thread_yield(JNIEnv *,jobject)200 static void Thread_yield(JNIEnv*, jobject) {
201   sched_yield();
202 }
203 
204 static JNINativeMethod gMethods[] = {
205   FAST_NATIVE_METHOD(Thread, currentThread, "()Ljava/lang/Thread;"),
206   FAST_NATIVE_METHOD(Thread, interrupted, "()Z"),
207   FAST_NATIVE_METHOD(Thread, isInterrupted, "()Z"),
208   FAST_NATIVE_METHOD(Thread, getNativeTid, "()I"),
209   NATIVE_METHOD(Thread, nativeCreate, "(Ljava/lang/Thread;JZ)V"),
210   NATIVE_METHOD(Thread, nativeGetStatus, "(Z)I"),
211   NATIVE_METHOD(Thread, holdsLock, "(Ljava/lang/Object;)Z"),
212   FAST_NATIVE_METHOD(Thread, interrupt0, "()V"),
213   NATIVE_METHOD(Thread, setNativeName, "(Ljava/lang/String;)V"),
214   NATIVE_METHOD(Thread, setPriority0, "(I)V"),
215   FAST_NATIVE_METHOD(Thread, sleep, "(Ljava/lang/Object;JI)V"),
216   NATIVE_METHOD(Thread, yield, "()V"),
217 };
218 
register_java_lang_Thread(JNIEnv * env)219 void register_java_lang_Thread(JNIEnv* env) {
220   REGISTER_NATIVE_METHODS("java/lang/Thread");
221 }
222 
223 }  // namespace art
224