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_holdsLock(JNIEnv * env,jclass,jobject java_object)115 static jboolean Thread_holdsLock(JNIEnv* env, jclass, jobject java_object) {
116   ScopedObjectAccess soa(env);
117   ObjPtr<mirror::Object> object = soa.Decode<mirror::Object>(java_object);
118   if (object == nullptr) {
119     ThrowNullPointerException("object == null");
120     return JNI_FALSE;
121   }
122   Thread* thread = soa.Self();
123   return thread->HoldsLock(object);
124 }
125 
Thread_interrupt0(JNIEnv * env,jobject java_thread)126 static void Thread_interrupt0(JNIEnv* env, jobject java_thread) {
127   ScopedFastNativeObjectAccess soa(env);
128   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
129   Thread* thread = Thread::FromManagedThread(soa, java_thread);
130   if (thread != nullptr) {
131     thread->Interrupt(soa.Self());
132   }
133 }
134 
Thread_setNativeName(JNIEnv * env,jobject peer,jstring java_name)135 static void Thread_setNativeName(JNIEnv* env, jobject peer, jstring java_name) {
136   ScopedUtfChars name(env, java_name);
137   {
138     ScopedObjectAccess soa(env);
139     if (soa.Decode<mirror::Object>(peer) == soa.Self()->GetPeer()) {
140       soa.Self()->SetThreadName(name.c_str());
141       return;
142     }
143   }
144   // Suspend thread to avoid it from killing itself while we set its name. We don't just hold the
145   // thread list lock to avoid this, as setting the thread name causes mutator to lock/unlock
146   // in the DDMS send code.
147   ThreadList* thread_list = Runtime::Current()->GetThreadList();
148   bool timed_out;
149   // Take suspend thread lock to avoid races with threads trying to suspend this one.
150   Thread* thread = thread_list->SuspendThreadByPeer(peer,
151                                                     /* request_suspension= */ true,
152                                                     SuspendReason::kInternal,
153                                                     &timed_out);
154   if (thread != nullptr) {
155     {
156       ScopedObjectAccess soa(env);
157       thread->SetThreadName(name.c_str());
158     }
159     bool resumed = thread_list->Resume(thread, SuspendReason::kInternal);
160     DCHECK(resumed);
161   } else if (timed_out) {
162     LOG(ERROR) << "Trying to set thread name to '" << name.c_str() << "' failed as the thread "
163         "failed to suspend within a generous timeout.";
164   }
165 }
166 
167 /*
168  * Alter the priority of the specified thread.  "new_priority" will range
169  * from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY (1-10), with "normal"
170  * threads at Thread.NORM_PRIORITY (5).
171  */
Thread_setPriority0(JNIEnv * env,jobject java_thread,jint new_priority)172 static void Thread_setPriority0(JNIEnv* env, jobject java_thread, jint new_priority) {
173   ScopedObjectAccess soa(env);
174   MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
175   Thread* thread = Thread::FromManagedThread(soa, java_thread);
176   if (thread != nullptr) {
177     thread->SetNativePriority(new_priority);
178   }
179 }
180 
Thread_sleep(JNIEnv * env,jclass,jobject java_lock,jlong ms,jint ns)181 static void Thread_sleep(JNIEnv* env, jclass, jobject java_lock, jlong ms, jint ns) {
182   ScopedFastNativeObjectAccess soa(env);
183   ObjPtr<mirror::Object> lock = soa.Decode<mirror::Object>(java_lock);
184   Monitor::Wait(Thread::Current(), lock.Ptr(), ms, ns, true, kSleeping);
185 }
186 
187 /*
188  * Causes the thread to temporarily pause and allow other threads to execute.
189  *
190  * The exact behavior is poorly defined.  Some discussion here:
191  *   http://www.cs.umd.edu/~pugh/java/memoryModel/archive/0944.html
192  */
Thread_yield(JNIEnv *,jobject)193 static void Thread_yield(JNIEnv*, jobject) {
194   sched_yield();
195 }
196 
197 static JNINativeMethod gMethods[] = {
198   FAST_NATIVE_METHOD(Thread, currentThread, "()Ljava/lang/Thread;"),
199   FAST_NATIVE_METHOD(Thread, interrupted, "()Z"),
200   FAST_NATIVE_METHOD(Thread, isInterrupted, "()Z"),
201   NATIVE_METHOD(Thread, nativeCreate, "(Ljava/lang/Thread;JZ)V"),
202   NATIVE_METHOD(Thread, nativeGetStatus, "(Z)I"),
203   NATIVE_METHOD(Thread, holdsLock, "(Ljava/lang/Object;)Z"),
204   FAST_NATIVE_METHOD(Thread, interrupt0, "()V"),
205   NATIVE_METHOD(Thread, setNativeName, "(Ljava/lang/String;)V"),
206   NATIVE_METHOD(Thread, setPriority0, "(I)V"),
207   FAST_NATIVE_METHOD(Thread, sleep, "(Ljava/lang/Object;JI)V"),
208   NATIVE_METHOD(Thread, yield, "()V"),
209 };
210 
register_java_lang_Thread(JNIEnv * env)211 void register_java_lang_Thread(JNIEnv* env) {
212   REGISTER_NATIVE_METHODS("java/lang/Thread");
213 }
214 
215 }  // namespace art
216