blob: 77301d20e854035712061bd4322b05d5e216b88e [file] [log] [blame]
Andreas Gampe73810102015-04-22 18:57:06 -07001/*
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"
Andreas Gampe88da3b02015-06-12 20:38:49 -070032#include "gc/heap.h"
33#include "gc/space/image_space.h"
34#include "oat_file.h"
Andreas Gampe73810102015-04-22 18:57:06 -070035#include "utils.h"
36
37namespace 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.
41static constexpr bool kCauseSegfault = false;
42char* go_away_compiler_cfi = nullptr;
43
44static 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
54extern "C" JNIEXPORT jboolean JNICALL Java_Main_sleep(JNIEnv*, jobject, jint, jboolean, jdouble) {
55 // Keep pausing.
56 for (;;) {
57 pause();
58 }
59}
60
61// Helper to look for a sequence in the stack trace.
62#if __linux__
63static bool CheckStack(Backtrace* bt, const std::vector<std::string>& seq) {
64 size_t cur_search_index = 0; // The currently active index in seq.
65 CHECK_GT(seq.size(), 0U);
66
67 for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
68 if (BacktraceMap::IsValid(it->map)) {
69 LOG(INFO) << "Got " << it->func_name << ", looking for " << seq[cur_search_index];
70 if (it->func_name == seq[cur_search_index]) {
71 cur_search_index++;
72 if (cur_search_index == seq.size()) {
73 return true;
74 }
75 }
76 }
77 }
78
Roland Levillain91d65e02016-01-19 15:59:16 +000079 printf("Cannot find %s in backtrace:\n", seq[cur_search_index].c_str());
David Srbecky020c5432015-06-10 22:43:11 +010080 for (Backtrace::const_iterator it = bt->begin(); it != bt->end(); ++it) {
81 if (BacktraceMap::IsValid(it->map)) {
82 printf(" %s\n", it->func_name.c_str());
83 }
84 }
85
Andreas Gampe73810102015-04-22 18:57:06 -070086 return false;
87}
88#endif
89
Andreas Gampe88da3b02015-06-12 20:38:49 -070090// Currently we have to fall back to our own loader for the boot image when it's compiled PIC
91// because its base is zero. Thus in-process unwinding through it won't work. This is a helper
92// detecting this.
93#if __linux__
94static bool IsPicImage() {
Jeff Haodcdc85b2015-12-04 14:06:18 -080095 std::vector<gc::space::ImageSpace*> image_spaces =
96 Runtime::Current()->GetHeap()->GetBootImageSpaces();
97 CHECK(!image_spaces.empty()); // We should be running with an image.
98 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Andreas Gampe88da3b02015-06-12 20:38:49 -070099 CHECK(oat_file != nullptr); // We should have an oat file to go with the image.
100 return oat_file->IsPic();
101}
102#endif
103
Andreas Gampe73810102015-04-22 18:57:06 -0700104extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindInProcess(JNIEnv*, jobject, jint, jboolean) {
105#if __linux__
Andreas Gampe88da3b02015-06-12 20:38:49 -0700106 if (IsPicImage()) {
107 LOG(INFO) << "Image is pic, in-process unwinding check bypassed.";
108 return JNI_TRUE;
109 }
110
Andreas Gampe73810102015-04-22 18:57:06 -0700111 // TODO: What to do on Valgrind?
112
113 std::unique_ptr<Backtrace> bt(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, GetTid()));
114 if (!bt->Unwind(0, nullptr)) {
Roland Levillain91d65e02016-01-19 15:59:16 +0000115 printf("Cannot unwind in process.\n");
Andreas Gampe73810102015-04-22 18:57:06 -0700116 return JNI_FALSE;
117 } else if (bt->NumFrames() == 0) {
David Srbecky020c5432015-06-10 22:43:11 +0100118 printf("No frames for unwind in process.\n");
Andreas Gampe73810102015-04-22 18:57:06 -0700119 return JNI_FALSE;
120 }
121
122 // We cannot really parse an exact stack, as the optimizing compiler may inline some functions.
123 // This is also risky, as deduping might play a trick on us, so the test needs to make sure that
124 // only unique functions are being expected.
125 std::vector<std::string> seq = {
126 "Java_Main_unwindInProcess", // This function.
127 "boolean Main.unwindInProcess(int, boolean)", // The corresponding Java native method frame.
David Srbecky3da76082015-06-10 21:52:06 +0000128 "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)", // Framework method.
Andreas Gampe73810102015-04-22 18:57:06 -0700129 "void Main.main(java.lang.String[])" // The Java entry method.
130 };
131
132 bool result = CheckStack(bt.get(), seq);
133 if (!kCauseSegfault) {
134 return result ? JNI_TRUE : JNI_FALSE;
135 } else {
136 LOG(INFO) << "Result of check-stack: " << result;
137 }
138#endif
139
140 if (kCauseSegfault) {
141 CauseSegfault();
142 }
143
144 return JNI_FALSE;
145}
146
147#if __linux__
148static constexpr int kSleepTimeMicroseconds = 50000; // 0.05 seconds
149static constexpr int kMaxTotalSleepTimeMicroseconds = 1000000; // 1 second
150
151// Wait for a sigstop. This code is copied from libbacktrace.
152int wait_for_sigstop(pid_t tid, int* total_sleep_time_usec, bool* detach_failed ATTRIBUTE_UNUSED) {
153 for (;;) {
154 int status;
155 pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG));
156 if (n == -1) {
157 PLOG(WARNING) << "waitpid failed: tid " << tid;
158 break;
159 } else if (n == tid) {
160 if (WIFSTOPPED(status)) {
161 return WSTOPSIG(status);
162 } else {
163 PLOG(ERROR) << "unexpected waitpid response: n=" << n << ", status=" << std::hex << status;
164 break;
165 }
166 }
167
168 if (*total_sleep_time_usec > kMaxTotalSleepTimeMicroseconds) {
169 PLOG(WARNING) << "timed out waiting for stop signal: tid=" << tid;
170 break;
171 }
172
173 usleep(kSleepTimeMicroseconds);
174 *total_sleep_time_usec += kSleepTimeMicroseconds;
175 }
176
177 return -1;
178}
179#endif
180
181extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindOtherProcess(JNIEnv*, jobject, jint pid_int) {
182#if __linux__
183 // TODO: What to do on Valgrind?
184 pid_t pid = static_cast<pid_t>(pid_int);
185
186 // OK, this is painful. debuggerd uses ptrace to unwind other processes.
187
188 if (ptrace(PTRACE_ATTACH, pid, 0, 0)) {
189 // Were not able to attach, bad.
David Srbecky020c5432015-06-10 22:43:11 +0100190 printf("Failed to attach to other process.\n");
Andreas Gampe73810102015-04-22 18:57:06 -0700191 PLOG(ERROR) << "Failed to attach.";
David Srbeckya70e5b92015-06-17 03:52:54 +0100192 kill(pid, SIGKILL);
Andreas Gampe73810102015-04-22 18:57:06 -0700193 return JNI_FALSE;
194 }
195
196 kill(pid, SIGSTOP);
197
198 bool detach_failed = false;
199 int total_sleep_time_usec = 0;
200 int signal = wait_for_sigstop(pid, &total_sleep_time_usec, &detach_failed);
201 if (signal == -1) {
202 LOG(WARNING) << "wait_for_sigstop failed.";
203 }
204
205 std::unique_ptr<Backtrace> bt(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
206 bool result = true;
207 if (!bt->Unwind(0, nullptr)) {
Roland Levillain91d65e02016-01-19 15:59:16 +0000208 printf("Cannot unwind other process.\n");
Andreas Gampe73810102015-04-22 18:57:06 -0700209 result = false;
210 } else if (bt->NumFrames() == 0) {
David Srbecky020c5432015-06-10 22:43:11 +0100211 printf("No frames for unwind of other process.\n");
Andreas Gampe73810102015-04-22 18:57:06 -0700212 result = false;
213 }
214
215 if (result) {
216 // See comment in unwindInProcess for non-exact stack matching.
217 std::vector<std::string> seq = {
218 // "Java_Main_sleep", // The sleep function being executed in the
219 // other runtime.
220 // Note: For some reason, the name isn't
221 // resolved, so don't look for it right now.
222 "boolean Main.sleep(int, boolean, double)", // The corresponding Java native method frame.
David Srbecky3da76082015-06-10 21:52:06 +0000223 "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)", // Framework method.
Andreas Gampe73810102015-04-22 18:57:06 -0700224 "void Main.main(java.lang.String[])" // The Java entry method.
225 };
226
227 result = CheckStack(bt.get(), seq);
228 }
229
230 if (ptrace(PTRACE_DETACH, pid, 0, 0) != 0) {
231 PLOG(ERROR) << "Detach failed";
232 }
233
David Srbeckya70e5b92015-06-17 03:52:54 +0100234 // Kill the other process once we are done with it.
235 kill(pid, SIGKILL);
Andreas Gampe73810102015-04-22 18:57:06 -0700236
237 return result ? JNI_TRUE : JNI_FALSE;
238#else
Andreas Gampe3faa5812015-09-14 13:59:51 -0700239 UNUSED(pid_int);
Andreas Gampe73810102015-04-22 18:57:06 -0700240 return JNI_FALSE;
241#endif
242}
243
244} // namespace art