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