blob: f166714b79c78bbcb17b4adfe8f3577f1e17652a [file] [log] [blame]
Andreas Gampe5dd44d02016-08-02 17:20:03 -07001/*
2 * Copyright (C) 2016 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#include "native_stack_dump.h"
18
19#include <ostream>
20
21#include <stdio.h>
22
23#include "art_method.h"
24
25// For DumpNativeStack.
26#include <backtrace/Backtrace.h>
27#include <backtrace/BacktraceMap.h>
28
29#if defined(__linux__)
30
31#include <memory>
32#include <vector>
33
34#include <linux/unistd.h>
35#include <signal.h>
36#include <stdlib.h>
37#include <sys/time.h>
38#include <sys/types.h>
39
Andreas Gampe46ee31b2016-12-14 10:11:49 -080040#include "android-base/stringprintf.h"
41
Andreas Gampe5dd44d02016-08-02 17:20:03 -070042#include "arch/instruction_set.h"
David Sehr891a50e2017-10-27 17:01:07 -070043#include "base/file_utils.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070044#include "base/memory_tool.h"
45#include "base/mutex.h"
Andreas Gampefcccbaf2016-08-02 17:20:03 -070046#include "base/unix_file/fd_file.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070047#include "oat_quick_method_header.h"
Andreas Gampefcccbaf2016-08-02 17:20:03 -070048#include "os.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070049#include "thread-current-inl.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070050#include "utils.h"
51
52#endif
53
54namespace art {
55
56#if defined(__linux__)
57
Andreas Gampe46ee31b2016-12-14 10:11:49 -080058using android::base::StringPrintf;
59
Andreas Gampe5dd44d02016-08-02 17:20:03 -070060static constexpr bool kUseAddr2line = !kIsTargetBuild;
61
62ALWAYS_INLINE
Andreas Gampefcccbaf2016-08-02 17:20:03 -070063static inline void WritePrefix(std::ostream& os, const char* prefix, bool odd) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -070064 if (prefix != nullptr) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070065 os << prefix;
Andreas Gampe5dd44d02016-08-02 17:20:03 -070066 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -070067 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070068 if (!odd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070069 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070070 }
71}
72
Andreas Gampefcccbaf2016-08-02 17:20:03 -070073// The state of an open pipe to addr2line. In "server" mode, addr2line takes input on stdin
74// and prints the result to stdout. This struct keeps the state of the open connection.
75struct Addr2linePipe {
76 Addr2linePipe(int in_fd, int out_fd, const std::string& file_name, pid_t pid)
77 : in(in_fd, false), out(out_fd, false), file(file_name), child_pid(pid), odd(true) {}
78
79 ~Addr2linePipe() {
80 kill(child_pid, SIGKILL);
81 }
82
83 File in; // The file descriptor that is connected to the output of addr2line.
84 File out; // The file descriptor that is connected to the input of addr2line.
85
86 const std::string file; // The file addr2line is working on, so that we know when to close
87 // and restart.
88 const pid_t child_pid; // The pid of the child, which we should kill when we're done.
89 bool odd; // Print state for indentation of lines.
90};
91
92static std::unique_ptr<Addr2linePipe> Connect(const std::string& name, const char* args[]) {
93 int caller_to_addr2line[2];
94 int addr2line_to_caller[2];
95
96 if (pipe(caller_to_addr2line) == -1) {
97 return nullptr;
98 }
99 if (pipe(addr2line_to_caller) == -1) {
100 close(caller_to_addr2line[0]);
101 close(caller_to_addr2line[1]);
102 return nullptr;
103 }
104
105 pid_t pid = fork();
106 if (pid == -1) {
107 close(caller_to_addr2line[0]);
108 close(caller_to_addr2line[1]);
Calin Juravle0ed6c802017-03-27 18:12:05 -0700109 close(addr2line_to_caller[0]);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700110 close(addr2line_to_caller[1]);
111 return nullptr;
112 }
113
114 if (pid == 0) {
115 dup2(caller_to_addr2line[0], STDIN_FILENO);
116 dup2(addr2line_to_caller[1], STDOUT_FILENO);
117
118 close(caller_to_addr2line[0]);
119 close(caller_to_addr2line[1]);
120 close(addr2line_to_caller[0]);
121 close(addr2line_to_caller[1]);
122
123 execv(args[0], const_cast<char* const*>(args));
124 exit(1);
125 } else {
126 close(caller_to_addr2line[0]);
127 close(addr2line_to_caller[1]);
128 return std::unique_ptr<Addr2linePipe>(new Addr2linePipe(addr2line_to_caller[0],
129 caller_to_addr2line[1],
130 name,
131 pid));
132 }
133}
134
135static void Drain(size_t expected,
136 const char* prefix,
137 std::unique_ptr<Addr2linePipe>* pipe /* inout */,
138 std::ostream& os) {
139 DCHECK(pipe != nullptr);
140 DCHECK(pipe->get() != nullptr);
141 int in = pipe->get()->in.Fd();
142 DCHECK_GE(in, 0);
143
144 bool prefix_written = false;
145
146 for (;;) {
147 constexpr uint32_t kWaitTimeExpectedMicros = 500 * 1000;
148 constexpr uint32_t kWaitTimeUnexpectedMicros = 50 * 1000;
149
150 struct timeval tv;
151 tv.tv_sec = 0;
152 tv.tv_usec = expected > 0 ? kWaitTimeExpectedMicros : kWaitTimeUnexpectedMicros;
153
154 fd_set rfds;
155 FD_ZERO(&rfds);
156 FD_SET(in, &rfds);
157
158 int retval = TEMP_FAILURE_RETRY(select(in + 1, &rfds, nullptr, nullptr, &tv));
159
160 if (retval < 0) {
161 // Other side may have crashed or other errors.
162 pipe->reset();
163 return;
164 }
165
166 if (retval == 0) {
167 // Timeout.
168 return;
169 }
170
171 DCHECK_EQ(retval, 1);
172
173 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
174 // alt stack, but just to be sure...
175 char buffer[kMaxBuffer];
176 memset(buffer, 0, kMaxBuffer);
177 int bytes_read = TEMP_FAILURE_RETRY(read(in, buffer, kMaxBuffer - 1));
178
179 if (bytes_read < 0) {
180 // This should not really happen...
181 pipe->reset();
182 return;
183 }
184
185 char* tmp = buffer;
186 while (*tmp != 0) {
187 if (!prefix_written) {
188 WritePrefix(os, prefix, (*pipe)->odd);
189 prefix_written = true;
190 }
191 char* new_line = strchr(tmp, '\n');
192 if (new_line == nullptr) {
193 os << tmp;
194
195 break;
196 } else {
197 char saved = *(new_line + 1);
198 *(new_line + 1) = 0;
199 os << tmp;
200 *(new_line + 1) = saved;
201
202 tmp = new_line + 1;
203 prefix_written = false;
204 (*pipe)->odd = !(*pipe)->odd;
205
206 if (expected > 0) {
207 expected--;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700208 }
209 }
210 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700211 }
212}
213
214static void Addr2line(const std::string& map_src,
215 uintptr_t offset,
216 std::ostream& os,
217 const char* prefix,
218 std::unique_ptr<Addr2linePipe>* pipe /* inout */) {
219 DCHECK(pipe != nullptr);
220
221 if (map_src == "[vdso]") {
222 // Special-case this, our setup has problems with this.
223 return;
224 }
225
226 if (*pipe == nullptr || (*pipe)->file != map_src) {
227 if (*pipe != nullptr) {
228 Drain(0, prefix, pipe, os);
229 }
230 pipe->reset(); // Close early.
231
232 const char* args[7] = {
233 "/usr/bin/addr2line",
234 "--functions",
235 "--inlines",
236 "--demangle",
237 "-e",
238 map_src.c_str(),
239 nullptr
240 };
241 *pipe = Connect(map_src, args);
242 }
243
244 Addr2linePipe* pipe_ptr = pipe->get();
245 if (pipe_ptr == nullptr) {
246 // Failed...
247 return;
248 }
249
250 // Send the offset.
251 const std::string hex_offset = StringPrintf("%zx\n", offset);
252
253 if (!pipe_ptr->out.WriteFully(hex_offset.data(), hex_offset.length())) {
254 // Error. :-(
255 pipe->reset();
256 return;
257 }
258
259 // Now drain (expecting two lines).
260 Drain(2U, prefix, pipe, os);
261}
262
Andreas Gampeca620d72016-11-08 08:09:33 -0800263static bool RunCommand(const std::string& cmd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700264 FILE* stream = popen(cmd.c_str(), "r");
265 if (stream) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700266 pclose(stream);
267 return true;
268 } else {
269 return false;
270 }
271}
272
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700273static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
274 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(
275 method->GetEntryPointFromQuickCompiledCode()));
276 if (code == 0) {
277 return pc == 0;
278 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700279 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].GetCodeSize();
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700280 return code <= pc && pc <= (code + code_size);
281}
282
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700283void DumpNativeStack(std::ostream& os,
284 pid_t tid,
285 BacktraceMap* existing_map,
286 const char* prefix,
287 ArtMethod* current_method,
288 void* ucontext_ptr) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700289 // b/18119146
290 if (RUNNING_ON_MEMORY_TOOL != 0) {
291 return;
292 }
293
294 BacktraceMap* map = existing_map;
295 std::unique_ptr<BacktraceMap> tmp_map;
296 if (map == nullptr) {
297 tmp_map.reset(BacktraceMap::Create(getpid()));
298 map = tmp_map.get();
299 }
300 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid, map));
301 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
302 os << prefix << "(backtrace::Unwind failed for thread " << tid
Andreas Gampeef295362016-10-11 20:04:11 -0700303 << ": " << backtrace->GetErrorString(backtrace->GetError()) << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700304 return;
305 } else if (backtrace->NumFrames() == 0) {
Andreas Gampeef295362016-10-11 20:04:11 -0700306 os << prefix << "(no native stack frames for thread " << tid << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700307 return;
308 }
309
310 // Check whether we have and should use addr2line.
311 bool use_addr2line;
312 if (kUseAddr2line) {
313 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
314 // and print to stderr.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700315 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h");
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700316 } else {
317 use_addr2line = false;
318 }
319
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700320 std::unique_ptr<Addr2linePipe> addr2line_state;
321
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700322 for (Backtrace::const_iterator it = backtrace->begin();
323 it != backtrace->end(); ++it) {
324 // We produce output like this:
325 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
326 // In order for parsing tools to continue to function, the stack dump
327 // format must at least adhere to this format:
328 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
329 // The parsers require a single space before and after pc, and two spaces
330 // after the <RELATIVE_ADDR>. There can be any prefix data before the
331 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
332 os << prefix << StringPrintf("#%02zu pc ", it->num);
333 bool try_addr2line = false;
334 if (!BacktraceMap::IsValid(it->map)) {
335 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " ???"
336 : "%08" PRIxPTR " ???",
337 it->pc);
338 } else {
339 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " "
340 : "%08" PRIxPTR " ",
Christopher Ferrisf88b5c02017-07-19 14:18:33 -0700341 it->rel_pc);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700342 os << it->map.name;
343 os << " (";
344 if (!it->func_name.empty()) {
345 os << it->func_name;
346 if (it->func_offset != 0) {
347 os << "+" << it->func_offset;
348 }
349 try_addr2line = true;
350 } else if (current_method != nullptr &&
351 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
352 PcIsWithinQuickCode(current_method, it->pc)) {
353 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
David Sehr709b0702016-10-13 09:12:37 -0700354 os << current_method->JniLongName() << "+"
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700355 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
356 } else {
357 os << "???";
358 }
359 os << ")";
360 }
Andreas Gampeef295362016-10-11 20:04:11 -0700361 os << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700362 if (try_addr2line && use_addr2line) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700363 Addr2line(it->map.name, it->pc - it->map.start, os, prefix, &addr2line_state);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700364 }
365 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700366
367 if (addr2line_state != nullptr) {
368 Drain(0, prefix, &addr2line_state, os);
369 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700370}
371
372void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
373 if (tid == GetTid()) {
374 // There's no point showing that we're reading our stack out of /proc!
375 return;
376 }
377
378 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
379 std::string kernel_stack;
380 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
381 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
382 return;
383 }
384
385 std::vector<std::string> kernel_stack_frames;
386 Split(kernel_stack, '\n', &kernel_stack_frames);
387 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
388 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
389 kernel_stack_frames.pop_back();
390 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
391 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
392 // into "futex_wait_queue_me+0xcd/0x110".
393 const char* text = kernel_stack_frames[i].c_str();
394 const char* close_bracket = strchr(text, ']');
395 if (close_bracket != nullptr) {
396 text = close_bracket + 2;
397 }
398 os << prefix;
399 if (include_count) {
400 os << StringPrintf("#%02zd ", i);
401 }
Andreas Gampeef295362016-10-11 20:04:11 -0700402 os << text << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700403 }
404}
405
406#elif defined(__APPLE__)
407
408void DumpNativeStack(std::ostream& os ATTRIBUTE_UNUSED,
409 pid_t tid ATTRIBUTE_UNUSED,
410 BacktraceMap* existing_map ATTRIBUTE_UNUSED,
411 const char* prefix ATTRIBUTE_UNUSED,
412 ArtMethod* current_method ATTRIBUTE_UNUSED,
413 void* ucontext_ptr ATTRIBUTE_UNUSED) {
414}
415
416void DumpKernelStack(std::ostream& os ATTRIBUTE_UNUSED,
417 pid_t tid ATTRIBUTE_UNUSED,
418 const char* prefix ATTRIBUTE_UNUSED,
419 bool include_count ATTRIBUTE_UNUSED) {
420}
421
422#else
423#error "Unsupported architecture for native stack dumps."
424#endif
425
426} // namespace art