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 <backtrace/Backtrace.h>
29
30#include "base/logging.h"
31#include "base/macros.h"
32#include "gc/heap.h"
33#include "gc/space/image_space.h"
34#include "oat_file.h"
35#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
79  printf("Can not find %s in backtrace:\n", seq[cur_search_index].c_str());
80  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
86  return false;
87}
88#endif
89
90// 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() {
95  gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
96  CHECK(image_space != nullptr);  // We should be running with an image.
97  const OatFile* oat_file = image_space->GetOatFile();
98  CHECK(oat_file != nullptr);     // We should have an oat file to go with the image.
99  return oat_file->IsPic();
100}
101#endif
102
103extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindInProcess(JNIEnv*, jobject, jint, jboolean) {
104#if __linux__
105  if (IsPicImage()) {
106    LOG(INFO) << "Image is pic, in-process unwinding check bypassed.";
107    return JNI_TRUE;
108  }
109
110  // TODO: What to do on Valgrind?
111
112  std::unique_ptr<Backtrace> bt(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, GetTid()));
113  if (!bt->Unwind(0, nullptr)) {
114    printf("Can not unwind in process.\n");
115    return JNI_FALSE;
116  } else if (bt->NumFrames() == 0) {
117    printf("No frames for unwind in process.\n");
118    return JNI_FALSE;
119  }
120
121  // We cannot really parse an exact stack, as the optimizing compiler may inline some functions.
122  // This is also risky, as deduping might play a trick on us, so the test needs to make sure that
123  // only unique functions are being expected.
124  std::vector<std::string> seq = {
125      "Java_Main_unwindInProcess",                   // This function.
126      "boolean Main.unwindInProcess(int, boolean)",  // The corresponding Java native method frame.
127      "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
128      "void Main.main(java.lang.String[])"           // The Java entry method.
129  };
130
131  bool result = CheckStack(bt.get(), seq);
132  if (!kCauseSegfault) {
133    return result ? JNI_TRUE : JNI_FALSE;
134  } else {
135    LOG(INFO) << "Result of check-stack: " << result;
136  }
137#endif
138
139  if (kCauseSegfault) {
140    CauseSegfault();
141  }
142
143  return JNI_FALSE;
144}
145
146#if __linux__
147static constexpr int kSleepTimeMicroseconds = 50000;            // 0.05 seconds
148static constexpr int kMaxTotalSleepTimeMicroseconds = 1000000;  // 1 second
149
150// Wait for a sigstop. This code is copied from libbacktrace.
151int wait_for_sigstop(pid_t tid, int* total_sleep_time_usec, bool* detach_failed ATTRIBUTE_UNUSED) {
152  for (;;) {
153    int status;
154    pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG));
155    if (n == -1) {
156      PLOG(WARNING) << "waitpid failed: tid " << tid;
157      break;
158    } else if (n == tid) {
159      if (WIFSTOPPED(status)) {
160        return WSTOPSIG(status);
161      } else {
162        PLOG(ERROR) << "unexpected waitpid response: n=" << n << ", status=" << std::hex << status;
163        break;
164      }
165    }
166
167    if (*total_sleep_time_usec > kMaxTotalSleepTimeMicroseconds) {
168      PLOG(WARNING) << "timed out waiting for stop signal: tid=" << tid;
169      break;
170    }
171
172    usleep(kSleepTimeMicroseconds);
173    *total_sleep_time_usec += kSleepTimeMicroseconds;
174  }
175
176  return -1;
177}
178#endif
179
180extern "C" JNIEXPORT jboolean JNICALL Java_Main_unwindOtherProcess(JNIEnv*, jobject, jint pid_int) {
181#if __linux__
182  // TODO: What to do on Valgrind?
183  pid_t pid = static_cast<pid_t>(pid_int);
184
185  // OK, this is painful. debuggerd uses ptrace to unwind other processes.
186
187  if (ptrace(PTRACE_ATTACH, pid, 0, 0)) {
188    // Were not able to attach, bad.
189    printf("Failed to attach to other process.\n");
190    PLOG(ERROR) << "Failed to attach.";
191    kill(pid, SIGKILL);
192    return JNI_FALSE;
193  }
194
195  kill(pid, SIGSTOP);
196
197  bool detach_failed = false;
198  int total_sleep_time_usec = 0;
199  int signal = wait_for_sigstop(pid, &total_sleep_time_usec, &detach_failed);
200  if (signal == -1) {
201    LOG(WARNING) << "wait_for_sigstop failed.";
202  }
203
204  std::unique_ptr<Backtrace> bt(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
205  bool result = true;
206  if (!bt->Unwind(0, nullptr)) {
207    printf("Can not unwind other process.\n");
208    result = false;
209  } else if (bt->NumFrames() == 0) {
210    printf("No frames for unwind of other process.\n");
211    result = false;
212  }
213
214  if (result) {
215    // See comment in unwindInProcess for non-exact stack matching.
216    std::vector<std::string> seq = {
217        // "Java_Main_sleep",                        // The sleep function being executed in the
218                                                     // other runtime.
219                                                     // Note: For some reason, the name isn't
220                                                     // resolved, so don't look for it right now.
221        "boolean Main.sleep(int, boolean, double)",  // The corresponding Java native method frame.
222        "int java.util.Arrays.binarySearch(java.lang.Object[], int, int, java.lang.Object, java.util.Comparator)",  // Framework method.
223        "void Main.main(java.lang.String[])"         // The Java entry method.
224    };
225
226    result = CheckStack(bt.get(), seq);
227  }
228
229  if (ptrace(PTRACE_DETACH, pid, 0, 0) != 0) {
230    PLOG(ERROR) << "Detach failed";
231  }
232
233  // Kill the other process once we are done with it.
234  kill(pid, SIGKILL);
235
236  return result ? JNI_TRUE : JNI_FALSE;
237#else
238  return JNI_FALSE;
239#endif
240}
241
242}  // namespace art
243