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 <sys/ptrace.h>
22 #include <sys/wait.h>
23 #include <unistd.h>
24 #endif
25 
26 #include "jni.h"
27 
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/stringprintf.h>
31 #include <backtrace/Backtrace.h>
32 
33 #include "base/file_utils.h"
34 #include "base/logging.h"
35 #include "base/macros.h"
36 #include "base/mutex.h"
37 #include "base/utils.h"
38 #include "gc/heap.h"
39 #include "gc/space/image_space.h"
40 #include "jit/debugger_interface.h"
41 #include "oat_file.h"
42 #include "runtime.h"
43 
44 namespace art {
45 
46 // For testing debuggerd. We do not have expected-death tests, so can't test this by default.
47 // Code for this is copied from SignalTest.
48 static constexpr bool kCauseSegfault = false;
49 char* go_away_compiler_cfi = nullptr;
50 
CauseSegfault()51 static void CauseSegfault() {
52 #if defined(__arm__) || defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
53   // On supported architectures we cause a real SEGV.
54   *go_away_compiler_cfi = 'a';
55 #else
56   // On other architectures we simulate SEGV.
57   kill(getpid(), SIGSEGV);
58 #endif
59 }
60 
Java_Main_startSecondaryProcess(JNIEnv *,jclass)61 extern "C" JNIEXPORT jint JNICALL Java_Main_startSecondaryProcess(JNIEnv*, jclass) {
62   printf("Java_Main_startSecondaryProcess\n");
63 #if __linux__
64   // Get our command line so that we can use it to start identical process.
65   std::string cmdline;  // null-separated and null-terminated arguments.
66   if (!android::base::ReadFileToString("/proc/self/cmdline", &cmdline)) {
67     LOG(FATAL) << "Failed to read /proc/self/cmdline.";
68   }
69   if (cmdline.empty()) {
70     LOG(FATAL) << "No data was read from /proc/self/cmdline.";
71   }
72   // Workaround for b/150189787.
73   if (cmdline.back() != '\0') {
74     cmdline += '\0';
75   }
76   cmdline = cmdline + "--secondary" + '\0';  // Let the child know it is a helper.
77 
78   // Split the string into individual arguments suitable for execv.
79   std::vector<char*> argv;
80   for (size_t i = 0; i < cmdline.size(); i += strlen(&cmdline[i]) + 1) {
81     argv.push_back(&cmdline[i]);
82   }
83   argv.push_back(nullptr);  // Terminate the list.
84 
85   pid_t pid = fork();
86   if (pid < 0) {
87     LOG(FATAL) << "Fork failed";
88   } else if (pid == 0) {
89     execv(argv[0], argv.data());
90     exit(1);
91   }
92   return pid;
93 #else
94   return 0;
95 #endif
96 }
97 
Java_Main_sigstop(JNIEnv *,jclass)98 extern "C" JNIEXPORT jboolean JNICALL Java_Main_sigstop(JNIEnv*, jclass) {
99   printf("Java_Main_sigstop\n");
100 #if __linux__
101   MutexLock mu(Thread::Current(), *GetNativeDebugInfoLock());  // Avoid races with the JIT thread.
102   raise(SIGSTOP);
103 #endif
104   return true;  // Prevent the compiler from tail-call optimizing this method away.
105 }
106 
107 // Helper to look for a sequence in the stack trace.
108 #if __linux__
CheckStack(Backtrace * bt,const std::vector<std::string> & seq)109 static bool CheckStack(Backtrace* bt, const std::vector<std::string>& seq) {
110   size_t cur_search_index = 0;  // The currently active index in seq.
111   CHECK_GT(seq.size(), 0U);
112 
113   for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
114     if (BacktraceMap::IsValid(it->map)) {
115       LOG(INFO) << "Got " << it->func_name << ", looking for " << seq[cur_search_index];
116       if (it->func_name.find(seq[cur_search_index]) != std::string::npos) {
117         cur_search_index++;
118         if (cur_search_index == seq.size()) {
119           return true;
120         }
121       }
122     }
123   }
124 
125   printf("Cannot find %s in backtrace:\n", seq[cur_search_index].c_str());
126   for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
127     if (BacktraceMap::IsValid(it->map)) {
128       printf("  %s\n", Backtrace::FormatFrameData(&*it).c_str());
129     }
130   }
131 
132   return false;
133 }
134 
MoreErrorInfo(pid_t pid,bool sig_quit_on_fail)135 static void MoreErrorInfo(pid_t pid, bool sig_quit_on_fail) {
136   PrintFileToLog(android::base::StringPrintf("/proc/%d/maps", pid), ::android::base::ERROR);
137 
138   if (sig_quit_on_fail) {
139     int res = kill(pid, SIGQUIT);
140     if (res != 0) {
141       PLOG(ERROR) << "Failed to send signal";
142     }
143   }
144 }
145 #endif
146 
Java_Main_unwindInProcess(JNIEnv *,jclass)147 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindInProcess(JNIEnv*, jclass) {
148   printf("Java_Main_unwindInProcess\n");
149 #if __linux__
150   MutexLock mu(Thread::Current(), *GetNativeDebugInfoLock());  // Avoid races with the JIT thread.
151 
152   std::unique_ptr<Backtrace> bt(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, GetTid()));
153   if (!bt->Unwind(0, nullptr)) {
154     printf("Cannot unwind in process.\n");
155     return JNI_FALSE;
156   } else if (bt->NumFrames() == 0) {
157     printf("No frames for unwind in process.\n");
158     return JNI_FALSE;
159   }
160 
161   // We cannot really parse an exact stack, as the optimizing compiler may inline some functions.
162   // This is also risky, as deduping might play a trick on us, so the test needs to make sure that
163   // only unique functions are being expected.
164   // "mini-debug-info" does not include parameters to save space.
165   std::vector<std::string> seq = {
166       "Java_Main_unwindInProcess",       // This function.
167       "java.util.Arrays.binarySearch0",  // Framework method.
168       "Base.$noinline$runTest",          // Method in other dex file.
169       "Main.main"                        // The Java entry method.
170   };
171 
172   bool result = CheckStack(bt.get(), seq);
173   if (!kCauseSegfault) {
174     return result ? JNI_TRUE : JNI_FALSE;
175   } else {
176     LOG(INFO) << "Result of check-stack: " << result;
177   }
178 #endif
179 
180   if (kCauseSegfault) {
181     CauseSegfault();
182   }
183 
184   return JNI_FALSE;
185 }
186 
187 #if __linux__
188 static constexpr int kSleepTimeMicroseconds = 50000;             // 0.05 seconds
189 static constexpr int kMaxTotalSleepTimeMicroseconds = 10000000;  // 10 seconds
190 
191 // 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)192 int wait_for_sigstop(pid_t tid, int* total_sleep_time_usec, bool* detach_failed ATTRIBUTE_UNUSED) {
193   for (;;) {
194     int status;
195     pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG));
196     if (n == -1) {
197       PLOG(WARNING) << "waitpid failed: tid " << tid;
198       break;
199     } else if (n == tid) {
200       if (WIFSTOPPED(status)) {
201         return WSTOPSIG(status);
202       } else {
203         PLOG(ERROR) << "unexpected waitpid response: n=" << n << ", status=" << std::hex << status;
204         break;
205       }
206     }
207 
208     if (*total_sleep_time_usec > kMaxTotalSleepTimeMicroseconds) {
209       PLOG(WARNING) << "timed out waiting for stop signal: tid=" << tid;
210       break;
211     }
212 
213     usleep(kSleepTimeMicroseconds);
214     *total_sleep_time_usec += kSleepTimeMicroseconds;
215   }
216 
217   return -1;
218 }
219 #endif
220 
Java_Main_unwindOtherProcess(JNIEnv *,jclass,jint pid_int)221 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindOtherProcess(JNIEnv*, jclass, jint pid_int) {
222   printf("Java_Main_unwindOtherProcess\n");
223 #if __linux__
224   pid_t pid = static_cast<pid_t>(pid_int);
225 
226   // SEIZE is like ATTACH, but it does not stop the process (we let it stop itself).
227   if (ptrace(PTRACE_SEIZE, pid, 0, 0)) {
228     // Were not able to attach, bad.
229     printf("Failed to attach to other process.\n");
230     PLOG(ERROR) << "Failed to attach.";
231     kill(pid, SIGKILL);
232     return JNI_FALSE;
233   }
234 
235   bool detach_failed = false;
236   int total_sleep_time_usec = 0;
237   int signal = wait_for_sigstop(pid, &total_sleep_time_usec, &detach_failed);
238   if (signal != SIGSTOP) {
239     printf("wait_for_sigstop failed.\n");
240     return JNI_FALSE;
241   }
242 
243   std::unique_ptr<Backtrace> bt(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
244   bool result = true;
245   if (!bt->Unwind(0, nullptr)) {
246     printf("Cannot unwind other process.\n");
247     result = false;
248   } else if (bt->NumFrames() == 0) {
249     printf("No frames for unwind of other process.\n");
250     result = false;
251   }
252 
253   if (result) {
254     // See comment in unwindInProcess for non-exact stack matching.
255     // "mini-debug-info" does not include parameters to save space.
256     std::vector<std::string> seq = {
257         "Java_Main_sigstop",                // The stop function in the other process.
258         "java.util.Arrays.binarySearch0",   // Framework method.
259         "Base.$noinline$runTest",           // Method in other dex file.
260         "Main.main"                         // The Java entry method.
261     };
262 
263     result = CheckStack(bt.get(), seq);
264   }
265 
266   constexpr bool kSigQuitOnFail = true;
267   if (!result) {
268     printf("Failed to unwind secondary with pid %d\n", pid);
269     MoreErrorInfo(pid, kSigQuitOnFail);
270   }
271 
272   if (ptrace(PTRACE_DETACH, pid, 0, 0) != 0) {
273     printf("Detach failed\n");
274     PLOG(ERROR) << "Detach failed";
275   }
276 
277   // If we failed to unwind and induced an ANR dump, give the child some time (20s).
278   if (!result && kSigQuitOnFail) {
279     sleep(20);
280   }
281 
282   // Kill the other process once we are done with it.
283   kill(pid, SIGKILL);
284 
285   return result ? JNI_TRUE : JNI_FALSE;
286 #else
287   printf("Remote unwind supported only on linux\n");
288   UNUSED(pid_int);
289   return JNI_FALSE;
290 #endif
291 }
292 
293 }  // namespace art
294