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 "org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
18 
19 #include <android-base/logging.h>
20 
21 #include "base/file_utils.h"
22 #include "base/mutex.h"
23 #include "base/endian_utils.h"
24 #include "debugger.h"
25 #include "gc/heap.h"
26 #include "jni/jni_internal.h"
27 #include "native_util.h"
28 #include "nativehelper/jni_macros.h"
29 #include "nativehelper/scoped_local_ref.h"
30 #include "nativehelper/scoped_primitive_array.h"
31 #include "scoped_fast_native_object_access-inl.h"
32 #include "thread_list.h"
33 
34 namespace art HIDDEN {
35 
DdmVmInternal_setRecentAllocationsTrackingEnabled(JNIEnv *,jclass,jboolean enable)36 static void DdmVmInternal_setRecentAllocationsTrackingEnabled(JNIEnv*, jclass, jboolean enable) {
37   Dbg::SetAllocTrackingEnabled(enable);
38 }
39 
DdmVmInternal_setThreadNotifyEnabled(JNIEnv *,jclass,jboolean enable)40 static void DdmVmInternal_setThreadNotifyEnabled(JNIEnv*, jclass, jboolean enable) {
41   Dbg::DdmSetThreadNotification(enable);
42 }
43 
GetSelf(JNIEnv * env)44 static Thread* GetSelf(JNIEnv* env) {
45   return static_cast<JNIEnvExt*>(env)->GetSelf();
46 }
47 
48 /*
49  * Get a stack trace as an array of StackTraceElement objects.  Returns
50  * nullptr on failure, e.g. if the threadId couldn't be found.
51  */
DdmVmInternal_getStackTraceById(JNIEnv * env,jclass,jint thin_lock_id)52 static jobjectArray DdmVmInternal_getStackTraceById(JNIEnv* env, jclass, jint thin_lock_id) {
53   jobjectArray trace = nullptr;
54   Thread* const self = GetSelf(env);
55   if (static_cast<uint32_t>(thin_lock_id) == self->GetThreadId()) {
56     // No need to suspend ourself to build stacktrace.
57     ScopedObjectAccess soa(env);
58     jobject internal_trace = self->CreateInternalStackTrace(soa);
59     trace = Thread::InternalStackTraceToStackTraceElementArray(soa, internal_trace);
60   } else {
61     ThreadList* thread_list = Runtime::Current()->GetThreadList();
62 
63     // Check for valid thread
64     if (thin_lock_id == ThreadList::kInvalidThreadId) {
65       return nullptr;
66     }
67 
68     // Suspend thread to build stack trace.
69     Thread* thread = thread_list->SuspendThreadByThreadId(thin_lock_id, SuspendReason::kInternal);
70     if (thread != nullptr) {
71       {
72         ScopedObjectAccess soa(env);
73         jobject internal_trace = thread->CreateInternalStackTrace(soa);
74         trace = Thread::InternalStackTraceToStackTraceElementArray(soa, internal_trace);
75       }
76       // Restart suspended thread.
77       bool resumed = thread_list->Resume(thread, SuspendReason::kInternal);
78       DCHECK(resumed);
79     }
80   }
81   return trace;
82 }
83 
ThreadCountCallback(Thread *,void * context)84 static void ThreadCountCallback(Thread*, void* context) {
85   uint16_t& count = *reinterpret_cast<uint16_t*>(context);
86   ++count;
87 }
88 
89 static const int kThstBytesPerEntry = 18;
90 static const int kThstHeaderLen = 4;
91 
ToJdwpThreadStatus(ThreadState state)92 static constexpr uint8_t ToJdwpThreadStatus(ThreadState state) {
93   /*
94   * ThreadStatus constants.
95   */
96   enum JdwpThreadStatus : uint8_t {
97     TS_ZOMBIE   = 0,
98     TS_RUNNING  = 1,  // RUNNING
99     TS_SLEEPING = 2,  // (in Thread.sleep())
100     TS_MONITOR  = 3,  // WAITING (monitor wait)
101     TS_WAIT     = 4,  // (in Object.wait())
102   };
103   switch (state) {
104     case ThreadState::kBlocked:
105       return TS_MONITOR;
106     case ThreadState::kNative:
107     case ThreadState::kRunnable:
108     case ThreadState::kSuspended:
109       return TS_RUNNING;
110     case ThreadState::kObsoleteRunnable:
111     case ThreadState::kInvalidState:
112       break;  // Obsolete or invalid value.
113     case ThreadState::kSleeping:
114       return TS_SLEEPING;
115     case ThreadState::kStarting:
116     case ThreadState::kTerminated:
117       return TS_ZOMBIE;
118     case ThreadState::kTimedWaiting:
119     case ThreadState::kWaitingForTaskProcessor:
120     case ThreadState::kWaitingForLockInflation:
121     case ThreadState::kWaitingForCheckPointsToRun:
122     case ThreadState::kWaitingForDebuggerSend:
123     case ThreadState::kWaitingForDebuggerSuspension:
124     case ThreadState::kWaitingForDebuggerToAttach:
125     case ThreadState::kWaitingForDeoptimization:
126     case ThreadState::kWaitingForGcToComplete:
127     case ThreadState::kWaitingForGetObjectsAllocated:
128     case ThreadState::kWaitingForJniOnLoad:
129     case ThreadState::kWaitingForMethodTracingStart:
130     case ThreadState::kWaitingForSignalCatcherOutput:
131     case ThreadState::kWaitingForVisitObjects:
132     case ThreadState::kWaitingInMainDebuggerLoop:
133     case ThreadState::kWaitingInMainSignalCatcherLoop:
134     case ThreadState::kWaitingPerformingGc:
135     case ThreadState::kWaitingWeakGcRootRead:
136     case ThreadState::kWaitingForGcThreadFlip:
137     case ThreadState::kNativeForAbort:
138     case ThreadState::kWaiting:
139       return TS_WAIT;
140       // Don't add a 'default' here so the compiler can spot incompatible enum changes.
141   }
142   LOG(FATAL) << "Unknown thread state: " << state;
143   UNREACHABLE();
144 }
145 
ThreadStatsGetterCallback(Thread * t,void * context)146 static void ThreadStatsGetterCallback(Thread* t, void* context) {
147   /*
148    * Generate the contents of a THST chunk.  The data encompasses all known
149    * threads.
150    *
151    * Response has:
152    *  (1b) header len
153    *  (1b) bytes per entry
154    *  (2b) thread count
155    * Then, for each thread:
156    *  (4b) thread id
157    *  (1b) thread status
158    *  (4b) tid
159    *  (4b) utime
160    *  (4b) stime
161    *  (1b) is daemon?
162    *
163    * The length fields exist in anticipation of adding additional fields
164    * without wanting to break ddms or bump the full protocol version.  I don't
165    * think it warrants full versioning.  They might be extraneous and could
166    * be removed from a future version.
167    */
168   char native_thread_state;
169   int utime;
170   int stime;
171   int task_cpu;
172   GetTaskStats(t->GetTid(), &native_thread_state, &utime, &stime, &task_cpu);
173 
174   std::vector<uint8_t>& bytes = *reinterpret_cast<std::vector<uint8_t>*>(context);
175   Append4BE(bytes, t->GetThreadId());
176   Append1BE(bytes, ToJdwpThreadStatus(t->GetState()));
177   Append4BE(bytes, t->GetTid());
178   Append4BE(bytes, utime);
179   Append4BE(bytes, stime);
180   Append1BE(bytes, t->IsDaemon());
181 }
182 
DdmVmInternal_getThreadStats(JNIEnv * env,jclass)183 static jbyteArray DdmVmInternal_getThreadStats(JNIEnv* env, jclass) {
184   std::vector<uint8_t> bytes;
185   Thread* self = GetSelf(env);
186   {
187     MutexLock mu(self, *Locks::thread_list_lock_);
188     ThreadList* thread_list = Runtime::Current()->GetThreadList();
189 
190     uint16_t thread_count = 0;
191     thread_list->ForEach(ThreadCountCallback, &thread_count);
192 
193     Append1BE(bytes, kThstHeaderLen);
194     Append1BE(bytes, kThstBytesPerEntry);
195     Append2BE(bytes, thread_count);
196 
197     thread_list->ForEach(ThreadStatsGetterCallback, &bytes);
198   }
199 
200   jbyteArray result = env->NewByteArray(bytes.size());
201   if (result != nullptr) {
202     env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
203   }
204   return result;
205 }
206 
207 static JNINativeMethod gMethods[] = {
208   NATIVE_METHOD(DdmVmInternal, setRecentAllocationsTrackingEnabled, "(Z)V"),
209   NATIVE_METHOD(DdmVmInternal, setThreadNotifyEnabled, "(Z)V"),
210   NATIVE_METHOD(DdmVmInternal, getStackTraceById, "(I)[Ljava/lang/StackTraceElement;"),
211   NATIVE_METHOD(DdmVmInternal, getThreadStats, "()[B"),
212 };
213 
register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv * env)214 void register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv* env) {
215   REGISTER_NATIVE_METHODS("org/apache/harmony/dalvik/ddmc/DdmVmInternal");
216 }
217 
218 }  // namespace art
219