blob: ba5d141b932aa7592489f85d640da46b4be77739 [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 Gampe43e72432019-05-14 16:15:24 -070042#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080043#include "android-base/stringprintf.h"
Christopher Ferrisb1f23f92018-03-07 14:10:49 -080044#include "android-base/strings.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080045
Andreas Gampe5dd44d02016-08-02 17:20:03 -070046#include "arch/instruction_set.h"
Andreas Gampe39b378c2017-12-07 15:44:13 -080047#include "base/aborting.h"
David Srbeckyeea5fd32019-02-13 17:24:17 +000048#include "base/bit_utils.h"
David Sehr891a50e2017-10-27 17:01:07 -070049#include "base/file_utils.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070050#include "base/memory_tool.h"
51#include "base/mutex.h"
David Sehrc431b9d2018-03-02 12:01:51 -080052#include "base/os.h"
Andreas Gampefcccbaf2016-08-02 17:20:03 -070053#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080054#include "base/utils.h"
David Srbeckybb720732019-01-29 16:54:47 +000055#include "class_linker.h"
David Srbeckyeea5fd32019-02-13 17:24:17 +000056#include "entrypoints/runtime_asm_entrypoints.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070057#include "oat_quick_method_header.h"
David Srbeckybb720732019-01-29 16:54:47 +000058#include "runtime.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070059#include "thread-current-inl.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070060
61#endif
62
63namespace art {
64
65#if defined(__linux__)
66
Andreas Gampe46ee31b2016-12-14 10:11:49 -080067using android::base::StringPrintf;
68
Andreas Gampe5dd44d02016-08-02 17:20:03 -070069static constexpr bool kUseAddr2line = !kIsTargetBuild;
70
David Srbecky87da30e2019-01-30 15:51:23 +000071std::string FindAddr2line() {
72 if (!kIsTargetBuild) {
73 constexpr const char* kAddr2linePrebuiltPath =
74 "/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.17-4.8/bin/x86_64-linux-addr2line";
75 const char* env_value = getenv("ANDROID_BUILD_TOP");
76 if (env_value != nullptr) {
77 return std::string(env_value) + kAddr2linePrebuiltPath;
78 }
79 }
80 return std::string("/usr/bin/addr2line");
81}
82
Andreas Gampe5dd44d02016-08-02 17:20:03 -070083ALWAYS_INLINE
Andreas Gampefcccbaf2016-08-02 17:20:03 -070084static inline void WritePrefix(std::ostream& os, const char* prefix, bool odd) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -070085 if (prefix != nullptr) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070086 os << prefix;
Andreas Gampe5dd44d02016-08-02 17:20:03 -070087 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -070088 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070089 if (!odd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -070090 os << " ";
Andreas Gampe5dd44d02016-08-02 17:20:03 -070091 }
92}
93
Andreas Gampefcccbaf2016-08-02 17:20:03 -070094// The state of an open pipe to addr2line. In "server" mode, addr2line takes input on stdin
95// and prints the result to stdout. This struct keeps the state of the open connection.
96struct Addr2linePipe {
97 Addr2linePipe(int in_fd, int out_fd, const std::string& file_name, pid_t pid)
98 : in(in_fd, false), out(out_fd, false), file(file_name), child_pid(pid), odd(true) {}
99
100 ~Addr2linePipe() {
101 kill(child_pid, SIGKILL);
102 }
103
104 File in; // The file descriptor that is connected to the output of addr2line.
105 File out; // The file descriptor that is connected to the input of addr2line.
106
107 const std::string file; // The file addr2line is working on, so that we know when to close
108 // and restart.
109 const pid_t child_pid; // The pid of the child, which we should kill when we're done.
110 bool odd; // Print state for indentation of lines.
111};
112
113static std::unique_ptr<Addr2linePipe> Connect(const std::string& name, const char* args[]) {
114 int caller_to_addr2line[2];
115 int addr2line_to_caller[2];
116
117 if (pipe(caller_to_addr2line) == -1) {
118 return nullptr;
119 }
120 if (pipe(addr2line_to_caller) == -1) {
121 close(caller_to_addr2line[0]);
122 close(caller_to_addr2line[1]);
123 return nullptr;
124 }
125
126 pid_t pid = fork();
127 if (pid == -1) {
128 close(caller_to_addr2line[0]);
129 close(caller_to_addr2line[1]);
Calin Juravle0ed6c802017-03-27 18:12:05 -0700130 close(addr2line_to_caller[0]);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700131 close(addr2line_to_caller[1]);
132 return nullptr;
133 }
134
135 if (pid == 0) {
136 dup2(caller_to_addr2line[0], STDIN_FILENO);
137 dup2(addr2line_to_caller[1], STDOUT_FILENO);
138
139 close(caller_to_addr2line[0]);
140 close(caller_to_addr2line[1]);
141 close(addr2line_to_caller[0]);
142 close(addr2line_to_caller[1]);
143
144 execv(args[0], const_cast<char* const*>(args));
145 exit(1);
146 } else {
147 close(caller_to_addr2line[0]);
148 close(addr2line_to_caller[1]);
Yi Kongc57c6802018-10-29 14:28:56 -0700149 return std::make_unique<Addr2linePipe>(addr2line_to_caller[0],
150 caller_to_addr2line[1],
151 name,
152 pid);
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700153 }
154}
155
156static void Drain(size_t expected,
157 const char* prefix,
158 std::unique_ptr<Addr2linePipe>* pipe /* inout */,
159 std::ostream& os) {
160 DCHECK(pipe != nullptr);
161 DCHECK(pipe->get() != nullptr);
162 int in = pipe->get()->in.Fd();
163 DCHECK_GE(in, 0);
164
165 bool prefix_written = false;
166
167 for (;;) {
Christopher Ferris453e0e52018-03-06 14:02:55 -0800168 constexpr uint32_t kWaitTimeExpectedMilli = 500;
169 constexpr uint32_t kWaitTimeUnexpectedMilli = 50;
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700170
Christopher Ferris453e0e52018-03-06 14:02:55 -0800171 int timeout = expected > 0 ? kWaitTimeExpectedMilli : kWaitTimeUnexpectedMilli;
172 struct pollfd read_fd{in, POLLIN, 0};
173 int retval = TEMP_FAILURE_RETRY(poll(&read_fd, 1, timeout));
174 if (retval == -1) {
175 // An error occurred.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700176 pipe->reset();
177 return;
178 }
179
180 if (retval == 0) {
181 // Timeout.
182 return;
183 }
184
Christopher Ferris453e0e52018-03-06 14:02:55 -0800185 if (!(read_fd.revents & POLLIN)) {
186 // addr2line call exited.
187 pipe->reset();
188 return;
189 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700190
191 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
192 // alt stack, but just to be sure...
193 char buffer[kMaxBuffer];
194 memset(buffer, 0, kMaxBuffer);
195 int bytes_read = TEMP_FAILURE_RETRY(read(in, buffer, kMaxBuffer - 1));
Christopher Ferris453e0e52018-03-06 14:02:55 -0800196 if (bytes_read <= 0) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700197 // This should not really happen...
198 pipe->reset();
199 return;
200 }
Christopher Ferris453e0e52018-03-06 14:02:55 -0800201 buffer[bytes_read] = '\0';
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700202
203 char* tmp = buffer;
204 while (*tmp != 0) {
205 if (!prefix_written) {
206 WritePrefix(os, prefix, (*pipe)->odd);
207 prefix_written = true;
208 }
209 char* new_line = strchr(tmp, '\n');
210 if (new_line == nullptr) {
211 os << tmp;
212
213 break;
214 } else {
215 char saved = *(new_line + 1);
216 *(new_line + 1) = 0;
217 os << tmp;
218 *(new_line + 1) = saved;
219
220 tmp = new_line + 1;
221 prefix_written = false;
222 (*pipe)->odd = !(*pipe)->odd;
223
224 if (expected > 0) {
225 expected--;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700226 }
227 }
228 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700229 }
230}
231
232static void Addr2line(const std::string& map_src,
233 uintptr_t offset,
234 std::ostream& os,
235 const char* prefix,
236 std::unique_ptr<Addr2linePipe>* pipe /* inout */) {
237 DCHECK(pipe != nullptr);
238
Christopher Ferrisb1f23f92018-03-07 14:10:49 -0800239 if (map_src == "[vdso]" || android::base::EndsWith(map_src, ".vdex")) {
240 // addr2line will not work on the vdso.
241 // vdex files are special frames injected for the interpreter
242 // so they don't have any line number information available.
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700243 return;
244 }
245
246 if (*pipe == nullptr || (*pipe)->file != map_src) {
247 if (*pipe != nullptr) {
248 Drain(0, prefix, pipe, os);
249 }
250 pipe->reset(); // Close early.
251
David Srbecky87da30e2019-01-30 15:51:23 +0000252 std::string addr2linePath = FindAddr2line();
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700253 const char* args[7] = {
David Srbecky87da30e2019-01-30 15:51:23 +0000254 addr2linePath.c_str(),
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700255 "--functions",
256 "--inlines",
257 "--demangle",
258 "-e",
259 map_src.c_str(),
260 nullptr
261 };
262 *pipe = Connect(map_src, args);
263 }
264
265 Addr2linePipe* pipe_ptr = pipe->get();
266 if (pipe_ptr == nullptr) {
267 // Failed...
268 return;
269 }
270
271 // Send the offset.
272 const std::string hex_offset = StringPrintf("%zx\n", offset);
273
274 if (!pipe_ptr->out.WriteFully(hex_offset.data(), hex_offset.length())) {
275 // Error. :-(
276 pipe->reset();
277 return;
278 }
279
280 // Now drain (expecting two lines).
281 Drain(2U, prefix, pipe, os);
282}
283
Andreas Gampeca620d72016-11-08 08:09:33 -0800284static bool RunCommand(const std::string& cmd) {
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700285 FILE* stream = popen(cmd.c_str(), "r");
286 if (stream) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700287 pclose(stream);
288 return true;
289 } else {
290 return false;
291 }
292}
293
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700294static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
David Srbeckybb720732019-01-29 16:54:47 +0000295 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
296 if (entry_point == nullptr) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700297 return pc == 0;
298 }
David Srbeckybb720732019-01-29 16:54:47 +0000299 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
300 if (class_linker->IsQuickGenericJniStub(entry_point) ||
301 class_linker->IsQuickResolutionStub(entry_point) ||
302 class_linker->IsQuickToInterpreterBridge(entry_point)) {
303 return false;
304 }
David Srbecky7f728562019-02-14 17:52:33 +0000305 // The backtrace library might have heuristically subracted instruction
306 // size from the pc, to pretend the pc is at the calling instruction.
307 if (reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) - pc <= 4) {
David Srbeckyeea5fd32019-02-13 17:24:17 +0000308 return false;
309 }
David Srbeckybb720732019-01-29 16:54:47 +0000310 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(entry_point));
Mingyao Yang063fc772016-08-02 11:02:54 -0700311 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].GetCodeSize();
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700312 return code <= pc && pc <= (code + code_size);
313}
314
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700315void DumpNativeStack(std::ostream& os,
316 pid_t tid,
317 BacktraceMap* existing_map,
318 const char* prefix,
319 ArtMethod* current_method,
Christopher Ferrisb2749312018-03-23 13:03:45 -0700320 void* ucontext_ptr,
321 bool skip_frames) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000322 // Historical note: This was disabled when running under Valgrind (b/18119146).
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700323
324 BacktraceMap* map = existing_map;
325 std::unique_ptr<BacktraceMap> tmp_map;
326 if (map == nullptr) {
327 tmp_map.reset(BacktraceMap::Create(getpid()));
328 map = tmp_map.get();
329 }
330 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid, map));
Christopher Ferrisb2749312018-03-23 13:03:45 -0700331 backtrace->SetSkipFrames(skip_frames);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700332 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
333 os << prefix << "(backtrace::Unwind failed for thread " << tid
Andreas Gampeef295362016-10-11 20:04:11 -0700334 << ": " << backtrace->GetErrorString(backtrace->GetError()) << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700335 return;
336 } else if (backtrace->NumFrames() == 0) {
Andreas Gampeef295362016-10-11 20:04:11 -0700337 os << prefix << "(no native stack frames for thread " << tid << ")" << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700338 return;
339 }
340
341 // Check whether we have and should use addr2line.
342 bool use_addr2line;
343 if (kUseAddr2line) {
344 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
345 // and print to stderr.
David Srbecky87da30e2019-01-30 15:51:23 +0000346 use_addr2line = (gAborting > 0) && RunCommand(FindAddr2line() + " -h");
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700347 } else {
348 use_addr2line = false;
349 }
350
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700351 std::unique_ptr<Addr2linePipe> addr2line_state;
352
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700353 for (Backtrace::const_iterator it = backtrace->begin();
354 it != backtrace->end(); ++it) {
355 // We produce output like this:
356 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
357 // In order for parsing tools to continue to function, the stack dump
358 // format must at least adhere to this format:
359 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
360 // The parsers require a single space before and after pc, and two spaces
361 // after the <RELATIVE_ADDR>. There can be any prefix data before the
362 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
363 os << prefix << StringPrintf("#%02zu pc ", it->num);
364 bool try_addr2line = false;
365 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800366 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " ???"
367 : "%08" PRIx64 " ???",
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700368 it->pc);
369 } else {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800370 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIx64 " "
371 : "%08" PRIx64 " ",
Christopher Ferrisf88b5c02017-07-19 14:18:33 -0700372 it->rel_pc);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800373 if (it->map.name.empty()) {
Christopher Ferris77b38df2018-01-18 16:16:49 -0800374 os << StringPrintf("<anonymous:%" PRIx64 ">", it->map.start);
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800375 } else {
376 os << it->map.name;
377 }
Christopher Ferris53ef6a62018-02-09 23:13:27 -0800378 if (it->map.offset != 0) {
379 os << StringPrintf(" (offset %" PRIx64 ")", it->map.offset);
380 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700381 os << " (";
382 if (!it->func_name.empty()) {
383 os << it->func_name;
384 if (it->func_offset != 0) {
385 os << "+" << it->func_offset;
386 }
Christopher Ferris8bd7d1b2018-01-08 11:12:40 -0800387 // Functions found using the gdb jit interface will be in an empty
388 // map that cannot be found using addr2line.
389 if (!it->map.name.empty()) {
390 try_addr2line = true;
391 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700392 } else if (current_method != nullptr &&
393 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
394 PcIsWithinQuickCode(current_method, it->pc)) {
395 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
David Sehr709b0702016-10-13 09:12:37 -0700396 os << current_method->JniLongName() << "+"
Christopher Ferris77b38df2018-01-18 16:16:49 -0800397 << (it->pc - reinterpret_cast<uint64_t>(start_of_code));
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700398 } else {
399 os << "???";
400 }
401 os << ")";
402 }
Andreas Gampeef295362016-10-11 20:04:11 -0700403 os << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700404 if (try_addr2line && use_addr2line) {
Andreas Gampe15a678a2018-11-06 17:14:10 -0800405 Addr2line(it->map.name, it->rel_pc, os, prefix, &addr2line_state);
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700406 }
407 }
Andreas Gampefcccbaf2016-08-02 17:20:03 -0700408
409 if (addr2line_state != nullptr) {
410 Drain(0, prefix, &addr2line_state, os);
411 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700412}
413
414void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
415 if (tid == GetTid()) {
416 // There's no point showing that we're reading our stack out of /proc!
417 return;
418 }
419
420 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
421 std::string kernel_stack;
Andreas Gampe43e72432019-05-14 16:15:24 -0700422 if (!android::base::ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700423 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
424 return;
425 }
426
427 std::vector<std::string> kernel_stack_frames;
428 Split(kernel_stack, '\n', &kernel_stack_frames);
yuanhao7a8b3f22018-02-01 15:58:53 +0800429 if (kernel_stack_frames.empty()) {
430 os << prefix << "(" << kernel_stack_filename << " is empty)\n";
431 return;
432 }
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700433 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
434 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
435 kernel_stack_frames.pop_back();
436 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
437 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
438 // into "futex_wait_queue_me+0xcd/0x110".
439 const char* text = kernel_stack_frames[i].c_str();
440 const char* close_bracket = strchr(text, ']');
441 if (close_bracket != nullptr) {
442 text = close_bracket + 2;
443 }
444 os << prefix;
445 if (include_count) {
446 os << StringPrintf("#%02zd ", i);
447 }
Andreas Gampeef295362016-10-11 20:04:11 -0700448 os << text << std::endl;
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700449 }
450}
451
452#elif defined(__APPLE__)
453
454void DumpNativeStack(std::ostream& os ATTRIBUTE_UNUSED,
455 pid_t tid ATTRIBUTE_UNUSED,
456 BacktraceMap* existing_map ATTRIBUTE_UNUSED,
457 const char* prefix ATTRIBUTE_UNUSED,
458 ArtMethod* current_method ATTRIBUTE_UNUSED,
Christopher Ferrisa0b25272018-03-27 17:04:44 -0700459 void* ucontext_ptr ATTRIBUTE_UNUSED,
460 bool skip_frames ATTRIBUTE_UNUSED) {
Andreas Gampe5dd44d02016-08-02 17:20:03 -0700461}
462
463void DumpKernelStack(std::ostream& os ATTRIBUTE_UNUSED,
464 pid_t tid ATTRIBUTE_UNUSED,
465 const char* prefix ATTRIBUTE_UNUSED,
466 bool include_count ATTRIBUTE_UNUSED) {
467}
468
469#else
470#error "Unsupported architecture for native stack dumps."
471#endif
472
473} // namespace art