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