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