blob: ad4047d33f9d84500229e8019818d5bad79c5ba2 [file] [log] [blame]
Austin Schuh906616c2019-01-21 20:25:11 -08001// Copyright (c) 1999, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite()
31
32#include "utilities.h"
33
34#include <algorithm>
35#include <assert.h>
36#include <iomanip>
37#include <string>
38#ifdef HAVE_UNISTD_H
39# include <unistd.h> // For _exit.
40#endif
41#include <climits>
42#include <sys/types.h>
43#include <sys/stat.h>
44#ifdef HAVE_SYS_UTSNAME_H
45# include <sys/utsname.h> // For uname.
46#endif
47#include <fcntl.h>
48#include <cstdio>
49#include <iostream>
50#include <stdarg.h>
51#include <stdlib.h>
52#ifdef HAVE_PWD_H
53# include <pwd.h>
54#endif
55#ifdef HAVE_SYSLOG_H
56# include <syslog.h>
57#endif
58#include <vector>
59#include <errno.h> // for errno
60#include <sstream>
61#include "base/commandlineflags.h" // to get the program name
62#include "glog/logging.h"
63#include "glog/raw_logging.h"
64#include "base/googleinit.h"
65
66#ifdef HAVE_STACKTRACE
67# include "stacktrace.h"
68#endif
69
70using std::string;
71using std::vector;
72using std::setw;
73using std::setfill;
74using std::hex;
75using std::dec;
76using std::min;
77using std::ostream;
78using std::ostringstream;
79
80using std::FILE;
81using std::fwrite;
82using std::fclose;
83using std::fflush;
84using std::fprintf;
85using std::perror;
86
87#ifdef __QNX__
88using std::fdopen;
89#endif
90
91#ifdef _WIN32
92#define fdopen _fdopen
93#endif
94
95// There is no thread annotation support.
96#define EXCLUSIVE_LOCKS_REQUIRED(mu)
97
98static bool BoolFromEnv(const char *varname, bool defval) {
99 const char* const valstr = getenv(varname);
100 if (!valstr) {
101 return defval;
102 }
103 return memchr("tTyY1\0", valstr[0], 6) != NULL;
104}
105
106GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
107 "log messages go to stderr instead of logfiles");
108GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
109 "log messages go to stderr in addition to logfiles");
110GLOG_DEFINE_bool(colorlogtostderr, false,
111 "color messages logged to stderr (if supported by terminal)");
112#ifdef OS_LINUX
113GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
114 "Logs can grow very quickly and they are rarely read before they "
115 "need to be evicted from memory. Instead, drop them from memory "
116 "as soon as they are flushed to disk.");
117#endif
118
119// By default, errors (including fatal errors) get logged to stderr as
120// well as the file.
121//
122// The default is ERROR instead of FATAL so that users can see problems
123// when they run a program without having to look in another file.
124DEFINE_int32(stderrthreshold,
125 GOOGLE_NAMESPACE::GLOG_ERROR,
126 "log messages at or above this level are copied to stderr in "
127 "addition to logfiles. This flag obsoletes --alsologtostderr.");
128
129GLOG_DEFINE_string(alsologtoemail, "",
130 "log messages go to these email addresses "
131 "in addition to logfiles");
132GLOG_DEFINE_bool(log_prefix, true,
133 "Prepend the log prefix to the start of each log line");
134GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
135 "actually get logged anywhere");
136GLOG_DEFINE_int32(logbuflevel, 0,
137 "Buffer log messages logged at this level or lower"
138 " (-1 means don't buffer; 0 means buffer INFO only;"
139 " ...)");
140GLOG_DEFINE_int32(logbufsecs, 30,
141 "Buffer log messages for at most this many seconds");
142GLOG_DEFINE_int32(logemaillevel, 999,
143 "Email log messages logged at this level or higher"
144 " (0 means email all; 3 means email FATAL only;"
145 " ...)");
146GLOG_DEFINE_string(logmailer, "/bin/mail",
147 "Mailer used to send logging email");
148
149// Compute the default value for --log_dir
150static const char* DefaultLogDir() {
151 const char* env;
152 env = getenv("GOOGLE_LOG_DIR");
153 if (env != NULL && env[0] != '\0') {
154 return env;
155 }
156 env = getenv("TEST_TMPDIR");
157 if (env != NULL && env[0] != '\0') {
158 return env;
159 }
160 return "";
161}
162
163GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions.");
164
165GLOG_DEFINE_string(log_dir, DefaultLogDir(),
166 "If specified, logfiles are written into this directory instead "
167 "of the default logging directory.");
168GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
169 "files in this directory");
170
171GLOG_DEFINE_int32(max_log_size, 1800,
172 "approx. maximum log file size (in MB). A value of 0 will "
173 "be silently overridden to 1.");
174
175GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
176 "Stop attempting to log to disk if the disk is full.");
177
178GLOG_DEFINE_string(log_backtrace_at, "",
179 "Emit a backtrace when logging at file:linenum.");
180
181// TODO(hamaji): consider windows
182#define PATH_SEPARATOR '/'
183
184#ifndef HAVE_PREAD
185#if defined(OS_WINDOWS)
186#include <basetsd.h>
187#define ssize_t SSIZE_T
188#endif
189static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
190 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
191 if (orig_offset == (off_t)-1)
192 return -1;
193 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
194 return -1;
195 ssize_t len = read(fd, buf, count);
196 if (len < 0)
197 return len;
198 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
199 return -1;
200 return len;
201}
202#endif // !HAVE_PREAD
203
204#ifndef HAVE_PWRITE
205static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
206 off_t orig_offset = lseek(fd, 0, SEEK_CUR);
207 if (orig_offset == (off_t)-1)
208 return -1;
209 if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
210 return -1;
211 ssize_t len = write(fd, buf, count);
212 if (len < 0)
213 return len;
214 if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
215 return -1;
216 return len;
217}
218#endif // !HAVE_PWRITE
219
220static void GetHostName(string* hostname) {
221#if defined(HAVE_SYS_UTSNAME_H)
222 struct utsname buf;
223 if (0 != uname(&buf)) {
224 // ensure null termination on failure
225 *buf.nodename = '\0';
226 }
227 *hostname = buf.nodename;
228#elif defined(OS_WINDOWS)
229 char buf[MAX_COMPUTERNAME_LENGTH + 1];
230 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
231 if (GetComputerNameA(buf, &len)) {
232 *hostname = buf;
233 } else {
234 hostname->clear();
235 }
236#else
237# warning There is no way to retrieve the host name.
238 *hostname = "(unknown)";
239#endif
240}
241
242// Returns true iff terminal supports using colors in output.
243static bool TerminalSupportsColor() {
244 bool term_supports_color = false;
245#ifdef OS_WINDOWS
246 // on Windows TERM variable is usually not set, but the console does
247 // support colors.
248 term_supports_color = true;
249#else
250 // On non-Windows platforms, we rely on the TERM variable.
251 const char* const term = getenv("TERM");
252 if (term != NULL && term[0] != '\0') {
253 term_supports_color =
254 !strcmp(term, "xterm") ||
255 !strcmp(term, "xterm-color") ||
256 !strcmp(term, "xterm-256color") ||
257 !strcmp(term, "screen-256color") ||
258 !strcmp(term, "konsole") ||
259 !strcmp(term, "konsole-16color") ||
260 !strcmp(term, "konsole-256color") ||
261 !strcmp(term, "screen") ||
262 !strcmp(term, "linux") ||
263 !strcmp(term, "cygwin");
264 }
265#endif
266 return term_supports_color;
267}
268
269_START_GOOGLE_NAMESPACE_
270
271enum GLogColor {
272 COLOR_DEFAULT,
273 COLOR_RED,
274 COLOR_GREEN,
275 COLOR_YELLOW
276};
277
278static GLogColor SeverityToColor(LogSeverity severity) {
279 assert(severity >= 0 && severity < NUM_SEVERITIES);
280 GLogColor color = COLOR_DEFAULT;
281 switch (severity) {
282 case GLOG_INFO:
283 color = COLOR_DEFAULT;
284 break;
285 case GLOG_WARNING:
286 color = COLOR_YELLOW;
287 break;
288 case GLOG_ERROR:
289 case GLOG_FATAL:
290 color = COLOR_RED;
291 break;
292 default:
293 // should never get here.
294 assert(false);
295 }
296 return color;
297}
298
299#ifdef OS_WINDOWS
300
301// Returns the character attribute for the given color.
302static WORD GetColorAttribute(GLogColor color) {
303 switch (color) {
304 case COLOR_RED: return FOREGROUND_RED;
305 case COLOR_GREEN: return FOREGROUND_GREEN;
306 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
307 default: return 0;
308 }
309}
310
311#else
312
313// Returns the ANSI color code for the given color.
314static const char* GetAnsiColorCode(GLogColor color) {
315 switch (color) {
316 case COLOR_RED: return "1";
317 case COLOR_GREEN: return "2";
318 case COLOR_YELLOW: return "3";
319 case COLOR_DEFAULT: return "";
320 };
321 return NULL; // stop warning about return type.
322}
323
324#endif // OS_WINDOWS
325
326// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
327static int32 MaxLogSize() {
328 return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
329}
330
331// An arbitrary limit on the length of a single log message. This
332// is so that streaming can be done more efficiently.
333const size_t LogMessage::kMaxLogMessageLen = 30000;
334
335struct LogMessage::LogMessageData {
336 LogMessageData();
337
338 int preserved_errno_; // preserved errno
339 // Buffer space; contains complete message text.
340 char message_text_[LogMessage::kMaxLogMessageLen+1];
341 LogStream stream_;
342 char severity_; // What level is this LogMessage logged at?
343 int line_; // line number where logging call is.
344 void (LogMessage::*send_method_)(); // Call this in destructor to send
345 union { // At most one of these is used: union to keep the size low.
346 LogSink* sink_; // NULL or sink to send message to
347 std::vector<std::string>* outvec_; // NULL or vector to push message onto
348 std::string* message_; // NULL or string to write message into
349 };
350 time_t timestamp_; // Time of creation of LogMessage
351 struct ::tm tm_time_; // Time of creation of LogMessage
352 size_t num_prefix_chars_; // # of chars of prefix in this message
353 size_t num_chars_to_log_; // # of chars of msg to send to log
354 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
355 const char* basename_; // basename of file that called LOG
356 const char* fullname_; // fullname of file that called LOG
357 bool has_been_flushed_; // false => data has not been flushed
358 bool first_fatal_; // true => this was first fatal msg
359
360 private:
361 LogMessageData(const LogMessageData&);
362 void operator=(const LogMessageData&);
363};
364
365// A mutex that allows only one thread to log at a time, to keep things from
366// getting jumbled. Some other very uncommon logging operations (like
367// changing the destination file for log messages of a given severity) also
368// lock this mutex. Please be sure that anybody who might possibly need to
369// lock it does so.
370static Mutex log_mutex;
371
372// Number of messages sent at each severity. Under log_mutex.
373int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
374
375// Globally disable log writing (if disk is full)
376static bool stop_writing = false;
377
378const char*const LogSeverityNames[NUM_SEVERITIES] = {
379 "INFO", "WARNING", "ERROR", "FATAL"
380};
381
382// Has the user called SetExitOnDFatal(true)?
383static bool exit_on_dfatal = true;
384
385const char* GetLogSeverityName(LogSeverity severity) {
386 return LogSeverityNames[severity];
387}
388
389static bool SendEmailInternal(const char*dest, const char *subject,
390 const char*body, bool use_logging);
391
392base::Logger::~Logger() {
393}
394
395namespace {
396
397// Encapsulates all file-system related state
398class LogFileObject : public base::Logger {
399 public:
400 LogFileObject(LogSeverity severity, const char* base_filename);
401 ~LogFileObject();
402
403 virtual void Write(bool force_flush, // Should we force a flush here?
404 time_t timestamp, // Timestamp for this entry
405 const char* message,
406 int message_len);
407
408 // Configuration options
409 void SetBasename(const char* basename);
410 void SetExtension(const char* ext);
411 void SetSymlinkBasename(const char* symlink_basename);
412
413 // Normal flushing routine
414 virtual void Flush();
415
416 // It is the actual file length for the system loggers,
417 // i.e., INFO, ERROR, etc.
418 virtual uint32 LogSize() {
419 MutexLock l(&lock_);
420 return file_length_;
421 }
422
423 // Internal flush routine. Exposed so that FlushLogFilesUnsafe()
424 // can avoid grabbing a lock. Usually Flush() calls it after
425 // acquiring lock_.
426 void FlushUnlocked();
427
428 private:
429 static const uint32 kRolloverAttemptFrequency = 0x20;
430
431 Mutex lock_;
432 bool base_filename_selected_;
433 string base_filename_;
434 string symlink_basename_;
435 string filename_extension_; // option users can specify (eg to add port#)
436 FILE* file_;
437 LogSeverity severity_;
438 uint32 bytes_since_flush_;
439 uint32 dropped_mem_length_;
440 uint32 file_length_;
441 unsigned int rollover_attempt_;
442 int64 next_flush_time_; // cycle count at which to flush log
443
444 // Actually create a logfile using the value of base_filename_ and the
445 // supplied argument time_pid_string
446 // REQUIRES: lock_ is held
447 bool CreateLogfile(const string& time_pid_string);
448};
449
450} // namespace
451
452class LogDestination {
453 public:
454 friend class LogMessage;
455 friend void ReprintFatalMessage();
456 friend base::Logger* base::GetLogger(LogSeverity);
457 friend void base::SetLogger(LogSeverity, base::Logger*);
458
459 // These methods are just forwarded to by their global versions.
460 static void SetLogDestination(LogSeverity severity,
461 const char* base_filename);
462 static void SetLogSymlink(LogSeverity severity,
463 const char* symlink_basename);
464 static void AddLogSink(LogSink *destination);
465 static void RemoveLogSink(LogSink *destination);
466 static void SetLogFilenameExtension(const char* filename_extension);
467 static void SetStderrLogging(LogSeverity min_severity);
468 static void SetEmailLogging(LogSeverity min_severity, const char* addresses);
469 static void LogToStderr();
470 // Flush all log files that are at least at the given severity level
471 static void FlushLogFiles(int min_severity);
472 static void FlushLogFilesUnsafe(int min_severity);
473
474 // we set the maximum size of our packet to be 1400, the logic being
475 // to prevent fragmentation.
476 // Really this number is arbitrary.
477 static const int kNetworkBytes = 1400;
478
479 static const string& hostname();
480 static const bool& terminal_supports_color() {
481 return terminal_supports_color_;
482 }
483
484 static void DeleteLogDestinations();
485
486 private:
487 LogDestination(LogSeverity severity, const char* base_filename);
488 ~LogDestination() { }
489
490 // Take a log message of a particular severity and log it to stderr
491 // iff it's of a high enough severity to deserve it.
492 static void MaybeLogToStderr(LogSeverity severity, const char* message,
493 size_t len);
494
495 // Take a log message of a particular severity and log it to email
496 // iff it's of a high enough severity to deserve it.
497 static void MaybeLogToEmail(LogSeverity severity, const char* message,
498 size_t len);
499 // Take a log message of a particular severity and log it to a file
500 // iff the base filename is not "" (which means "don't log to me")
501 static void MaybeLogToLogfile(LogSeverity severity,
502 time_t timestamp,
503 const char* message, size_t len);
504 // Take a log message of a particular severity and log it to the file
505 // for that severity and also for all files with severity less than
506 // this severity.
507 static void LogToAllLogfiles(LogSeverity severity,
508 time_t timestamp,
509 const char* message, size_t len);
510
511 // Send logging info to all registered sinks.
512 static void LogToSinks(LogSeverity severity,
513 const char *full_filename,
514 const char *base_filename,
515 int line,
516 const struct ::tm* tm_time,
517 const char* message,
518 size_t message_len);
519
520 // Wait for all registered sinks via WaitTillSent
521 // including the optional one in "data".
522 static void WaitForSinks(LogMessage::LogMessageData* data);
523
524 static LogDestination* log_destination(LogSeverity severity);
525
526 LogFileObject fileobject_;
527 base::Logger* logger_; // Either &fileobject_, or wrapper around it
528
529 static LogDestination* log_destinations_[NUM_SEVERITIES];
530 static LogSeverity email_logging_severity_;
531 static string addresses_;
532 static string hostname_;
533 static bool terminal_supports_color_;
534
535 // arbitrary global logging destinations.
536 static vector<LogSink*>* sinks_;
537
538 // Protects the vector sinks_,
539 // but not the LogSink objects its elements reference.
540 static Mutex sink_mutex_;
541
542 // Disallow
543 LogDestination(const LogDestination&);
544 LogDestination& operator=(const LogDestination&);
545};
546
547// Errors do not get logged to email by default.
548LogSeverity LogDestination::email_logging_severity_ = 99999;
549
550string LogDestination::addresses_;
551string LogDestination::hostname_;
552
553vector<LogSink*>* LogDestination::sinks_ = NULL;
554Mutex LogDestination::sink_mutex_;
555bool LogDestination::terminal_supports_color_ = TerminalSupportsColor();
556
557/* static */
558const string& LogDestination::hostname() {
559 if (hostname_.empty()) {
560 GetHostName(&hostname_);
561 if (hostname_.empty()) {
562 hostname_ = "(unknown)";
563 }
564 }
565 return hostname_;
566}
567
568LogDestination::LogDestination(LogSeverity severity,
569 const char* base_filename)
570 : fileobject_(severity, base_filename),
571 logger_(&fileobject_) {
572}
573
574inline void LogDestination::FlushLogFilesUnsafe(int min_severity) {
575 // assume we have the log_mutex or we simply don't care
576 // about it
577 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
578 LogDestination* log = log_destinations_[i];
579 if (log != NULL) {
580 // Flush the base fileobject_ logger directly instead of going
581 // through any wrappers to reduce chance of deadlock.
582 log->fileobject_.FlushUnlocked();
583 }
584 }
585}
586
587inline void LogDestination::FlushLogFiles(int min_severity) {
588 // Prevent any subtle race conditions by wrapping a mutex lock around
589 // all this stuff.
590 MutexLock l(&log_mutex);
591 for (int i = min_severity; i < NUM_SEVERITIES; i++) {
592 LogDestination* log = log_destination(i);
593 if (log != NULL) {
594 log->logger_->Flush();
595 }
596 }
597}
598
599inline void LogDestination::SetLogDestination(LogSeverity severity,
600 const char* base_filename) {
601 assert(severity >= 0 && severity < NUM_SEVERITIES);
602 // Prevent any subtle race conditions by wrapping a mutex lock around
603 // all this stuff.
604 MutexLock l(&log_mutex);
605 log_destination(severity)->fileobject_.SetBasename(base_filename);
606}
607
608inline void LogDestination::SetLogSymlink(LogSeverity severity,
609 const char* symlink_basename) {
610 CHECK_GE(severity, 0);
611 CHECK_LT(severity, NUM_SEVERITIES);
612 MutexLock l(&log_mutex);
613 log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename);
614}
615
616inline void LogDestination::AddLogSink(LogSink *destination) {
617 // Prevent any subtle race conditions by wrapping a mutex lock around
618 // all this stuff.
619 MutexLock l(&sink_mutex_);
620 if (!sinks_) sinks_ = new vector<LogSink*>;
621 sinks_->push_back(destination);
622}
623
624inline void LogDestination::RemoveLogSink(LogSink *destination) {
625 // Prevent any subtle race conditions by wrapping a mutex lock around
626 // all this stuff.
627 MutexLock l(&sink_mutex_);
628 // This doesn't keep the sinks in order, but who cares?
629 if (sinks_) {
630 for (int i = sinks_->size() - 1; i >= 0; i--) {
631 if ((*sinks_)[i] == destination) {
632 (*sinks_)[i] = (*sinks_)[sinks_->size() - 1];
633 sinks_->pop_back();
634 break;
635 }
636 }
637 }
638}
639
640inline void LogDestination::SetLogFilenameExtension(const char* ext) {
641 // Prevent any subtle race conditions by wrapping a mutex lock around
642 // all this stuff.
643 MutexLock l(&log_mutex);
644 for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) {
645 log_destination(severity)->fileobject_.SetExtension(ext);
646 }
647}
648
649inline void LogDestination::SetStderrLogging(LogSeverity min_severity) {
650 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
651 // Prevent any subtle race conditions by wrapping a mutex lock around
652 // all this stuff.
653 MutexLock l(&log_mutex);
654 FLAGS_stderrthreshold = min_severity;
655}
656
657inline void LogDestination::LogToStderr() {
658 // *Don't* put this stuff in a mutex lock, since SetStderrLogging &
659 // SetLogDestination already do the locking!
660 SetStderrLogging(0); // thus everything is "also" logged to stderr
661 for ( int i = 0; i < NUM_SEVERITIES; ++i ) {
662 SetLogDestination(i, ""); // "" turns off logging to a logfile
663 }
664}
665
666inline void LogDestination::SetEmailLogging(LogSeverity min_severity,
667 const char* addresses) {
668 assert(min_severity >= 0 && min_severity < NUM_SEVERITIES);
669 // Prevent any subtle race conditions by wrapping a mutex lock around
670 // all this stuff.
671 MutexLock l(&log_mutex);
672 LogDestination::email_logging_severity_ = min_severity;
673 LogDestination::addresses_ = addresses;
674}
675
676static void ColoredWriteToStderr(LogSeverity severity,
677 const char* message, size_t len) {
678 const GLogColor color =
679 (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ?
680 SeverityToColor(severity) : COLOR_DEFAULT;
681
682 // Avoid using cerr from this module since we may get called during
683 // exit code, and cerr may be partially or fully destroyed by then.
684 if (COLOR_DEFAULT == color) {
685 fwrite(message, len, 1, stderr);
686 return;
687 }
688#ifdef OS_WINDOWS
689 const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
690
691 // Gets the current text color.
692 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
693 GetConsoleScreenBufferInfo(stderr_handle, &buffer_info);
694 const WORD old_color_attrs = buffer_info.wAttributes;
695
696 // We need to flush the stream buffers into the console before each
697 // SetConsoleTextAttribute call lest it affect the text that is already
698 // printed but has not yet reached the console.
699 fflush(stderr);
700 SetConsoleTextAttribute(stderr_handle,
701 GetColorAttribute(color) | FOREGROUND_INTENSITY);
702 fwrite(message, len, 1, stderr);
703 fflush(stderr);
704 // Restores the text color.
705 SetConsoleTextAttribute(stderr_handle, old_color_attrs);
706#else
707 fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color));
708 fwrite(message, len, 1, stderr);
709 fprintf(stderr, "\033[m"); // Resets the terminal to default.
710#endif // OS_WINDOWS
711}
712
713static void WriteToStderr(const char* message, size_t len) {
714 // Avoid using cerr from this module since we may get called during
715 // exit code, and cerr may be partially or fully destroyed by then.
716 fwrite(message, len, 1, stderr);
717}
718
719inline void LogDestination::MaybeLogToStderr(LogSeverity severity,
720 const char* message, size_t len) {
721 if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) {
722 ColoredWriteToStderr(severity, message, len);
723#ifdef OS_WINDOWS
724 // On Windows, also output to the debugger
725 ::OutputDebugStringA(string(message,len).c_str());
726#endif
727 }
728}
729
730
731inline void LogDestination::MaybeLogToEmail(LogSeverity severity,
732 const char* message, size_t len) {
733 if (severity >= email_logging_severity_ ||
734 severity >= FLAGS_logemaillevel) {
735 string to(FLAGS_alsologtoemail);
736 if (!addresses_.empty()) {
737 if (!to.empty()) {
738 to += ",";
739 }
740 to += addresses_;
741 }
742 const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " +
743 glog_internal_namespace_::ProgramInvocationShortName());
744 string body(hostname());
745 body += "\n\n";
746 body.append(message, len);
747
748 // should NOT use SendEmail(). The caller of this function holds the
749 // log_mutex and SendEmail() calls LOG/VLOG which will block trying to
750 // acquire the log_mutex object. Use SendEmailInternal() and set
751 // use_logging to false.
752 SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false);
753 }
754}
755
756
757inline void LogDestination::MaybeLogToLogfile(LogSeverity severity,
758 time_t timestamp,
759 const char* message,
760 size_t len) {
761 const bool should_flush = severity > FLAGS_logbuflevel;
762 LogDestination* destination = log_destination(severity);
763 destination->logger_->Write(should_flush, timestamp, message, len);
764}
765
766inline void LogDestination::LogToAllLogfiles(LogSeverity severity,
767 time_t timestamp,
768 const char* message,
769 size_t len) {
770
771 if ( FLAGS_logtostderr ) { // global flag: never log to file
772 ColoredWriteToStderr(severity, message, len);
773 } else {
774 for (int i = severity; i >= 0; --i)
775 LogDestination::MaybeLogToLogfile(i, timestamp, message, len);
776 }
777}
778
779inline void LogDestination::LogToSinks(LogSeverity severity,
780 const char *full_filename,
781 const char *base_filename,
782 int line,
783 const struct ::tm* tm_time,
784 const char* message,
785 size_t message_len) {
786 ReaderMutexLock l(&sink_mutex_);
787 if (sinks_) {
788 for (int i = sinks_->size() - 1; i >= 0; i--) {
789 (*sinks_)[i]->send(severity, full_filename, base_filename,
790 line, tm_time, message, message_len);
791 }
792 }
793}
794
795inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
796 ReaderMutexLock l(&sink_mutex_);
797 if (sinks_) {
798 for (int i = sinks_->size() - 1; i >= 0; i--) {
799 (*sinks_)[i]->WaitTillSent();
800 }
801 }
802 const bool send_to_sink =
803 (data->send_method_ == &LogMessage::SendToSink) ||
804 (data->send_method_ == &LogMessage::SendToSinkAndLog);
805 if (send_to_sink && data->sink_ != NULL) {
806 data->sink_->WaitTillSent();
807 }
808}
809
810LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
811
812inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
813 assert(severity >=0 && severity < NUM_SEVERITIES);
814 if (!log_destinations_[severity]) {
815 log_destinations_[severity] = new LogDestination(severity, NULL);
816 }
817 return log_destinations_[severity];
818}
819
820void LogDestination::DeleteLogDestinations() {
821 for (int severity = 0; severity < NUM_SEVERITIES; ++severity) {
822 delete log_destinations_[severity];
823 log_destinations_[severity] = NULL;
824 }
825 MutexLock l(&sink_mutex_);
826 delete sinks_;
827 sinks_ = NULL;
828}
829
830namespace {
831
832LogFileObject::LogFileObject(LogSeverity severity,
833 const char* base_filename)
834 : base_filename_selected_(base_filename != NULL),
835 base_filename_((base_filename != NULL) ? base_filename : ""),
836 symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
837 filename_extension_(),
838 file_(NULL),
839 severity_(severity),
840 bytes_since_flush_(0),
841 dropped_mem_length_(0),
842 file_length_(0),
843 rollover_attempt_(kRolloverAttemptFrequency-1),
844 next_flush_time_(0) {
845 assert(severity >= 0);
846 assert(severity < NUM_SEVERITIES);
847}
848
849LogFileObject::~LogFileObject() {
850 MutexLock l(&lock_);
851 if (file_ != NULL) {
852 fclose(file_);
853 file_ = NULL;
854 }
855}
856
857void LogFileObject::SetBasename(const char* basename) {
858 MutexLock l(&lock_);
859 base_filename_selected_ = true;
860 if (base_filename_ != basename) {
861 // Get rid of old log file since we are changing names
862 if (file_ != NULL) {
863 fclose(file_);
864 file_ = NULL;
865 rollover_attempt_ = kRolloverAttemptFrequency-1;
866 }
867 base_filename_ = basename;
868 }
869}
870
871void LogFileObject::SetExtension(const char* ext) {
872 MutexLock l(&lock_);
873 if (filename_extension_ != ext) {
874 // Get rid of old log file since we are changing names
875 if (file_ != NULL) {
876 fclose(file_);
877 file_ = NULL;
878 rollover_attempt_ = kRolloverAttemptFrequency-1;
879 }
880 filename_extension_ = ext;
881 }
882}
883
884void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
885 MutexLock l(&lock_);
886 symlink_basename_ = symlink_basename;
887}
888
889void LogFileObject::Flush() {
890 MutexLock l(&lock_);
891 FlushUnlocked();
892}
893
894void LogFileObject::FlushUnlocked(){
895 if (file_ != NULL) {
896 fflush(file_);
897 bytes_since_flush_ = 0;
898 }
899 // Figure out when we are due for another flush.
900 const int64 next = (FLAGS_logbufsecs
901 * static_cast<int64>(1000000)); // in usec
902 next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
903}
904
905bool LogFileObject::CreateLogfile(const string& time_pid_string) {
906 string string_filename = base_filename_+filename_extension_+
907 time_pid_string;
908 const char* filename = string_filename.c_str();
909 int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, FLAGS_logfile_mode);
910 if (fd == -1) return false;
911#ifdef HAVE_FCNTL
912 // Mark the file close-on-exec. We don't really care if this fails
913 fcntl(fd, F_SETFD, FD_CLOEXEC);
914#endif
915
916 file_ = fdopen(fd, "a"); // Make a FILE*.
917 if (file_ == NULL) { // Man, we're screwed!
918 close(fd);
919 unlink(filename); // Erase the half-baked evidence: an unusable log file
920 return false;
921 }
922
923 // We try to create a symlink called <program_name>.<severity>,
924 // which is easier to use. (Every time we create a new logfile,
925 // we destroy the old symlink and create a new one, so it always
926 // points to the latest logfile.) If it fails, we're sad but it's
927 // no error.
928 if (!symlink_basename_.empty()) {
929 // take directory from filename
930 const char* slash = strrchr(filename, PATH_SEPARATOR);
931 const string linkname =
932 symlink_basename_ + '.' + LogSeverityNames[severity_];
933 string linkpath;
934 if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname
935 linkpath += linkname;
936 unlink(linkpath.c_str()); // delete old one if it exists
937
938#if defined(OS_WINDOWS)
939 // TODO(hamaji): Create lnk file on Windows?
940#elif defined(HAVE_UNISTD_H)
941 // We must have unistd.h.
942 // Make the symlink be relative (in the same dir) so that if the
943 // entire log directory gets relocated the link is still valid.
944 const char *linkdest = slash ? (slash + 1) : filename;
945 if (symlink(linkdest, linkpath.c_str()) != 0) {
946 // silently ignore failures
947 }
948
949 // Make an additional link to the log file in a place specified by
950 // FLAGS_log_link, if indicated
951 if (!FLAGS_log_link.empty()) {
952 linkpath = FLAGS_log_link + "/" + linkname;
953 unlink(linkpath.c_str()); // delete old one if it exists
954 if (symlink(filename, linkpath.c_str()) != 0) {
955 // silently ignore failures
956 }
957 }
958#endif
959 }
960
961 return true; // Everything worked
962}
963
964void LogFileObject::Write(bool force_flush,
965 time_t timestamp,
966 const char* message,
967 int message_len) {
968 MutexLock l(&lock_);
969
970 // We don't log if the base_name_ is "" (which means "don't write")
971 if (base_filename_selected_ && base_filename_.empty()) {
972 return;
973 }
974
975 if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
976 PidHasChanged()) {
977 if (file_ != NULL) fclose(file_);
978 file_ = NULL;
979 file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0;
980 rollover_attempt_ = kRolloverAttemptFrequency-1;
981 }
982
983 // If there's no destination file, make one before outputting
984 if (file_ == NULL) {
985 // Try to rollover the log file every 32 log messages. The only time
986 // this could matter would be when we have trouble creating the log
987 // file. If that happens, we'll lose lots of log messages, of course!
988 if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
989 rollover_attempt_ = 0;
990
991 struct ::tm tm_time;
992 localtime_r(&timestamp, &tm_time);
993
994 // The logfile's filename will have the date/time & pid in it
995 ostringstream time_pid_stream;
996 time_pid_stream.fill('0');
997 time_pid_stream << 1900+tm_time.tm_year
998 << setw(2) << 1+tm_time.tm_mon
999 << setw(2) << tm_time.tm_mday
1000 << '-'
1001 << setw(2) << tm_time.tm_hour
1002 << setw(2) << tm_time.tm_min
1003 << setw(2) << tm_time.tm_sec
1004 << '.'
1005 << GetMainThreadPid();
1006 const string& time_pid_string = time_pid_stream.str();
1007
1008 if (base_filename_selected_) {
1009 if (!CreateLogfile(time_pid_string)) {
1010 perror("Could not create log file");
1011 fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
1012 time_pid_string.c_str());
1013 return;
1014 }
1015 } else {
1016 // If no base filename for logs of this severity has been set, use a
1017 // default base filename of
1018 // "<program name>.<hostname>.<user name>.log.<severity level>.". So
1019 // logfiles will have names like
1020 // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1021 // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1022 // and 4354 is the pid of the logging process. The date & time reflect
1023 // when the file was created for output.
1024 //
1025 // Where does the file get put? Successively try the directories
1026 // "/tmp", and "."
1027 string stripped_filename(
1028 glog_internal_namespace_::ProgramInvocationShortName());
1029 string hostname;
1030 GetHostName(&hostname);
1031
1032 string uidname = MyUserName();
1033 // We should not call CHECK() here because this function can be
1034 // called after holding on to log_mutex. We don't want to
1035 // attempt to hold on to the same mutex, and get into a
1036 // deadlock. Simply use a name like invalid-user.
1037 if (uidname.empty()) uidname = "invalid-user";
1038
1039 stripped_filename = stripped_filename+'.'+hostname+'.'
1040 +uidname+".log."
1041 +LogSeverityNames[severity_]+'.';
1042 // We're going to (potentially) try to put logs in several different dirs
1043 const vector<string> & log_dirs = GetLoggingDirectories();
1044
1045 // Go through the list of dirs, and try to create the log file in each
1046 // until we succeed or run out of options
1047 bool success = false;
1048 for (vector<string>::const_iterator dir = log_dirs.begin();
1049 dir != log_dirs.end();
1050 ++dir) {
1051 base_filename_ = *dir + "/" + stripped_filename;
1052 if ( CreateLogfile(time_pid_string) ) {
1053 success = true;
1054 break;
1055 }
1056 }
1057 // If we never succeeded, we have to give up
1058 if ( success == false ) {
1059 perror("Could not create logging file");
1060 fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1061 time_pid_string.c_str());
1062 return;
1063 }
1064 }
1065
1066 // Write a header message into the log file
1067 ostringstream file_header_stream;
1068 file_header_stream.fill('0');
1069 file_header_stream << "Log file created at: "
1070 << 1900+tm_time.tm_year << '/'
1071 << setw(2) << 1+tm_time.tm_mon << '/'
1072 << setw(2) << tm_time.tm_mday
1073 << ' '
1074 << setw(2) << tm_time.tm_hour << ':'
1075 << setw(2) << tm_time.tm_min << ':'
1076 << setw(2) << tm_time.tm_sec << '\n'
1077 << "Running on machine: "
1078 << LogDestination::hostname() << '\n'
1079 << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1080 << "threadid file:line] msg" << '\n';
1081 const string& file_header_string = file_header_stream.str();
1082
1083 const int header_len = file_header_string.size();
1084 fwrite(file_header_string.data(), 1, header_len, file_);
1085 file_length_ += header_len;
1086 bytes_since_flush_ += header_len;
1087 }
1088
1089 // Write to LOG file
1090 if ( !stop_writing ) {
1091 // fwrite() doesn't return an error when the disk is full, for
1092 // messages that are less than 4096 bytes. When the disk is full,
1093 // it returns the message length for messages that are less than
1094 // 4096 bytes. fwrite() returns 4096 for message lengths that are
1095 // greater than 4096, thereby indicating an error.
1096 errno = 0;
1097 fwrite(message, 1, message_len, file_);
1098 if ( FLAGS_stop_logging_if_full_disk &&
1099 errno == ENOSPC ) { // disk full, stop writing to disk
1100 stop_writing = true; // until the disk is
1101 return;
1102 } else {
1103 file_length_ += message_len;
1104 bytes_since_flush_ += message_len;
1105 }
1106 } else {
1107 if ( CycleClock_Now() >= next_flush_time_ )
1108 stop_writing = false; // check to see if disk has free space.
1109 return; // no need to flush
1110 }
1111
1112 // See important msgs *now*. Also, flush logs at least every 10^6 chars,
1113 // or every "FLAGS_logbufsecs" seconds.
1114 if ( force_flush ||
1115 (bytes_since_flush_ >= 1000000) ||
1116 (CycleClock_Now() >= next_flush_time_) ) {
1117 FlushUnlocked();
1118#ifdef OS_LINUX
1119 // Only consider files >= 3MiB
1120 if (FLAGS_drop_log_memory && file_length_ >= (3 << 20)) {
1121 // Don't evict the most recent 1-2MiB so as not to impact a tailer
1122 // of the log file and to avoid page rounding issue on linux < 4.7
1123 uint32 total_drop_length = (file_length_ & ~((1 << 20) - 1)) - (1 << 20);
1124 uint32 this_drop_length = total_drop_length - dropped_mem_length_;
1125 if (this_drop_length >= (2 << 20)) {
1126 // Only advise when >= 2MiB to drop
1127 posix_fadvise(fileno(file_), dropped_mem_length_, this_drop_length,
1128 POSIX_FADV_DONTNEED);
1129 dropped_mem_length_ = total_drop_length;
1130 }
1131 }
1132#endif
1133 }
1134}
1135
1136} // namespace
1137
1138
1139// Static log data space to avoid alloc failures in a LOG(FATAL)
1140//
1141// Since multiple threads may call LOG(FATAL), and we want to preserve
1142// the data from the first call, we allocate two sets of space. One
1143// for exclusive use by the first thread, and one for shared use by
1144// all other threads.
1145static Mutex fatal_msg_lock;
1146static CrashReason crash_reason;
1147static bool fatal_msg_exclusive = true;
1148static LogMessage::LogMessageData fatal_msg_data_exclusive;
1149static LogMessage::LogMessageData fatal_msg_data_shared;
1150
1151#ifdef GLOG_THREAD_LOCAL_STORAGE
1152// Static thread-local log data space to use, because typically at most one
1153// LogMessageData object exists (in this case glog makes zero heap memory
1154// allocations).
1155static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true;
1156
1157#ifdef HAVE_ALIGNED_STORAGE
1158static GLOG_THREAD_LOCAL_STORAGE
1159 std::aligned_storage<sizeof(LogMessage::LogMessageData),
1160 alignof(LogMessage::LogMessageData)>::type thread_msg_data;
1161#else
1162static GLOG_THREAD_LOCAL_STORAGE
1163 char thread_msg_data[sizeof(void*) + sizeof(LogMessage::LogMessageData)];
1164#endif // HAVE_ALIGNED_STORAGE
1165#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1166
1167LogMessage::LogMessageData::LogMessageData()
1168 : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1169}
1170
1171LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1172 int ctr, void (LogMessage::*send_method)())
1173 : allocated_(NULL) {
1174 Init(file, line, severity, send_method);
1175 data_->stream_.set_ctr(ctr);
1176}
1177
1178LogMessage::LogMessage(const char* file, int line,
1179 const CheckOpString& result)
1180 : allocated_(NULL) {
1181 Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1182 stream() << "Check failed: " << (*result.str_) << " ";
1183}
1184
1185LogMessage::LogMessage(const char* file, int line)
1186 : allocated_(NULL) {
1187 Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1188}
1189
1190LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1191 : allocated_(NULL) {
1192 Init(file, line, severity, &LogMessage::SendToLog);
1193}
1194
1195LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1196 LogSink* sink, bool also_send_to_log)
1197 : allocated_(NULL) {
1198 Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1199 &LogMessage::SendToSink);
1200 data_->sink_ = sink; // override Init()'s setting to NULL
1201}
1202
1203LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1204 vector<string> *outvec)
1205 : allocated_(NULL) {
1206 Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1207 data_->outvec_ = outvec; // override Init()'s setting to NULL
1208}
1209
1210LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1211 string *message)
1212 : allocated_(NULL) {
1213 Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1214 data_->message_ = message; // override Init()'s setting to NULL
1215}
1216
1217void LogMessage::Init(const char* file,
1218 int line,
1219 LogSeverity severity,
1220 void (LogMessage::*send_method)()) {
1221 allocated_ = NULL;
1222 if (severity != GLOG_FATAL || !exit_on_dfatal) {
1223#ifdef GLOG_THREAD_LOCAL_STORAGE
1224 // No need for locking, because this is thread local.
1225 if (thread_data_available) {
1226 thread_data_available = false;
1227#ifdef HAVE_ALIGNED_STORAGE
1228 data_ = new (&thread_msg_data) LogMessageData;
1229#else
1230 const uintptr_t kAlign = sizeof(void*) - 1;
1231
1232 char* align_ptr =
1233 reinterpret_cast<char*>(reinterpret_cast<uintptr_t>(thread_msg_data + kAlign) & ~kAlign);
1234 data_ = new (align_ptr) LogMessageData;
1235 assert(reinterpret_cast<uintptr_t>(align_ptr) % sizeof(void*) == 0);
1236#endif
1237 } else {
1238 allocated_ = new LogMessageData();
1239 data_ = allocated_;
1240 }
1241#else // !defined(GLOG_THREAD_LOCAL_STORAGE)
1242 allocated_ = new LogMessageData();
1243 data_ = allocated_;
1244#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1245 data_->first_fatal_ = false;
1246 } else {
1247 MutexLock l(&fatal_msg_lock);
1248 if (fatal_msg_exclusive) {
1249 fatal_msg_exclusive = false;
1250 data_ = &fatal_msg_data_exclusive;
1251 data_->first_fatal_ = true;
1252 } else {
1253 data_ = &fatal_msg_data_shared;
1254 data_->first_fatal_ = false;
1255 }
1256 }
1257
1258 stream().fill('0');
1259 data_->preserved_errno_ = errno;
1260 data_->severity_ = severity;
1261 data_->line_ = line;
1262 data_->send_method_ = send_method;
1263 data_->sink_ = NULL;
1264 data_->outvec_ = NULL;
1265 WallTime now = WallTime_Now();
1266 data_->timestamp_ = static_cast<time_t>(now);
1267 localtime_r(&data_->timestamp_, &data_->tm_time_);
1268 int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1269 RawLog__SetLastTime(data_->tm_time_, usecs);
1270
1271 data_->num_chars_to_log_ = 0;
1272 data_->num_chars_to_syslog_ = 0;
1273 data_->basename_ = const_basename(file);
1274 data_->fullname_ = file;
1275 data_->has_been_flushed_ = false;
1276
1277 // If specified, prepend a prefix to each line. For example:
1278 // I1018 160715 f5d4fbb0 logging.cc:1153]
1279 // (log level, GMT month, date, time, thread_id, file basename, line)
1280 // We exclude the thread_id for the default thread.
1281 if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1282 stream() << LogSeverityNames[severity][0]
1283 << setw(2) << 1+data_->tm_time_.tm_mon
1284 << setw(2) << data_->tm_time_.tm_mday
1285 << ' '
1286 << setw(2) << data_->tm_time_.tm_hour << ':'
1287 << setw(2) << data_->tm_time_.tm_min << ':'
1288 << setw(2) << data_->tm_time_.tm_sec << "."
1289 << setw(6) << usecs
1290 << ' '
1291 << setfill(' ') << setw(5)
1292 << static_cast<unsigned int>(GetTID()) << setfill('0')
1293 << ' '
1294 << data_->basename_ << ':' << data_->line_ << "] ";
1295 }
1296 data_->num_prefix_chars_ = data_->stream_.pcount();
1297
1298 if (!FLAGS_log_backtrace_at.empty()) {
1299 char fileline[128];
1300 snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1301#ifdef HAVE_STACKTRACE
1302 if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1303 string stacktrace;
1304 DumpStackTraceToString(&stacktrace);
1305 stream() << " (stacktrace:\n" << stacktrace << ") ";
1306 }
1307#endif
1308 }
1309}
1310
1311LogMessage::~LogMessage() {
1312 Flush();
1313#ifdef GLOG_THREAD_LOCAL_STORAGE
1314 if (data_ == static_cast<void*>(&thread_msg_data)) {
1315 data_->~LogMessageData();
1316 thread_data_available = true;
1317 }
1318 else {
1319 delete allocated_;
1320 }
1321#else // !defined(GLOG_THREAD_LOCAL_STORAGE)
1322 delete allocated_;
1323#endif // defined(GLOG_THREAD_LOCAL_STORAGE)
1324}
1325
1326int LogMessage::preserved_errno() const {
1327 return data_->preserved_errno_;
1328}
1329
1330ostream& LogMessage::stream() {
1331 return data_->stream_;
1332}
1333
1334// Flush buffered message, called by the destructor, or any other function
1335// that needs to synchronize the log.
1336void LogMessage::Flush() {
1337 if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1338 return;
1339
1340 data_->num_chars_to_log_ = data_->stream_.pcount();
1341 data_->num_chars_to_syslog_ =
1342 data_->num_chars_to_log_ - data_->num_prefix_chars_;
1343
1344 // Do we need to add a \n to the end of this message?
1345 bool append_newline =
1346 (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1347 char original_final_char = '\0';
1348
1349 // If we do need to add a \n, we'll do it by violating the memory of the
1350 // ostrstream buffer. This is quick, and we'll make sure to undo our
1351 // modification before anything else is done with the ostrstream. It
1352 // would be preferable not to do things this way, but it seems to be
1353 // the best way to deal with this.
1354 if (append_newline) {
1355 original_final_char = data_->message_text_[data_->num_chars_to_log_];
1356 data_->message_text_[data_->num_chars_to_log_++] = '\n';
1357 }
1358
1359 // Prevent any subtle race conditions by wrapping a mutex lock around
1360 // the actual logging action per se.
1361 {
1362 MutexLock l(&log_mutex);
1363 (this->*(data_->send_method_))();
1364 ++num_messages_[static_cast<int>(data_->severity_)];
1365 }
1366 LogDestination::WaitForSinks(data_);
1367
1368 if (append_newline) {
1369 // Fix the ostrstream back how it was before we screwed with it.
1370 // It's 99.44% certain that we don't need to worry about doing this.
1371 data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1372 }
1373
1374 // If errno was already set before we enter the logging call, we'll
1375 // set it back to that value when we return from the logging call.
1376 // It happens often that we log an error message after a syscall
1377 // failure, which can potentially set the errno to some other
1378 // values. We would like to preserve the original errno.
1379 if (data_->preserved_errno_ != 0) {
1380 errno = data_->preserved_errno_;
1381 }
1382
1383 // Note that this message is now safely logged. If we're asked to flush
1384 // again, as a result of destruction, say, we'll do nothing on future calls.
1385 data_->has_been_flushed_ = true;
1386}
1387
1388// Copy of first FATAL log message so that we can print it out again
1389// after all the stack traces. To preserve legacy behavior, we don't
1390// use fatal_msg_data_exclusive.
1391static time_t fatal_time;
1392static char fatal_message[256];
1393
1394void ReprintFatalMessage() {
1395 if (fatal_message[0]) {
1396 const int n = strlen(fatal_message);
1397 if (!FLAGS_logtostderr) {
1398 // Also write to stderr (don't color to avoid terminal checks)
1399 WriteToStderr(fatal_message, n);
1400 }
1401 LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1402 }
1403}
1404
1405// L >= log_mutex (callers must hold the log_mutex).
1406void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1407 static bool already_warned_before_initgoogle = false;
1408
1409 log_mutex.AssertHeld();
1410
1411 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1412 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1413
1414 // Messages of a given severity get logged to lower severity logs, too
1415
1416 if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1417 const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1418 "written to STDERR\n";
1419 WriteToStderr(w, strlen(w));
1420 already_warned_before_initgoogle = true;
1421 }
1422
1423 // global flag: never log to file if set. Also -- don't log to a
1424 // file if we haven't parsed the command line flags to get the
1425 // program name.
1426 if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1427 ColoredWriteToStderr(data_->severity_,
1428 data_->message_text_, data_->num_chars_to_log_);
1429
1430 // this could be protected by a flag if necessary.
1431 LogDestination::LogToSinks(data_->severity_,
1432 data_->fullname_, data_->basename_,
1433 data_->line_, &data_->tm_time_,
1434 data_->message_text_ + data_->num_prefix_chars_,
1435 (data_->num_chars_to_log_ -
1436 data_->num_prefix_chars_ - 1));
1437 } else {
1438
1439 // log this message to all log files of severity <= severity_
1440 LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1441 data_->message_text_,
1442 data_->num_chars_to_log_);
1443
1444 LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1445 data_->num_chars_to_log_);
1446 LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1447 data_->num_chars_to_log_);
1448 LogDestination::LogToSinks(data_->severity_,
1449 data_->fullname_, data_->basename_,
1450 data_->line_, &data_->tm_time_,
1451 data_->message_text_ + data_->num_prefix_chars_,
1452 (data_->num_chars_to_log_
1453 - data_->num_prefix_chars_ - 1));
1454 // NOTE: -1 removes trailing \n
1455 }
1456
1457 // If we log a FATAL message, flush all the log destinations, then toss
1458 // a signal for others to catch. We leave the logs in a state that
1459 // someone else can use them (as long as they flush afterwards)
1460 if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1461 if (data_->first_fatal_) {
1462 // Store crash information so that it is accessible from within signal
1463 // handlers that may be invoked later.
1464 RecordCrashReason(&crash_reason);
1465 SetCrashReason(&crash_reason);
1466
1467 // Store shortened fatal message for other logs and GWQ status
1468 const int copy = min<int>(data_->num_chars_to_log_,
1469 sizeof(fatal_message)-1);
1470 memcpy(fatal_message, data_->message_text_, copy);
1471 fatal_message[copy] = '\0';
1472 fatal_time = data_->timestamp_;
1473 }
1474
1475 if (!FLAGS_logtostderr) {
1476 for (int i = 0; i < NUM_SEVERITIES; ++i) {
1477 if ( LogDestination::log_destinations_[i] )
1478 LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1479 }
1480 }
1481
1482 // release the lock that our caller (directly or indirectly)
1483 // LogMessage::~LogMessage() grabbed so that signal handlers
1484 // can use the logging facility. Alternately, we could add
1485 // an entire unsafe logging interface to bypass locking
1486 // for signal handlers but this seems simpler.
1487 log_mutex.Unlock();
1488 LogDestination::WaitForSinks(data_);
1489
1490 const char* message = "*** Check failure stack trace: ***\n";
1491 if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1492 // Ignore errors.
1493 }
1494 Fail();
1495 }
1496}
1497
1498void LogMessage::RecordCrashReason(
1499 glog_internal_namespace_::CrashReason* reason) {
1500 reason->filename = fatal_msg_data_exclusive.fullname_;
1501 reason->line_number = fatal_msg_data_exclusive.line_;
1502 reason->message = fatal_msg_data_exclusive.message_text_ +
1503 fatal_msg_data_exclusive.num_prefix_chars_;
1504#ifdef HAVE_STACKTRACE
1505 // Retrieve the stack trace, omitting the logging frames that got us here.
1506 reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1507#else
1508 reason->depth = 0;
1509#endif
1510}
1511
1512#ifdef HAVE___ATTRIBUTE__
1513# define ATTRIBUTE_NORETURN __attribute__((noreturn))
1514#else
1515# define ATTRIBUTE_NORETURN
1516#endif
1517
1518#if defined(OS_WINDOWS)
1519__declspec(noreturn)
1520#endif
1521static void logging_fail() ATTRIBUTE_NORETURN;
1522
1523static void logging_fail() {
1524 abort();
1525}
1526
1527typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1528
1529GOOGLE_GLOG_DLL_DECL
1530logging_fail_func_t g_logging_fail_func = &logging_fail;
1531
1532void InstallFailureFunction(void (*fail_func)()) {
1533 g_logging_fail_func = (logging_fail_func_t)fail_func;
1534}
1535
1536void LogMessage::Fail() {
1537 g_logging_fail_func();
1538}
1539
1540// L >= log_mutex (callers must hold the log_mutex).
1541void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1542 if (data_->sink_ != NULL) {
1543 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1544 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1545 data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1546 data_->line_, &data_->tm_time_,
1547 data_->message_text_ + data_->num_prefix_chars_,
1548 (data_->num_chars_to_log_ -
1549 data_->num_prefix_chars_ - 1));
1550 }
1551}
1552
1553// L >= log_mutex (callers must hold the log_mutex).
1554void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1555 SendToSink();
1556 SendToLog();
1557}
1558
1559// L >= log_mutex (callers must hold the log_mutex).
1560void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1561 if (data_->outvec_ != NULL) {
1562 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1563 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1564 // Omit prefix of message and trailing newline when recording in outvec_.
1565 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1566 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1567 data_->outvec_->push_back(string(start, len));
1568 } else {
1569 SendToLog();
1570 }
1571}
1572
1573void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1574 if (data_->message_ != NULL) {
1575 RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1576 data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1577 // Omit prefix of message and trailing newline when writing to message_.
1578 const char *start = data_->message_text_ + data_->num_prefix_chars_;
1579 int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1580 data_->message_->assign(start, len);
1581 }
1582 SendToLog();
1583}
1584
1585// L >= log_mutex (callers must hold the log_mutex).
1586void LogMessage::SendToSyslogAndLog() {
1587#ifdef HAVE_SYSLOG_H
1588 // Before any calls to syslog(), make a single call to openlog()
1589 static bool openlog_already_called = false;
1590 if (!openlog_already_called) {
1591 openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1592 LOG_CONS | LOG_NDELAY | LOG_PID,
1593 LOG_USER);
1594 openlog_already_called = true;
1595 }
1596
1597 // This array maps Google severity levels to syslog levels
1598 const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1599 syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1600 int(data_->num_chars_to_syslog_),
1601 data_->message_text_ + data_->num_prefix_chars_);
1602 SendToLog();
1603#else
1604 LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1605#endif
1606}
1607
1608base::Logger* base::GetLogger(LogSeverity severity) {
1609 MutexLock l(&log_mutex);
1610 return LogDestination::log_destination(severity)->logger_;
1611}
1612
1613void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1614 MutexLock l(&log_mutex);
1615 LogDestination::log_destination(severity)->logger_ = logger;
1616}
1617
1618// L < log_mutex. Acquires and releases mutex_.
1619int64 LogMessage::num_messages(int severity) {
1620 MutexLock l(&log_mutex);
1621 return num_messages_[severity];
1622}
1623
1624// Output the COUNTER value. This is only valid if ostream is a
1625// LogStream.
1626ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1627#ifdef DISABLE_RTTI
1628 LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1629#else
1630 LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1631#endif
1632 CHECK(log && log == log->self())
1633 << "You must not use COUNTER with non-glog ostream";
1634 os << log->ctr();
1635 return os;
1636}
1637
1638ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1639 LogSeverity severity, int ctr,
1640 void (LogMessage::*send_method)())
1641 : LogMessage(file, line, severity, ctr, send_method) {
1642}
1643
1644ErrnoLogMessage::~ErrnoLogMessage() {
1645 // Don't access errno directly because it may have been altered
1646 // while streaming the message.
1647 stream() << ": " << StrError(preserved_errno()) << " ["
1648 << preserved_errno() << "]";
1649}
1650
1651void FlushLogFiles(LogSeverity min_severity) {
1652 LogDestination::FlushLogFiles(min_severity);
1653}
1654
1655void FlushLogFilesUnsafe(LogSeverity min_severity) {
1656 LogDestination::FlushLogFilesUnsafe(min_severity);
1657}
1658
1659void SetLogDestination(LogSeverity severity, const char* base_filename) {
1660 LogDestination::SetLogDestination(severity, base_filename);
1661}
1662
1663void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1664 LogDestination::SetLogSymlink(severity, symlink_basename);
1665}
1666
1667LogSink::~LogSink() {
1668}
1669
1670void LogSink::WaitTillSent() {
1671 // noop default
1672}
1673
1674string LogSink::ToString(LogSeverity severity, const char* file, int line,
1675 const struct ::tm* tm_time,
1676 const char* message, size_t message_len) {
1677 ostringstream stream(string(message, message_len));
1678 stream.fill('0');
1679
1680 // FIXME(jrvb): Updating this to use the correct value for usecs
1681 // requires changing the signature for both this method and
1682 // LogSink::send(). This change needs to be done in a separate CL
1683 // so subclasses of LogSink can be updated at the same time.
1684 int usecs = 0;
1685
1686 stream << LogSeverityNames[severity][0]
1687 << setw(2) << 1+tm_time->tm_mon
1688 << setw(2) << tm_time->tm_mday
1689 << ' '
1690 << setw(2) << tm_time->tm_hour << ':'
1691 << setw(2) << tm_time->tm_min << ':'
1692 << setw(2) << tm_time->tm_sec << '.'
1693 << setw(6) << usecs
1694 << ' '
1695 << setfill(' ') << setw(5) << GetTID() << setfill('0')
1696 << ' '
1697 << file << ':' << line << "] ";
1698
1699 stream << string(message, message_len);
1700 return stream.str();
1701}
1702
1703void AddLogSink(LogSink *destination) {
1704 LogDestination::AddLogSink(destination);
1705}
1706
1707void RemoveLogSink(LogSink *destination) {
1708 LogDestination::RemoveLogSink(destination);
1709}
1710
1711void SetLogFilenameExtension(const char* ext) {
1712 LogDestination::SetLogFilenameExtension(ext);
1713}
1714
1715void SetStderrLogging(LogSeverity min_severity) {
1716 LogDestination::SetStderrLogging(min_severity);
1717}
1718
1719void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1720 LogDestination::SetEmailLogging(min_severity, addresses);
1721}
1722
1723void LogToStderr() {
1724 LogDestination::LogToStderr();
1725}
1726
1727namespace base {
1728namespace internal {
1729
1730bool GetExitOnDFatal();
1731bool GetExitOnDFatal() {
1732 MutexLock l(&log_mutex);
1733 return exit_on_dfatal;
1734}
1735
1736// Determines whether we exit the program for a LOG(DFATAL) message in
1737// debug mode. It does this by skipping the call to Fail/FailQuietly.
1738// This is intended for testing only.
1739//
1740// This can have some effects on LOG(FATAL) as well. Failure messages
1741// are always allocated (rather than sharing a buffer), the crash
1742// reason is not recorded, the "gwq" status message is not updated,
1743// and the stack trace is not recorded. The LOG(FATAL) *will* still
1744// exit the program. Since this function is used only in testing,
1745// these differences are acceptable.
1746void SetExitOnDFatal(bool value);
1747void SetExitOnDFatal(bool value) {
1748 MutexLock l(&log_mutex);
1749 exit_on_dfatal = value;
1750}
1751
1752} // namespace internal
1753} // namespace base
1754
1755// Shell-escaping as we need to shell out ot /bin/mail.
1756static const char kDontNeedShellEscapeChars[] =
1757 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1758 "abcdefghijklmnopqrstuvwxyz"
1759 "0123456789+-_.=/:,@";
1760
1761static string ShellEscape(const string& src) {
1762 string result;
1763 if (!src.empty() && // empty string needs quotes
1764 src.find_first_not_of(kDontNeedShellEscapeChars) == string::npos) {
1765 // only contains chars that don't need quotes; it's fine
1766 result.assign(src);
1767 } else if (src.find_first_of('\'') == string::npos) {
1768 // no single quotes; just wrap it in single quotes
1769 result.assign("'");
1770 result.append(src);
1771 result.append("'");
1772 } else {
1773 // needs double quote escaping
1774 result.assign("\"");
1775 for (size_t i = 0; i < src.size(); ++i) {
1776 switch (src[i]) {
1777 case '\\':
1778 case '$':
1779 case '"':
1780 case '`':
1781 result.append("\\");
1782 }
1783 result.append(src, i, 1);
1784 }
1785 result.append("\"");
1786 }
1787 return result;
1788}
1789
1790
1791// use_logging controls whether the logging functions LOG/VLOG are used
1792// to log errors. It should be set to false when the caller holds the
1793// log_mutex.
1794static bool SendEmailInternal(const char*dest, const char *subject,
1795 const char*body, bool use_logging) {
1796 if (dest && *dest) {
1797 if ( use_logging ) {
1798 VLOG(1) << "Trying to send TITLE:" << subject
1799 << " BODY:" << body << " to " << dest;
1800 } else {
1801 fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1802 subject, body, dest);
1803 }
1804
1805 string cmd =
1806 FLAGS_logmailer + " -s" +
1807 ShellEscape(subject) + " " + ShellEscape(dest);
1808 VLOG(4) << "Mailing command: " << cmd;
1809
1810 FILE* pipe = popen(cmd.c_str(), "w");
1811 if (pipe != NULL) {
1812 // Add the body if we have one
1813 if (body)
1814 fwrite(body, sizeof(char), strlen(body), pipe);
1815 bool ok = pclose(pipe) != -1;
1816 if ( !ok ) {
1817 if ( use_logging ) {
1818 LOG(ERROR) << "Problems sending mail to " << dest << ": "
1819 << StrError(errno);
1820 } else {
1821 fprintf(stderr, "Problems sending mail to %s: %s\n",
1822 dest, StrError(errno).c_str());
1823 }
1824 }
1825 return ok;
1826 } else {
1827 if ( use_logging ) {
1828 LOG(ERROR) << "Unable to send mail to " << dest;
1829 } else {
1830 fprintf(stderr, "Unable to send mail to %s\n", dest);
1831 }
1832 }
1833 }
1834 return false;
1835}
1836
1837bool SendEmail(const char*dest, const char *subject, const char*body){
1838 return SendEmailInternal(dest, subject, body, true);
1839}
1840
1841static void GetTempDirectories(vector<string>* list) {
1842 list->clear();
1843#ifdef OS_WINDOWS
1844 // On windows we'll try to find a directory in this order:
1845 // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1846 // C:/TMP/
1847 // C:/TEMP/
1848 // C:/WINDOWS/ or C:/WINNT/
1849 // .
1850 char tmp[MAX_PATH];
1851 if (GetTempPathA(MAX_PATH, tmp))
1852 list->push_back(tmp);
1853 list->push_back("C:\\tmp\\");
1854 list->push_back("C:\\temp\\");
1855#else
1856 // Directories, in order of preference. If we find a dir that
1857 // exists, we stop adding other less-preferred dirs
1858 const char * candidates[] = {
1859 // Non-null only during unittest/regtest
1860 getenv("TEST_TMPDIR"),
1861
1862 // Explicitly-supplied temp dirs
1863 getenv("TMPDIR"), getenv("TMP"),
1864
1865 // If all else fails
1866 "/tmp",
1867 };
1868
1869 for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1870 const char *d = candidates[i];
1871 if (!d) continue; // Empty env var
1872
1873 // Make sure we don't surprise anyone who's expecting a '/'
1874 string dstr = d;
1875 if (dstr[dstr.size() - 1] != '/') {
1876 dstr += "/";
1877 }
1878 list->push_back(dstr);
1879
1880 struct stat statbuf;
1881 if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1882 // We found a dir that exists - we're done.
1883 return;
1884 }
1885 }
1886
1887#endif
1888}
1889
1890static vector<string>* logging_directories_list;
1891
1892const vector<string>& GetLoggingDirectories() {
1893 // Not strictly thread-safe but we're called early in InitGoogle().
1894 if (logging_directories_list == NULL) {
1895 logging_directories_list = new vector<string>;
1896
1897 if ( !FLAGS_log_dir.empty() ) {
1898 // A dir was specified, we should use it
1899 logging_directories_list->push_back(FLAGS_log_dir.c_str());
1900 } else {
1901 GetTempDirectories(logging_directories_list);
1902#ifdef OS_WINDOWS
1903 char tmp[MAX_PATH];
1904 if (GetWindowsDirectoryA(tmp, MAX_PATH))
1905 logging_directories_list->push_back(tmp);
1906 logging_directories_list->push_back(".\\");
1907#else
1908 logging_directories_list->push_back("./");
1909#endif
1910 }
1911 }
1912 return *logging_directories_list;
1913}
1914
1915void TestOnly_ClearLoggingDirectoriesList() {
1916 fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1917 "called from test code.\n");
1918 delete logging_directories_list;
1919 logging_directories_list = NULL;
1920}
1921
1922void GetExistingTempDirectories(vector<string>* list) {
1923 GetTempDirectories(list);
1924 vector<string>::iterator i_dir = list->begin();
1925 while( i_dir != list->end() ) {
1926 // zero arg to access means test for existence; no constant
1927 // defined on windows
1928 if ( access(i_dir->c_str(), 0) ) {
1929 i_dir = list->erase(i_dir);
1930 } else {
1931 ++i_dir;
1932 }
1933 }
1934}
1935
1936void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1937#ifdef HAVE_UNISTD_H
1938 struct stat statbuf;
1939 const int kCopyBlockSize = 8 << 10;
1940 char copybuf[kCopyBlockSize];
1941 int64 read_offset, write_offset;
1942 // Don't follow symlinks unless they're our own fd symlinks in /proc
1943 int flags = O_RDWR;
1944 // TODO(hamaji): Support other environments.
1945#ifdef OS_LINUX
1946 const char *procfd_prefix = "/proc/self/fd/";
1947 if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1948#endif
1949
1950 int fd = open(path, flags);
1951 if (fd == -1) {
1952 if (errno == EFBIG) {
1953 // The log file in question has got too big for us to open. The
1954 // real fix for this would be to compile logging.cc (or probably
1955 // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1956 // rather scary.
1957 // Instead just truncate the file to something we can manage
1958 if (truncate(path, 0) == -1) {
1959 PLOG(ERROR) << "Unable to truncate " << path;
1960 } else {
1961 LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1962 }
1963 } else {
1964 PLOG(ERROR) << "Unable to open " << path;
1965 }
1966 return;
1967 }
1968
1969 if (fstat(fd, &statbuf) == -1) {
1970 PLOG(ERROR) << "Unable to fstat()";
1971 goto out_close_fd;
1972 }
1973
1974 // See if the path refers to a regular file bigger than the
1975 // specified limit
1976 if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1977 if (statbuf.st_size <= limit) goto out_close_fd;
1978 if (statbuf.st_size <= keep) goto out_close_fd;
1979
1980 // This log file is too large - we need to truncate it
1981 LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1982
1983 // Copy the last "keep" bytes of the file to the beginning of the file
1984 read_offset = statbuf.st_size - keep;
1985 write_offset = 0;
1986 int bytesin, bytesout;
1987 while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1988 bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1989 if (bytesout == -1) {
1990 PLOG(ERROR) << "Unable to write to " << path;
1991 break;
1992 } else if (bytesout != bytesin) {
1993 LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1994 }
1995 read_offset += bytesin;
1996 write_offset += bytesout;
1997 }
1998 if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1999
2000 // Truncate the remainder of the file. If someone else writes to the
2001 // end of the file after our last read() above, we lose their latest
2002 // data. Too bad ...
2003 if (ftruncate(fd, write_offset) == -1) {
2004 PLOG(ERROR) << "Unable to truncate " << path;
2005 }
2006
2007 out_close_fd:
2008 close(fd);
2009#else
2010 LOG(ERROR) << "No log truncation support.";
Austin Schuh10358f22019-01-21 20:25:11 -08002011 (void)path;
2012 (void)limit;
2013 (void)keep;
Austin Schuh906616c2019-01-21 20:25:11 -08002014#endif
2015}
2016
2017void TruncateStdoutStderr() {
2018#ifdef HAVE_UNISTD_H
2019 int64 limit = MaxLogSize() << 20;
2020 int64 keep = 1 << 20;
2021 TruncateLogFile("/proc/self/fd/1", limit, keep);
2022 TruncateLogFile("/proc/self/fd/2", limit, keep);
2023#else
2024 LOG(ERROR) << "No log truncation support.";
2025#endif
2026}
2027
2028
2029// Helper functions for string comparisons.
2030#define DEFINE_CHECK_STROP_IMPL(name, func, expected) \
2031 string* Check##func##expected##Impl(const char* s1, const char* s2, \
2032 const char* names) { \
2033 bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
2034 if (equal == expected) return NULL; \
2035 else { \
2036 ostringstream ss; \
2037 if (!s1) s1 = ""; \
2038 if (!s2) s2 = ""; \
2039 ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
2040 return new string(ss.str()); \
2041 } \
2042 }
2043DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
2044DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
2045DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
2046DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
2047#undef DEFINE_CHECK_STROP_IMPL
2048
2049int posix_strerror_r(int err, char *buf, size_t len) {
2050 // Sanity check input parameters
2051 if (buf == NULL || len <= 0) {
2052 errno = EINVAL;
2053 return -1;
2054 }
2055
2056 // Reset buf and errno, and try calling whatever version of strerror_r()
2057 // is implemented by glibc
2058 buf[0] = '\000';
2059 int old_errno = errno;
2060 errno = 0;
2061 char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
2062
2063 // Both versions set errno on failure
2064 if (errno) {
2065 // Should already be there, but better safe than sorry
2066 buf[0] = '\000';
2067 return -1;
2068 }
2069 errno = old_errno;
2070
2071 // POSIX is vague about whether the string will be terminated, although
2072 // is indirectly implies that typically ERANGE will be returned, instead
2073 // of truncating the string. This is different from the GNU implementation.
2074 // We play it safe by always terminating the string explicitly.
2075 buf[len-1] = '\000';
2076
2077 // If the function succeeded, we can use its exit code to determine the
2078 // semantics implemented by glibc
2079 if (!rc) {
2080 return 0;
2081 } else {
2082 // GNU semantics detected
2083 if (rc == buf) {
2084 return 0;
2085 } else {
2086 buf[0] = '\000';
2087#if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
2088 if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
2089 // This means an error on MacOSX or FreeBSD.
2090 return -1;
2091 }
2092#endif
2093 strncat(buf, rc, len-1);
2094 return 0;
2095 }
2096 }
2097}
2098
2099string StrError(int err) {
2100 char buf[100];
2101 int rc = posix_strerror_r(err, buf, sizeof(buf));
2102 if ((rc < 0) || (buf[0] == '\000')) {
2103 snprintf(buf, sizeof(buf), "Error number %d", err);
2104 }
2105 return buf;
2106}
2107
2108LogMessageFatal::LogMessageFatal(const char* file, int line) :
2109 LogMessage(file, line, GLOG_FATAL) {}
2110
2111LogMessageFatal::LogMessageFatal(const char* file, int line,
2112 const CheckOpString& result) :
2113 LogMessage(file, line, result) {}
2114
2115LogMessageFatal::~LogMessageFatal() {
2116 Flush();
2117 LogMessage::Fail();
2118}
2119
2120namespace base {
2121
2122CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2123 : stream_(new ostringstream) {
2124 *stream_ << exprtext << " (";
2125}
2126
2127CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2128 delete stream_;
2129}
2130
2131ostream* CheckOpMessageBuilder::ForVar2() {
2132 *stream_ << " vs. ";
2133 return stream_;
2134}
2135
2136string* CheckOpMessageBuilder::NewString() {
2137 *stream_ << ")";
2138 return new string(stream_->str());
2139}
2140
2141} // namespace base
2142
2143template <>
2144void MakeCheckOpValueString(std::ostream* os, const char& v) {
2145 if (v >= 32 && v <= 126) {
2146 (*os) << "'" << v << "'";
2147 } else {
2148 (*os) << "char value " << (short)v;
2149 }
2150}
2151
2152template <>
2153void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2154 if (v >= 32 && v <= 126) {
2155 (*os) << "'" << v << "'";
2156 } else {
2157 (*os) << "signed char value " << (short)v;
2158 }
2159}
2160
2161template <>
2162void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2163 if (v >= 32 && v <= 126) {
2164 (*os) << "'" << v << "'";
2165 } else {
2166 (*os) << "unsigned char value " << (unsigned short)v;
2167 }
2168}
2169
2170void InitGoogleLogging(const char* argv0) {
2171 glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2172}
2173
2174void ShutdownGoogleLogging() {
2175 glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2176 LogDestination::DeleteLogDestinations();
2177 delete logging_directories_list;
2178 logging_directories_list = NULL;
2179}
2180
2181_END_GOOGLE_NAMESPACE_