blob: 88adad0f918445576826827b840e7151f2684128 [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
Yi Kongc57c6802018-10-29 14:28:56 -070019#include <memory>
Andreas Gampe5dd44d02016-08-02 17:20:03 -070020#include <ostream>
21
22#include <stdio.h>
23
24#include "art_method.h"
25
26// For DumpNativeStack.
27#include <backtrace/Backtrace.h>
28#include <backtrace/BacktraceMap.h>
29
30#if defined(__linux__)
31
32#include <memory>
33#include <vector>
34
35#include <linux/unistd.h>
Christopher Ferris453e0e52018-03-06 14:02:55 -080036#include <poll.h>
Andreas Gampe5dd44d02016-08-02 17:20:03 -070037#include <signal.h>
38#include <stdlib.h>
39#include <sys/time.h>
40#include <sys/types.h>
41
Andreas Gampe46ee31b2016-12-14 10:11:49 -080042#include "android-base/stringprintf.h"
Christopher Ferrisb1f23f92018-03-07 14:10:49 -080043#include "android-base/strings.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080044
Andreas Gampe5dd44d02016-08-02 17:20:03 -070045#include "arch/instruction_set.h"
Andreas Gampe39b378c2017-12-07 15:44:13 -080046#include "base/aborting.h"
David Sehr891a50e2017-10-27 17:01:07 -070047#include "base/file_utils.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070048#include "base/memory_tool.h"
49#include "base/mutex.h"
David Sehrc431b9d2018-03-02 12:01:51 -080050#include "base/os.h"
Andreas Gampefcccbaf2016-08-02 17:20:03 -070051#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080052#include "base/utils.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070053#include "oat_quick_method_header.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070054#include "thread-current-inl.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070055
56#endif
57
58namespace art {
59
60#if defined(__linux__)
61
Andreas Gampe46ee31b2016-12-14 10:11:49 -080062using android::base::StringPrintf;
63
Andreas Gampe5dd44d02016-08-02 17:20:03 -070064static constexpr bool kUseAddr2line = !kIsTargetBuild;
65
66ALWAYS_INLINE
Andreas Gampefcccbaf2016-08-02 17:20:03 -070067static inline void WritePrefix(std::ostream& os, const char* prefix, bool odd) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -070068 if (prefix != nullptr) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070069 os << prefix;
Andreas Gampe5dd44d02016-08-02 17:20:03 -070070 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -070071 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070072 if (!odd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070073 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070074 }
75}
76
Andreas Gampefcccbaf2016-08-02 17:20:03 -070077// The state of an open pipe to addr2line. In "server" mode, addr2line takes input on stdin
78// and prints the result to stdout. This struct keeps the state of the open connection.
79struct Addr2linePipe {
80 Addr2linePipe(int in_fd, int out_fd, const std::string& file_name, pid_t pid)
81 : in(in_fd, false), out(out_fd, false), file(file_name), child_pid(pid), odd(true) {}
82
83 ~Addr2linePipe() {
84 kill(child_pid, SIGKILL);
85 }
86
87 File in; // The file descriptor that is connected to the output of addr2line.
88 File out; // The file descriptor that is connected to the input of addr2line.
89
90 const std::string file; // The file addr2line is working on, so that we know when to close
91 // and restart.
92 const pid_t child_pid; // The pid of the child, which we should kill when we're done.
93 bool odd; // Print state for indentation of lines.
94};
95
96static std::unique_ptr<Addr2linePipe> Connect(const std::string& name, const char* args[]) {
97 int caller_to_addr2line[2];
98 int addr2line_to_caller[2];
99
100 if (pipe(caller_to_addr2line) == -1) {
101 return nullptr;
102 }
103 if (pipe(addr2line_to_caller) == -1) {
104 close(caller_to_addr2line[0]);
105 close(caller_to_addr2line[1]);
106 return nullptr;
107 }
108
109 pid_t pid = fork();
110 if (pid == -1) {
111 close(caller_to_addr2line[0]);
112 close(caller_to_addr2line[1]);
Calin Juravle0ed6c802017-03-27 18:12:05 -0700113 close(addr2line_to_caller[0]);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700114 close(addr2line_to_caller[1]);
115 return nullptr;
116 }
117
118 if (pid == 0) {
119 dup2(caller_to_addr2line[0], STDIN_FILENO);
120 dup2(addr2line_to_caller[1], STDOUT_FILENO);
121
122 close(caller_to_addr2line[0]);
123 close(caller_to_addr2line[1]);
124 close(addr2line_to_caller[0]);
125 close(addr2line_to_caller[1]);
126
127 execv(args[0], const_cast<char* const*>(args));
128 exit(1);
129 } else {
130 close(caller_to_addr2line[0]);
131 close(addr2line_to_caller[1]);
Yi Kongc57c6802018-10-29 14:28:56 -0700132 return std::make_unique<Addr2linePipe>(addr2line_to_caller[0],
133 caller_to_addr2line[1],
134 name,
135 pid);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700136 }
137}
138
139static void Drain(size_t expected,
140 const char* prefix,
141 std::unique_ptr<Addr2linePipe>* pipe /* inout */,
142 std::ostream& os) {
143 DCHECK(pipe != nullptr);
144 DCHECK(pipe->get() != nullptr);
145 int in = pipe->get()->in.Fd();
146 DCHECK_GE(in, 0);
147
148 bool prefix_written = false;
149
150 for (;;) {
Christopher Ferris453e0e52018-03-06 14:02:55 -0800151 constexpr uint32_t kWaitTimeExpectedMilli = 500;
152 constexpr uint32_t kWaitTimeUnexpectedMilli = 50;
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700153
Christopher Ferris453e0e52018-03-06 14:02:55 -0800154 int timeout = expected > 0 ? kWaitTimeExpectedMilli : kWaitTimeUnexpectedMilli;
155 struct pollfd read_fd{in, POLLIN, 0};
156 int retval = TEMP_FAILURE_RETRY(poll(&read_fd, 1, timeout));
157 if (retval == -1) {
158 // An error occurred.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700159 pipe->reset();
160 return;
161 }
162
163 if (retval == 0) {
164 // Timeout.
165 return;
166 }
167
Christopher Ferris453e0e52018-03-06 14:02:55 -0800168 if (!(read_fd.revents & POLLIN)) {
169 // addr2line call exited.
170 pipe->reset();
171 return;
172 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700173
174 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
175 // alt stack, but just to be sure...
176 char buffer[kMaxBuffer];
177 memset(buffer, 0, kMaxBuffer);
178 int bytes_read = TEMP_FAILURE_RETRY(read(in, buffer, kMaxBuffer - 1));
Christopher Ferris453e0e52018-03-06 14:02:55 -0800179 if (bytes_read <= 0) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700180 // This should not really happen...
181 pipe->reset();
182 return;
183 }
Christopher Ferris453e0e52018-03-06 14:02:55 -0800184 buffer[bytes_read] = '\0';
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700185
186 char* tmp = buffer;
187 while (*tmp != 0) {
188 if (!prefix_written) {
189 WritePrefix(os, prefix, (*pipe)->odd);
190 prefix_written = true;
191 }
192 char* new_line = strchr(tmp, '\n');
193 if (new_line == nullptr) {
194 os << tmp;
195
196 break;
197 } else {
198 char saved = *(new_line + 1);
199 *(new_line + 1) = 0;
200 os << tmp;
201 *(new_line + 1) = saved;
202
203 tmp = new_line + 1;
204 prefix_written = false;
205 (*pipe)->odd = !(*pipe)->odd;
206
207 if (expected > 0) {
208 expected--;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700209 }
210 }
211 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700212 }
213}
214
215static void Addr2line(const std::string& map_src,
216 uintptr_t offset,
217 std::ostream& os,
218 const char* prefix,
219 std::unique_ptr<Addr2linePipe>* pipe /* inout */) {
220 DCHECK(pipe != nullptr);
221
Christopher Ferrisb1f23f92018-03-07 14:10:49 -0800222 if (map_src == "[vdso]" || android::base::EndsWith(map_src, ".vdex")) {
223 // addr2line will not work on the vdso.
224 // vdex files are special frames injected for the interpreter
225 // so they don't have any line number information available.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700226 return;
227 }
228
229 if (*pipe == nullptr || (*pipe)->file != map_src) {
230 if (*pipe != nullptr) {
231 Drain(0, prefix, pipe, os);
232 }
233 pipe->reset(); // Close early.
234
235 const char* args[7] = {
236 "/usr/bin/addr2line",
237 "--functions",
238 "--inlines",
239 "--demangle",
240 "-e",
241 map_src.c_str(),
242 nullptr
243 };
244 *pipe = Connect(map_src, args);
245 }
246
247 Addr2linePipe* pipe_ptr = pipe->get();
248 if (pipe_ptr == nullptr) {
249 // Failed...
250 return;
251 }
252
253 // Send the offset.
254 const std::string hex_offset = StringPrintf("%zx\n", offset);
255
256 if (!pipe_ptr->out.WriteFully(hex_offset.data(), hex_offset.length())) {
257 // Error. :-(
258 pipe->reset();
259 return;
260 }
261
262 // Now drain (expecting two lines).
263 Drain(2U, prefix, pipe, os);
264}
265
Andreas Gampeca620d72016-11-08 08:09:33 -0800266static bool RunCommand(const std::string& cmd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700267 FILE* stream = popen(cmd.c_str(), "r");
268 if (stream) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700269 pclose(stream);
270 return true;
271 } else {
272 return false;
273 }
274}
275
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700276static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
277 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(
278 method->GetEntryPointFromQuickCompiledCode()));
279 if (code == 0) {
280 return pc == 0;
281 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700282 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].GetCodeSize();
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700283 return code <= pc && pc <= (code + code_size);
284}
285
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700286void DumpNativeStack(std::ostream& os,
287 pid_t tid,
288 BacktraceMap* existing_map,
289 const char* prefix,
290 ArtMethod* current_method,
Christopher Ferrisb2749312018-03-23 13:03:45 -0700291 void* ucontext_ptr,
292 bool skip_frames) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000293 // Historical note: This was disabled when running under Valgrind (b/18119146).
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700294
295 BacktraceMap* map = existing_map;
296 std::unique_ptr<BacktraceMap> tmp_map;
297 if (map == nullptr) {
298 tmp_map.reset(BacktraceMap::Create(getpid()));
299 map = tmp_map.get();
300 }
301 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid, map));
Christopher Ferrisb2749312018-03-23 13:03:45 -0700302 backtrace->SetSkipFrames(skip_frames);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700303 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
304 os << prefix << "(backtrace::Unwind failed for thread " << tid
Andreas Gampeef295362016-10-11 20:04:11 -0700305 << ": " << backtrace->GetErrorString(backtrace->GetError()) << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700306 return;
307 } else if (backtrace->NumFrames() == 0) {
Andreas Gampeef295362016-10-11 20:04:11 -0700308 os << prefix << "(no native stack frames for thread " << tid << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700309 return;
310 }
311
312 // Check whether we have and should use addr2line.
313 bool use_addr2line;
314 if (kUseAddr2line) {
315 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
316 // and print to stderr.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700317 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h");
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700318 } else {
319 use_addr2line = false;
320 }
321
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700322 std::unique_ptr<Addr2linePipe> addr2line_state;
323
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700324 for (Backtrace::const_iterator it = backtrace->begin();
325 it != backtrace->end(); ++it) {
326 // We produce output like this:
327 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
328 // In order for parsing tools to continue to function, the stack dump
329 // format must at least adhere to this format:
330 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
331 // The parsers require a single space before and after pc, and two spaces
332 // after the <RELATIVE_ADDR>. There can be any prefix data before the
333 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
334 os << prefix << StringPrintf("#%02zu pc ", it->num);
335 bool try_addr2line = false;
336 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800337 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " ???"
338 : "%08" PRIx64 " ???",
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700339 it->pc);
340 } else {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800341 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " "
342 : "%08" PRIx64 " ",
Christopher Ferrisf88b5c02017-07-19 14:18:33 -0700343 it->rel_pc);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800344 if (it->map.name.empty()) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800345 os << StringPrintf("<anonymous:%" PRIx64 ">", it->map.start);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800346 } else {
347 os << it->map.name;
348 }
Christopher Ferris53ef6a62018-02-09 23:13:27 -0800349 if (it->map.offset != 0) {
350 os << StringPrintf(" (offset %" PRIx64 ")", it->map.offset);
351 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700352 os << " (";
353 if (!it->func_name.empty()) {
354 os << it->func_name;
355 if (it->func_offset != 0) {
356 os << "+" << it->func_offset;
357 }
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800358 // Functions found using the gdb jit interface will be in an empty
359 // map that cannot be found using addr2line.
360 if (!it->map.name.empty()) {
361 try_addr2line = true;
362 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700363 } else if (current_method != nullptr &&
364 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
365 PcIsWithinQuickCode(current_method, it->pc)) {
366 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
David Sehr709b0702016-10-13 09:12:37 -0700367 os << current_method->JniLongName() << "+"
Christopher Ferris77b38df2018-01-18 16:16:49 -0800368 << (it->pc - reinterpret_cast<uint64_t>(start_of_code));
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700369 } else {
370 os << "???";
371 }
372 os << ")";
373 }
Andreas Gampeef295362016-10-11 20:04:11 -0700374 os << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700375 if (try_addr2line && use_addr2line) {
Andreas Gampe15a678a2018-11-06 17:14:10 -0800376 Addr2line(it->map.name, it->rel_pc, os, prefix, &addr2line_state);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700377 }
378 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700379
380 if (addr2line_state != nullptr) {
381 Drain(0, prefix, &addr2line_state, os);
382 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700383}
384
385void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
386 if (tid == GetTid()) {
387 // There's no point showing that we're reading our stack out of /proc!
388 return;
389 }
390
391 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
392 std::string kernel_stack;
393 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
394 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
395 return;
396 }
397
398 std::vector<std::string> kernel_stack_frames;
399 Split(kernel_stack, '\n', &kernel_stack_frames);
yuanhao7a8b3f22018-02-01 15:58:53 +0800400 if (kernel_stack_frames.empty()) {
401 os << prefix << "(" << kernel_stack_filename << " is empty)\n";
402 return;
403 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700404 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
405 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
406 kernel_stack_frames.pop_back();
407 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
408 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
409 // into "futex_wait_queue_me+0xcd/0x110".
410 const char* text = kernel_stack_frames[i].c_str();
411 const char* close_bracket = strchr(text, ']');
412 if (close_bracket != nullptr) {
413 text = close_bracket + 2;
414 }
415 os << prefix;
416 if (include_count) {
417 os << StringPrintf("#%02zd ", i);
418 }
Andreas Gampeef295362016-10-11 20:04:11 -0700419 os << text << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700420 }
421}
422
423#elif defined(__APPLE__)
424
425void DumpNativeStack(std::ostream& os ATTRIBUTE_UNUSED,
426 pid_t tid ATTRIBUTE_UNUSED,
427 BacktraceMap* existing_map ATTRIBUTE_UNUSED,
428 const char* prefix ATTRIBUTE_UNUSED,
429 ArtMethod* current_method ATTRIBUTE_UNUSED,
Christopher Ferrisa0b25272018-03-27 17:04:44 -0700430 void* ucontext_ptr ATTRIBUTE_UNUSED,
431 bool skip_frames ATTRIBUTE_UNUSED) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700432}
433
434void DumpKernelStack(std::ostream& os ATTRIBUTE_UNUSED,
435 pid_t tid ATTRIBUTE_UNUSED,
436 const char* prefix ATTRIBUTE_UNUSED,
437 bool include_count ATTRIBUTE_UNUSED) {
438}
439
440#else
441#error "Unsupported architecture for native stack dumps."
442#endif
443
444} // namespace art