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 bool any_empty_name = false;
114 for (size_t i = 0; i < bt->NumFrames(); i++) {
115 const backtrace_frame_data_t* frame = bt->GetFrame(i);
116 if (BacktraceMap::IsValid(frame->map)) {
117 if (cur_search_index < seq.size()) {
118 LOG(INFO) << "Got " << frame->func_name << ", looking for " << seq[cur_search_index];
119 if (frame->func_name.find(seq[cur_search_index]) != std::string::npos) {
120 cur_search_index++;
121 }
122 }
123 }
124 any_empty_name |= frame->func_name.empty();
125 if (frame->func_name == "main") {
126 break;
127 }
128 }
129
130 if (cur_search_index < seq.size()) {
131 printf("Cannot find %s in backtrace:\n", seq[cur_search_index].c_str());
132 } else if (any_empty_name) {
133 #if defined(__BIONIC__ ) && !defined(__ANDROID__)
134 // TODO(b/182810709): Unwinding is broken on host-bionic so we expect some empty frames.
135 return true;
136 #else
137 printf("Missing frames in backtrace:\n");
138 #endif
139 } else {
140 return true;
141 }
142
143 for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
144 if (BacktraceMap::IsValid(it->map)) {
145 printf(" %s\n", Backtrace::FormatFrameData(&*it).c_str());
146 }
147 }
148
149 return false;
150 }
151
MoreErrorInfo(pid_t pid,bool sig_quit_on_fail)152 static void MoreErrorInfo(pid_t pid, bool sig_quit_on_fail) {
153 PrintFileToLog(android::base::StringPrintf("/proc/%d/maps", pid), ::android::base::ERROR);
154
155 if (sig_quit_on_fail) {
156 int res = kill(pid, SIGQUIT);
157 if (res != 0) {
158 PLOG(ERROR) << "Failed to send signal";
159 }
160 }
161 }
162 #endif
163
Java_Main_unwindInProcess(JNIEnv *,jclass)164 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindInProcess(JNIEnv*, jclass) {
165 printf("Java_Main_unwindInProcess\n");
166 #if __linux__
167 MutexLock mu(Thread::Current(), *GetNativeDebugInfoLock()); // Avoid races with the JIT thread.
168
169 std::unique_ptr<Backtrace> bt(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, GetTid()));
170 if (!bt->Unwind(0, nullptr)) {
171 printf("Cannot unwind in process.\n");
172 return JNI_FALSE;
173 } else if (bt->NumFrames() == 0) {
174 printf("No frames for unwind in process.\n");
175 return JNI_FALSE;
176 }
177
178 // We cannot really parse an exact stack, as the optimizing compiler may inline some functions.
179 // This is also risky, as deduping might play a trick on us, so the test needs to make sure that
180 // only unique functions are being expected.
181 // "mini-debug-info" does not include parameters to save space.
182 std::vector<std::string> seq = {
183 "Java_Main_unwindInProcess", // This function.
184 "java.util.Arrays.binarySearch0", // Framework method.
185 "Base.$noinline$runTest", // Method in other dex file.
186 "Main.main" // The Java entry method.
187 };
188
189 bool result = CheckStack(bt.get(), seq);
190 if (!kCauseSegfault) {
191 return result ? JNI_TRUE : JNI_FALSE;
192 } else {
193 LOG(INFO) << "Result of check-stack: " << result;
194 }
195 #endif
196
197 if (kCauseSegfault) {
198 CauseSegfault();
199 }
200
201 return JNI_FALSE;
202 }
203
204 #if __linux__
205 static constexpr int kSleepTimeMicroseconds = 50000; // 0.05 seconds
206 static constexpr int kMaxTotalSleepTimeMicroseconds = 10000000; // 10 seconds
207
208 // 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)209 int wait_for_sigstop(pid_t tid, int* total_sleep_time_usec, bool* detach_failed ATTRIBUTE_UNUSED) {
210 for (;;) {
211 int status;
212 pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG | WUNTRACED));
213 if (n == -1) {
214 PLOG(WARNING) << "waitpid failed: tid " << tid;
215 break;
216 } else if (n == tid) {
217 if (WIFSTOPPED(status)) {
218 return WSTOPSIG(status);
219 } else {
220 PLOG(ERROR) << "unexpected waitpid response: n=" << n << ", status=" << std::hex << status;
221 break;
222 }
223 }
224
225 if (*total_sleep_time_usec > kMaxTotalSleepTimeMicroseconds) {
226 PLOG(WARNING) << "timed out waiting for stop signal: tid=" << tid;
227 break;
228 }
229
230 usleep(kSleepTimeMicroseconds);
231 *total_sleep_time_usec += kSleepTimeMicroseconds;
232 }
233
234 return -1;
235 }
236 #endif
237
Java_Main_unwindOtherProcess(JNIEnv *,jclass,jint pid_int)238 extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindOtherProcess(JNIEnv*, jclass, jint pid_int) {
239 printf("Java_Main_unwindOtherProcess\n");
240 #if __linux__
241 pid_t pid = static_cast<pid_t>(pid_int);
242
243 // We wait for the SIGSTOP while the child process is untraced (using
244 // `WUNTRACED` in `wait_for_sigstop()`) to avoid a SIGSEGV for implicit
245 // suspend check stopping the process because it's being traced.
246 bool detach_failed = false;
247 int total_sleep_time_usec = 0;
248 int signal = wait_for_sigstop(pid, &total_sleep_time_usec, &detach_failed);
249 if (signal != SIGSTOP) {
250 printf("wait_for_sigstop failed.\n");
251 return JNI_FALSE;
252 }
253
254 // SEIZE is like ATTACH, but it does not stop the process (it has already stopped itself).
255 if (ptrace(PTRACE_SEIZE, pid, 0, 0)) {
256 // Were not able to attach, bad.
257 printf("Failed to attach to other process.\n");
258 PLOG(ERROR) << "Failed to attach.";
259 kill(pid, SIGKILL);
260 return JNI_FALSE;
261 }
262
263 std::unique_ptr<Backtrace> bt(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
264 bool result = true;
265 if (!bt->Unwind(0, nullptr)) {
266 printf("Cannot unwind other process.\n");
267 result = false;
268 } else if (bt->NumFrames() == 0) {
269 printf("No frames for unwind of other process.\n");
270 result = false;
271 }
272
273 if (result) {
274 // See comment in unwindInProcess for non-exact stack matching.
275 // "mini-debug-info" does not include parameters to save space.
276 std::vector<std::string> seq = {
277 "Java_Main_sigstop", // The stop function in the other process.
278 "java.util.Arrays.binarySearch0", // Framework method.
279 "Base.$noinline$runTest", // Method in other dex file.
280 "Main.main" // The Java entry method.
281 };
282
283 result = CheckStack(bt.get(), seq);
284 }
285
286 constexpr bool kSigQuitOnFail = true;
287 if (!result) {
288 printf("Failed to unwind secondary with pid %d\n", pid);
289 MoreErrorInfo(pid, kSigQuitOnFail);
290 }
291
292 if (ptrace(PTRACE_DETACH, pid, 0, 0) != 0) {
293 printf("Detach failed\n");
294 PLOG(ERROR) << "Detach failed";
295 }
296
297 // If we failed to unwind and induced an ANR dump, give the child some time (20s).
298 if (!result && kSigQuitOnFail) {
299 sleep(20);
300 }
301
302 // Kill the other process once we are done with it.
303 kill(pid, SIGKILL);
304
305 return result ? JNI_TRUE : JNI_FALSE;
306 #else
307 printf("Remote unwind supported only on linux\n");
308 UNUSED(pid_int);
309 return JNI_FALSE;
310 #endif
311 }
312
313 } // namespace art
314