debugger_posix.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/debug/debugger.h"
6#include "build/build_config.h"
7
8#include <errno.h>
9#include <fcntl.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <sys/param.h>
13#include <sys/stat.h>
14#include <sys/types.h>
15#include <unistd.h>
16
17#include <string>
18#include <vector>
19
20#if defined(__GLIBCXX__)
21#include <cxxabi.h>
22#endif
23
24#if defined(OS_MACOSX)
25#include <AvailabilityMacros.h>
26#endif
27
28#if defined(OS_MACOSX) || defined(OS_BSD)
29#include <sys/sysctl.h>
30#endif
31
32#if defined(OS_FREEBSD)
33#include <sys/user.h>
34#endif
35
36#include <ostream>
37
38#include "base/basictypes.h"
39#include "base/logging.h"
40#include "base/memory/scoped_ptr.h"
41#include "base/posix/eintr_wrapper.h"
42#include "base/safe_strerror_posix.h"
43#include "base/strings/string_piece.h"
44#include "base/strings/stringprintf.h"
45
46#if defined(USE_SYMBOLIZE)
47#include "base/third_party/symbolize/symbolize.h"
48#endif
49
50#if defined(OS_ANDROID)
51#include "base/threading/platform_thread.h"
52#endif
53
54namespace base {
55namespace debug {
56
57bool SpawnDebuggerOnProcess(unsigned process_id) {
58#if OS_ANDROID || OS_NACL
59  NOTIMPLEMENTED();
60  return false;
61#else
62  const std::string debug_cmd =
63      StringPrintf("xterm -e 'gdb --pid=%u' &", process_id);
64  LOG(WARNING) << "Starting debugger on pid " << process_id
65               << " with command `" << debug_cmd << "`";
66  int ret = system(debug_cmd.c_str());
67  if (ret == -1)
68    return false;
69  return true;
70#endif
71}
72
73#if defined(OS_MACOSX) || defined(OS_BSD)
74
75// Based on Apple's recommended method as described in
76// http://developer.apple.com/qa/qa2004/qa1361.html
77bool BeingDebugged() {
78  // NOTE: This code MUST be async-signal safe (it's used by in-process
79  // stack dumping signal handler). NO malloc or stdio is allowed here.
80  //
81  // While some code used below may be async-signal unsafe, note how
82  // the result is cached (see |is_set| and |being_debugged| static variables
83  // right below). If this code is properly warmed-up early
84  // in the start-up process, it should be safe to use later.
85
86  // If the process is sandboxed then we can't use the sysctl, so cache the
87  // value.
88  static bool is_set = false;
89  static bool being_debugged = false;
90
91  if (is_set)
92    return being_debugged;
93
94  // Initialize mib, which tells sysctl what info we want.  In this case,
95  // we're looking for information about a specific process ID.
96  int mib[] = {
97    CTL_KERN,
98    KERN_PROC,
99    KERN_PROC_PID,
100    getpid()
101#if defined(OS_OPENBSD)
102    , sizeof(struct kinfo_proc),
103    0
104#endif
105  };
106
107  // Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE.  The source and
108  // binary interfaces may change.
109  struct kinfo_proc info;
110  size_t info_size = sizeof(info);
111
112#if defined(OS_OPENBSD)
113  if (sysctl(mib, arraysize(mib), NULL, &info_size, NULL, 0) < 0)
114    return -1;
115
116  mib[5] = (info_size / sizeof(struct kinfo_proc));
117#endif
118
119  int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
120  DCHECK_EQ(sysctl_result, 0);
121  if (sysctl_result != 0) {
122    is_set = true;
123    being_debugged = false;
124    return being_debugged;
125  }
126
127  // This process is being debugged if the P_TRACED flag is set.
128  is_set = true;
129#if defined(OS_FREEBSD)
130  being_debugged = (info.ki_flag & P_TRACED) != 0;
131#elif defined(OS_BSD)
132  being_debugged = (info.p_flag & P_TRACED) != 0;
133#else
134  being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
135#endif
136  return being_debugged;
137}
138
139#elif defined(OS_LINUX) || defined(OS_ANDROID)
140
141// We can look in /proc/self/status for TracerPid.  We are likely used in crash
142// handling, so we are careful not to use the heap or have side effects.
143// Another option that is common is to try to ptrace yourself, but then we
144// can't detach without forking(), and that's not so great.
145// static
146bool BeingDebugged() {
147  // NOTE: This code MUST be async-signal safe (it's used by in-process
148  // stack dumping signal handler). NO malloc or stdio is allowed here.
149
150  int status_fd = open("/proc/self/status", O_RDONLY);
151  if (status_fd == -1)
152    return false;
153
154  // We assume our line will be in the first 1024 characters and that we can
155  // read this much all at once.  In practice this will generally be true.
156  // This simplifies and speeds up things considerably.
157  char buf[1024];
158
159  ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
160  if (IGNORE_EINTR(close(status_fd)) < 0)
161    return false;
162
163  if (num_read <= 0)
164    return false;
165
166  StringPiece status(buf, num_read);
167  StringPiece tracer("TracerPid:\t");
168
169  StringPiece::size_type pid_index = status.find(tracer);
170  if (pid_index == StringPiece::npos)
171    return false;
172
173  // Our pid is 0 without a debugger, assume this for any pid starting with 0.
174  pid_index += tracer.size();
175  return pid_index < status.size() && status[pid_index] != '0';
176}
177
178#else
179
180bool BeingDebugged() {
181  NOTIMPLEMENTED();
182  return false;
183}
184
185#endif
186
187// We want to break into the debugger in Debug mode, and cause a crash dump in
188// Release mode. Breakpad behaves as follows:
189//
190// +-------+-----------------+-----------------+
191// | OS    | Dump on SIGTRAP | Dump on SIGABRT |
192// +-------+-----------------+-----------------+
193// | Linux |       N         |        Y        |
194// | Mac   |       Y         |        N        |
195// +-------+-----------------+-----------------+
196//
197// Thus we do the following:
198// Linux: Debug mode if a debugger is attached, send SIGTRAP; otherwise send
199//        SIGABRT
200// Mac: Always send SIGTRAP.
201
202#if defined(ARCH_CPU_ARMEL)
203#define DEBUG_BREAK_ASM() asm("bkpt 0")
204#elif defined(ARCH_CPU_ARM64)
205#define DEBUG_BREAK_ASM() asm("brk 0")
206#elif defined(ARCH_CPU_MIPS_FAMILY)
207#define DEBUG_BREAK_ASM() asm("break 2")
208#elif defined(ARCH_CPU_X86_FAMILY)
209#define DEBUG_BREAK_ASM() asm("int3")
210#endif
211
212#if defined(NDEBUG) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
213#define DEBUG_BREAK() abort()
214#elif defined(OS_NACL)
215// The NaCl verifier doesn't let use use int3.  For now, we call abort().  We
216// should ask for advice from some NaCl experts about the optimum thing here.
217// http://code.google.com/p/nativeclient/issues/detail?id=645
218#define DEBUG_BREAK() abort()
219#elif !defined(OS_MACOSX)
220// Though Android has a "helpful" process called debuggerd to catch native
221// signals on the general assumption that they are fatal errors. If no debugger
222// is attached, we call abort since Breakpad needs SIGABRT to create a dump.
223// When debugger is attached, for ARM platform the bkpt instruction appears
224// to cause SIGBUS which is trapped by debuggerd, and we've had great
225// difficulty continuing in a debugger once we stop from SIG triggered by native
226// code, use GDB to set |go| to 1 to resume execution; for X86 platform, use
227// "int3" to setup breakpiont and raise SIGTRAP.
228//
229// On other POSIX architectures, except Mac OS X, we use the same logic to
230// ensure that breakpad creates a dump on crashes while it is still possible to
231// use a debugger.
232namespace {
233void DebugBreak() {
234  if (!BeingDebugged()) {
235    abort();
236  } else {
237#if defined(DEBUG_BREAK_ASM)
238    DEBUG_BREAK_ASM();
239#else
240    volatile int go = 0;
241    while (!go) {
242      base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
243    }
244#endif
245  }
246}
247}  // namespace
248#define DEBUG_BREAK() DebugBreak()
249#elif defined(DEBUG_BREAK_ASM)
250#define DEBUG_BREAK() DEBUG_BREAK_ASM()
251#else
252#error "Don't know how to debug break on this architecture/OS"
253#endif
254
255void BreakDebugger() {
256  // NOTE: This code MUST be async-signal safe (it's used by in-process
257  // stack dumping signal handler). NO malloc or stdio is allowed here.
258
259  DEBUG_BREAK();
260#if defined(OS_ANDROID) && !defined(OFFICIAL_BUILD)
261  // For Android development we always build release (debug builds are
262  // unmanageably large), so the unofficial build is used for debugging. It is
263  // helpful to be able to insert BreakDebugger() statements in the source,
264  // attach the debugger, inspect the state of the program and then resume it by
265  // setting the 'go' variable above.
266#elif defined(NDEBUG)
267  // Terminate the program after signaling the debug break.
268  _exit(1);
269#endif
270}
271
272}  // namespace debug
273}  // namespace base
274