1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // Chromium headers must come before Mozilla headers.
8 #include "base/process_util.h"
9
10 #include "mozilla/Atomics.h"
11
12 #include "nsDebugImpl.h"
13 #include "nsDebug.h"
14 #ifdef MOZ_CRASHREPORTER
15 # include "nsExceptionHandler.h"
16 #endif
17 #include "nsString.h"
18 #include "nsXULAppAPI.h"
19 #include "prprf.h"
20 #include "nsError.h"
21 #include "prerror.h"
22 #include "prerr.h"
23 #include "prenv.h"
24
25 #ifdef ANDROID
26 #include <android/log.h>
27 #endif
28
29 #ifdef _WIN32
30 /* for getenv() */
31 #include <stdlib.h>
32 #endif
33
34 #include "nsTraceRefcnt.h"
35
36 #if defined(XP_UNIX)
37 #include <signal.h>
38 #endif
39
40 #if defined(XP_WIN)
41 #include <tchar.h>
42 #include "nsString.h"
43 #endif
44
45 #if defined(XP_MACOSX) || defined(__DragonFly__) || defined(__FreeBSD__) \
46 || defined(__NetBSD__) || defined(__OpenBSD__)
47 #include <stdbool.h>
48 #include <unistd.h>
49 #include <sys/param.h>
50 #include <sys/sysctl.h>
51 #endif
52
53 #if defined(__OpenBSD__)
54 #include <sys/proc.h>
55 #endif
56
57 #if defined(__DragonFly__) || defined(__FreeBSD__)
58 #include <sys/user.h>
59 #endif
60
61 #if defined(__NetBSD__)
62 #undef KERN_PROC
63 #define KERN_PROC KERN_PROC2
64 #define KINFO_PROC struct kinfo_proc2
65 #else
66 #define KINFO_PROC struct kinfo_proc
67 #endif
68
69 #if defined(XP_MACOSX)
70 #define KP_FLAGS kp_proc.p_flag
71 #elif defined(__DragonFly__)
72 #define KP_FLAGS kp_flags
73 #elif defined(__FreeBSD__)
74 #define KP_FLAGS ki_flag
75 #elif defined(__OpenBSD__) && !defined(_P_TRACED)
76 #define KP_FLAGS p_psflags
77 #define P_TRACED PS_TRACED
78 #else
79 #define KP_FLAGS p_flag
80 #endif
81
82 #include "mozilla/mozalloc_abort.h"
83
84 static void
85 Abort(const char* aMsg);
86
87 static void
88 RealBreak();
89
90 static void
91 Break(const char* aMsg);
92
93 #if defined(_WIN32)
94 #include <windows.h>
95 #include <signal.h>
96 #include <malloc.h> // for _alloca
97 #elif defined(XP_UNIX)
98 #include <stdlib.h>
99 #endif
100
101 using namespace mozilla;
102
103 static const char* sMultiprocessDescription = nullptr;
104
105 static Atomic<int32_t> gAssertionCount;
106
NS_IMPL_QUERY_INTERFACE(nsDebugImpl,nsIDebug2)107 NS_IMPL_QUERY_INTERFACE(nsDebugImpl, nsIDebug2)
108
109 NS_IMETHODIMP_(MozExternalRefCountType)
110 nsDebugImpl::AddRef()
111 {
112 return 2;
113 }
114
NS_IMETHODIMP_(MozExternalRefCountType)115 NS_IMETHODIMP_(MozExternalRefCountType)
116 nsDebugImpl::Release()
117 {
118 return 1;
119 }
120
121 NS_IMETHODIMP
Assertion(const char * aStr,const char * aExpr,const char * aFile,int32_t aLine)122 nsDebugImpl::Assertion(const char* aStr, const char* aExpr,
123 const char* aFile, int32_t aLine)
124 {
125 NS_DebugBreak(NS_DEBUG_ASSERTION, aStr, aExpr, aFile, aLine);
126 return NS_OK;
127 }
128
129 NS_IMETHODIMP
Warning(const char * aStr,const char * aFile,int32_t aLine)130 nsDebugImpl::Warning(const char* aStr, const char* aFile, int32_t aLine)
131 {
132 NS_DebugBreak(NS_DEBUG_WARNING, aStr, nullptr, aFile, aLine);
133 return NS_OK;
134 }
135
136 NS_IMETHODIMP
Break(const char * aFile,int32_t aLine)137 nsDebugImpl::Break(const char* aFile, int32_t aLine)
138 {
139 NS_DebugBreak(NS_DEBUG_BREAK, nullptr, nullptr, aFile, aLine);
140 return NS_OK;
141 }
142
143 NS_IMETHODIMP
Abort(const char * aFile,int32_t aLine)144 nsDebugImpl::Abort(const char* aFile, int32_t aLine)
145 {
146 NS_DebugBreak(NS_DEBUG_ABORT, nullptr, nullptr, aFile, aLine);
147 return NS_OK;
148 }
149
150 NS_IMETHODIMP
GetIsDebugBuild(bool * aResult)151 nsDebugImpl::GetIsDebugBuild(bool* aResult)
152 {
153 #ifdef DEBUG
154 *aResult = true;
155 #else
156 *aResult = false;
157 #endif
158 return NS_OK;
159 }
160
161 NS_IMETHODIMP
GetAssertionCount(int32_t * aResult)162 nsDebugImpl::GetAssertionCount(int32_t* aResult)
163 {
164 *aResult = gAssertionCount;
165 return NS_OK;
166 }
167
168 NS_IMETHODIMP
GetIsDebuggerAttached(bool * aResult)169 nsDebugImpl::GetIsDebuggerAttached(bool* aResult)
170 {
171 *aResult = false;
172
173 #if defined(XP_WIN)
174 *aResult = ::IsDebuggerPresent();
175 #elif defined(XP_MACOSX) || defined(__DragonFly__) || defined(__FreeBSD__) \
176 || defined(__NetBSD__) || defined(__OpenBSD__)
177 // Specify the info we're looking for
178 int mib[] = {
179 CTL_KERN,
180 KERN_PROC,
181 KERN_PROC_PID,
182 getpid(),
183 #if defined(__NetBSD__) || defined(__OpenBSD__)
184 sizeof(KINFO_PROC),
185 1,
186 #endif
187 };
188 u_int mibSize = sizeof(mib) / sizeof(int);
189
190 KINFO_PROC info;
191 size_t infoSize = sizeof(info);
192 memset(&info, 0, infoSize);
193
194 if (sysctl(mib, mibSize, &info, &infoSize, nullptr, 0)) {
195 // if the call fails, default to false
196 *aResult = false;
197 return NS_OK;
198 }
199
200 if (info.KP_FLAGS & P_TRACED) {
201 *aResult = true;
202 }
203 #endif
204
205 return NS_OK;
206 }
207
208 /* static */ void
SetMultiprocessMode(const char * aDesc)209 nsDebugImpl::SetMultiprocessMode(const char* aDesc)
210 {
211 sMultiprocessDescription = aDesc;
212 }
213
214 /**
215 * Implementation of the nsDebug methods. Note that this code is
216 * always compiled in, in case some other module that uses it is
217 * compiled with debugging even if this library is not.
218 */
219 enum nsAssertBehavior
220 {
221 NS_ASSERT_UNINITIALIZED,
222 NS_ASSERT_WARN,
223 NS_ASSERT_SUSPEND,
224 NS_ASSERT_STACK,
225 NS_ASSERT_TRAP,
226 NS_ASSERT_ABORT,
227 NS_ASSERT_STACK_AND_ABORT
228 };
229
230 static nsAssertBehavior
GetAssertBehavior()231 GetAssertBehavior()
232 {
233 static nsAssertBehavior gAssertBehavior = NS_ASSERT_UNINITIALIZED;
234 if (gAssertBehavior != NS_ASSERT_UNINITIALIZED) {
235 return gAssertBehavior;
236 }
237
238 gAssertBehavior = NS_ASSERT_WARN;
239
240 const char* assertString = PR_GetEnv("XPCOM_DEBUG_BREAK");
241 if (!assertString || !*assertString) {
242 return gAssertBehavior;
243 }
244 if (!strcmp(assertString, "warn")) {
245 return gAssertBehavior = NS_ASSERT_WARN;
246 }
247 if (!strcmp(assertString, "suspend")) {
248 return gAssertBehavior = NS_ASSERT_SUSPEND;
249 }
250 if (!strcmp(assertString, "stack")) {
251 return gAssertBehavior = NS_ASSERT_STACK;
252 }
253 if (!strcmp(assertString, "abort")) {
254 return gAssertBehavior = NS_ASSERT_ABORT;
255 }
256 if (!strcmp(assertString, "trap") || !strcmp(assertString, "break")) {
257 return gAssertBehavior = NS_ASSERT_TRAP;
258 }
259 if (!strcmp(assertString, "stack-and-abort")) {
260 return gAssertBehavior = NS_ASSERT_STACK_AND_ABORT;
261 }
262
263 fprintf(stderr, "Unrecognized value of XPCOM_DEBUG_BREAK\n");
264 return gAssertBehavior;
265 }
266
267 struct FixedBuffer
268 {
FixedBufferFixedBuffer269 FixedBuffer() : curlen(0)
270 {
271 buffer[0] = '\0';
272 }
273
274 char buffer[500];
275 uint32_t curlen;
276 };
277
278 static int
StuffFixedBuffer(void * aClosure,const char * aBuf,uint32_t aLen)279 StuffFixedBuffer(void* aClosure, const char* aBuf, uint32_t aLen)
280 {
281 if (!aLen) {
282 return 0;
283 }
284
285 FixedBuffer* fb = (FixedBuffer*)aClosure;
286
287 // strip the trailing null, we add it again later
288 if (aBuf[aLen - 1] == '\0') {
289 --aLen;
290 }
291
292 if (fb->curlen + aLen >= sizeof(fb->buffer)) {
293 aLen = sizeof(fb->buffer) - fb->curlen - 1;
294 }
295
296 if (aLen) {
297 memcpy(fb->buffer + fb->curlen, aBuf, aLen);
298 fb->curlen += aLen;
299 fb->buffer[fb->curlen] = '\0';
300 }
301
302 return aLen;
303 }
304
305 EXPORT_XPCOM_API(void)
NS_DebugBreak(uint32_t aSeverity,const char * aStr,const char * aExpr,const char * aFile,int32_t aLine)306 NS_DebugBreak(uint32_t aSeverity, const char* aStr, const char* aExpr,
307 const char* aFile, int32_t aLine)
308 {
309 FixedBuffer nonPIDBuf;
310 FixedBuffer buf;
311 const char* sevString = "WARNING";
312
313 switch (aSeverity) {
314 case NS_DEBUG_ASSERTION:
315 sevString = "###!!! ASSERTION";
316 break;
317
318 case NS_DEBUG_BREAK:
319 sevString = "###!!! BREAK";
320 break;
321
322 case NS_DEBUG_ABORT:
323 sevString = "###!!! ABORT";
324 break;
325
326 default:
327 aSeverity = NS_DEBUG_WARNING;
328 }
329
330 #define PRINT_TO_NONPID_BUFFER(...) PR_sxprintf(StuffFixedBuffer, &nonPIDBuf, __VA_ARGS__)
331 PRINT_TO_NONPID_BUFFER("%s: ", sevString);
332 if (aStr) {
333 PRINT_TO_NONPID_BUFFER("%s: ", aStr);
334 }
335 if (aExpr) {
336 PRINT_TO_NONPID_BUFFER("'%s', ", aExpr);
337 }
338 if (aFile) {
339 PRINT_TO_NONPID_BUFFER("file %s, ", aFile);
340 }
341 if (aLine != -1) {
342 PRINT_TO_NONPID_BUFFER("line %d", aLine);
343 }
344 #undef PRINT_TO_NONPID_BUFFER
345
346 // Print "[PID]" or "[Desc PID]" at the beginning of the message.
347 #define PRINT_TO_BUFFER(...) PR_sxprintf(StuffFixedBuffer, &buf, __VA_ARGS__)
348 PRINT_TO_BUFFER("[");
349 if (sMultiprocessDescription) {
350 PRINT_TO_BUFFER("%s ", sMultiprocessDescription);
351 }
352 PRINT_TO_BUFFER("%d] %s", base::GetCurrentProcId(), nonPIDBuf.buffer);
353 #undef PRINT_TO_BUFFER
354
355
356 // errors on platforms without a debugdlg ring a bell on stderr
357 #if !defined(XP_WIN)
358 if (aSeverity != NS_DEBUG_WARNING) {
359 fprintf(stderr, "\07");
360 }
361 #endif
362
363 #ifdef ANDROID
364 __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", buf.buffer);
365 #endif
366
367 // Write the message to stderr unless it's a warning and MOZ_IGNORE_WARNINGS
368 // is set.
369 if (!(PR_GetEnv("MOZ_IGNORE_WARNINGS") && aSeverity == NS_DEBUG_WARNING)) {
370 fprintf(stderr, "%s\n", buf.buffer);
371 fflush(stderr);
372 }
373
374 switch (aSeverity) {
375 case NS_DEBUG_WARNING:
376 return;
377
378 case NS_DEBUG_BREAK:
379 Break(buf.buffer);
380 return;
381
382 case NS_DEBUG_ABORT: {
383 #if defined(MOZ_CRASHREPORTER)
384 // Updating crash annotations in the child causes us to do IPC. This can
385 // really cause trouble if we're asserting from within IPC code. So we
386 // have to do without the annotations in that case.
387 if (XRE_IsParentProcess()) {
388 // Don't include the PID in the crash report annotation to
389 // allow faceting on crash-stats.mozilla.org.
390 nsCString note("xpcom_runtime_abort(");
391 note += nonPIDBuf.buffer;
392 note += ")";
393 CrashReporter::AppendAppNotesToCrashReport(note);
394 CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("AbortMessage"),
395 nsDependentCString(nonPIDBuf.buffer));
396 }
397 #endif // MOZ_CRASHREPORTER
398
399 #if defined(DEBUG) && defined(_WIN32)
400 RealBreak();
401 #endif
402 #if defined(DEBUG)
403 nsTraceRefcnt::WalkTheStack(stderr);
404 #endif
405 Abort(buf.buffer);
406 return;
407 }
408 }
409
410 // Now we deal with assertions
411 gAssertionCount++;
412
413 switch (GetAssertBehavior()) {
414 case NS_ASSERT_WARN:
415 return;
416
417 case NS_ASSERT_SUSPEND:
418 #ifdef XP_UNIX
419 fprintf(stderr, "Suspending process; attach with the debugger.\n");
420 kill(0, SIGSTOP);
421 #else
422 Break(buf.buffer);
423 #endif
424 return;
425
426 case NS_ASSERT_STACK:
427 nsTraceRefcnt::WalkTheStack(stderr);
428 return;
429
430 case NS_ASSERT_STACK_AND_ABORT:
431 nsTraceRefcnt::WalkTheStack(stderr);
432 // Fall through to abort
433 MOZ_FALLTHROUGH;
434
435 case NS_ASSERT_ABORT:
436 Abort(buf.buffer);
437 return;
438
439 case NS_ASSERT_TRAP:
440 case NS_ASSERT_UNINITIALIZED: // Default to "trap" behavior
441 Break(buf.buffer);
442 return;
443 }
444 }
445
446 static void
Abort(const char * aMsg)447 Abort(const char* aMsg)
448 {
449 mozalloc_abort(aMsg);
450 }
451
452 static void
RealBreak()453 RealBreak()
454 {
455 #if defined(_WIN32)
456 ::DebugBreak();
457 #elif defined(XP_MACOSX)
458 raise(SIGTRAP);
459 #elif defined(__GNUC__) && (defined(__i386__) || defined(__i386) || defined(__x86_64__))
460 asm("int $3");
461 #elif defined(__arm__)
462 asm(
463 #ifdef __ARM_ARCH_4T__
464 /* ARMv4T doesn't support the BKPT instruction, so if the compiler target
465 * is ARMv4T, we want to ensure the assembler will understand that ARMv5T
466 * instruction, while keeping the resulting object tagged as ARMv4T.
467 */
468 ".arch armv5t\n"
469 ".object_arch armv4t\n"
470 #endif
471 "BKPT #0");
472 #elif defined(SOLARIS)
473 #if defined(__i386__) || defined(__i386) || defined(__x86_64__)
474 asm("int $3");
475 #else
476 raise(SIGTRAP);
477 #endif
478 #else
479 #warning do not know how to break on this platform
480 #endif
481 }
482
483 // Abort() calls this function, don't call it!
484 static void
Break(const char * aMsg)485 Break(const char* aMsg)
486 {
487 #if defined(_WIN32)
488 static int ignoreDebugger;
489 if (!ignoreDebugger) {
490 const char* shouldIgnoreDebugger = getenv("XPCOM_DEBUG_DLG");
491 ignoreDebugger =
492 1 + (shouldIgnoreDebugger && !strcmp(shouldIgnoreDebugger, "1"));
493 }
494 if ((ignoreDebugger == 2) || !::IsDebuggerPresent()) {
495 DWORD code = IDRETRY;
496
497 /* Create the debug dialog out of process to avoid the crashes caused by
498 * Windows events leaking into our event loop from an in process dialog.
499 * We do this by launching windbgdlg.exe (built in xpcom/windbgdlg).
500 * See http://bugzilla.mozilla.org/show_bug.cgi?id=54792
501 */
502 PROCESS_INFORMATION pi;
503 STARTUPINFOW si;
504 wchar_t executable[MAX_PATH];
505 wchar_t* pName;
506
507 memset(&pi, 0, sizeof(pi));
508
509 memset(&si, 0, sizeof(si));
510 si.cb = sizeof(si);
511 si.wShowWindow = SW_SHOW;
512
513 // 2nd arg of CreateProcess is in/out
514 wchar_t* msgCopy = (wchar_t*)_alloca((strlen(aMsg) + 1) * sizeof(wchar_t));
515 wcscpy(msgCopy, NS_ConvertUTF8toUTF16(aMsg).get());
516
517 if (GetModuleFileNameW(GetModuleHandleW(L"xpcom.dll"), executable, MAX_PATH) &&
518 (pName = wcsrchr(executable, '\\')) != nullptr &&
519 wcscpy(pName + 1, L"windbgdlg.exe") &&
520 CreateProcessW(executable, msgCopy, nullptr, nullptr,
521 false, DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
522 nullptr, nullptr, &si, &pi)) {
523 WaitForSingleObject(pi.hProcess, INFINITE);
524 GetExitCodeProcess(pi.hProcess, &code);
525 CloseHandle(pi.hProcess);
526 CloseHandle(pi.hThread);
527 }
528
529 switch (code) {
530 case IDABORT:
531 //This should exit us
532 raise(SIGABRT);
533 //If we are ignored exit this way..
534 _exit(3);
535
536 case IDIGNORE:
537 return;
538 }
539 }
540
541 RealBreak();
542 #elif defined(XP_MACOSX)
543 /* Note that we put this Mac OS X test above the GNUC/x86 test because the
544 * GNUC/x86 test is also true on Intel Mac OS X and we want the PPC/x86
545 * impls to be the same.
546 */
547 RealBreak();
548 #elif defined(__GNUC__) && (defined(__i386__) || defined(__i386) || defined(__x86_64__))
549 RealBreak();
550 #elif defined(__arm__)
551 RealBreak();
552 #elif defined(SOLARIS)
553 RealBreak();
554 #else
555 #warning do not know how to break on this platform
556 #endif
557 }
558
559 nsresult
Create(nsISupports * aOuter,const nsIID & aIID,void ** aInstancePtr)560 nsDebugImpl::Create(nsISupports* aOuter, const nsIID& aIID, void** aInstancePtr)
561 {
562 static const nsDebugImpl* sImpl;
563
564 if (NS_WARN_IF(aOuter)) {
565 return NS_ERROR_NO_AGGREGATION;
566 }
567
568 if (!sImpl) {
569 sImpl = new nsDebugImpl();
570 }
571
572 return const_cast<nsDebugImpl*>(sImpl)->QueryInterface(aIID, aInstancePtr);
573 }
574
575 ////////////////////////////////////////////////////////////////////////////////
576
577 nsresult
NS_ErrorAccordingToNSPR()578 NS_ErrorAccordingToNSPR()
579 {
580 PRErrorCode err = PR_GetError();
581 switch (err) {
582 case PR_OUT_OF_MEMORY_ERROR: return NS_ERROR_OUT_OF_MEMORY;
583 case PR_WOULD_BLOCK_ERROR: return NS_BASE_STREAM_WOULD_BLOCK;
584 case PR_FILE_NOT_FOUND_ERROR: return NS_ERROR_FILE_NOT_FOUND;
585 case PR_READ_ONLY_FILESYSTEM_ERROR: return NS_ERROR_FILE_READ_ONLY;
586 case PR_NOT_DIRECTORY_ERROR: return NS_ERROR_FILE_NOT_DIRECTORY;
587 case PR_IS_DIRECTORY_ERROR: return NS_ERROR_FILE_IS_DIRECTORY;
588 case PR_LOOP_ERROR: return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK;
589 case PR_FILE_EXISTS_ERROR: return NS_ERROR_FILE_ALREADY_EXISTS;
590 case PR_FILE_IS_LOCKED_ERROR: return NS_ERROR_FILE_IS_LOCKED;
591 case PR_FILE_TOO_BIG_ERROR: return NS_ERROR_FILE_TOO_BIG;
592 case PR_NO_DEVICE_SPACE_ERROR: return NS_ERROR_FILE_NO_DEVICE_SPACE;
593 case PR_NAME_TOO_LONG_ERROR: return NS_ERROR_FILE_NAME_TOO_LONG;
594 case PR_DIRECTORY_NOT_EMPTY_ERROR: return NS_ERROR_FILE_DIR_NOT_EMPTY;
595 case PR_NO_ACCESS_RIGHTS_ERROR: return NS_ERROR_FILE_ACCESS_DENIED;
596 default: return NS_ERROR_FAILURE;
597 }
598 }
599
600 void
NS_ABORT_OOM(size_t aSize)601 NS_ABORT_OOM(size_t aSize)
602 {
603 #if defined(MOZ_CRASHREPORTER)
604 CrashReporter::AnnotateOOMAllocationSize(aSize);
605 #endif
606 MOZ_CRASH("OOM");
607 }
608