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