2 * $Id: debug.cc,v 1.109 2008/02/26 18:43:30 rousskov Exp $
4 * DEBUG: section 0 Debug Routines
5 * AUTHOR: Harvest Derived
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
36 #include "SquidTime.h"
41 int Debug::Levels
[MAX_DEBUG_SECTIONS
];
43 FILE *debug_log
= NULL
;
44 static char *debug_log_file
= NULL
;
45 static int Ctx_Lock
= 0;
46 static const char *debugLogTime(void);
47 static void ctx_print(void);
50 static int syslog_facility
= 0;
52 static void _db_print_syslog(const char *format
, va_list args
);
54 static void _db_print_stderr(const char *format
, va_list args
);
55 static void _db_print_file(const char *format
, va_list args
);
58 SQUIDCEXTERN LPCRITICAL_SECTION dbg_mutex
;
59 typedef BOOL (WINAPI
* PFInitializeCriticalSectionAndSpinCount
) (LPCRITICAL_SECTION
, DWORD
);
65 _db_print(const char *format
,...)
70 const char *format
= NULL
;
73 LOCAL_ARRAY(char, f
, BUFSIZ
);
84 /* Multiple WIN32 threads may call this simultaneously */
87 HMODULE krnl_lib
= GetModuleHandle("Kernel32");
88 PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount
= NULL
;
91 InitializeCriticalSectionAndSpinCount
=
92 (PFInitializeCriticalSectionAndSpinCount
) GetProcAddress(krnl_lib
,
93 "InitializeCriticalSectionAndSpinCount");
95 dbg_mutex
= static_cast<CRITICAL_SECTION
*>(xcalloc(1, sizeof(CRITICAL_SECTION
)));
97 if (InitializeCriticalSectionAndSpinCount
) {
98 /* let multiprocessor systems EnterCriticalSection() fast */
100 if (!InitializeCriticalSectionAndSpinCount(dbg_mutex
, 4000)) {
102 fprintf(debug_log
, "FATAL: _db_print: can't initialize critical section\n");
106 fprintf(stderr
, "FATAL: _db_print: can't initialize critical section\n");
109 InitializeCriticalSection(dbg_mutex
);
113 EnterCriticalSection(dbg_mutex
);
115 /* give a chance to context-based debugging to print current context */
122 va_start(args1
, format
);
124 va_start(args2
, format
);
126 va_start(args3
, format
);
130 format
= va_arg(args1
, const char *);
134 snprintf(f
, BUFSIZ
, "%s| %s",
138 _db_print_file(f
, args1
);
140 _db_print_stderr(f
, args2
);
144 _db_print_syslog(format
, args3
);
149 LeaveCriticalSection(dbg_mutex
);
165 _db_print_file(const char *format
, va_list args
) {
166 if (debug_log
== NULL
)
169 /* give a chance to context-based debugging to print current context */
173 vfprintf(debug_log
, format
, args
);
175 //*AYJ:*/ if (!Config.onoff.buffered_logs)
180 _db_print_stderr(const char *format
, va_list args
) {
181 if (opt_debug_stderr
< Debug::level
)
184 if (debug_log
== stderr
)
187 vfprintf(stderr
, format
, args
);
192 _db_print_syslog(const char *format
, va_list args
) {
193 LOCAL_ARRAY(char, tmpbuf
, BUFSIZ
);
194 /* level 0,1 go to syslog */
196 if (Debug::level
> 1)
199 if (0 == opt_syslog_enable
)
204 vsnprintf(tmpbuf
, BUFSIZ
, format
, args
);
206 tmpbuf
[BUFSIZ
- 1] = '\0';
208 syslog(Debug::level
== 0 ? LOG_WARNING
: LOG_NOTICE
, "%s", tmpbuf
);
211 #endif /* HAVE_SYSLOG */
214 debugArg(const char *arg
) {
219 if (!strncasecmp(arg
, "ALL", 3)) {
225 while (*arg
&& *arg
++ != ',');
231 if (s
>= MAX_DEBUG_SECTIONS
)
232 s
= MAX_DEBUG_SECTIONS
-1;
241 Debug::Levels
[s
] = l
;
245 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
246 Debug::Levels
[i
] = l
;
250 debugOpenLog(const char *logfile
) {
251 if (logfile
== NULL
) {
257 xfree(debug_log_file
);
259 debug_log_file
= xstrdup(logfile
); /* keep a static copy */
261 if (debug_log
&& debug_log
!= stderr
)
264 debug_log
= fopen(logfile
, "a+");
267 fprintf(stderr
, "WARNING: Cannot write log file: %s\n", logfile
);
269 fprintf(stderr
, " messages will be sent to 'stderr'.\n");
275 setmode(fileno(debug_log
), O_TEXT
);
283 static struct syslog_facility_name
{
288 syslog_facility_names
[] = {
297 "authpriv", LOG_AUTHPRIV
398 _db_set_syslog(const char *facility
) {
399 opt_syslog_enable
= 1;
403 syslog_facility
= LOG_DAEMON
;
406 syslog_facility
= LOG_LOCAL4
;
411 struct syslog_facility_name
*n
;
413 for (n
= syslog_facility_names
; n
->name
; n
++) {
414 if (strcmp(n
->name
, facility
) == 0) {
415 syslog_facility
= n
->facility
;
420 fprintf(stderr
, "unknown syslog facility '%s'\n", facility
);
426 fprintf(stderr
, "syslog facility type not supported on your system\n");
434 Debug::parseOptions(char const *options
) {
439 if (Config
.onoff
.debug_override_X
) {
440 debugs(0, 9, "command-line -X overrides: " << options
);
444 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
445 Debug::Levels
[i
] = 0;
448 p
= xstrdup(options
);
450 for (s
= strtok(p
, w_space
); s
; s
= strtok(NULL
, w_space
))
458 _db_init(const char *logfile
, const char *options
) {
459 Debug::parseOptions(options
);
461 debugOpenLog(logfile
);
463 #if HAVE_SYSLOG && defined(LOG_LOCAL4)
465 if (opt_syslog_enable
)
466 openlog(APP_SHORTNAME
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, syslog_facility
);
468 #endif /* HAVE_SYSLOG */
473 _db_rotate_log(void) {
475 LOCAL_ARRAY(char, from
, MAXPATHLEN
);
476 LOCAL_ARRAY(char, to
, MAXPATHLEN
);
482 if (debug_log_file
== NULL
)
487 if (stat(debug_log_file
, &sb
) == 0)
488 if (S_ISREG(sb
.st_mode
) == 0)
494 * NOTE: we cannot use xrename here without having it in a
495 * separate file -- tools.c has too many dependencies to be
496 * used everywhere debug.c is used.
498 /* Rotate numbers 0 through N up one */
499 for (i
= Config
.Log
.rotateNumber
; i
> 1;) {
501 snprintf(from
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
- 1);
502 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
);
514 * You can't rename open files on Microsoft "operating systems"
515 * so we close before renaming.
518 if (debug_log
!= stderr
)
522 /* Rotate the current log to .0 */
523 if (Config
.Log
.rotateNumber
> 0) {
524 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, 0);
532 rename(debug_log_file
, to
);
535 /* Close and reopen the log. It may have been renamed "manually"
536 * before HUP'ing us. */
537 if (debug_log
!= stderr
)
538 debugOpenLog(Config
.Log
.log
);
544 time_t t
= getCurrentTime();
547 static char buf
[128];
548 static time_t last_t
= 0;
550 if (Debug::level
> 1) {
553 strftime(buf2
, 127, "%Y/%m/%d %H:%M:%S", tm
);
555 snprintf(buf
, 127, "%s.%03d", buf2
, (int) current_time
.tv_usec
/ 1000);
557 } else if (t
!= last_t
) {
559 strftime(buf
, 127, "%Y/%m/%d %H:%M:%S", tm
);
568 xassert(const char *msg
, const char *file
, int line
) {
569 debugs(0, 0, "assertion failed: " << file
<< ":" << line
<< ": \"" << msg
<< "\"");
576 * Context-based Debugging
581 * When you have a long nested processing sequence, it is often impossible
582 * for low level routines to know in what larger context they operate. If a
583 * routine coredumps, one can restore the context using debugger trace.
584 * However, in many case you do not want to coredump, but just want to report
585 * a potential problem. A report maybe useless out of problem context.
587 * To solve this potential problem, use the following approach:
590 * top_level_foo(const char *url)
592 * // define current context
593 * // note: we stack but do not dup ctx descriptions!
594 * Ctx ctx = ctx_enter(url);
596 * // go down; middle_level_bar will eventually call bottom_level_boo
597 * middle_level_bar(method, protocol);
599 * // exit, clean after yourself
604 * bottom_level_boo(int status, void *data)
606 * // detect exceptional condition, and simply report it, the context
607 * // information will be available somewhere close in the log file
608 * if (status == STRANGE_STATUS)
609 * debugs(13, 6, "DOS attack detected, data: " << data);
613 * Current implementation is extremely simple but still very handy. It has a
614 * negligible overhead (descriptions are not duplicated).
616 * When the _first_ debug message for a given context is printed, it is
617 * prepended with the current context description. Context is printed with
618 * the same debugging level as the original message.
620 * Note that we do not print context every type you do ctx_enter(). This
621 * approach would produce too many useless messages. For the same reason, a
622 * context description is printed at most _once_ even if you have 10
623 * debugging messages within one context.
625 * Contexts can be nested, of course. You must use ctx_enter() to enter a
626 * context (push it onto stack). It is probably safe to exit several nested
627 * contexts at _once_ by calling ctx_exit() at the top level (this will pop
628 * all context till current one). However, as in any stack, you cannot start
632 * i) locate debugging message,
633 * ii) locate current context by going _upstream_ in your log file,
640 * decide if we want to dup() descriptions (adds overhead) but allows to
641 * add printf()-style interface
646 * descriptions for contexts over CTX_MAX_LEVEL limit are ignored, you probably
647 * have a bug if your nesting goes that deep.
650 #define CTX_MAX_LEVEL 255
653 * produce a warning when nesting reaches this level and then double
656 static int Ctx_Warn_Level
= 32;
657 /* all descriptions has been printed up to this level */
658 static int Ctx_Reported_Level
= -1;
659 /* descriptions are still valid or active up to this level */
660 static int Ctx_Valid_Level
= -1;
661 /* current level, the number of nested ctx_enter() calls */
662 static int Ctx_Current_Level
= -1;
663 /* saved descriptions (stack) */
664 static const char *Ctx_Descrs
[CTX_MAX_LEVEL
+ 1];
665 /* "safe" get secription */
666 static const char *ctx_get_descr(Ctx ctx
);
670 ctx_enter(const char *descr
) {
673 if (Ctx_Current_Level
<= CTX_MAX_LEVEL
)
674 Ctx_Descrs
[Ctx_Current_Level
] = descr
;
676 if (Ctx_Current_Level
== Ctx_Warn_Level
) {
677 debugs(0, 0, "# ctx: suspiciously deep (" << Ctx_Warn_Level
<< ") nesting:");
681 return Ctx_Current_Level
;
687 Ctx_Current_Level
= (ctx
>= 0) ? ctx
- 1 : -1;
689 if (Ctx_Valid_Level
> Ctx_Current_Level
)
690 Ctx_Valid_Level
= Ctx_Current_Level
;
694 * the idea id to print each context description at most once but provide enough
695 * info for deducing the current execution stack
699 /* lock so _db_print will not call us recursively */
701 /* ok, user saw [0,Ctx_Reported_Level] descriptions */
702 /* first inform about entries popped since user saw them */
704 if (Ctx_Valid_Level
< Ctx_Reported_Level
) {
705 if (Ctx_Reported_Level
!= Ctx_Valid_Level
+ 1)
706 _db_print("ctx: exit levels from %2d down to %2d\n",
707 Ctx_Reported_Level
, Ctx_Valid_Level
+ 1);
709 _db_print("ctx: exit level %2d\n", Ctx_Reported_Level
);
711 Ctx_Reported_Level
= Ctx_Valid_Level
;
714 /* report new contexts that were pushed since last report */
715 while (Ctx_Reported_Level
< Ctx_Current_Level
) {
716 Ctx_Reported_Level
++;
718 _db_print("ctx: enter level %2d: '%s'\n", Ctx_Reported_Level
,
719 ctx_get_descr(Ctx_Reported_Level
));
726 /* checks for nulls and overflows */
728 ctx_get_descr(Ctx ctx
) {
729 if (ctx
< 0 || ctx
> CTX_MAX_LEVEL
)
732 return Ctx_Descrs
[ctx
] ? Ctx_Descrs
[ctx
] : "<null>";
735 int Debug::TheDepth
= 0;
738 Debug::getDebugOut() {
739 assert(TheDepth
>= 0);
742 assert(CurrentDebug
);
743 *CurrentDebug
<< std::endl
<< "reentrant debuging " << TheDepth
<< "-{";
745 assert(!CurrentDebug
);
746 CurrentDebug
= new std::ostringstream();
747 // set default formatting flags
748 CurrentDebug
->setf(std::ios::fixed
);
749 CurrentDebug
->precision(2);
751 return *CurrentDebug
;
755 Debug::finishDebug() {
756 assert(TheDepth
>= 0);
757 assert(CurrentDebug
);
759 *CurrentDebug
<< "}-" << TheDepth
<< std::endl
;
761 assert(TheDepth
== 1);
762 _db_print("%s\n", CurrentDebug
->str().c_str());
769 // Hack: replaces global ::xassert() to debug debugging assertions
770 // Relies on assert macro calling xassert() without a specific scope.
772 Debug::xassert(const char *msg
, const char *file
, int line
) {
775 *CurrentDebug
<< "assertion failed: " << file
<< ":" << line
<<
776 ": \"" << msg
<< "\"";
781 std::ostringstream (*Debug::CurrentDebug
)(NULL
);