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 "dalvik_system_VMStack.h"
18 
19 #include <type_traits>
20 
21 #include "nativehelper/jni_macros.h"
22 
23 #include "art_method-inl.h"
24 #include "gc/task_processor.h"
25 #include "jni/jni_internal.h"
26 #include "mirror/class-inl.h"
27 #include "mirror/class_loader.h"
28 #include "mirror/object-inl.h"
29 #include "native_util.h"
30 #include "nth_caller_visitor.h"
31 #include "scoped_fast_native_object_access-inl.h"
32 #include "scoped_thread_state_change-inl.h"
33 #include "thread_list.h"
34 
35 namespace art {
36 
37 template <typename T,
38           typename ResultT =
39               typename std::result_of<T(Thread*, const ScopedFastNativeObjectAccess&)>::type>
GetThreadStack(const ScopedFastNativeObjectAccess & soa,jobject peer,T fn)40 static ResultT GetThreadStack(const ScopedFastNativeObjectAccess& soa,
41                               jobject peer,
42                               T fn)
43     REQUIRES_SHARED(Locks::mutator_lock_) {
44   ResultT trace = nullptr;
45   ObjPtr<mirror::Object> decoded_peer = soa.Decode<mirror::Object>(peer);
46   if (decoded_peer == soa.Self()->GetPeer()) {
47     trace = fn(soa.Self(), soa);
48   } else {
49     // Never allow suspending the heap task thread since it may deadlock if allocations are
50     // required for the stack trace.
51     Thread* heap_task_thread =
52         Runtime::Current()->GetHeap()->GetTaskProcessor()->GetRunningThread();
53     // heap_task_thread could be null if the daemons aren't yet started.
54     if (heap_task_thread != nullptr && decoded_peer == heap_task_thread->GetPeerFromOtherThread()) {
55       return nullptr;
56     }
57     // Suspend thread to build stack trace.
58     ScopedThreadSuspension sts(soa.Self(), kNative);
59     ThreadList* thread_list = Runtime::Current()->GetThreadList();
60     bool timed_out;
61     Thread* thread = thread_list->SuspendThreadByPeer(peer,
62                                                       /* request_suspension= */ true,
63                                                       SuspendReason::kInternal,
64                                                       &timed_out);
65     if (thread != nullptr) {
66       // Must be runnable to create returned array.
67       {
68         ScopedObjectAccess soa2(soa.Self());
69         trace = fn(thread, soa);
70       }
71       // Restart suspended thread.
72       bool resumed = thread_list->Resume(thread, SuspendReason::kInternal);
73       DCHECK(resumed);
74     } else if (timed_out) {
75       LOG(ERROR) << "Trying to get thread's stack failed as the thread failed to suspend within a "
76           "generous timeout.";
77     }
78   }
79   return trace;
80 }
81 
VMStack_fillStackTraceElements(JNIEnv * env,jclass,jobject javaThread,jobjectArray javaSteArray)82 static jint VMStack_fillStackTraceElements(JNIEnv* env, jclass, jobject javaThread,
83                                            jobjectArray javaSteArray) {
84   ScopedFastNativeObjectAccess soa(env);
85   auto fn = [](Thread* thread, const ScopedFastNativeObjectAccess& soaa)
86       REQUIRES_SHARED(Locks::mutator_lock_) -> jobject {
87     return thread->CreateInternalStackTrace(soaa);
88   };
89   jobject trace = GetThreadStack(soa, javaThread, fn);
90   if (trace == nullptr) {
91     return 0;
92   }
93   int32_t depth;
94   Thread::InternalStackTraceToStackTraceElementArray(soa, trace, javaSteArray, &depth);
95   return depth;
96 }
97 
98 // Returns the defining class loader of the caller's caller.
VMStack_getCallingClassLoader(JNIEnv * env,jclass)99 static jobject VMStack_getCallingClassLoader(JNIEnv* env, jclass) {
100   ScopedFastNativeObjectAccess soa(env);
101   NthCallerVisitor visitor(soa.Self(), 2);
102   visitor.WalkStack();
103   if (UNLIKELY(visitor.caller == nullptr)) {
104     // The caller is an attached native thread.
105     return nullptr;
106   }
107   return soa.AddLocalReference<jobject>(visitor.caller->GetDeclaringClass()->GetClassLoader());
108 }
109 
VMStack_getClosestUserClassLoader(JNIEnv * env,jclass)110 static jobject VMStack_getClosestUserClassLoader(JNIEnv* env, jclass) {
111   struct ClosestUserClassLoaderVisitor : public StackVisitor {
112     explicit ClosestUserClassLoaderVisitor(Thread* thread)
113       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
114         class_loader(nullptr) {}
115 
116     bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
117       DCHECK(class_loader == nullptr);
118       ObjPtr<mirror::Class> c = GetMethod()->GetDeclaringClass();
119       // c is null for runtime methods.
120       if (c != nullptr) {
121         ObjPtr<mirror::Object> cl = c->GetClassLoader();
122         if (cl != nullptr) {
123           class_loader = cl;
124           return false;
125         }
126       }
127       return true;
128     }
129 
130     ObjPtr<mirror::Object> class_loader;
131   };
132   ScopedFastNativeObjectAccess soa(env);
133   ClosestUserClassLoaderVisitor visitor(soa.Self());
134   visitor.WalkStack();
135   return soa.AddLocalReference<jobject>(visitor.class_loader);
136 }
137 
138 // Returns the class of the caller's caller's caller.
VMStack_getStackClass2(JNIEnv * env,jclass)139 static jclass VMStack_getStackClass2(JNIEnv* env, jclass) {
140   ScopedFastNativeObjectAccess soa(env);
141   NthCallerVisitor visitor(soa.Self(), 3);
142   visitor.WalkStack();
143   if (UNLIKELY(visitor.caller == nullptr)) {
144     // The caller is an attached native thread.
145     return nullptr;
146   }
147   return soa.AddLocalReference<jclass>(visitor.caller->GetDeclaringClass());
148 }
149 
VMStack_getThreadStackTrace(JNIEnv * env,jclass,jobject javaThread)150 static jobjectArray VMStack_getThreadStackTrace(JNIEnv* env, jclass, jobject javaThread) {
151   ScopedFastNativeObjectAccess soa(env);
152   auto fn = [](Thread* thread, const ScopedFastNativeObjectAccess& soaa)
153      REQUIRES_SHARED(Locks::mutator_lock_) -> jobject {
154     return thread->CreateInternalStackTrace(soaa);
155   };
156   jobject trace = GetThreadStack(soa, javaThread, fn);
157   if (trace == nullptr) {
158     return nullptr;
159   }
160   return Thread::InternalStackTraceToStackTraceElementArray(soa, trace);
161 }
162 
VMStack_getAnnotatedThreadStackTrace(JNIEnv * env,jclass,jobject javaThread)163 static jobjectArray VMStack_getAnnotatedThreadStackTrace(JNIEnv* env, jclass, jobject javaThread) {
164   ScopedFastNativeObjectAccess soa(env);
165   auto fn = [](Thread* thread, const ScopedFastNativeObjectAccess& soaa)
166       REQUIRES_SHARED(Locks::mutator_lock_) -> jobjectArray {
167     return thread->CreateAnnotatedStackTrace(soaa);
168   };
169   return GetThreadStack(soa, javaThread, fn);
170 }
171 
172 static JNINativeMethod gMethods[] = {
173   FAST_NATIVE_METHOD(VMStack, fillStackTraceElements, "(Ljava/lang/Thread;[Ljava/lang/StackTraceElement;)I"),
174   FAST_NATIVE_METHOD(VMStack, getCallingClassLoader, "()Ljava/lang/ClassLoader;"),
175   FAST_NATIVE_METHOD(VMStack, getClosestUserClassLoader, "()Ljava/lang/ClassLoader;"),
176   FAST_NATIVE_METHOD(VMStack, getStackClass2, "()Ljava/lang/Class;"),
177   FAST_NATIVE_METHOD(VMStack, getThreadStackTrace, "(Ljava/lang/Thread;)[Ljava/lang/StackTraceElement;"),
178   FAST_NATIVE_METHOD(VMStack, getAnnotatedThreadStackTrace, "(Ljava/lang/Thread;)[Ldalvik/system/AnnotatedStackTraceElement;"),
179 };
180 
register_dalvik_system_VMStack(JNIEnv * env)181 void register_dalvik_system_VMStack(JNIEnv* env) {
182   REGISTER_NATIVE_METHODS("dalvik/system/VMStack");
183 }
184 
185 }  // namespace art
186