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_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
32namespace art {
33
34static jobject Thread_currentThread(JNIEnv* env, jclass) {
35  ScopedFastNativeObjectAccess soa(env);
36  return soa.AddLocalReference<jobject>(soa.Self()->GetPeer());
37}
38
39static jboolean Thread_interrupted(JNIEnv* env, jclass) {
40  return static_cast<JNIEnvExt*>(env)->GetSelf()->Interrupted() ? JNI_TRUE : JNI_FALSE;
41}
42
43static 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
50static 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
64static 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 kSuspended:                      return kJavaRunnable;
108    // Don't add a 'default' here so the compiler can spot incompatible enum changes.
109  }
110  LOG(ERROR) << "Unexpected thread state: " << internal_thread_state;
111  return -1;  // Unreachable.
112}
113
114static jboolean Thread_nativeHoldsLock(JNIEnv* env, jobject java_thread, jobject java_object) {
115  ScopedObjectAccess soa(env);
116  ObjPtr<mirror::Object> object = soa.Decode<mirror::Object>(java_object);
117  if (object == nullptr) {
118    ThrowNullPointerException("object == null");
119    return JNI_FALSE;
120  }
121  MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
122  Thread* thread = Thread::FromManagedThread(soa, java_thread);
123  return thread->HoldsLock(object.Ptr());
124}
125
126static void Thread_nativeInterrupt(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
135static void Thread_nativeSetName(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 */
172static void Thread_nativeSetPriority(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
181static 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 */
193static void Thread_yield(JNIEnv*, jobject) {
194  sched_yield();
195}
196
197static 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, nativeHoldsLock, "(Ljava/lang/Object;)Z"),
204  FAST_NATIVE_METHOD(Thread, nativeInterrupt, "()V"),
205  NATIVE_METHOD(Thread, nativeSetName, "(Ljava/lang/String;)V"),
206  NATIVE_METHOD(Thread, nativeSetPriority, "(I)V"),
207  FAST_NATIVE_METHOD(Thread, sleep, "(Ljava/lang/Object;JI)V"),
208  NATIVE_METHOD(Thread, yield, "()V"),
209};
210
211void register_java_lang_Thread(JNIEnv* env) {
212  REGISTER_NATIVE_METHODS("java/lang/Thread");
213}
214
215}  // namespace art
216