4 * DEBUG: section 00 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"
41 /* for shutting_down flag in xassert() */
44 char *Debug::debugOptions
= NULL
;
45 int Debug::override_X
= 0;
46 int Debug::log_stderr
= -1;
47 bool Debug::log_syslog
= false;
48 int Debug::Levels
[MAX_DEBUG_SECTIONS
];
50 char *Debug::cache_log
= NULL
;
51 int Debug::rotateNumber
= -1;
52 FILE *debug_log
= NULL
;
53 static char *debug_log_file
= NULL
;
54 static int Ctx_Lock
= 0;
55 static const char *debugLogTime(void);
56 static const char *debugLogKid(void);
57 static void ctx_print(void);
60 static int syslog_facility
= 0;
62 static void _db_print_syslog(const char *format
, va_list args
);
64 static void _db_print_stderr(const char *format
, va_list args
);
65 static void _db_print_file(const char *format
, va_list args
);
68 SQUIDCEXTERN LPCRITICAL_SECTION dbg_mutex
;
69 typedef BOOL (WINAPI
* PFInitializeCriticalSectionAndSpinCount
) (LPCRITICAL_SECTION
, DWORD
);
73 _db_print(const char *format
,...)
82 /* Multiple WIN32 threads may call this simultaneously */
85 HMODULE krnl_lib
= GetModuleHandle("Kernel32");
86 PFInitializeCriticalSectionAndSpinCount InitializeCriticalSectionAndSpinCount
= NULL
;
89 InitializeCriticalSectionAndSpinCount
=
90 (PFInitializeCriticalSectionAndSpinCount
) GetProcAddress(krnl_lib
,
91 "InitializeCriticalSectionAndSpinCount");
93 dbg_mutex
= static_cast<CRITICAL_SECTION
*>(xcalloc(1, sizeof(CRITICAL_SECTION
)));
95 if (InitializeCriticalSectionAndSpinCount
) {
96 /* let multiprocessor systems EnterCriticalSection() fast */
98 if (!InitializeCriticalSectionAndSpinCount(dbg_mutex
, 4000)) {
100 fprintf(debug_log
, "FATAL: _db_print: can't initialize critical section\n");
104 fprintf(stderr
, "FATAL: _db_print: can't initialize critical section\n");
107 InitializeCriticalSection(dbg_mutex
);
111 EnterCriticalSection(dbg_mutex
);
114 /* give a chance to context-based debugging to print current context */
118 va_start(args1
, format
);
119 va_start(args2
, format
);
120 va_start(args3
, format
);
122 snprintf(f
, BUFSIZ
, "%s%s| %s",
127 _db_print_file(f
, args1
);
128 _db_print_stderr(f
, args2
);
131 _db_print_syslog(format
, args3
);
135 LeaveCriticalSection(dbg_mutex
);
144 _db_print_file(const char *format
, va_list args
)
146 if (debug_log
== NULL
)
149 /* give a chance to context-based debugging to print current context */
153 vfprintf(debug_log
, format
, args
);
158 _db_print_stderr(const char *format
, va_list args
)
160 if (Debug::log_stderr
< Debug::level
)
163 if (debug_log
== stderr
)
166 vfprintf(stderr
, format
, args
);
171 _db_print_syslog(const char *format
, va_list args
)
173 /* level 0,1 go to syslog */
175 if (Debug::level
> 1)
178 if (!Debug::log_syslog
)
184 vsnprintf(tmpbuf
, BUFSIZ
, format
, args
);
186 tmpbuf
[BUFSIZ
- 1] = '\0';
188 syslog(Debug::level
== 0 ? LOG_WARNING
: LOG_NOTICE
, "%s", tmpbuf
);
190 #endif /* HAVE_SYSLOG */
193 debugArg(const char *arg
)
199 if (!strncasecmp(arg
, "rotate=", 7)) {
201 Debug::rotateNumber
= atoi(arg
);
203 } else if (!strncasecmp(arg
, "ALL", 3)) {
208 while (*arg
&& *arg
++ != ',');
214 if (s
>= MAX_DEBUG_SECTIONS
)
215 s
= MAX_DEBUG_SECTIONS
-1;
224 Debug::Levels
[s
] = l
;
228 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
229 Debug::Levels
[i
] = l
;
233 debugOpenLog(const char *logfile
)
235 if (logfile
== NULL
) {
241 xfree(debug_log_file
);
243 debug_log_file
= xstrdup(logfile
); /* keep a static copy */
245 if (debug_log
&& debug_log
!= stderr
)
248 debug_log
= fopen(logfile
, "a+");
251 fprintf(stderr
, "WARNING: Cannot write log file: %s\n", logfile
);
253 fprintf(stderr
, " messages will be sent to 'stderr'.\n");
259 setmode(fileno(debug_log
), O_TEXT
);
267 static struct syslog_facility_name
{
272 syslog_facility_names
[] = {
281 "authpriv", LOG_AUTHPRIV
382 _db_set_syslog(const char *facility
)
384 Debug::log_syslog
= true;
389 syslog_facility
= LOG_DAEMON
;
392 syslog_facility
= LOG_LOCAL4
;
393 #endif /* LOG_DAEMON */
397 struct syslog_facility_name
*n
;
399 for (n
= syslog_facility_names
; n
->name
; n
++) {
400 if (strcmp(n
->name
, facility
) == 0) {
401 syslog_facility
= n
->facility
;
406 fprintf(stderr
, "unknown syslog facility '%s'\n", facility
);
412 fprintf(stderr
, "syslog facility type not supported on your system\n");
414 #endif /* LOG_LOCAL4 */
420 Debug::parseOptions(char const *options
)
427 debugs(0, 9, "command-line -X overrides: " << options
);
431 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; i
++)
432 Debug::Levels
[i
] = 0;
435 p
= xstrdup(options
);
437 for (s
= strtok(p
, w_space
); s
; s
= strtok(NULL
, w_space
))
445 _db_init(const char *logfile
, const char *options
)
447 Debug::parseOptions(options
);
449 debugOpenLog(logfile
);
451 #if HAVE_SYSLOG && defined(LOG_LOCAL4)
453 if (Debug::log_syslog
)
454 openlog(APP_SHORTNAME
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, syslog_facility
);
456 #endif /* HAVE_SYSLOG */
458 /* Pre-Init TZ env, see bug #2656 */
465 if (debug_log_file
== NULL
)
470 if (stat(debug_log_file
, &sb
) == 0)
471 if (S_ISREG(sb
.st_mode
) == 0)
475 char from
[MAXPATHLEN
];
482 * NOTE: we cannot use xrename here without having it in a
483 * separate file -- tools.c has too many dependencies to be
484 * used everywhere debug.c is used.
486 /* Rotate numbers 0 through N up one */
487 for (int i
= Debug::rotateNumber
; i
> 1;) {
489 snprintf(from
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
- 1);
490 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
);
499 * You can't rename open files on Microsoft "operating systems"
500 * so we close before renaming.
503 if (debug_log
!= stderr
)
506 /* Rotate the current log to .0 */
507 if (Debug::rotateNumber
> 0) {
508 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, 0);
513 rename(debug_log_file
, to
);
516 /* Close and reopen the log. It may have been renamed "manually"
517 * before HUP'ing us. */
518 if (debug_log
!= stderr
)
519 debugOpenLog(Debug::cache_log
);
526 time_t t
= getCurrentTime();
529 static char buf
[128];
530 static time_t last_t
= 0;
532 if (Debug::level
> 1) {
535 strftime(buf2
, 127, "%Y/%m/%d %H:%M:%S", tm
);
537 snprintf(buf
, 127, "%s.%03d", buf2
, (int) current_time
.tv_usec
/ 1000);
539 } else if (t
!= last_t
) {
541 strftime(buf
, 127, "%Y/%m/%d %H:%M:%S", tm
);
552 if (KidIdentifier
!= 0) {
554 if (!*buf
) // optimization: fill only once after KidIdentifier is set
555 snprintf(buf
, sizeof(buf
), " kid%d", KidIdentifier
);
563 xassert(const char *msg
, const char *file
, int line
)
565 debugs(0, 0, "assertion failed: " << file
<< ":" << line
<< ": \"" << msg
<< "\"");
572 * Context-based Debugging
577 * When you have a long nested processing sequence, it is often impossible
578 * for low level routines to know in what larger context they operate. If a
579 * routine coredumps, one can restore the context using debugger trace.
580 * However, in many case you do not want to coredump, but just want to report
581 * a potential problem. A report maybe useless out of problem context.
583 * To solve this potential problem, use the following approach:
586 * top_level_foo(const char *url)
588 * // define current context
589 * // note: we stack but do not dup ctx descriptions!
590 * Ctx ctx = ctx_enter(url);
592 * // go down; middle_level_bar will eventually call bottom_level_boo
593 * middle_level_bar(method, protocol);
595 * // exit, clean after yourself
600 * bottom_level_boo(int status, void *data)
602 * // detect exceptional condition, and simply report it, the context
603 * // information will be available somewhere close in the log file
604 * if (status == STRANGE_STATUS)
605 * debugs(13, 6, "DOS attack detected, data: " << data);
609 * Current implementation is extremely simple but still very handy. It has a
610 * negligible overhead (descriptions are not duplicated).
612 * When the _first_ debug message for a given context is printed, it is
613 * prepended with the current context description. Context is printed with
614 * the same debugging level as the original message.
616 * Note that we do not print context every type you do ctx_enter(). This
617 * approach would produce too many useless messages. For the same reason, a
618 * context description is printed at most _once_ even if you have 10
619 * debugging messages within one context.
621 * Contexts can be nested, of course. You must use ctx_enter() to enter a
622 * context (push it onto stack). It is probably safe to exit several nested
623 * contexts at _once_ by calling ctx_exit() at the top level (this will pop
624 * all context till current one). However, as in any stack, you cannot start
628 * i) locate debugging message,
629 * ii) locate current context by going _upstream_ in your log file,
636 * decide if we want to dup() descriptions (adds overhead) but allows to
637 * add printf()-style interface
642 * descriptions for contexts over CTX_MAX_LEVEL limit are ignored, you probably
643 * have a bug if your nesting goes that deep.
646 #define CTX_MAX_LEVEL 255
649 * produce a warning when nesting reaches this level and then double
652 static int Ctx_Warn_Level
= 32;
653 /* all descriptions has been printed up to this level */
654 static int Ctx_Reported_Level
= -1;
655 /* descriptions are still valid or active up to this level */
656 static int Ctx_Valid_Level
= -1;
657 /* current level, the number of nested ctx_enter() calls */
658 static int Ctx_Current_Level
= -1;
659 /* saved descriptions (stack) */
660 static const char *Ctx_Descrs
[CTX_MAX_LEVEL
+ 1];
661 /* "safe" get secription */
662 static const char *ctx_get_descr(Ctx ctx
);
666 ctx_enter(const char *descr
)
670 if (Ctx_Current_Level
<= CTX_MAX_LEVEL
)
671 Ctx_Descrs
[Ctx_Current_Level
] = descr
;
673 if (Ctx_Current_Level
== Ctx_Warn_Level
) {
674 debugs(0, 0, "# ctx: suspiciously deep (" << Ctx_Warn_Level
<< ") nesting:");
678 return Ctx_Current_Level
;
685 Ctx_Current_Level
= (ctx
>= 0) ? ctx
- 1 : -1;
687 if (Ctx_Valid_Level
> Ctx_Current_Level
)
688 Ctx_Valid_Level
= Ctx_Current_Level
;
692 * the idea id to print each context description at most once but provide enough
693 * info for deducing the current execution stack
698 /* lock so _db_print will not call us recursively */
700 /* ok, user saw [0,Ctx_Reported_Level] descriptions */
701 /* first inform about entries popped since user saw them */
703 if (Ctx_Valid_Level
< Ctx_Reported_Level
) {
704 if (Ctx_Reported_Level
!= Ctx_Valid_Level
+ 1)
705 _db_print("ctx: exit levels from %2d down to %2d\n",
706 Ctx_Reported_Level
, Ctx_Valid_Level
+ 1);
708 _db_print("ctx: exit level %2d\n", Ctx_Reported_Level
);
710 Ctx_Reported_Level
= Ctx_Valid_Level
;
713 /* report new contexts that were pushed since last report */
714 while (Ctx_Reported_Level
< Ctx_Current_Level
) {
715 Ctx_Reported_Level
++;
717 _db_print("ctx: enter level %2d: '%s'\n", Ctx_Reported_Level
,
718 ctx_get_descr(Ctx_Reported_Level
));
725 /* checks for nulls and overflows */
727 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;
740 assert(TheDepth
>= 0);
743 assert(CurrentDebug
);
744 *CurrentDebug
<< std::endl
<< "reentrant debuging " << TheDepth
<< "-{";
746 assert(!CurrentDebug
);
747 CurrentDebug
= new std::ostringstream();
748 // set default formatting flags
749 CurrentDebug
->setf(std::ios::fixed
);
750 CurrentDebug
->precision(2);
752 return *CurrentDebug
;
758 assert(TheDepth
>= 0);
759 assert(CurrentDebug
);
761 *CurrentDebug
<< "}-" << TheDepth
<< std::endl
;
763 assert(TheDepth
== 1);
764 _db_print("%s\n", CurrentDebug
->str().c_str());
771 // Hack: replaces global ::xassert() to debug debugging assertions
772 // Relies on assert macro calling xassert() without a specific scope.
774 Debug::xassert(const char *msg
, const char *file
, int line
)
778 *CurrentDebug
<< "assertion failed: " << file
<< ":" << line
<<
779 ": \"" << msg
<< "\"";
784 std::ostringstream (*Debug::CurrentDebug
)(NULL
);
789 // XXX: This must be kept in sync with the actual debug.cc location
790 const char *ThisFileNameTail
= "src/debug.cc";
792 const char *file
=__FILE__
;
794 // Disable heuristic if it does not work.
795 if (!strstr(file
, ThisFileNameTail
))
798 return strlen(file
)-strlen(ThisFileNameTail
);
802 SkipBuildPrefix(const char* path
)
804 static const size_t BuildPrefixLength
= BuildPrefixInit();
806 return path
+BuildPrefixLength
;