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