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