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