2 * $Id: debug.cc,v 1.106 2007/12/04 15:20:22 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.
37 #include "SquidTime.h"
40 int Debug::Levels
[MAX_DEBUG_SECTIONS
];
43 static char *debug_log_file
= NULL
;
44 static int Ctx_Lock
= 0;
45 static const char *debugLogTime(void);
46 static void ctx_print(void);
49 static int syslog_facility
= 0;
51 static void _db_print_syslog(const char *format
, va_list args
);
53 static void _db_print_stderr(const char *format
, va_list args
);
54 static void _db_print_file(const char *format
, va_list args
);
57 SQUIDCEXTERN LPCRITICAL_SECTION dbg_mutex
;
58 typedef BOOL (WINAPI
* PFInitializeCriticalSectionAndSpinCount
) (LPCRITICAL_SECTION
, DWORD
);
64 _db_print(const char *format
,...)
70 const char *format
= NULL
;
73 LOCAL_ARRAY(char, f
, BUFSIZ
);
84 /* Multiple WIN32 threads may call this simultaneously */
88 HMODULE krnl_lib
= GetModuleHandle("Kernel32");
89 PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount
= NULL
;
92 InitializeCriticalSectionAndSpinCount
=
93 (PFInitializeCriticalSectionAndSpinCount
) GetProcAddress(krnl_lib
,
94 "InitializeCriticalSectionAndSpinCount");
96 dbg_mutex
= static_cast<CRITICAL_SECTION
*>(xcalloc(1, sizeof(CRITICAL_SECTION
)));
98 if (InitializeCriticalSectionAndSpinCount
) {
99 /* let multiprocessor systems EnterCriticalSection() fast */
101 if (!InitializeCriticalSectionAndSpinCount(dbg_mutex
, 4000)) {
103 fprintf(debug_log
, "FATAL: _db_print: can't initialize critical section\n");
107 fprintf(stderr
, "FATAL: _db_print: can't initialize critical section\n");
110 InitializeCriticalSection(dbg_mutex
);
114 EnterCriticalSection(dbg_mutex
);
116 /* give a chance to context-based debugging to print current context */
123 va_start(args1
, format
);
125 va_start(args2
, format
);
127 va_start(args3
, format
);
131 format
= va_arg(args1
, const char *);
135 snprintf(f
, BUFSIZ
, "%s| %s",
139 _db_print_file(f
, args1
);
141 _db_print_stderr(f
, args2
);
145 _db_print_syslog(format
, args3
);
150 LeaveCriticalSection(dbg_mutex
);
166 _db_print_file(const char *format
, va_list args
) {
167 if (debug_log
== NULL
)
170 /* give a chance to context-based debugging to print current context */
174 vfprintf(debug_log
, format
, args
);
176 if (!Config
.onoff
.buffered_logs
)
181 _db_print_stderr(const char *format
, va_list args
) {
182 if (opt_debug_stderr
< Debug::level
)
185 if (debug_log
== stderr
)
188 vfprintf(stderr
, format
, args
);
193 _db_print_syslog(const char *format
, va_list args
) {
194 LOCAL_ARRAY(char, tmpbuf
, BUFSIZ
);
195 /* level 0,1 go to syslog */
197 if (Debug::level
> 1)
200 if (0 == opt_syslog_enable
)
205 vsnprintf(tmpbuf
, BUFSIZ
, format
, args
);
207 tmpbuf
[BUFSIZ
- 1] = '\0';
209 syslog(Debug::level
== 0 ? LOG_WARNING
: LOG_NOTICE
, "%s", tmpbuf
);
212 #endif /* HAVE_SYSLOG */
215 debugArg(const char *arg
) {
220 if (!strncasecmp(arg
, "ALL", 3)) {
226 while (*arg
&& *arg
++ != ',')
234 if(s
>= MAX_DEBUG_SECTIONS
)
235 s
= MAX_DEBUG_SECTIONS
-1;
244 Debug::Levels
[s
] = l
;
248 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
249 Debug::Levels
[i
] = l
;
253 debugOpenLog(const char *logfile
) {
254 if (logfile
== NULL
) {
260 xfree(debug_log_file
);
262 debug_log_file
= xstrdup(logfile
); /* keep a static copy */
264 if (debug_log
&& debug_log
!= stderr
)
267 debug_log
= fopen(logfile
, "a+");
270 fprintf(stderr
, "WARNING: Cannot write log file: %s\n", logfile
);
272 fprintf(stderr
, " messages will be sent to 'stderr'.\n");
278 setmode(fileno(debug_log
), O_TEXT
);
286 static struct syslog_facility_name
{
291 syslog_facility_names
[] = {
300 "authpriv", LOG_AUTHPRIV
401 _db_set_syslog(const char *facility
) {
402 opt_syslog_enable
= 1;
406 syslog_facility
= LOG_DAEMON
;
409 syslog_facility
= LOG_LOCAL4
;
414 struct syslog_facility_name
*n
;
416 for (n
= syslog_facility_names
; n
->name
; n
++) {
417 if (strcmp(n
->name
, facility
) == 0) {
418 syslog_facility
= n
->facility
;
423 fprintf(stderr
, "unknown syslog facility '%s'\n", facility
);
429 fprintf(stderr
, "syslog facility type not supported on your system\n");
437 Debug::parseOptions(char const *options
) {
442 if(Config
.onoff
.debug_override_X
) {
443 debugs(0, 9, "command-line -X overrides: " << options
);
447 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
448 Debug::Levels
[i
] = -1;
451 p
= xstrdup(options
);
453 for (s
= strtok(p
, w_space
); s
; s
= strtok(NULL
, w_space
))
461 _db_init(const char *logfile
, const char *options
) {
462 Debug::parseOptions(options
);
464 debugOpenLog(logfile
);
466 #if HAVE_SYSLOG && defined(LOG_LOCAL4)
468 if (opt_syslog_enable
)
469 openlog(appname
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, syslog_facility
);
471 #endif /* HAVE_SYSLOG */
476 _db_rotate_log(void) {
478 LOCAL_ARRAY(char, from
, MAXPATHLEN
);
479 LOCAL_ARRAY(char, to
, MAXPATHLEN
);
485 if (debug_log_file
== NULL
)
490 if (stat(debug_log_file
, &sb
) == 0)
491 if (S_ISREG(sb
.st_mode
) == 0)
497 * NOTE: we cannot use xrename here without having it in a
498 * separate file -- tools.c has too many dependencies to be
499 * used everywhere debug.c is used.
501 /* Rotate numbers 0 through N up one */
502 for (i
= Config
.Log
.rotateNumber
; i
> 1;) {
504 snprintf(from
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
- 1);
505 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
);
517 * You can't rename open files on Microsoft "operating systems"
518 * so we close before renaming.
521 if (debug_log
!= stderr
)
525 /* Rotate the current log to .0 */
526 if (Config
.Log
.rotateNumber
> 0) {
527 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, 0);
535 rename(debug_log_file
, to
);
538 /* Close and reopen the log. It may have been renamed "manually"
539 * before HUP'ing us. */
540 if (debug_log
!= stderr
)
541 debugOpenLog(Config
.Log
.log
);
547 time_t t
= getCurrentTime();
550 static char buf
[128];
551 static time_t last_t
= 0;
553 if (Debug::level
> 1) {
556 strftime(buf2
, 127, "%Y/%m/%d %H:%M:%S", tm
);
558 snprintf(buf
, 127, "%s.%03d", buf2
, (int) current_time
.tv_usec
/ 1000);
560 } else if (t
!= last_t
) {
562 strftime(buf
, 127, "%Y/%m/%d %H:%M:%S", tm
);
571 xassert(const char *msg
, const char *file
, int line
) {
572 debugs(0, 0, "assertion failed: " << file
<< ":" << line
<< ": \"" << msg
<< "\"");
579 * Context-based Debugging
584 * When you have a long nested processing sequence, it is often impossible
585 * for low level routines to know in what larger context they operate. If a
586 * routine coredumps, one can restore the context using debugger trace.
587 * However, in many case you do not want to coredump, but just want to report
588 * a potential problem. A report maybe useless out of problem context.
590 * To solve this potential problem, use the following approach:
593 * top_level_foo(const char *url)
595 * // define current context
596 * // note: we stack but do not dup ctx descriptions!
597 * Ctx ctx = ctx_enter(url);
599 * // go down; middle_level_bar will eventually call bottom_level_boo
600 * middle_level_bar(method, protocol);
602 * // exit, clean after yourself
607 * bottom_level_boo(int status, void *data)
609 * // detect exceptional condition, and simply report it, the context
610 * // information will be available somewhere close in the log file
611 * if (status == STRANGE_STATUS)
612 * debugs(13, 6, "DOS attack detected, data: " << data);
616 * Current implementation is extremely simple but still very handy. It has a
617 * negligible overhead (descriptions are not duplicated).
619 * When the _first_ debug message for a given context is printed, it is
620 * prepended with the current context description. Context is printed with
621 * the same debugging level as the original message.
623 * Note that we do not print context every type you do ctx_enter(). This
624 * approach would produce too many useless messages. For the same reason, a
625 * context description is printed at most _once_ even if you have 10
626 * debugging messages within one context.
628 * Contexts can be nested, of course. You must use ctx_enter() to enter a
629 * context (push it onto stack). It is probably safe to exit several nested
630 * contexts at _once_ by calling ctx_exit() at the top level (this will pop
631 * all context till current one). However, as in any stack, you cannot start
635 * i) locate debugging message,
636 * ii) locate current context by going _upstream_ in your log file,
643 * decide if we want to dup() descriptions (adds overhead) but allows to
644 * add printf()-style interface
649 * descriptions for contexts over CTX_MAX_LEVEL limit are ignored, you probably
650 * have a bug if your nesting goes that deep.
653 #define CTX_MAX_LEVEL 255
656 * produce a warning when nesting reaches this level and then double
659 static int Ctx_Warn_Level
= 32;
660 /* all descriptions has been printed up to this level */
661 static int Ctx_Reported_Level
= -1;
662 /* descriptions are still valid or active up to this level */
663 static int Ctx_Valid_Level
= -1;
664 /* current level, the number of nested ctx_enter() calls */
665 static int Ctx_Current_Level
= -1;
666 /* saved descriptions (stack) */
667 static const char *Ctx_Descrs
[CTX_MAX_LEVEL
+ 1];
668 /* "safe" get secription */
669 static const char *ctx_get_descr(Ctx ctx
);
673 ctx_enter(const char *descr
) {
676 if (Ctx_Current_Level
<= CTX_MAX_LEVEL
)
677 Ctx_Descrs
[Ctx_Current_Level
] = descr
;
679 if (Ctx_Current_Level
== Ctx_Warn_Level
) {
680 debugs(0, 0, "# ctx: suspiciously deep (" << Ctx_Warn_Level
<< ") nesting:");
684 return Ctx_Current_Level
;
690 Ctx_Current_Level
= (ctx
>= 0) ? ctx
- 1 : -1;
692 if (Ctx_Valid_Level
> Ctx_Current_Level
)
693 Ctx_Valid_Level
= Ctx_Current_Level
;
697 * the idea id to print each context description at most once but provide enough
698 * info for deducing the current execution stack
702 /* lock so _db_print will not call us recursively */
704 /* ok, user saw [0,Ctx_Reported_Level] descriptions */
705 /* first inform about entries popped since user saw them */
707 if (Ctx_Valid_Level
< Ctx_Reported_Level
) {
708 if (Ctx_Reported_Level
!= Ctx_Valid_Level
+ 1)
709 _db_print("ctx: exit levels from %2d down to %2d\n",
710 Ctx_Reported_Level
, Ctx_Valid_Level
+ 1);
712 _db_print("ctx: exit level %2d\n", Ctx_Reported_Level
);
714 Ctx_Reported_Level
= Ctx_Valid_Level
;
717 /* report new contexts that were pushed since last report */
718 while (Ctx_Reported_Level
< Ctx_Current_Level
) {
719 Ctx_Reported_Level
++;
721 _db_print("ctx: enter level %2d: '%s'\n", Ctx_Reported_Level
,
722 ctx_get_descr(Ctx_Reported_Level
));
729 /* checks for nulls and overflows */
731 ctx_get_descr(Ctx ctx
) {
732 if (ctx
< 0 || ctx
> CTX_MAX_LEVEL
)
735 return Ctx_Descrs
[ctx
] ? Ctx_Descrs
[ctx
] : "<null>";
739 Debug::getDebugOut() {
740 assert (CurrentDebug
== NULL
);
741 CurrentDebug
= new std::ostringstream();
742 // set default formatting flags
743 CurrentDebug
->setf(std::ios::fixed
);
744 CurrentDebug
->precision(2);
745 return *CurrentDebug
;
749 Debug::finishDebug() {
750 _db_print("%s\n", CurrentDebug
->str().c_str());
755 std::ostringstream (*Debug::CurrentDebug
)(NULL
);