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/check_op.h"
21 #include "base/clang_profiling_buildflags.h"
22 #include "base/notreached.h"
23 #include "base/stl_util.h"
24 #include "base/strings/string_util.h"
25 #include "base/threading/platform_thread.h"
26 #include "base/time/time.h"
27 #include "build/build_config.h"
28
29 #if defined(__GLIBCXX__)
30 #include <cxxabi.h>
31 #endif
32
33 #if defined(OS_APPLE)
34 #include <AvailabilityMacros.h>
35 #endif
36
37 #if defined(OS_APPLE) || defined(OS_BSD)
38 #include <sys/sysctl.h>
39 #endif
40
41 #if defined(OS_FREEBSD) || defined(OS_DRAGONFLY)
42 #include <sys/user.h>
43 #endif
44
45 #if defined(OS_FUCHSIA)
46 #include <zircon/process.h>
47 #include <zircon/syscalls.h>
48 #endif
49
50 #include <ostream>
51
52 #include "base/check.h"
53 #include "base/debug/alias.h"
54 #include "base/debug/debugging_buildflags.h"
55 #include "base/environment.h"
56 #include "base/files/file_util.h"
57 #include "base/posix/eintr_wrapper.h"
58 #include "base/process/process.h"
59 #include "base/strings/string_number_conversions.h"
60 #include "base/strings/string_piece.h"
61
62 #if BUILDFLAG(CLANG_PROFILING)
63 #include "base/test/clang_profiling.h"
64 #endif
65
66 #if defined(USE_SYMBOLIZE)
67 #include "base/third_party/symbolize/symbolize.h"
68 #endif
69
70 namespace base {
71 namespace debug {
72
73 #if defined(OS_APPLE) || defined(OS_BSD)
74
75 // Based on Apple's recommended method as described in
76 // http://developer.apple.com/qa/qa2004/qa1361.html
BeingDebugged()77 bool 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_BSD)
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;
111
112 if (sysctl(mib, base::size(mib), NULL, &info_size, NULL, 0) < 0)
113 return -1;
114
115 info = (struct kinfo_proc *)malloc(info_size);
116 mib[5] = (info_size / sizeof(struct kinfo_proc));
117
118 int sysctl_result = sysctl(mib, base::size(mib), info, &info_size, NULL, 0);
119 DCHECK_EQ(sysctl_result, 0);
120 if (sysctl_result != 0) {
121 is_set = true;
122 being_debugged = false;
123 goto out;
124 }
125
126 // This process is being debugged if the P_TRACED flag is set.
127 is_set = true;
128 #if defined(OS_FREEBSD)
129 being_debugged = (info->ki_flag & P_TRACED) != 0;
130 #elif defined(OS_DRAGONFLY)
131 being_debugged = (info->kp_flags & P_TRACED) != 0;
132 #elif defined(OS_BSD)
133 being_debugged = (info->p_flag & P_TRACED) != 0;
134 #else
135 being_debugged = (info->kp_proc.p_flag & P_TRACED) != 0;
136 #endif
137
138 out:
139 free(info);
140 return being_debugged;
141 }
142
VerifyDebugger()143 void VerifyDebugger() {
144 #if BUILDFLAG(ENABLE_LLDBINIT_WARNING)
145 if (Environment::Create()->HasVar("CHROMIUM_LLDBINIT_SOURCED"))
146 return;
147 if (!BeingDebugged())
148 return;
149 DCHECK(false)
150 << "Detected lldb without sourcing //tools/lldb/lldbinit.py. lldb may "
151 "not be able to find debug symbols. Please see debug instructions for "
152 "using //tools/lldb/lldbinit.py:\n"
153 "https://chromium.googlesource.com/chromium/src/+/master/docs/"
154 "lldbinit.md\n"
155 "To continue anyway, type 'continue' in lldb. To always skip this "
156 "check, define an environment variable CHROMIUM_LLDBINIT_SOURCED=1";
157 #endif
158 }
159
160 #elif defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \
161 defined(OS_AIX)
162
163 // We can look in /proc/self/status for TracerPid. We are likely used in crash
164 // handling, so we are careful not to use the heap or have side effects.
165 // Another option that is common is to try to ptrace yourself, but then we
166 // can't detach without forking(), and that's not so great.
167 // static
168 Process GetDebuggerProcess() {
169 // NOTE: This code MUST be async-signal safe (it's used by in-process
170 // stack dumping signal handler). NO malloc or stdio is allowed here.
171
172 int status_fd = open("/proc/self/status", O_RDONLY);
173 if (status_fd == -1)
174 return Process();
175
176 // We assume our line will be in the first 1024 characters and that we can
177 // read this much all at once. In practice this will generally be true.
178 // This simplifies and speeds up things considerably.
179 char buf[1024];
180
181 ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
182 if (IGNORE_EINTR(close(status_fd)) < 0)
183 return Process();
184
185 if (num_read <= 0)
186 return Process();
187
188 StringPiece status(buf, num_read);
189 StringPiece tracer("TracerPid:\t");
190
191 StringPiece::size_type pid_index = status.find(tracer);
192 if (pid_index == StringPiece::npos)
193 return Process();
194 pid_index += tracer.size();
195 StringPiece::size_type pid_end_index = status.find('\n', pid_index);
196 if (pid_end_index == StringPiece::npos)
197 return Process();
198
199 StringPiece pid_str(buf + pid_index, pid_end_index - pid_index);
200 int pid = 0;
201 if (!StringToInt(pid_str, &pid))
202 return Process();
203
204 return Process(pid);
205 }
206
207 bool BeingDebugged() {
208 return GetDebuggerProcess().IsValid();
209 }
210
211 void VerifyDebugger() {
212 #if BUILDFLAG(ENABLE_GDBINIT_WARNING)
213 // Quick check before potentially slower GetDebuggerProcess().
214 if (Environment::Create()->HasVar("CHROMIUM_GDBINIT_SOURCED"))
215 return;
216
217 Process proc = GetDebuggerProcess();
218 if (!proc.IsValid())
219 return;
220
221 FilePath cmdline_file =
222 FilePath("/proc").Append(NumberToString(proc.Handle())).Append("cmdline");
223 std::string cmdline;
224 if (!ReadFileToString(cmdline_file, &cmdline))
225 return;
226
227 // /proc/*/cmdline separates arguments with null bytes, but we only care about
228 // the executable name, so interpret |cmdline| as a null-terminated C string
229 // to extract the exe portion.
230 StringPiece exe(cmdline.c_str());
231
232 DCHECK(ToLowerASCII(exe).find("gdb") == std::string::npos)
233 << "Detected gdb without sourcing //tools/gdb/gdbinit. gdb may not be "
234 "able to find debug symbols, and pretty-printing of STL types may not "
235 "work. Please see debug instructions for using //tools/gdb/gdbinit:\n"
236 "https://chromium.googlesource.com/chromium/src/+/master/docs/"
237 "gdbinit.md\n"
238 "To continue anyway, type 'continue' in gdb. To always skip this "
239 "check, define an environment variable CHROMIUM_GDBINIT_SOURCED=1";
240 #endif
241 }
242
243 #elif defined(OS_FUCHSIA)
244
245 bool BeingDebugged() {
246 zx_info_process_t info = {};
247 // Ignore failures. The 0-initialization above will result in "false" for
248 // error cases.
249 zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS, &info, sizeof(info),
250 nullptr, nullptr);
251 return info.debugger_attached;
252 }
253
254 void VerifyDebugger() {}
255
256 #else
257
258 bool BeingDebugged() {
259 NOTIMPLEMENTED();
260 return false;
261 }
262
263 void VerifyDebugger() {}
264
265 #endif
266
267 // We want to break into the debugger in Debug mode, and cause a crash dump in
268 // Release mode. Breakpad behaves as follows:
269 //
270 // +-------+-----------------+-----------------+
271 // | OS | Dump on SIGTRAP | Dump on SIGABRT |
272 // +-------+-----------------+-----------------+
273 // | Linux | N | Y |
274 // | Mac | Y | N |
275 // +-------+-----------------+-----------------+
276 //
277 // Thus we do the following:
278 // Linux: Debug mode if a debugger is attached, send SIGTRAP; otherwise send
279 // SIGABRT
280 // Mac: Always send SIGTRAP.
281
282 #if defined(ARCH_CPU_ARMEL)
283 #define DEBUG_BREAK_ASM() asm("bkpt 0")
284 #elif defined(ARCH_CPU_ARM64)
285 #define DEBUG_BREAK_ASM() asm("brk 0")
286 #elif defined(ARCH_CPU_MIPS_FAMILY)
287 #define DEBUG_BREAK_ASM() asm("break 2")
288 #elif defined(ARCH_CPU_X86_FAMILY)
289 #define DEBUG_BREAK_ASM() asm("int3")
290 #endif
291
292 #if defined(NDEBUG) && !defined(OS_APPLE) && !defined(OS_ANDROID)
293 #define DEBUG_BREAK() abort()
294 #elif defined(OS_NACL)
295 // The NaCl verifier doesn't let use use int3. For now, we call abort(). We
296 // should ask for advice from some NaCl experts about the optimum thing here.
297 // http://code.google.com/p/nativeclient/issues/detail?id=645
298 #define DEBUG_BREAK() abort()
299 #elif !defined(OS_APPLE)
300 // Though Android has a "helpful" process called debuggerd to catch native
301 // signals on the general assumption that they are fatal errors. If no debugger
302 // is attached, we call abort since Breakpad needs SIGABRT to create a dump.
303 // When debugger is attached, for ARM platform the bkpt instruction appears
304 // to cause SIGBUS which is trapped by debuggerd, and we've had great
305 // difficulty continuing in a debugger once we stop from SIG triggered by native
306 // code, use GDB to set |go| to 1 to resume execution; for X86 platform, use
307 // "int3" to setup breakpiont and raise SIGTRAP.
308 //
309 // On other POSIX architectures, except Mac OS X, we use the same logic to
310 // ensure that breakpad creates a dump on crashes while it is still possible to
311 // use a debugger.
312 namespace {
DebugBreak()313 void DebugBreak() {
314 if (!BeingDebugged()) {
315 abort();
316 } else {
317 #if defined(DEBUG_BREAK_ASM)
318 DEBUG_BREAK_ASM();
319 #else
320 volatile int go = 0;
321 while (!go)
322 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
323 #endif
324 }
325 }
326 } // namespace
327 #define DEBUG_BREAK() DebugBreak()
328 #elif defined(DEBUG_BREAK_ASM)
329 #define DEBUG_BREAK() DEBUG_BREAK_ASM()
330 #else
331 #error "Don't know how to debug break on this architecture/OS"
332 #endif
333
BreakDebugger()334 void BreakDebugger() {
335 #if BUILDFLAG(CLANG_PROFILING)
336 WriteClangProfilingProfile();
337 #endif
338
339 // NOTE: This code MUST be async-signal safe (it's used by in-process
340 // stack dumping signal handler). NO malloc or stdio is allowed here.
341
342 // Linker's ICF feature may merge this function with other functions with the
343 // same definition (e.g. any function whose sole job is to call abort()) and
344 // it may confuse the crash report processing system. http://crbug.com/508489
345 static int static_variable_to_make_this_function_unique = 0;
346 Alias(&static_variable_to_make_this_function_unique);
347
348 DEBUG_BREAK();
349 #if defined(OS_ANDROID) && !defined(OFFICIAL_BUILD)
350 // For Android development we always build release (debug builds are
351 // unmanageably large), so the unofficial build is used for debugging. It is
352 // helpful to be able to insert BreakDebugger() statements in the source,
353 // attach the debugger, inspect the state of the program and then resume it by
354 // setting the 'go' variable above.
355 #elif defined(NDEBUG)
356 // Terminate the program after signaling the debug break.
357 // When DEBUG_BREAK() expands to abort(), this is unreachable code. Rather
358 // than carefully tracking in which cases DEBUG_BREAK()s is noreturn, just
359 // disable the unreachable code warning here.
360 #pragma GCC diagnostic push
361 #pragma GCC diagnostic ignored "-Wunreachable-code"
362 _exit(1);
363 #pragma GCC diagnostic pop
364 #endif
365 }
366
367 } // namespace debug
368 } // namespace base
369