1 /*
2  * Copyright (C) 2015 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 #if __linux__
18 #include <errno.h>
19 #include <signal.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <sys/ptrace.h>
23 #include <sys/wait.h>
24 #endif
25 
26 #include "jni.h"
27 
28 #include <backtrace/Backtrace.h>
29 
30 #include "base/logging.h"
31 #include "base/macros.h"
32 #include "gc/heap.h"
33 #include "gc/space/image_space.h"
34 #include "oat_file.h"
35 #include "utils.h"
36 
37 namespace art {
38 
39 // For testing debuggerd. We do not have expected-death tests, so can't test this by default.
40 // Code for this is copied from SignalTest.
41 static constexpr bool kCauseSegfault = false;
42 char* go_away_compiler_cfi = nullptr;
43 
CauseSegfault()44 static void CauseSegfault() {
45 #if defined(__arm__) || defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
46   // On supported architectures we cause a real SEGV.
47   *go_away_compiler_cfi = 'a';
48 #else
49   // On other architectures we simulate SEGV.
50   kill(getpid(), SIGSEGV);
51 #endif
52 }
53 
Java_Main_sleep(JNIEnv *,jobject,jint,jboolean,jdouble)54 extern "C" JNIEXPORT jboolean JNICALL Java_Main_sleep(JNIEnv*, jobject, jint, jboolean, jdouble) {
55   // Keep pausing.
56   printf("Going to sleep\n");
57   for (;;) {
58     pause();
59   }
60 }
61 
62 // Helper to look for a sequence in the stack trace.
63 #if __linux__
CheckStack(Backtrace * bt,const std::vector<std::string> & seq)64 static bool CheckStack(Backtrace* bt, const std::vector<std::string>& seq) {
65   size_t cur_search_index = 0;  // The currently active index in seq.
66   CHECK_GT(seq.size(), 0U);
67 
68   for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
69     if (BacktraceMap::IsValid(it->map)) {
70       LOG(INFO) << "Got " << it->func_name << ", looking for " << seq[cur_search_index];
71       if (it->func_name == seq[cur_search_index]) {
72         cur_search_index++;
73         if (cur_search_index == seq.size()) {
74           return true;
75         }
76       }
77     }
78   }
79 
80   printf("Cannot find %s in backtrace:\n", seq[cur_search_index].c_str());
81   for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
82     if (BacktraceMap::IsValid(it->map)) {
83       printf("  %s\n", it->func_name.c_str());
84     }
85   }
86 
87   return false;
88 }
89 #endif
90 
91 // Currently we have to fall back to our own loader for the boot image when it's compiled PIC
92 // because its base is zero. Thus in-process unwinding through it won't work. This is a helper
93 // detecting this.
94 #if __linux__
IsPicImage()95 static bool IsPicImage() {
96   std::vector<gc::space::ImageSpace*> image_spaces =
97       Runtime::Current()->GetHeap()->GetBootImageSpaces();
98   CHECK(!image_spaces.empty());  // We should be running with an image.
99   const OatFile* oat_file = image_spaces[0]->GetOatFile();
100   CHECK(oat_file != nullptr);     // We should have an oat file to go with the image.
101   return oat_file->IsPic();
102 }
103 #endif
104 
Java_Main_unwindInProcess(JNIEnv *,jobject,jboolean full_signatrues,jint,jboolean)105 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindInProcess(
106     JNIEnv*,
107     jobject,
108     jboolean full_signatrues,
109     jint,
110     jboolean) {
111 #if __linux__
112   if (IsPicImage()) {
113     LOG(INFO) << "Image is pic, in-process unwinding check bypassed.";
114     return JNI_TRUE;
115   }
116 
117   // TODO: What to do on Valgrind?
118 
119   std::unique_ptr<Backtrace> bt(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, GetTid()));
120   if (!bt->Unwind(0, nullptr)) {
121     printf("Cannot unwind in process.\n");
122     return JNI_FALSE;
123   } else if (bt->NumFrames() == 0) {
124     printf("No frames for unwind in process.\n");
125     return JNI_FALSE;
126   }
127 
128   // We cannot really parse an exact stack, as the optimizing compiler may inline some functions.
129   // This is also risky, as deduping might play a trick on us, so the test needs to make sure that
130   // only unique functions are being expected.
131   // "mini-debug-info" does not include parameters to save space.
132   std::vector<std::string> seq = {
133       "Java_Main_unwindInProcess",                   // This function.
134       "Main.unwindInProcess",                        // The corresponding Java native method frame.
135       "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
136       "Main.main"                                    // The Java entry method.
137   };
138   std::vector<std::string> full_seq = {
139       "Java_Main_unwindInProcess",                   // This function.
140       "boolean Main.unwindInProcess(boolean, int, boolean)",  // The corresponding Java native method frame.
141       "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
142       "void Main.main(java.lang.String[])"           // The Java entry method.
143   };
144 
145   bool result = CheckStack(bt.get(), full_signatrues ? full_seq : seq);
146   if (!kCauseSegfault) {
147     return result ? JNI_TRUE : JNI_FALSE;
148   } else {
149     LOG(INFO) << "Result of check-stack: " << result;
150   }
151 #endif
152 
153   if (kCauseSegfault) {
154     CauseSegfault();
155   }
156 
157   return JNI_FALSE;
158 }
159 
160 #if __linux__
161 static constexpr int kSleepTimeMicroseconds = 50000;            // 0.05 seconds
162 static constexpr int kMaxTotalSleepTimeMicroseconds = 1000000;  // 1 second
163 
164 // Wait for a sigstop. This code is copied from libbacktrace.
wait_for_sigstop(pid_t tid,int * total_sleep_time_usec,bool * detach_failed ATTRIBUTE_UNUSED)165 int wait_for_sigstop(pid_t tid, int* total_sleep_time_usec, bool* detach_failed ATTRIBUTE_UNUSED) {
166   for (;;) {
167     int status;
168     pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG));
169     if (n == -1) {
170       PLOG(WARNING) << "waitpid failed: tid " << tid;
171       break;
172     } else if (n == tid) {
173       if (WIFSTOPPED(status)) {
174         return WSTOPSIG(status);
175       } else {
176         PLOG(ERROR) << "unexpected waitpid response: n=" << n << ", status=" << std::hex << status;
177         break;
178       }
179     }
180 
181     if (*total_sleep_time_usec > kMaxTotalSleepTimeMicroseconds) {
182       PLOG(WARNING) << "timed out waiting for stop signal: tid=" << tid;
183       break;
184     }
185 
186     usleep(kSleepTimeMicroseconds);
187     *total_sleep_time_usec += kSleepTimeMicroseconds;
188   }
189 
190   return -1;
191 }
192 #endif
193 
Java_Main_unwindOtherProcess(JNIEnv *,jobject,jboolean full_signatrues,jint pid_int)194 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindOtherProcess(
195     JNIEnv*,
196     jobject,
197     jboolean full_signatrues,
198     jint pid_int) {
199 #if __linux__
200   // TODO: What to do on Valgrind?
201   pid_t pid = static_cast<pid_t>(pid_int);
202 
203   // OK, this is painful. debuggerd uses ptrace to unwind other processes.
204 
205   if (ptrace(PTRACE_ATTACH, pid, 0, 0)) {
206     // Were not able to attach, bad.
207     printf("Failed to attach to other process.\n");
208     PLOG(ERROR) << "Failed to attach.";
209     kill(pid, SIGKILL);
210     return JNI_FALSE;
211   }
212 
213   kill(pid, SIGSTOP);
214 
215   bool detach_failed = false;
216   int total_sleep_time_usec = 0;
217   int signal = wait_for_sigstop(pid, &total_sleep_time_usec, &detach_failed);
218   if (signal == -1) {
219     LOG(WARNING) << "wait_for_sigstop failed.";
220   }
221 
222   std::unique_ptr<Backtrace> bt(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
223   bool result = true;
224   if (!bt->Unwind(0, nullptr)) {
225     printf("Cannot unwind other process.\n");
226     result = false;
227   } else if (bt->NumFrames() == 0) {
228     printf("No frames for unwind of other process.\n");
229     result = false;
230   }
231 
232   if (result) {
233     // See comment in unwindInProcess for non-exact stack matching.
234     // "mini-debug-info" does not include parameters to save space.
235     std::vector<std::string> seq = {
236         // "Java_Main_sleep",                        // The sleep function being executed in the
237                                                      // other runtime.
238                                                      // Note: For some reason, the name isn't
239                                                      // resolved, so don't look for it right now.
240         "Main.sleep",                                // The corresponding Java native method frame.
241         "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
242         "Main.main"                                  // The Java entry method.
243     };
244     std::vector<std::string> full_seq = {
245         // "Java_Main_sleep",                        // The sleep function being executed in the
246                                                      // other runtime.
247                                                      // Note: For some reason, the name isn't
248                                                      // resolved, so don't look for it right now.
249         "boolean Main.sleep(int, boolean, double)",  // The corresponding Java native method frame.
250         "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
251         "void Main.main(java.lang.String[])"         // The Java entry method.
252     };
253 
254     result = CheckStack(bt.get(), full_signatrues ? full_seq : seq);
255   }
256 
257   if (ptrace(PTRACE_DETACH, pid, 0, 0) != 0) {
258     PLOG(ERROR) << "Detach failed";
259   }
260 
261   // Kill the other process once we are done with it.
262   kill(pid, SIGKILL);
263 
264   return result ? JNI_TRUE : JNI_FALSE;
265 #else
266   UNUSED(pid_int);
267   return JNI_FALSE;
268 #endif
269 }
270 
271 }  // namespace art
272