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 "base/logging.h"
20 #include "base/mutex.h"
21 #include "debugger.h"
22 #include "jni_internal.h"
23 #include "scoped_fast_native_object_access-inl.h"
24 #include "ScopedLocalRef.h"
25 #include "ScopedPrimitiveArray.h"
26 #include "thread_list.h"
27 
28 namespace art {
29 
DdmVmInternal_enableRecentAllocations(JNIEnv *,jclass,jboolean enable)30 static void DdmVmInternal_enableRecentAllocations(JNIEnv*, jclass, jboolean enable) {
31   Dbg::SetAllocTrackingEnabled(enable);
32 }
33 
DdmVmInternal_getRecentAllocations(JNIEnv * env,jclass)34 static jbyteArray DdmVmInternal_getRecentAllocations(JNIEnv* env, jclass) {
35   ScopedFastNativeObjectAccess soa(env);
36   return Dbg::GetRecentAllocations();
37 }
38 
DdmVmInternal_getRecentAllocationStatus(JNIEnv *,jclass)39 static jboolean DdmVmInternal_getRecentAllocationStatus(JNIEnv*, jclass) {
40   return Runtime::Current()->GetHeap()->IsAllocTrackingEnabled();
41 }
42 
43 /*
44  * Get a stack trace as an array of StackTraceElement objects.  Returns
45  * nullptr on failure, e.g. if the threadId couldn't be found.
46  */
DdmVmInternal_getStackTraceById(JNIEnv * env,jclass,jint thin_lock_id)47 static jobjectArray DdmVmInternal_getStackTraceById(JNIEnv* env, jclass, jint thin_lock_id) {
48   jobjectArray trace = nullptr;
49   Thread* const self = Thread::Current();
50   if (static_cast<uint32_t>(thin_lock_id) == self->GetThreadId()) {
51     // No need to suspend ourself to build stacktrace.
52     ScopedObjectAccess soa(env);
53     jobject internal_trace = self->CreateInternalStackTrace<false>(soa);
54     trace = Thread::InternalStackTraceToStackTraceElementArray(soa, internal_trace);
55   } else {
56     ThreadList* thread_list = Runtime::Current()->GetThreadList();
57     bool timed_out;
58 
59     // Check for valid thread
60     if (thin_lock_id == ThreadList::kInvalidThreadId) {
61       return nullptr;
62     }
63 
64     // Suspend thread to build stack trace.
65     Thread* thread = thread_list->SuspendThreadByThreadId(thin_lock_id, false, &timed_out);
66     if (thread != nullptr) {
67       {
68         ScopedObjectAccess soa(env);
69         jobject internal_trace = thread->CreateInternalStackTrace<false>(soa);
70         trace = Thread::InternalStackTraceToStackTraceElementArray(soa, internal_trace);
71       }
72       // Restart suspended thread.
73       thread_list->Resume(thread, false);
74     } else {
75       if (timed_out) {
76         LOG(ERROR) << "Trying to get thread's stack by id failed as the thread failed to suspend "
77             "within a generous timeout.";
78       }
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 
ThreadStatsGetterCallback(Thread * t,void * context)92 static void ThreadStatsGetterCallback(Thread* t, void* context) {
93   /*
94    * Generate the contents of a THST chunk.  The data encompasses all known
95    * threads.
96    *
97    * Response has:
98    *  (1b) header len
99    *  (1b) bytes per entry
100    *  (2b) thread count
101    * Then, for each thread:
102    *  (4b) thread id
103    *  (1b) thread status
104    *  (4b) tid
105    *  (4b) utime
106    *  (4b) stime
107    *  (1b) is daemon?
108    *
109    * The length fields exist in anticipation of adding additional fields
110    * without wanting to break ddms or bump the full protocol version.  I don't
111    * think it warrants full versioning.  They might be extraneous and could
112    * be removed from a future version.
113    */
114   char native_thread_state;
115   int utime;
116   int stime;
117   int task_cpu;
118   GetTaskStats(t->GetTid(), &native_thread_state, &utime, &stime, &task_cpu);
119 
120   std::vector<uint8_t>& bytes = *reinterpret_cast<std::vector<uint8_t>*>(context);
121   JDWP::Append4BE(bytes, t->GetThreadId());
122   JDWP::Append1BE(bytes, Dbg::ToJdwpThreadStatus(t->GetState()));
123   JDWP::Append4BE(bytes, t->GetTid());
124   JDWP::Append4BE(bytes, utime);
125   JDWP::Append4BE(bytes, stime);
126   JDWP::Append1BE(bytes, t->IsDaemon());
127 }
128 
DdmVmInternal_getThreadStats(JNIEnv * env,jclass)129 static jbyteArray DdmVmInternal_getThreadStats(JNIEnv* env, jclass) {
130   std::vector<uint8_t> bytes;
131   Thread* self = static_cast<JNIEnvExt*>(env)->self;
132   {
133     MutexLock mu(self, *Locks::thread_list_lock_);
134     ThreadList* thread_list = Runtime::Current()->GetThreadList();
135 
136     uint16_t thread_count = 0;
137     thread_list->ForEach(ThreadCountCallback, &thread_count);
138 
139     JDWP::Append1BE(bytes, kThstHeaderLen);
140     JDWP::Append1BE(bytes, kThstBytesPerEntry);
141     JDWP::Append2BE(bytes, thread_count);
142 
143     thread_list->ForEach(ThreadStatsGetterCallback, &bytes);
144   }
145 
146   jbyteArray result = env->NewByteArray(bytes.size());
147   if (result != nullptr) {
148     env->SetByteArrayRegion(result, 0, bytes.size(), reinterpret_cast<const jbyte*>(&bytes[0]));
149   }
150   return result;
151 }
152 
DdmVmInternal_heapInfoNotify(JNIEnv * env,jclass,jint when)153 static jint DdmVmInternal_heapInfoNotify(JNIEnv* env, jclass, jint when) {
154   ScopedFastNativeObjectAccess soa(env);
155   return Dbg::DdmHandleHpifChunk(static_cast<Dbg::HpifWhen>(when));
156 }
157 
DdmVmInternal_heapSegmentNotify(JNIEnv *,jclass,jint when,jint what,jboolean native)158 static jboolean DdmVmInternal_heapSegmentNotify(JNIEnv*, jclass, jint when, jint what, jboolean native) {
159   return Dbg::DdmHandleHpsgNhsgChunk(static_cast<Dbg::HpsgWhen>(when), static_cast<Dbg::HpsgWhat>(what), native);
160 }
161 
DdmVmInternal_threadNotify(JNIEnv *,jclass,jboolean enable)162 static void DdmVmInternal_threadNotify(JNIEnv*, jclass, jboolean enable) {
163   Dbg::DdmSetThreadNotification(enable);
164 }
165 
166 static JNINativeMethod gMethods[] = {
167   NATIVE_METHOD(DdmVmInternal, enableRecentAllocations, "(Z)V"),
168   FAST_NATIVE_METHOD(DdmVmInternal, getRecentAllocations, "()[B"),
169   FAST_NATIVE_METHOD(DdmVmInternal, getRecentAllocationStatus, "()Z"),
170   NATIVE_METHOD(DdmVmInternal, getStackTraceById, "(I)[Ljava/lang/StackTraceElement;"),
171   NATIVE_METHOD(DdmVmInternal, getThreadStats, "()[B"),
172   FAST_NATIVE_METHOD(DdmVmInternal, heapInfoNotify, "(I)Z"),
173   NATIVE_METHOD(DdmVmInternal, heapSegmentNotify, "(IIZ)Z"),
174   NATIVE_METHOD(DdmVmInternal, threadNotify, "(Z)V"),
175 };
176 
register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv * env)177 void register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(JNIEnv* env) {
178   REGISTER_NATIVE_METHODS("org/apache/harmony/dalvik/ddmc/DdmVmInternal");
179 }
180 
181 }  // namespace art
182