2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 00 Debug Routines */
14 #include "SquidTime.h"
17 /* for shutting_down flag in xassert() */
20 char *Debug::debugOptions
= NULL
;
21 int Debug::override_X
= 0;
22 int Debug::log_stderr
= -1;
23 bool Debug::log_syslog
= false;
24 int Debug::Levels
[MAX_DEBUG_SECTIONS
];
26 int Debug::sectionLevel
;
27 char *Debug::cache_log
= NULL
;
28 int Debug::rotateNumber
= -1;
29 FILE *debug_log
= NULL
;
30 static char *debug_log_file
= NULL
;
31 static int Ctx_Lock
= 0;
32 static const char *debugLogTime(void);
33 static const char *debugLogKid(void);
34 static void ctx_print(void);
37 static int syslog_facility
= 0;
39 static void _db_print_syslog(const char *format
, va_list args
);
41 static void _db_print_stderr(const char *format
, va_list args
);
42 static void _db_print_file(const char *format
, va_list args
);
45 extern LPCRITICAL_SECTION dbg_mutex
;
46 typedef BOOL (WINAPI
* PFInitializeCriticalSectionAndSpinCount
) (LPCRITICAL_SECTION
, DWORD
);
50 _db_print(const char *format
,...)
59 /* Multiple WIN32 threads may call this simultaneously */
62 HMODULE krnl_lib
= GetModuleHandle("Kernel32");
63 PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount
= NULL
;
66 InitializeCriticalSectionAndSpinCount
=
67 (PFInitializeCriticalSectionAndSpinCount
) GetProcAddress(krnl_lib
,
68 "InitializeCriticalSectionAndSpinCount");
70 dbg_mutex
= static_cast<CRITICAL_SECTION
*>(xcalloc(1, sizeof(CRITICAL_SECTION
)));
72 if (InitializeCriticalSectionAndSpinCount
) {
73 /* let multiprocessor systems EnterCriticalSection() fast */
75 if (!InitializeCriticalSectionAndSpinCount(dbg_mutex
, 4000)) {
77 fprintf(debug_log
, "FATAL: _db_print: can't initialize critical section\n");
81 fprintf(stderr
, "FATAL: _db_print: can't initialize critical section\n");
84 InitializeCriticalSection(dbg_mutex
);
88 EnterCriticalSection(dbg_mutex
);
91 /* give a chance to context-based debugging to print current context */
95 va_start(args1
, format
);
96 va_start(args2
, format
);
97 va_start(args3
, format
);
99 snprintf(f
, BUFSIZ
, "%s%s| %s",
104 _db_print_file(f
, args1
);
105 _db_print_stderr(f
, args2
);
108 _db_print_syslog(format
, args3
);
112 LeaveCriticalSection(dbg_mutex
);
121 _db_print_file(const char *format
, va_list args
)
123 if (debug_log
== NULL
)
126 /* give a chance to context-based debugging to print current context */
130 vfprintf(debug_log
, format
, args
);
135 _db_print_stderr(const char *format
, va_list args
)
137 if (Debug::log_stderr
< Debug::level
)
140 if (debug_log
== stderr
)
143 vfprintf(stderr
, format
, args
);
148 _db_print_syslog(const char *format
, va_list args
)
150 /* level 0,1 go to syslog */
152 if (Debug::level
> 1)
155 if (!Debug::log_syslog
)
161 vsnprintf(tmpbuf
, BUFSIZ
, format
, args
);
163 tmpbuf
[BUFSIZ
- 1] = '\0';
165 syslog(Debug::level
== 0 ? LOG_WARNING
: LOG_NOTICE
, "%s", tmpbuf
);
167 #endif /* HAVE_SYSLOG */
170 debugArg(const char *arg
)
176 if (!strncasecmp(arg
, "rotate=", 7)) {
178 Debug::rotateNumber
= atoi(arg
);
180 } else if (!strncasecmp(arg
, "ALL", 3)) {
185 while (*arg
&& *arg
++ != ',');
191 if (s
>= MAX_DEBUG_SECTIONS
)
192 s
= MAX_DEBUG_SECTIONS
-1;
201 Debug::Levels
[s
] = l
;
205 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; ++i
)
206 Debug::Levels
[i
] = l
;
210 debugOpenLog(const char *logfile
)
212 if (logfile
== NULL
) {
218 xfree(debug_log_file
);
220 debug_log_file
= xstrdup(logfile
); /* keep a static copy */
222 if (debug_log
&& debug_log
!= stderr
)
225 debug_log
= fopen(logfile
, "a+");
228 fprintf(stderr
, "WARNING: Cannot write log file: %s\n", logfile
);
230 fprintf(stderr
, " messages will be sent to 'stderr'.\n");
236 setmode(fileno(debug_log
), O_TEXT
);
243 static struct syslog_facility_name
{
248 syslog_facility_names
[] = {
257 "authpriv", LOG_AUTHPRIV
358 _db_set_syslog(const char *facility
)
360 Debug::log_syslog
= true;
365 syslog_facility
= LOG_DAEMON
;
368 syslog_facility
= LOG_LOCAL4
;
369 #endif /* LOG_DAEMON */
373 struct syslog_facility_name
*n
;
375 for (n
= syslog_facility_names
; n
->name
; ++n
) {
376 if (strcmp(n
->name
, facility
) == 0) {
377 syslog_facility
= n
->facility
;
382 fprintf(stderr
, "unknown syslog facility '%s'\n", facility
);
388 fprintf(stderr
, "syslog facility type not supported on your system\n");
390 #endif /* LOG_LOCAL4 */
396 Debug::parseOptions(char const *options
)
403 debugs(0, 9, "command-line -X overrides: " << options
);
407 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; ++i
)
408 Debug::Levels
[i
] = 0;
411 p
= xstrdup(options
);
413 for (s
= strtok(p
, w_space
); s
; s
= strtok(NULL
, w_space
))
421 _db_init(const char *logfile
, const char *options
)
423 Debug::parseOptions(options
);
425 debugOpenLog(logfile
);
427 #if HAVE_SYSLOG && defined(LOG_LOCAL4)
429 if (Debug::log_syslog
)
430 openlog(APP_SHORTNAME
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, syslog_facility
);
432 #endif /* HAVE_SYSLOG */
434 /* Pre-Init TZ env, see bug #2656 */
441 if (debug_log_file
== NULL
)
446 if (stat(debug_log_file
, &sb
) == 0)
447 if (S_ISREG(sb
.st_mode
) == 0)
451 char from
[MAXPATHLEN
];
458 * NOTE: we cannot use xrename here without having it in a
459 * separate file -- tools.c has too many dependencies to be
460 * used everywhere debug.c is used.
462 /* Rotate numbers 0 through N up one */
463 for (int i
= Debug::rotateNumber
; i
> 1;) {
465 snprintf(from
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
- 1);
466 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
);
472 if (rename(from
, to
) == -1) {
473 const auto saved_errno
= errno
;
474 debugs(0, DBG_IMPORTANT
, "log rotation failed: " << xstrerr(saved_errno
));
479 * You can't rename open files on Microsoft "operating systems"
480 * so we close before renaming.
483 if (debug_log
!= stderr
)
486 /* Rotate the current log to .0 */
487 if (Debug::rotateNumber
> 0) {
488 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, 0);
491 if (remove(to
) == -1) {
492 const auto saved_errno
= errno
;
493 debugs(0, DBG_IMPORTANT
, "removal of log file " << to
<< " failed: " << xstrerr(saved_errno
));
497 if (rename(debug_log_file
, to
) == -1) {
498 const auto saved_errno
= errno
;
499 debugs(0, DBG_IMPORTANT
, "renaming file " << debug_log_file
<< " to "
500 << to
<< "failed: " << xstrerr(saved_errno
));
504 /* Close and reopen the log. It may have been renamed "manually"
505 * before HUP'ing us. */
506 if (debug_log
!= stderr
)
507 debugOpenLog(Debug::cache_log
);
514 time_t t
= getCurrentTime();
517 static char buf
[128];
518 static time_t last_t
= 0;
520 if (Debug::level
> 1) {
523 strftime(buf2
, 127, "%Y/%m/%d %H:%M:%S", tm
);
525 snprintf(buf
, 127, "%s.%03d", buf2
, (int) current_time
.tv_usec
/ 1000);
527 } else if (t
!= last_t
) {
529 strftime(buf
, 127, "%Y/%m/%d %H:%M:%S", tm
);
540 if (KidIdentifier
!= 0) {
542 if (!*buf
) // optimization: fill only once after KidIdentifier is set
543 snprintf(buf
, sizeof(buf
), " kid%d", KidIdentifier
);
551 xassert(const char *msg
, const char *file
, int line
)
553 debugs(0, DBG_CRITICAL
, "assertion failed: " << file
<< ":" << line
<< ": \"" << msg
<< "\"");
560 * Context-based Debugging
565 * When you have a long nested processing sequence, it is often impossible
566 * for low level routines to know in what larger context they operate. If a
567 * routine coredumps, one can restore the context using debugger trace.
568 * However, in many case you do not want to coredump, but just want to report
569 * a potential problem. A report maybe useless out of problem context.
571 * To solve this potential problem, use the following approach:
574 * top_level_foo(const char *url)
576 * // define current context
577 * // note: we stack but do not dup ctx descriptions!
578 * Ctx ctx = ctx_enter(url);
580 * // go down; middle_level_bar will eventually call bottom_level_boo
581 * middle_level_bar(method, protocol);
583 * // exit, clean after yourself
588 * bottom_level_boo(int status, void *data)
590 * // detect exceptional condition, and simply report it, the context
591 * // information will be available somewhere close in the log file
592 * if (status == STRANGE_STATUS)
593 * debugs(13, 6, "DOS attack detected, data: " << data);
597 * Current implementation is extremely simple but still very handy. It has a
598 * negligible overhead (descriptions are not duplicated).
600 * When the _first_ debug message for a given context is printed, it is
601 * prepended with the current context description. Context is printed with
602 * the same debugging level as the original message.
604 * Note that we do not print context every type you do ctx_enter(). This
605 * approach would produce too many useless messages. For the same reason, a
606 * context description is printed at most _once_ even if you have 10
607 * debugging messages within one context.
609 * Contexts can be nested, of course. You must use ctx_enter() to enter a
610 * context (push it onto stack). It is probably safe to exit several nested
611 * contexts at _once_ by calling ctx_exit() at the top level (this will pop
612 * all context till current one). However, as in any stack, you cannot start
616 * i) locate debugging message,
617 * ii) locate current context by going _upstream_ in your log file,
624 * decide if we want to dup() descriptions (adds overhead) but allows to
625 * add printf()-style interface
630 * descriptions for contexts over CTX_MAX_LEVEL limit are ignored, you probably
631 * have a bug if your nesting goes that deep.
634 #define CTX_MAX_LEVEL 255
637 * produce a warning when nesting reaches this level and then double
640 static int Ctx_Warn_Level
= 32;
641 /* all descriptions has been printed up to this level */
642 static int Ctx_Reported_Level
= -1;
643 /* descriptions are still valid or active up to this level */
644 static int Ctx_Valid_Level
= -1;
645 /* current level, the number of nested ctx_enter() calls */
646 static int Ctx_Current_Level
= -1;
647 /* saved descriptions (stack) */
648 static const char *Ctx_Descrs
[CTX_MAX_LEVEL
+ 1];
649 /* "safe" get secription */
650 static const char *ctx_get_descr(Ctx ctx
);
653 ctx_enter(const char *descr
)
657 if (Ctx_Current_Level
<= CTX_MAX_LEVEL
)
658 Ctx_Descrs
[Ctx_Current_Level
] = descr
;
660 if (Ctx_Current_Level
== Ctx_Warn_Level
) {
661 debugs(0, DBG_CRITICAL
, "# ctx: suspiciously deep (" << Ctx_Warn_Level
<< ") nesting:");
665 return Ctx_Current_Level
;
672 Ctx_Current_Level
= (ctx
>= 0) ? ctx
- 1 : -1;
674 if (Ctx_Valid_Level
> Ctx_Current_Level
)
675 Ctx_Valid_Level
= Ctx_Current_Level
;
679 * the idea id to print each context description at most once but provide enough
680 * info for deducing the current execution stack
685 /* lock so _db_print will not call us recursively */
687 /* ok, user saw [0,Ctx_Reported_Level] descriptions */
688 /* first inform about entries popped since user saw them */
690 if (Ctx_Valid_Level
< Ctx_Reported_Level
) {
691 if (Ctx_Reported_Level
!= Ctx_Valid_Level
+ 1)
692 _db_print("ctx: exit levels from %2d down to %2d\n",
693 Ctx_Reported_Level
, Ctx_Valid_Level
+ 1);
695 _db_print("ctx: exit level %2d\n", Ctx_Reported_Level
);
697 Ctx_Reported_Level
= Ctx_Valid_Level
;
700 /* report new contexts that were pushed since last report */
701 while (Ctx_Reported_Level
< Ctx_Current_Level
) {
702 ++Ctx_Reported_Level
;
704 _db_print("ctx: enter level %2d: '%s'\n", Ctx_Reported_Level
,
705 ctx_get_descr(Ctx_Reported_Level
));
712 /* checks for nulls and overflows */
714 ctx_get_descr(Ctx ctx
)
716 if (ctx
< 0 || ctx
> CTX_MAX_LEVEL
)
719 return Ctx_Descrs
[ctx
] ? Ctx_Descrs
[ctx
] : "<null>";
722 int Debug::TheDepth
= 0;
724 Debug::OutStream
*Debug::CurrentDebug(NULL
);
729 assert(TheDepth
>= 0);
732 assert(CurrentDebug
);
733 *CurrentDebug
<< std::endl
<< "reentrant debuging " << TheDepth
<< "-{";
735 assert(!CurrentDebug
);
736 CurrentDebug
= new Debug::OutStream
;
737 // set default formatting flags
738 CurrentDebug
->setf(std::ios::fixed
);
739 CurrentDebug
->precision(2);
741 return *CurrentDebug
;
747 assert(TheDepth
>= 0);
748 assert(CurrentDebug
);
750 *CurrentDebug
<< "}-" << TheDepth
<< std::endl
;
752 assert(TheDepth
== 1);
753 _db_print("%s\n", CurrentDebug
->str().c_str());
760 // Hack: replaces global ::xassert() to debug debugging assertions
761 // Relies on assert macro calling xassert() without a specific scope.
763 Debug::xassert(const char *msg
, const char *file
, int line
)
767 *CurrentDebug
<< "assertion failed: " << file
<< ":" << line
<<
768 ": \"" << msg
<< "\"";
776 // XXX: This must be kept in sync with the actual debug.cc location
777 const char *ThisFileNameTail
= "src/debug.cc";
779 const char *file
=__FILE__
;
781 // Disable heuristic if it does not work.
782 if (!strstr(file
, ThisFileNameTail
))
785 return strlen(file
)-strlen(ThisFileNameTail
);
789 SkipBuildPrefix(const char* path
)
791 static const size_t BuildPrefixLength
= BuildPrefixInit();
793 return path
+BuildPrefixLength
;
797 Raw::print(std::ostream
&os
) const
800 os
<< ' ' << label_
<< '[' << size_
<< ']';
805 // finalize debugging level if no level was set explicitly via minLevel()
806 const int finalLevel
= (level
>= 0) ? level
:
807 (size_
> 40 ? DBG_DATA
: Debug::sectionLevel
);
808 if (finalLevel
<= Debug::sectionLevel
) {
809 os
<< (label_
? '=' : ' ');
811 os
.write(data_
, size_
);