2 * Copyright (C) 1996-2016 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"
19 /* for shutting_down flag in xassert() */
22 char *Debug::debugOptions
= NULL
;
23 int Debug::override_X
= 0;
24 int Debug::log_stderr
= -1;
25 bool Debug::log_syslog
= false;
26 int Debug::Levels
[MAX_DEBUG_SECTIONS
];
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 // Bug 4423: ignore the stdio: logging module name if present
226 const char *logfilename
;
227 if (strncmp(logfile
, "stdio:",6) == 0)
228 logfilename
= logfile
+ 6;
230 logfilename
= logfile
;
232 debug_log
= fopen(logfilename
, "a+");
235 fprintf(stderr
, "WARNING: Cannot write log file: %s\n", logfile
);
237 fprintf(stderr
, " messages will be sent to 'stderr'.\n");
243 setmode(fileno(debug_log
), O_TEXT
);
250 static struct syslog_facility_name
{
255 syslog_facility_names
[] = {
264 "authpriv", LOG_AUTHPRIV
365 _db_set_syslog(const char *facility
)
367 Debug::log_syslog
= true;
372 syslog_facility
= LOG_DAEMON
;
375 syslog_facility
= LOG_LOCAL4
;
376 #endif /* LOG_DAEMON */
380 struct syslog_facility_name
*n
;
382 for (n
= syslog_facility_names
; n
->name
; ++n
) {
383 if (strcmp(n
->name
, facility
) == 0) {
384 syslog_facility
= n
->facility
;
389 fprintf(stderr
, "unknown syslog facility '%s'\n", facility
);
395 fprintf(stderr
, "syslog facility type not supported on your system\n");
397 #endif /* LOG_LOCAL4 */
403 Debug::parseOptions(char const *options
)
410 debugs(0, 9, "command-line -X overrides: " << options
);
414 for (i
= 0; i
< MAX_DEBUG_SECTIONS
; ++i
)
415 Debug::Levels
[i
] = 0;
418 p
= xstrdup(options
);
420 for (s
= strtok(p
, w_space
); s
; s
= strtok(NULL
, w_space
))
428 _db_init(const char *logfile
, const char *options
)
430 Debug::parseOptions(options
);
432 debugOpenLog(logfile
);
434 #if HAVE_SYSLOG && defined(LOG_LOCAL4)
436 if (Debug::log_syslog
)
437 openlog(APP_SHORTNAME
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, syslog_facility
);
439 #endif /* HAVE_SYSLOG */
441 /* Pre-Init TZ env, see bug #2656 */
448 if (debug_log_file
== NULL
)
453 if (stat(debug_log_file
, &sb
) == 0)
454 if (S_ISREG(sb
.st_mode
) == 0)
458 char from
[MAXPATHLEN
];
465 * NOTE: we cannot use xrename here without having it in a
466 * separate file -- tools.c has too many dependencies to be
467 * used everywhere debug.c is used.
469 /* Rotate numbers 0 through N up one */
470 for (int i
= Debug::rotateNumber
; i
> 1;) {
472 snprintf(from
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
- 1);
473 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, i
);
479 if (rename(from
, to
) == -1) {
480 const auto saved_errno
= errno
;
481 debugs(0, DBG_IMPORTANT
, "log rotation failed: " << xstrerr(saved_errno
));
486 * You can't rename open files on Microsoft "operating systems"
487 * so we close before renaming.
490 if (debug_log
!= stderr
)
493 /* Rotate the current log to .0 */
494 if (Debug::rotateNumber
> 0) {
495 snprintf(to
, MAXPATHLEN
, "%s.%d", debug_log_file
, 0);
498 if (remove(to
) == -1) {
499 const auto saved_errno
= errno
;
500 debugs(0, DBG_IMPORTANT
, "removal of log file " << to
<< " failed: " << xstrerr(saved_errno
));
504 if (rename(debug_log_file
, to
) == -1) {
505 const auto saved_errno
= errno
;
506 debugs(0, DBG_IMPORTANT
, "renaming file " << debug_log_file
<< " to "
507 << to
<< "failed: " << xstrerr(saved_errno
));
511 /* Close and reopen the log. It may have been renamed "manually"
512 * before HUP'ing us. */
513 if (debug_log
!= stderr
)
514 debugOpenLog(Debug::cache_log
);
521 time_t t
= getCurrentTime();
524 static char buf
[128];
525 static time_t last_t
= 0;
527 if (Debug::Level() > 1) {
530 strftime(buf2
, 127, "%Y/%m/%d %H:%M:%S", tm
);
532 snprintf(buf
, 127, "%s.%03d", buf2
, (int) current_time
.tv_usec
/ 1000);
534 } else if (t
!= last_t
) {
536 strftime(buf
, 127, "%Y/%m/%d %H:%M:%S", tm
);
547 if (KidIdentifier
!= 0) {
549 if (!*buf
) // optimization: fill only once after KidIdentifier is set
550 snprintf(buf
, sizeof(buf
), " kid%d", KidIdentifier
);
558 xassert(const char *msg
, const char *file
, int line
)
560 debugs(0, DBG_CRITICAL
, "assertion failed: " << file
<< ":" << line
<< ": \"" << msg
<< "\"");
567 * Context-based Debugging
572 * When you have a long nested processing sequence, it is often impossible
573 * for low level routines to know in what larger context they operate. If a
574 * routine coredumps, one can restore the context using debugger trace.
575 * However, in many case you do not want to coredump, but just want to report
576 * a potential problem. A report maybe useless out of problem context.
578 * To solve this potential problem, use the following approach:
581 * top_level_foo(const char *url)
583 * // define current context
584 * // note: we stack but do not dup ctx descriptions!
585 * Ctx ctx = ctx_enter(url);
587 * // go down; middle_level_bar will eventually call bottom_level_boo
588 * middle_level_bar(method, protocol);
590 * // exit, clean after yourself
595 * bottom_level_boo(int status, void *data)
597 * // detect exceptional condition, and simply report it, the context
598 * // information will be available somewhere close in the log file
599 * if (status == STRANGE_STATUS)
600 * debugs(13, 6, "DOS attack detected, data: " << data);
604 * Current implementation is extremely simple but still very handy. It has a
605 * negligible overhead (descriptions are not duplicated).
607 * When the _first_ debug message for a given context is printed, it is
608 * prepended with the current context description. Context is printed with
609 * the same debugging level as the original message.
611 * Note that we do not print context every type you do ctx_enter(). This
612 * approach would produce too many useless messages. For the same reason, a
613 * context description is printed at most _once_ even if you have 10
614 * debugging messages within one context.
616 * Contexts can be nested, of course. You must use ctx_enter() to enter a
617 * context (push it onto stack). It is probably safe to exit several nested
618 * contexts at _once_ by calling ctx_exit() at the top level (this will pop
619 * all context till current one). However, as in any stack, you cannot start
623 * i) locate debugging message,
624 * ii) locate current context by going _upstream_ in your log file,
631 * decide if we want to dup() descriptions (adds overhead) but allows to
632 * add printf()-style interface
637 * descriptions for contexts over CTX_MAX_LEVEL limit are ignored, you probably
638 * have a bug if your nesting goes that deep.
641 #define CTX_MAX_LEVEL 255
644 * produce a warning when nesting reaches this level and then double
647 static int Ctx_Warn_Level
= 32;
648 /* all descriptions has been printed up to this level */
649 static int Ctx_Reported_Level
= -1;
650 /* descriptions are still valid or active up to this level */
651 static int Ctx_Valid_Level
= -1;
652 /* current level, the number of nested ctx_enter() calls */
653 static int Ctx_Current_Level
= -1;
654 /* saved descriptions (stack) */
655 static const char *Ctx_Descrs
[CTX_MAX_LEVEL
+ 1];
656 /* "safe" get secription */
657 static const char *ctx_get_descr(Ctx ctx
);
660 ctx_enter(const char *descr
)
664 if (Ctx_Current_Level
<= CTX_MAX_LEVEL
)
665 Ctx_Descrs
[Ctx_Current_Level
] = descr
;
667 if (Ctx_Current_Level
== Ctx_Warn_Level
) {
668 debugs(0, DBG_CRITICAL
, "# ctx: suspiciously deep (" << Ctx_Warn_Level
<< ") nesting:");
672 return Ctx_Current_Level
;
679 Ctx_Current_Level
= (ctx
>= 0) ? ctx
- 1 : -1;
681 if (Ctx_Valid_Level
> Ctx_Current_Level
)
682 Ctx_Valid_Level
= Ctx_Current_Level
;
686 * the idea id to print each context description at most once but provide enough
687 * info for deducing the current execution stack
692 /* lock so _db_print will not call us recursively */
694 /* ok, user saw [0,Ctx_Reported_Level] descriptions */
695 /* first inform about entries popped since user saw them */
697 if (Ctx_Valid_Level
< Ctx_Reported_Level
) {
698 if (Ctx_Reported_Level
!= Ctx_Valid_Level
+ 1)
699 _db_print("ctx: exit levels from %2d down to %2d\n",
700 Ctx_Reported_Level
, Ctx_Valid_Level
+ 1);
702 _db_print("ctx: exit level %2d\n", Ctx_Reported_Level
);
704 Ctx_Reported_Level
= Ctx_Valid_Level
;
707 /* report new contexts that were pushed since last report */
708 while (Ctx_Reported_Level
< Ctx_Current_Level
) {
709 ++Ctx_Reported_Level
;
711 _db_print("ctx: enter level %2d: '%s'\n", Ctx_Reported_Level
,
712 ctx_get_descr(Ctx_Reported_Level
));
719 /* checks for nulls and overflows */
721 ctx_get_descr(Ctx ctx
)
723 if (ctx
< 0 || ctx
> CTX_MAX_LEVEL
)
726 return Ctx_Descrs
[ctx
] ? Ctx_Descrs
[ctx
] : "<null>";
729 Debug::Context
*Debug::Current
= nullptr;
731 Debug::Context::Context(const int aSection
, const int aLevel
):
733 sectionLevel(Levels
[aSection
]),
739 /// Optimization: avoids new Context creation for every debugs().
741 Debug::Context::rewind(const int aSection
, const int aLevel
)
744 sectionLevel
= Levels
[aSection
];
745 assert(upper
== Current
);
747 buf
.str(std::string());
749 // debugs() users are supposed to preserve format, but
750 // some do not, so we have to waste cycles resetting it for all.
754 /// configures default formatting for the debugging stream
756 Debug::Context::formatStream()
758 const static std::ostringstream cleanStream
;
759 buf
.flags(cleanStream
.flags() | std::ios::fixed
);
760 buf
.width(cleanStream
.width());
763 // If this is not enough, use copyfmt(cleanStream) which is ~10% slower.
767 Debug::Start(const int section
, const int level
)
769 Context
*future
= nullptr;
771 // prepare future context
773 // all reentrant debugs() calls get here; create a dedicated context
774 future
= new Context(section
, level
);
776 // Optimization: Nearly all debugs() calls get here; avoid allocations
777 static Context
*topContext
= new Context(1, 1);
778 topContext
->rewind(section
, level
);
790 // TODO: Optimize to remove at least one extra copy.
791 _db_print("%s\n", Current
->buf
.str().c_str());
793 Context
*past
= Current
;
794 Current
= past
->upper
;
797 // else it was a static topContext from Debug::Start()
803 // XXX: This must be kept in sync with the actual debug.cc location
804 const char *ThisFileNameTail
= "src/debug.cc";
806 const char *file
=__FILE__
;
808 // Disable heuristic if it does not work.
809 if (!strstr(file
, ThisFileNameTail
))
812 return strlen(file
)-strlen(ThisFileNameTail
);
816 SkipBuildPrefix(const char* path
)
818 static const size_t BuildPrefixLength
= BuildPrefixInit();
820 return path
+BuildPrefixLength
;
823 /// print data bytes using hex notation
825 Raw::printHex(std::ostream
&os
) const
827 const auto savedFill
= os
.fill('0');
828 const auto savedFlags
= os
.flags(); // std::ios_base::fmtflags
830 std::for_each(data_
, data_
+ size_
,
831 [&os
](const char &c
) { os
<< std::setw(2) << static_cast<uint8_t>(c
); });
832 os
.flags(savedFlags
);
837 Raw::print(std::ostream
&os
) const
840 os
<< ' ' << label_
<< '[' << size_
<< ']';
845 // finalize debugging level if no level was set explicitly via minLevel()
846 const int finalLevel
= (level
>= 0) ? level
:
847 (size_
> 40 ? DBG_DATA
: Debug::SectionLevel());
848 if (finalLevel
<= Debug::SectionLevel()) {
849 os
<< (label_
? '=' : ' ');
854 os
.write(data_
, size_
);