blob: 11f4203150b60c1a401262d5297387dc8d7ddb94 [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"
David Srbeckybb720732019-01-29 16:54:47 +000053#include "class_linker.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070054#include "oat_quick_method_header.h"
David Srbeckybb720732019-01-29 16:54:47 +000055#include "runtime.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070056#include "thread-current-inl.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070057
58#endif
59
60namespace art {
61
62#if defined(__linux__)
63
Andreas Gampe46ee31b2016-12-14 10:11:49 -080064using android::base::StringPrintf;
65
Andreas Gampe5dd44d02016-08-02 17:20:03 -070066static constexpr bool kUseAddr2line = !kIsTargetBuild;
67
68ALWAYS_INLINE
Andreas Gampefcccbaf2016-08-02 17:20:03 -070069static inline void WritePrefix(std::ostream& os, const char* prefix, bool odd) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -070070 if (prefix != nullptr) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070071 os << prefix;
Andreas Gampe5dd44d02016-08-02 17:20:03 -070072 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -070073 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070074 if (!odd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070075 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070076 }
77}
78
Andreas Gampefcccbaf2016-08-02 17:20:03 -070079// The state of an open pipe to addr2line. In "server" mode, addr2line takes input on stdin
80// and prints the result to stdout. This struct keeps the state of the open connection.
81struct Addr2linePipe {
82 Addr2linePipe(int in_fd, int out_fd, const std::string& file_name, pid_t pid)
83 : in(in_fd, false), out(out_fd, false), file(file_name), child_pid(pid), odd(true) {}
84
85 ~Addr2linePipe() {
86 kill(child_pid, SIGKILL);
87 }
88
89 File in; // The file descriptor that is connected to the output of addr2line.
90 File out; // The file descriptor that is connected to the input of addr2line.
91
92 const std::string file; // The file addr2line is working on, so that we know when to close
93 // and restart.
94 const pid_t child_pid; // The pid of the child, which we should kill when we're done.
95 bool odd; // Print state for indentation of lines.
96};
97
98static std::unique_ptr<Addr2linePipe> Connect(const std::string& name, const char* args[]) {
99 int caller_to_addr2line[2];
100 int addr2line_to_caller[2];
101
102 if (pipe(caller_to_addr2line) == -1) {
103 return nullptr;
104 }
105 if (pipe(addr2line_to_caller) == -1) {
106 close(caller_to_addr2line[0]);
107 close(caller_to_addr2line[1]);
108 return nullptr;
109 }
110
111 pid_t pid = fork();
112 if (pid == -1) {
113 close(caller_to_addr2line[0]);
114 close(caller_to_addr2line[1]);
Calin Juravle0ed6c802017-03-27 18:12:05 -0700115 close(addr2line_to_caller[0]);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700116 close(addr2line_to_caller[1]);
117 return nullptr;
118 }
119
120 if (pid == 0) {
121 dup2(caller_to_addr2line[0], STDIN_FILENO);
122 dup2(addr2line_to_caller[1], STDOUT_FILENO);
123
124 close(caller_to_addr2line[0]);
125 close(caller_to_addr2line[1]);
126 close(addr2line_to_caller[0]);
127 close(addr2line_to_caller[1]);
128
129 execv(args[0], const_cast<char* const*>(args));
130 exit(1);
131 } else {
132 close(caller_to_addr2line[0]);
133 close(addr2line_to_caller[1]);
Yi Kongc57c6802018-10-29 14:28:56 -0700134 return std::make_unique<Addr2linePipe>(addr2line_to_caller[0],
135 caller_to_addr2line[1],
136 name,
137 pid);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700138 }
139}
140
141static void Drain(size_t expected,
142 const char* prefix,
143 std::unique_ptr<Addr2linePipe>* pipe /* inout */,
144 std::ostream& os) {
145 DCHECK(pipe != nullptr);
146 DCHECK(pipe->get() != nullptr);
147 int in = pipe->get()->in.Fd();
148 DCHECK_GE(in, 0);
149
150 bool prefix_written = false;
151
152 for (;;) {
Christopher Ferris453e0e52018-03-06 14:02:55 -0800153 constexpr uint32_t kWaitTimeExpectedMilli = 500;
154 constexpr uint32_t kWaitTimeUnexpectedMilli = 50;
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700155
Christopher Ferris453e0e52018-03-06 14:02:55 -0800156 int timeout = expected > 0 ? kWaitTimeExpectedMilli : kWaitTimeUnexpectedMilli;
157 struct pollfd read_fd{in, POLLIN, 0};
158 int retval = TEMP_FAILURE_RETRY(poll(&read_fd, 1, timeout));
159 if (retval == -1) {
160 // An error occurred.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700161 pipe->reset();
162 return;
163 }
164
165 if (retval == 0) {
166 // Timeout.
167 return;
168 }
169
Christopher Ferris453e0e52018-03-06 14:02:55 -0800170 if (!(read_fd.revents & POLLIN)) {
171 // addr2line call exited.
172 pipe->reset();
173 return;
174 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700175
176 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
177 // alt stack, but just to be sure...
178 char buffer[kMaxBuffer];
179 memset(buffer, 0, kMaxBuffer);
180 int bytes_read = TEMP_FAILURE_RETRY(read(in, buffer, kMaxBuffer - 1));
Christopher Ferris453e0e52018-03-06 14:02:55 -0800181 if (bytes_read <= 0) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700182 // This should not really happen...
183 pipe->reset();
184 return;
185 }
Christopher Ferris453e0e52018-03-06 14:02:55 -0800186 buffer[bytes_read] = '\0';
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700187
188 char* tmp = buffer;
189 while (*tmp != 0) {
190 if (!prefix_written) {
191 WritePrefix(os, prefix, (*pipe)->odd);
192 prefix_written = true;
193 }
194 char* new_line = strchr(tmp, '\n');
195 if (new_line == nullptr) {
196 os << tmp;
197
198 break;
199 } else {
200 char saved = *(new_line + 1);
201 *(new_line + 1) = 0;
202 os << tmp;
203 *(new_line + 1) = saved;
204
205 tmp = new_line + 1;
206 prefix_written = false;
207 (*pipe)->odd = !(*pipe)->odd;
208
209 if (expected > 0) {
210 expected--;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700211 }
212 }
213 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700214 }
215}
216
217static void Addr2line(const std::string& map_src,
218 uintptr_t offset,
219 std::ostream& os,
220 const char* prefix,
221 std::unique_ptr<Addr2linePipe>* pipe /* inout */) {
222 DCHECK(pipe != nullptr);
223
Christopher Ferrisb1f23f92018-03-07 14:10:49 -0800224 if (map_src == "[vdso]" || android::base::EndsWith(map_src, ".vdex")) {
225 // addr2line will not work on the vdso.
226 // vdex files are special frames injected for the interpreter
227 // so they don't have any line number information available.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700228 return;
229 }
230
231 if (*pipe == nullptr || (*pipe)->file != map_src) {
232 if (*pipe != nullptr) {
233 Drain(0, prefix, pipe, os);
234 }
235 pipe->reset(); // Close early.
236
237 const char* args[7] = {
238 "/usr/bin/addr2line",
239 "--functions",
240 "--inlines",
241 "--demangle",
242 "-e",
243 map_src.c_str(),
244 nullptr
245 };
246 *pipe = Connect(map_src, args);
247 }
248
249 Addr2linePipe* pipe_ptr = pipe->get();
250 if (pipe_ptr == nullptr) {
251 // Failed...
252 return;
253 }
254
255 // Send the offset.
256 const std::string hex_offset = StringPrintf("%zx\n", offset);
257
258 if (!pipe_ptr->out.WriteFully(hex_offset.data(), hex_offset.length())) {
259 // Error. :-(
260 pipe->reset();
261 return;
262 }
263
264 // Now drain (expecting two lines).
265 Drain(2U, prefix, pipe, os);
266}
267
Andreas Gampeca620d72016-11-08 08:09:33 -0800268static bool RunCommand(const std::string& cmd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700269 FILE* stream = popen(cmd.c_str(), "r");
270 if (stream) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700271 pclose(stream);
272 return true;
273 } else {
274 return false;
275 }
276}
277
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700278static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
David Srbeckybb720732019-01-29 16:54:47 +0000279 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
280 if (entry_point == nullptr) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700281 return pc == 0;
282 }
David Srbeckybb720732019-01-29 16:54:47 +0000283 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
284 if (class_linker->IsQuickGenericJniStub(entry_point) ||
285 class_linker->IsQuickResolutionStub(entry_point) ||
286 class_linker->IsQuickToInterpreterBridge(entry_point)) {
287 return false;
288 }
289 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(entry_point));
Mingyao Yang063fc772016-08-02 11:02:54 -0700290 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].GetCodeSize();
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700291 return code <= pc && pc <= (code + code_size);
292}
293
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700294void DumpNativeStack(std::ostream& os,
295 pid_t tid,
296 BacktraceMap* existing_map,
297 const char* prefix,
298 ArtMethod* current_method,
Christopher Ferrisb2749312018-03-23 13:03:45 -0700299 void* ucontext_ptr,
300 bool skip_frames) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000301 // Historical note: This was disabled when running under Valgrind (b/18119146).
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700302
303 BacktraceMap* map = existing_map;
304 std::unique_ptr<BacktraceMap> tmp_map;
305 if (map == nullptr) {
306 tmp_map.reset(BacktraceMap::Create(getpid()));
307 map = tmp_map.get();
308 }
309 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid, map));
Christopher Ferrisb2749312018-03-23 13:03:45 -0700310 backtrace->SetSkipFrames(skip_frames);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700311 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
312 os << prefix << "(backtrace::Unwind failed for thread " << tid
Andreas Gampeef295362016-10-11 20:04:11 -0700313 << ": " << backtrace->GetErrorString(backtrace->GetError()) << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700314 return;
315 } else if (backtrace->NumFrames() == 0) {
Andreas Gampeef295362016-10-11 20:04:11 -0700316 os << prefix << "(no native stack frames for thread " << tid << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700317 return;
318 }
319
320 // Check whether we have and should use addr2line.
321 bool use_addr2line;
322 if (kUseAddr2line) {
323 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
324 // and print to stderr.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700325 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h");
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700326 } else {
327 use_addr2line = false;
328 }
329
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700330 std::unique_ptr<Addr2linePipe> addr2line_state;
331
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700332 for (Backtrace::const_iterator it = backtrace->begin();
333 it != backtrace->end(); ++it) {
334 // We produce output like this:
335 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
336 // In order for parsing tools to continue to function, the stack dump
337 // format must at least adhere to this format:
338 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
339 // The parsers require a single space before and after pc, and two spaces
340 // after the <RELATIVE_ADDR>. There can be any prefix data before the
341 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
342 os << prefix << StringPrintf("#%02zu pc ", it->num);
343 bool try_addr2line = false;
344 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800345 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " ???"
346 : "%08" PRIx64 " ???",
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700347 it->pc);
348 } else {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800349 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " "
350 : "%08" PRIx64 " ",
Christopher Ferrisf88b5c02017-07-19 14:18:33 -0700351 it->rel_pc);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800352 if (it->map.name.empty()) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800353 os << StringPrintf("<anonymous:%" PRIx64 ">", it->map.start);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800354 } else {
355 os << it->map.name;
356 }
Christopher Ferris53ef6a62018-02-09 23:13:27 -0800357 if (it->map.offset != 0) {
358 os << StringPrintf(" (offset %" PRIx64 ")", it->map.offset);
359 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700360 os << " (";
361 if (!it->func_name.empty()) {
362 os << it->func_name;
363 if (it->func_offset != 0) {
364 os << "+" << it->func_offset;
365 }
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800366 // Functions found using the gdb jit interface will be in an empty
367 // map that cannot be found using addr2line.
368 if (!it->map.name.empty()) {
369 try_addr2line = true;
370 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700371 } else if (current_method != nullptr &&
372 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
373 PcIsWithinQuickCode(current_method, it->pc)) {
374 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
David Sehr709b0702016-10-13 09:12:37 -0700375 os << current_method->JniLongName() << "+"
Christopher Ferris77b38df2018-01-18 16:16:49 -0800376 << (it->pc - reinterpret_cast<uint64_t>(start_of_code));
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700377 } else {
378 os << "???";
379 }
380 os << ")";
381 }
Andreas Gampeef295362016-10-11 20:04:11 -0700382 os << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700383 if (try_addr2line && use_addr2line) {
Andreas Gampe15a678a2018-11-06 17:14:10 -0800384 Addr2line(it->map.name, it->rel_pc, os, prefix, &addr2line_state);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700385 }
386 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700387
388 if (addr2line_state != nullptr) {
389 Drain(0, prefix, &addr2line_state, os);
390 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700391}
392
393void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
394 if (tid == GetTid()) {
395 // There's no point showing that we're reading our stack out of /proc!
396 return;
397 }
398
399 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
400 std::string kernel_stack;
401 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
402 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
403 return;
404 }
405
406 std::vector<std::string> kernel_stack_frames;
407 Split(kernel_stack, '\n', &kernel_stack_frames);
yuanhao7a8b3f22018-02-01 15:58:53 +0800408 if (kernel_stack_frames.empty()) {
409 os << prefix << "(" << kernel_stack_filename << " is empty)\n";
410 return;
411 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700412 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
413 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
414 kernel_stack_frames.pop_back();
415 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
416 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
417 // into "futex_wait_queue_me+0xcd/0x110".
418 const char* text = kernel_stack_frames[i].c_str();
419 const char* close_bracket = strchr(text, ']');
420 if (close_bracket != nullptr) {
421 text = close_bracket + 2;
422 }
423 os << prefix;
424 if (include_count) {
425 os << StringPrintf("#%02zd ", i);
426 }
Andreas Gampeef295362016-10-11 20:04:11 -0700427 os << text << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700428 }
429}
430
431#elif defined(__APPLE__)
432
433void DumpNativeStack(std::ostream& os ATTRIBUTE_UNUSED,
434 pid_t tid ATTRIBUTE_UNUSED,
435 BacktraceMap* existing_map ATTRIBUTE_UNUSED,
436 const char* prefix ATTRIBUTE_UNUSED,
437 ArtMethod* current_method ATTRIBUTE_UNUSED,
Christopher Ferrisa0b25272018-03-27 17:04:44 -0700438 void* ucontext_ptr ATTRIBUTE_UNUSED,
439 bool skip_frames ATTRIBUTE_UNUSED) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700440}
441
442void DumpKernelStack(std::ostream& os ATTRIBUTE_UNUSED,
443 pid_t tid ATTRIBUTE_UNUSED,
444 const char* prefix ATTRIBUTE_UNUSED,
445 bool include_count ATTRIBUTE_UNUSED) {
446}
447
448#else
449#error "Unsupported architecture for native stack dumps."
450#endif
451
452} // namespace art