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 {
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 bool timed_out;
63
64 // Check for valid thread
65 if (thin_lock_id == ThreadList::kInvalidThreadId) {
66 return nullptr;
67 }
68
69 // Suspend thread to build stack trace.
70 Thread* thread = thread_list->SuspendThreadByThreadId(thin_lock_id,
71 SuspendReason::kInternal,
72 &timed_out);
73 if (thread != nullptr) {
74 {
75 ScopedObjectAccess soa(env);
76 jobject internal_trace = thread->CreateInternalStackTrace(soa);
77 trace = Thread::InternalStackTraceToStackTraceElementArray(soa, internal_trace);
78 }
79 // Restart suspended thread.
80 bool resumed = thread_list->Resume(thread, SuspendReason::kInternal);
81 DCHECK(resumed);
82 } else {
83 if (timed_out) {
84 LOG(ERROR) << "Trying to get thread's stack by id failed as the thread failed to suspend "
85 "within a generous timeout.";
86 }
87 }
88 }
89 return trace;
90 }
91
ThreadCountCallback(Thread *,void * context)92 static void ThreadCountCallback(Thread*, void* context) {
93 uint16_t& count = *reinterpret_cast<uint16_t*>(context);
94 ++count;
95 }
96
97 static const int kThstBytesPerEntry = 18;
98 static const int kThstHeaderLen = 4;
99
ToJdwpThreadStatus(ThreadState state)100 static constexpr uint8_t ToJdwpThreadStatus(ThreadState state) {
101 /*
102 * ThreadStatus constants.
103 */
104 enum JdwpThreadStatus : uint8_t {
105 TS_ZOMBIE = 0,
106 TS_RUNNING = 1, // RUNNING
107 TS_SLEEPING = 2, // (in Thread.sleep())
108 TS_MONITOR = 3, // WAITING (monitor wait)
109 TS_WAIT = 4, // (in Object.wait())
110 };
111 switch (state) {
112 case ThreadState::kBlocked:
113 return TS_MONITOR;
114 case ThreadState::kNative:
115 case ThreadState::kRunnable:
116 case ThreadState::kSuspended:
117 return TS_RUNNING;
118 case ThreadState::kObsoleteRunnable:
119 break; // Obsolete value.
120 case ThreadState::kSleeping:
121 return TS_SLEEPING;
122 case ThreadState::kStarting:
123 case ThreadState::kTerminated:
124 return TS_ZOMBIE;
125 case ThreadState::kTimedWaiting:
126 case ThreadState::kWaitingForTaskProcessor:
127 case ThreadState::kWaitingForLockInflation:
128 case ThreadState::kWaitingForCheckPointsToRun:
129 case ThreadState::kWaitingForDebuggerSend:
130 case ThreadState::kWaitingForDebuggerSuspension:
131 case ThreadState::kWaitingForDebuggerToAttach:
132 case ThreadState::kWaitingForDeoptimization:
133 case ThreadState::kWaitingForGcToComplete:
134 case ThreadState::kWaitingForGetObjectsAllocated:
135 case ThreadState::kWaitingForJniOnLoad:
136 case ThreadState::kWaitingForMethodTracingStart:
137 case ThreadState::kWaitingForSignalCatcherOutput:
138 case ThreadState::kWaitingForVisitObjects:
139 case ThreadState::kWaitingInMainDebuggerLoop:
140 case ThreadState::kWaitingInMainSignalCatcherLoop:
141 case ThreadState::kWaitingPerformingGc:
142 case ThreadState::kWaitingWeakGcRootRead:
143 case ThreadState::kWaitingForGcThreadFlip:
144 case ThreadState::kNativeForAbort:
145 case ThreadState::kWaiting:
146 return TS_WAIT;
147 // Don't add a 'default' here so the compiler can spot incompatible enum changes.
148 }
149 LOG(FATAL) << "Unknown thread state: " << state;
150 UNREACHABLE();
151 }
152
ThreadStatsGetterCallback(Thread * t,void * context)153 static void ThreadStatsGetterCallback(Thread* t, void* context) {
154 /*
155 * Generate the contents of a THST chunk. The data encompasses all known
156 * threads.
157 *
158 * Response has:
159 * (1b) header len
160 * (1b) bytes per entry
161 * (2b) thread count
162 * Then, for each thread:
163 * (4b) thread id
164 * (1b) thread status
165 * (4b) tid
166 * (4b) utime
167 * (4b) stime
168 * (1b) is daemon?
169 *
170 * The length fields exist in anticipation of adding additional fields
171 * without wanting to break ddms or bump the full protocol version. I don't
172 * think it warrants full versioning. They might be extraneous and could
173 * be removed from a future version.
174 */
175 char native_thread_state;
176 int utime;
177 int stime;
178 int task_cpu;
179 GetTaskStats(t->GetTid(), &native_thread_state, &utime, &stime, &task_cpu);
180
181 std::vector<uint8_t>& bytes = *reinterpret_cast<std::vector<uint8_t>*>(context);
182 Append4BE(bytes, t->GetThreadId());
183 Append1BE(bytes, ToJdwpThreadStatus(t->GetState()));
184 Append4BE(bytes, t->GetTid());
185 Append4BE(bytes, utime);
186 Append4BE(bytes, stime);
187 Append1BE(bytes, t->IsDaemon());
188 }
189
DdmVmInternal_getThreadStats(JNIEnv * env,jclass)190 static jbyteArray DdmVmInternal_getThreadStats(JNIEnv* env, jclass) {
191 std::vector<uint8_t> bytes;
192 Thread* self = GetSelf(env);
193 {
194 MutexLock mu(self, *Locks::thread_list_lock_);
195 ThreadList* thread_list = Runtime::Current()->GetThreadList();
196
197 uint16_t thread_count = 0;
198 thread_list->ForEach(ThreadCountCallback, &thread_count);
199
200 Append1BE(bytes, kThstHeaderLen);
201 Append1BE(bytes, kThstBytesPerEntry);
202 Append2BE(bytes, thread_count);
203
204 thread_list->ForEach(ThreadStatsGetterCallback, &bytes);
205 }
206
207 jbyteArray result = env->NewByteArray(bytes.size());
208 if (result != nullptr) {
209 env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
210 }
211 return result;
212 }
213
214 static JNINativeMethod gMethods[] = {
215 NATIVE_METHOD(DdmVmInternal, setRecentAllocationsTrackingEnabled, "(Z)V"),
216 NATIVE_METHOD(DdmVmInternal, setThreadNotifyEnabled, "(Z)V"),
217 NATIVE_METHOD(DdmVmInternal, getStackTraceById, "(I)[Ljava/lang/StackTraceElement;"),
218 NATIVE_METHOD(DdmVmInternal, getThreadStats, "()[B"),
219 };
220
register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv * env)221 void register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv* env) {
222 REGISTER_NATIVE_METHODS("org/apache/harmony/dalvik/ddmc/DdmVmInternal");
223 }
224
225 } // namespace art
226