Merge pull request #49 from sergiud/cmake-visibility
[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 // There is no thread annotation support.
92 #define EXCLUSIVE_LOCKS_REQUIRED(mu)
93
94 static bool BoolFromEnv(const char *varname, bool defval) {
95   const char* const valstr = getenv(varname);
96   if (!valstr) {
97     return defval;
98   }
99   return memchr("tTyY1\0", valstr[0], 6) != NULL;
100 }
101
102 GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false),
103                  "log messages go to stderr instead of logfiles");
104 GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false),
105                  "log messages go to stderr in addition to logfiles");
106 GLOG_DEFINE_bool(colorlogtostderr, false,
107                  "color messages logged to stderr (if supported by terminal)");
108 #ifdef OS_LINUX
109 GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. "
110                  "Logs can grow very quickly and they are rarely read before they "
111                  "need to be evicted from memory. Instead, drop them from memory "
112                  "as soon as they are flushed to disk.");
113 _START_GOOGLE_NAMESPACE_
114 namespace logging {
115 static const int64 kPageSize = getpagesize();
116 }
117 _END_GOOGLE_NAMESPACE_
118 #endif
119
120 // By default, errors (including fatal errors) get logged to stderr as
121 // well as the file.
122 //
123 // The default is ERROR instead of FATAL so that users can see problems
124 // when they run a program without having to look in another file.
125 DEFINE_int32(stderrthreshold,
126              GOOGLE_NAMESPACE::GLOG_ERROR,
127              "log messages at or above this level are copied to stderr in "
128              "addition to logfiles.  This flag obsoletes --alsologtostderr.");
129
130 GLOG_DEFINE_string(alsologtoemail, "",
131                    "log messages go to these email addresses "
132                    "in addition to logfiles");
133 GLOG_DEFINE_bool(log_prefix, true,
134                  "Prepend the log prefix to the start of each log line");
135 GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't "
136                   "actually get logged anywhere");
137 GLOG_DEFINE_int32(logbuflevel, 0,
138                   "Buffer log messages logged at this level or lower"
139                   " (-1 means don't buffer; 0 means buffer INFO only;"
140                   " ...)");
141 GLOG_DEFINE_int32(logbufsecs, 30,
142                   "Buffer log messages for at most this many seconds");
143 GLOG_DEFINE_int32(logemaillevel, 999,
144                   "Email log messages logged at this level or higher"
145                   " (0 means email all; 3 means email FATAL only;"
146                   " ...)");
147 GLOG_DEFINE_string(logmailer, "/bin/mail",
148                    "Mailer used to send logging email");
149
150 // Compute the default value for --log_dir
151 static const char* DefaultLogDir() {
152   const char* env;
153   env = getenv("GOOGLE_LOG_DIR");
154   if (env != NULL && env[0] != '\0') {
155     return env;
156   }
157   env = getenv("TEST_TMPDIR");
158   if (env != NULL && env[0] != '\0') {
159     return env;
160   }
161   return "";
162 }
163
164 GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions.");
165
166 GLOG_DEFINE_string(log_dir, DefaultLogDir(),
167                    "If specified, logfiles are written into this directory instead "
168                    "of the default logging directory.");
169 GLOG_DEFINE_string(log_link, "", "Put additional links to the log "
170                    "files in this directory");
171
172 GLOG_DEFINE_int32(max_log_size, 1800,
173                   "approx. maximum log file size (in MB). A value of 0 will "
174                   "be silently overridden to 1.");
175
176 GLOG_DEFINE_bool(stop_logging_if_full_disk, false,
177                  "Stop attempting to log to disk if the disk is full.");
178
179 GLOG_DEFINE_string(log_backtrace_at, "",
180                    "Emit a backtrace when logging at file:linenum.");
181
182 // TODO(hamaji): consider windows
183 #define PATH_SEPARATOR '/'
184
185 #ifndef HAVE_PREAD
186 #if defined(OS_WINDOWS)
187 #include <BaseTsd.h>
188 #define ssize_t SSIZE_T
189 #endif
190 static ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
191   off_t orig_offset = lseek(fd, 0, SEEK_CUR);
192   if (orig_offset == (off_t)-1)
193     return -1;
194   if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
195     return -1;
196   ssize_t len = read(fd, buf, count);
197   if (len < 0)
198     return len;
199   if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
200     return -1;
201   return len;
202 }
203 #endif  // !HAVE_PREAD
204
205 #ifndef HAVE_PWRITE
206 static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) {
207   off_t orig_offset = lseek(fd, 0, SEEK_CUR);
208   if (orig_offset == (off_t)-1)
209     return -1;
210   if (lseek(fd, offset, SEEK_CUR) == (off_t)-1)
211     return -1;
212   ssize_t len = write(fd, buf, count);
213   if (len < 0)
214     return len;
215   if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1)
216     return -1;
217   return len;
218 }
219 #endif  // !HAVE_PWRITE
220
221 static void GetHostName(string* hostname) {
222 #if defined(HAVE_SYS_UTSNAME_H)
223   struct utsname buf;
224   if (0 != uname(&buf)) {
225     // ensure null termination on failure
226     *buf.nodename = '\0';
227   }
228   *hostname = buf.nodename;
229 #elif defined(OS_WINDOWS)
230   char buf[MAX_COMPUTERNAME_LENGTH + 1];
231   DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
232   if (GetComputerNameA(buf, &len)) {
233     *hostname = buf;
234   } else {
235     hostname->clear();
236   }
237 #else
238 # warning There is no way to retrieve the host name.
239   *hostname = "(unknown)";
240 #endif
241 }
242
243 // Returns true iff terminal supports using colors in output.
244 static bool TerminalSupportsColor() {
245   bool term_supports_color = false;
246 #ifdef OS_WINDOWS
247   // on Windows TERM variable is usually not set, but the console does
248   // support colors.
249   term_supports_color = true;
250 #else
251   // On non-Windows platforms, we rely on the TERM variable.
252   const char* const term = getenv("TERM");
253   if (term != NULL && term[0] != '\0') {
254     term_supports_color =
255       !strcmp(term, "xterm") ||
256       !strcmp(term, "xterm-color") ||
257       !strcmp(term, "xterm-256color") ||
258       !strcmp(term, "screen-256color") ||
259       !strcmp(term, "screen") ||
260       !strcmp(term, "linux") ||
261       !strcmp(term, "cygwin");
262   }
263 #endif
264   return term_supports_color;
265 }
266
267 _START_GOOGLE_NAMESPACE_
268
269 enum GLogColor {
270   COLOR_DEFAULT,
271   COLOR_RED,
272   COLOR_GREEN,
273   COLOR_YELLOW
274 };
275
276 static GLogColor SeverityToColor(LogSeverity severity) {
277   assert(severity >= 0 && severity < NUM_SEVERITIES);
278   GLogColor color = COLOR_DEFAULT;
279   switch (severity) {
280   case GLOG_INFO:
281     color = COLOR_DEFAULT;
282     break;
283   case GLOG_WARNING:
284     color = COLOR_YELLOW;
285     break;
286   case GLOG_ERROR:
287   case GLOG_FATAL:
288     color = COLOR_RED;
289     break;
290   default:
291     // should never get here.
292     assert(false);
293   }
294   return color;
295 }
296
297 #ifdef OS_WINDOWS
298
299 // Returns the character attribute for the given color.
300 WORD GetColorAttribute(GLogColor color) {
301   switch (color) {
302     case COLOR_RED:    return FOREGROUND_RED;
303     case COLOR_GREEN:  return FOREGROUND_GREEN;
304     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
305     default:           return 0;
306   }
307 }
308
309 #else
310
311 // Returns the ANSI color code for the given color.
312 const char* GetAnsiColorCode(GLogColor color) {
313   switch (color) {
314   case COLOR_RED:     return "1";
315   case COLOR_GREEN:   return "2";
316   case COLOR_YELLOW:  return "3";
317   case COLOR_DEFAULT:  return "";
318   };
319   return NULL; // stop warning about return type.
320 }
321
322 #endif  // OS_WINDOWS
323
324 // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0
325 static int32 MaxLogSize() {
326   return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1);
327 }
328
329 // An arbitrary limit on the length of a single log message.  This
330 // is so that streaming can be done more efficiently.
331 const size_t LogMessage::kMaxLogMessageLen = 30000;
332
333 struct LogMessage::LogMessageData  {
334   LogMessageData();
335
336   int preserved_errno_;      // preserved errno
337   // Buffer space; contains complete message text.
338   char message_text_[LogMessage::kMaxLogMessageLen+1];
339   LogStream stream_;
340   char severity_;      // What level is this LogMessage logged at?
341   int line_;                 // line number where logging call is.
342   void (LogMessage::*send_method_)();  // Call this in destructor to send
343   union {  // At most one of these is used: union to keep the size low.
344     LogSink* sink_;             // NULL or sink to send message to
345     std::vector<std::string>* outvec_; // NULL or vector to push message onto
346     std::string* message_;             // NULL or string to write message into
347   };
348   time_t timestamp_;            // Time of creation of LogMessage
349   struct ::tm tm_time_;         // Time of creation of LogMessage
350   size_t num_prefix_chars_;     // # of chars of prefix in this message
351   size_t num_chars_to_log_;     // # of chars of msg to send to log
352   size_t num_chars_to_syslog_;  // # of chars of msg to send to syslog
353   const char* basename_;        // basename of file that called LOG
354   const char* fullname_;        // fullname of file that called LOG
355   bool has_been_flushed_;       // false => data has not been flushed
356   bool first_fatal_;            // true => this was first fatal msg
357
358  private:
359   LogMessageData(const LogMessageData&);
360   void operator=(const LogMessageData&);
361 };
362
363 // A mutex that allows only one thread to log at a time, to keep things from
364 // getting jumbled.  Some other very uncommon logging operations (like
365 // changing the destination file for log messages of a given severity) also
366 // lock this mutex.  Please be sure that anybody who might possibly need to
367 // lock it does so.
368 static Mutex log_mutex;
369
370 // Number of messages sent at each severity.  Under log_mutex.
371 int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0};
372
373 // Globally disable log writing (if disk is full)
374 static bool stop_writing = false;
375
376 const char*const LogSeverityNames[NUM_SEVERITIES] = {
377   "INFO", "WARNING", "ERROR", "FATAL"
378 };
379
380 // Has the user called SetExitOnDFatal(true)?
381 static bool exit_on_dfatal = true;
382
383 const char* GetLogSeverityName(LogSeverity severity) {
384   return LogSeverityNames[severity];
385 }
386
387 static bool SendEmailInternal(const char*dest, const char *subject,
388                               const char*body, bool use_logging);
389
390 base::Logger::~Logger() {
391 }
392
393 namespace {
394
395 // Encapsulates all file-system related state
396 class LogFileObject : public base::Logger {
397  public:
398   LogFileObject(LogSeverity severity, const char* base_filename);
399   ~LogFileObject();
400
401   virtual void Write(bool force_flush, // Should we force a flush here?
402                      time_t timestamp,  // Timestamp for this entry
403                      const char* message,
404                      int message_len);
405
406   // Configuration options
407   void SetBasename(const char* basename);
408   void SetExtension(const char* ext);
409   void SetSymlinkBasename(const char* symlink_basename);
410
411   // Normal flushing routine
412   virtual void Flush();
413
414   // It is the actual file length for the system loggers,
415   // i.e., INFO, ERROR, etc.
416   virtual uint32 LogSize() {
417     MutexLock l(&lock_);
418     return file_length_;
419   }
420
421   // Internal flush routine.  Exposed so that FlushLogFilesUnsafe()
422   // can avoid grabbing a lock.  Usually Flush() calls it after
423   // acquiring lock_.
424   void FlushUnlocked();
425
426  private:
427   static const uint32 kRolloverAttemptFrequency = 0x20;
428
429   Mutex lock_;
430   bool base_filename_selected_;
431   string base_filename_;
432   string symlink_basename_;
433   string filename_extension_;     // option users can specify (eg to add port#)
434   FILE* file_;
435   LogSeverity severity_;
436   uint32 bytes_since_flush_;
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_destination(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 }
825
826 namespace {
827
828 LogFileObject::LogFileObject(LogSeverity severity,
829                              const char* base_filename)
830   : base_filename_selected_(base_filename != NULL),
831     base_filename_((base_filename != NULL) ? base_filename : ""),
832     symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
833     filename_extension_(),
834     file_(NULL),
835     severity_(severity),
836     bytes_since_flush_(0),
837     file_length_(0),
838     rollover_attempt_(kRolloverAttemptFrequency-1),
839     next_flush_time_(0) {
840   assert(severity >= 0);
841   assert(severity < NUM_SEVERITIES);
842 }
843
844 LogFileObject::~LogFileObject() {
845   MutexLock l(&lock_);
846   if (file_ != NULL) {
847     fclose(file_);
848     file_ = NULL;
849   }
850 }
851
852 void LogFileObject::SetBasename(const char* basename) {
853   MutexLock l(&lock_);
854   base_filename_selected_ = true;
855   if (base_filename_ != basename) {
856     // Get rid of old log file since we are changing names
857     if (file_ != NULL) {
858       fclose(file_);
859       file_ = NULL;
860       rollover_attempt_ = kRolloverAttemptFrequency-1;
861     }
862     base_filename_ = basename;
863   }
864 }
865
866 void LogFileObject::SetExtension(const char* ext) {
867   MutexLock l(&lock_);
868   if (filename_extension_ != ext) {
869     // Get rid of old log file since we are changing names
870     if (file_ != NULL) {
871       fclose(file_);
872       file_ = NULL;
873       rollover_attempt_ = kRolloverAttemptFrequency-1;
874     }
875     filename_extension_ = ext;
876   }
877 }
878
879 void LogFileObject::SetSymlinkBasename(const char* symlink_basename) {
880   MutexLock l(&lock_);
881   symlink_basename_ = symlink_basename;
882 }
883
884 void LogFileObject::Flush() {
885   MutexLock l(&lock_);
886   FlushUnlocked();
887 }
888
889 void LogFileObject::FlushUnlocked(){
890   if (file_ != NULL) {
891     fflush(file_);
892     bytes_since_flush_ = 0;
893   }
894   // Figure out when we are due for another flush.
895   const int64 next = (FLAGS_logbufsecs
896                       * static_cast<int64>(1000000));  // in usec
897   next_flush_time_ = CycleClock_Now() + UsecToCycles(next);
898 }
899
900 bool LogFileObject::CreateLogfile(const string& time_pid_string) {
901   string string_filename = base_filename_+filename_extension_+
902                            time_pid_string;
903   const char* filename = string_filename.c_str();
904   int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, FLAGS_logfile_mode);
905   if (fd == -1) return false;
906 #ifdef HAVE_FCNTL
907   // Mark the file close-on-exec. We don't really care if this fails
908   fcntl(fd, F_SETFD, FD_CLOEXEC);
909 #endif
910
911   file_ = fdopen(fd, "a");  // Make a FILE*.
912   if (file_ == NULL) {  // Man, we're screwed!
913     close(fd);
914     unlink(filename);  // Erase the half-baked evidence: an unusable log file
915     return false;
916   }
917
918   // We try to create a symlink called <program_name>.<severity>,
919   // which is easier to use.  (Every time we create a new logfile,
920   // we destroy the old symlink and create a new one, so it always
921   // points to the latest logfile.)  If it fails, we're sad but it's
922   // no error.
923   if (!symlink_basename_.empty()) {
924     // take directory from filename
925     const char* slash = strrchr(filename, PATH_SEPARATOR);
926     const string linkname =
927       symlink_basename_ + '.' + LogSeverityNames[severity_];
928     string linkpath;
929     if ( slash ) linkpath = string(filename, slash-filename+1);  // get dirname
930     linkpath += linkname;
931     unlink(linkpath.c_str());                    // delete old one if it exists
932
933 #if defined(OS_WINDOWS)
934     // TODO(hamaji): Create lnk file on Windows?
935 #elif defined(HAVE_UNISTD_H)
936     // We must have unistd.h.
937     // Make the symlink be relative (in the same dir) so that if the
938     // entire log directory gets relocated the link is still valid.
939     const char *linkdest = slash ? (slash + 1) : filename;
940     if (symlink(linkdest, linkpath.c_str()) != 0) {
941       // silently ignore failures
942     }
943
944     // Make an additional link to the log file in a place specified by
945     // FLAGS_log_link, if indicated
946     if (!FLAGS_log_link.empty()) {
947       linkpath = FLAGS_log_link + "/" + linkname;
948       unlink(linkpath.c_str());                  // delete old one if it exists
949       if (symlink(filename, linkpath.c_str()) != 0) {
950         // silently ignore failures
951       }
952     }
953 #endif
954   }
955
956   return true;  // Everything worked
957 }
958
959 void LogFileObject::Write(bool force_flush,
960                           time_t timestamp,
961                           const char* message,
962                           int message_len) {
963   MutexLock l(&lock_);
964
965   // We don't log if the base_name_ is "" (which means "don't write")
966   if (base_filename_selected_ && base_filename_.empty()) {
967     return;
968   }
969
970   if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() ||
971       PidHasChanged()) {
972     if (file_ != NULL) fclose(file_);
973     file_ = NULL;
974     file_length_ = bytes_since_flush_ = 0;
975     rollover_attempt_ = kRolloverAttemptFrequency-1;
976   }
977
978   // If there's no destination file, make one before outputting
979   if (file_ == NULL) {
980     // Try to rollover the log file every 32 log messages.  The only time
981     // this could matter would be when we have trouble creating the log
982     // file.  If that happens, we'll lose lots of log messages, of course!
983     if (++rollover_attempt_ != kRolloverAttemptFrequency) return;
984     rollover_attempt_ = 0;
985
986     struct ::tm tm_time;
987     localtime_r(&timestamp, &tm_time);
988
989     // The logfile's filename will have the date/time & pid in it
990     ostringstream time_pid_stream;
991     time_pid_stream.fill('0');
992     time_pid_stream << 1900+tm_time.tm_year
993                     << setw(2) << 1+tm_time.tm_mon
994                     << setw(2) << tm_time.tm_mday
995                     << '-'
996                     << setw(2) << tm_time.tm_hour
997                     << setw(2) << tm_time.tm_min
998                     << setw(2) << tm_time.tm_sec
999                     << '.'
1000                     << GetMainThreadPid();
1001     const string& time_pid_string = time_pid_stream.str();
1002
1003     if (base_filename_selected_) {
1004       if (!CreateLogfile(time_pid_string)) {
1005         perror("Could not create log file");
1006         fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n",
1007                 time_pid_string.c_str());
1008         return;
1009       }
1010     } else {
1011       // If no base filename for logs of this severity has been set, use a
1012       // default base filename of
1013       // "<program name>.<hostname>.<user name>.log.<severity level>.".  So
1014       // logfiles will have names like
1015       // webserver.examplehost.root.log.INFO.19990817-150000.4354, where
1016       // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00),
1017       // and 4354 is the pid of the logging process.  The date & time reflect
1018       // when the file was created for output.
1019       //
1020       // Where does the file get put?  Successively try the directories
1021       // "/tmp", and "."
1022       string stripped_filename(
1023           glog_internal_namespace_::ProgramInvocationShortName());
1024       string hostname;
1025       GetHostName(&hostname);
1026
1027       string uidname = MyUserName();
1028       // We should not call CHECK() here because this function can be
1029       // called after holding on to log_mutex. We don't want to
1030       // attempt to hold on to the same mutex, and get into a
1031       // deadlock. Simply use a name like invalid-user.
1032       if (uidname.empty()) uidname = "invalid-user";
1033
1034       stripped_filename = stripped_filename+'.'+hostname+'.'
1035                           +uidname+".log."
1036                           +LogSeverityNames[severity_]+'.';
1037       // We're going to (potentially) try to put logs in several different dirs
1038       const vector<string> & log_dirs = GetLoggingDirectories();
1039
1040       // Go through the list of dirs, and try to create the log file in each
1041       // until we succeed or run out of options
1042       bool success = false;
1043       for (vector<string>::const_iterator dir = log_dirs.begin();
1044            dir != log_dirs.end();
1045            ++dir) {
1046         base_filename_ = *dir + "/" + stripped_filename;
1047         if ( CreateLogfile(time_pid_string) ) {
1048           success = true;
1049           break;
1050         }
1051       }
1052       // If we never succeeded, we have to give up
1053       if ( success == false ) {
1054         perror("Could not create logging file");
1055         fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
1056                 time_pid_string.c_str());
1057         return;
1058       }
1059     }
1060
1061     // Write a header message into the log file
1062     ostringstream file_header_stream;
1063     file_header_stream.fill('0');
1064     file_header_stream << "Log file created at: "
1065                        << 1900+tm_time.tm_year << '/'
1066                        << setw(2) << 1+tm_time.tm_mon << '/'
1067                        << setw(2) << tm_time.tm_mday
1068                        << ' '
1069                        << setw(2) << tm_time.tm_hour << ':'
1070                        << setw(2) << tm_time.tm_min << ':'
1071                        << setw(2) << tm_time.tm_sec << '\n'
1072                        << "Running on machine: "
1073                        << LogDestination::hostname() << '\n'
1074                        << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu "
1075                        << "threadid file:line] msg" << '\n';
1076     const string& file_header_string = file_header_stream.str();
1077
1078     const int header_len = file_header_string.size();
1079     fwrite(file_header_string.data(), 1, header_len, file_);
1080     file_length_ += header_len;
1081     bytes_since_flush_ += header_len;
1082   }
1083
1084   // Write to LOG file
1085   if ( !stop_writing ) {
1086     // fwrite() doesn't return an error when the disk is full, for
1087     // messages that are less than 4096 bytes. When the disk is full,
1088     // it returns the message length for messages that are less than
1089     // 4096 bytes. fwrite() returns 4096 for message lengths that are
1090     // greater than 4096, thereby indicating an error.
1091     errno = 0;
1092     fwrite(message, 1, message_len, file_);
1093     if ( FLAGS_stop_logging_if_full_disk &&
1094          errno == ENOSPC ) {  // disk full, stop writing to disk
1095       stop_writing = true;  // until the disk is
1096       return;
1097     } else {
1098       file_length_ += message_len;
1099       bytes_since_flush_ += message_len;
1100     }
1101   } else {
1102     if ( CycleClock_Now() >= next_flush_time_ )
1103       stop_writing = false;  // check to see if disk has free space.
1104     return;  // no need to flush
1105   }
1106
1107   // See important msgs *now*.  Also, flush logs at least every 10^6 chars,
1108   // or every "FLAGS_logbufsecs" seconds.
1109   if ( force_flush ||
1110        (bytes_since_flush_ >= 1000000) ||
1111        (CycleClock_Now() >= next_flush_time_) ) {
1112     FlushUnlocked();
1113 #ifdef OS_LINUX
1114     if (FLAGS_drop_log_memory) {
1115       if (file_length_ >= logging::kPageSize) {
1116         // don't evict the most recent page
1117         uint32 len = file_length_ & ~(logging::kPageSize - 1);
1118         posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED);
1119       }
1120     }
1121 #endif
1122   }
1123 }
1124
1125 }  // namespace
1126
1127
1128 // Static log data space to avoid alloc failures in a LOG(FATAL)
1129 //
1130 // Since multiple threads may call LOG(FATAL), and we want to preserve
1131 // the data from the first call, we allocate two sets of space.  One
1132 // for exclusive use by the first thread, and one for shared use by
1133 // all other threads.
1134 static Mutex fatal_msg_lock;
1135 static CrashReason crash_reason;
1136 static bool fatal_msg_exclusive = true;
1137 static LogMessage::LogMessageData fatal_msg_data_exclusive;
1138 static LogMessage::LogMessageData fatal_msg_data_shared;
1139
1140 LogMessage::LogMessageData::LogMessageData()
1141   : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {
1142 }
1143
1144 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1145                        int ctr, void (LogMessage::*send_method)())
1146     : allocated_(NULL) {
1147   Init(file, line, severity, send_method);
1148   data_->stream_.set_ctr(ctr);
1149 }
1150
1151 LogMessage::LogMessage(const char* file, int line,
1152                        const CheckOpString& result)
1153     : allocated_(NULL) {
1154   Init(file, line, GLOG_FATAL, &LogMessage::SendToLog);
1155   stream() << "Check failed: " << (*result.str_) << " ";
1156 }
1157
1158 LogMessage::LogMessage(const char* file, int line)
1159     : allocated_(NULL) {
1160   Init(file, line, GLOG_INFO, &LogMessage::SendToLog);
1161 }
1162
1163 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
1164     : allocated_(NULL) {
1165   Init(file, line, severity, &LogMessage::SendToLog);
1166 }
1167
1168 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1169                        LogSink* sink, bool also_send_to_log)
1170     : allocated_(NULL) {
1171   Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog :
1172                                                 &LogMessage::SendToSink);
1173   data_->sink_ = sink;  // override Init()'s setting to NULL
1174 }
1175
1176 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1177                        vector<string> *outvec)
1178     : allocated_(NULL) {
1179   Init(file, line, severity, &LogMessage::SaveOrSendToLog);
1180   data_->outvec_ = outvec; // override Init()'s setting to NULL
1181 }
1182
1183 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
1184                        string *message)
1185     : allocated_(NULL) {
1186   Init(file, line, severity, &LogMessage::WriteToStringAndLog);
1187   data_->message_ = message;  // override Init()'s setting to NULL
1188 }
1189
1190 void LogMessage::Init(const char* file,
1191                       int line,
1192                       LogSeverity severity,
1193                       void (LogMessage::*send_method)()) {
1194   allocated_ = NULL;
1195   if (severity != GLOG_FATAL || !exit_on_dfatal) {
1196     allocated_ = new LogMessageData();
1197     data_ = allocated_;
1198     data_->first_fatal_ = false;
1199   } else {
1200     MutexLock l(&fatal_msg_lock);
1201     if (fatal_msg_exclusive) {
1202       fatal_msg_exclusive = false;
1203       data_ = &fatal_msg_data_exclusive;
1204       data_->first_fatal_ = true;
1205     } else {
1206       data_ = &fatal_msg_data_shared;
1207       data_->first_fatal_ = false;
1208     }
1209   }
1210
1211   stream().fill('0');
1212   data_->preserved_errno_ = errno;
1213   data_->severity_ = severity;
1214   data_->line_ = line;
1215   data_->send_method_ = send_method;
1216   data_->sink_ = NULL;
1217   data_->outvec_ = NULL;
1218   WallTime now = WallTime_Now();
1219   data_->timestamp_ = static_cast<time_t>(now);
1220   localtime_r(&data_->timestamp_, &data_->tm_time_);
1221   int usecs = static_cast<int>((now - data_->timestamp_) * 1000000);
1222   RawLog__SetLastTime(data_->tm_time_, usecs);
1223
1224   data_->num_chars_to_log_ = 0;
1225   data_->num_chars_to_syslog_ = 0;
1226   data_->basename_ = const_basename(file);
1227   data_->fullname_ = file;
1228   data_->has_been_flushed_ = false;
1229
1230   // If specified, prepend a prefix to each line.  For example:
1231   //    I1018 160715 f5d4fbb0 logging.cc:1153]
1232   //    (log level, GMT month, date, time, thread_id, file basename, line)
1233   // We exclude the thread_id for the default thread.
1234   if (FLAGS_log_prefix && (line != kNoLogPrefix)) {
1235     stream() << LogSeverityNames[severity][0]
1236              << setw(2) << 1+data_->tm_time_.tm_mon
1237              << setw(2) << data_->tm_time_.tm_mday
1238              << ' '
1239              << setw(2) << data_->tm_time_.tm_hour  << ':'
1240              << setw(2) << data_->tm_time_.tm_min   << ':'
1241              << setw(2) << data_->tm_time_.tm_sec   << "."
1242              << setw(6) << usecs
1243              << ' '
1244              << setfill(' ') << setw(5)
1245              << static_cast<unsigned int>(GetTID()) << setfill('0')
1246              << ' '
1247              << data_->basename_ << ':' << data_->line_ << "] ";
1248   }
1249   data_->num_prefix_chars_ = data_->stream_.pcount();
1250
1251   if (!FLAGS_log_backtrace_at.empty()) {
1252     char fileline[128];
1253     snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line);
1254 #ifdef HAVE_STACKTRACE
1255     if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) {
1256       string stacktrace;
1257       DumpStackTraceToString(&stacktrace);
1258       stream() << " (stacktrace:\n" << stacktrace << ") ";
1259     }
1260 #endif
1261   }
1262 }
1263
1264 LogMessage::~LogMessage() {
1265   Flush();
1266   delete allocated_;
1267 }
1268
1269 int LogMessage::preserved_errno() const {
1270   return data_->preserved_errno_;
1271 }
1272
1273 ostream& LogMessage::stream() {
1274   return data_->stream_;
1275 }
1276
1277 // Flush buffered message, called by the destructor, or any other function
1278 // that needs to synchronize the log.
1279 void LogMessage::Flush() {
1280   if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel)
1281     return;
1282
1283   data_->num_chars_to_log_ = data_->stream_.pcount();
1284   data_->num_chars_to_syslog_ =
1285     data_->num_chars_to_log_ - data_->num_prefix_chars_;
1286
1287   // Do we need to add a \n to the end of this message?
1288   bool append_newline =
1289       (data_->message_text_[data_->num_chars_to_log_-1] != '\n');
1290   char original_final_char = '\0';
1291
1292   // If we do need to add a \n, we'll do it by violating the memory of the
1293   // ostrstream buffer.  This is quick, and we'll make sure to undo our
1294   // modification before anything else is done with the ostrstream.  It
1295   // would be preferable not to do things this way, but it seems to be
1296   // the best way to deal with this.
1297   if (append_newline) {
1298     original_final_char = data_->message_text_[data_->num_chars_to_log_];
1299     data_->message_text_[data_->num_chars_to_log_++] = '\n';
1300   }
1301
1302   // Prevent any subtle race conditions by wrapping a mutex lock around
1303   // the actual logging action per se.
1304   {
1305     MutexLock l(&log_mutex);
1306     (this->*(data_->send_method_))();
1307     ++num_messages_[static_cast<int>(data_->severity_)];
1308   }
1309   LogDestination::WaitForSinks(data_);
1310
1311   if (append_newline) {
1312     // Fix the ostrstream back how it was before we screwed with it.
1313     // It's 99.44% certain that we don't need to worry about doing this.
1314     data_->message_text_[data_->num_chars_to_log_-1] = original_final_char;
1315   }
1316
1317   // If errno was already set before we enter the logging call, we'll
1318   // set it back to that value when we return from the logging call.
1319   // It happens often that we log an error message after a syscall
1320   // failure, which can potentially set the errno to some other
1321   // values.  We would like to preserve the original errno.
1322   if (data_->preserved_errno_ != 0) {
1323     errno = data_->preserved_errno_;
1324   }
1325
1326   // Note that this message is now safely logged.  If we're asked to flush
1327   // again, as a result of destruction, say, we'll do nothing on future calls.
1328   data_->has_been_flushed_ = true;
1329 }
1330
1331 // Copy of first FATAL log message so that we can print it out again
1332 // after all the stack traces.  To preserve legacy behavior, we don't
1333 // use fatal_msg_data_exclusive.
1334 static time_t fatal_time;
1335 static char fatal_message[256];
1336
1337 void ReprintFatalMessage() {
1338   if (fatal_message[0]) {
1339     const int n = strlen(fatal_message);
1340     if (!FLAGS_logtostderr) {
1341       // Also write to stderr (don't color to avoid terminal checks)
1342       WriteToStderr(fatal_message, n);
1343     }
1344     LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n);
1345   }
1346 }
1347
1348 // L >= log_mutex (callers must hold the log_mutex).
1349 void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1350   static bool already_warned_before_initgoogle = false;
1351
1352   log_mutex.AssertHeld();
1353
1354   RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1355              data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1356
1357   // Messages of a given severity get logged to lower severity logs, too
1358
1359   if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) {
1360     const char w[] = "WARNING: Logging before InitGoogleLogging() is "
1361                      "written to STDERR\n";
1362     WriteToStderr(w, strlen(w));
1363     already_warned_before_initgoogle = true;
1364   }
1365
1366   // global flag: never log to file if set.  Also -- don't log to a
1367   // file if we haven't parsed the command line flags to get the
1368   // program name.
1369   if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) {
1370     ColoredWriteToStderr(data_->severity_,
1371                          data_->message_text_, data_->num_chars_to_log_);
1372
1373     // this could be protected by a flag if necessary.
1374     LogDestination::LogToSinks(data_->severity_,
1375                                data_->fullname_, data_->basename_,
1376                                data_->line_, &data_->tm_time_,
1377                                data_->message_text_ + data_->num_prefix_chars_,
1378                                (data_->num_chars_to_log_ -
1379                                 data_->num_prefix_chars_ - 1));
1380   } else {
1381
1382     // log this message to all log files of severity <= severity_
1383     LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_,
1384                                      data_->message_text_,
1385                                      data_->num_chars_to_log_);
1386
1387     LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_,
1388                                      data_->num_chars_to_log_);
1389     LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_,
1390                                     data_->num_chars_to_log_);
1391     LogDestination::LogToSinks(data_->severity_,
1392                                data_->fullname_, data_->basename_,
1393                                data_->line_, &data_->tm_time_,
1394                                data_->message_text_ + data_->num_prefix_chars_,
1395                                (data_->num_chars_to_log_
1396                                 - data_->num_prefix_chars_ - 1));
1397     // NOTE: -1 removes trailing \n
1398   }
1399
1400   // If we log a FATAL message, flush all the log destinations, then toss
1401   // a signal for others to catch. We leave the logs in a state that
1402   // someone else can use them (as long as they flush afterwards)
1403   if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) {
1404     if (data_->first_fatal_) {
1405       // Store crash information so that it is accessible from within signal
1406       // handlers that may be invoked later.
1407       RecordCrashReason(&crash_reason);
1408       SetCrashReason(&crash_reason);
1409
1410       // Store shortened fatal message for other logs and GWQ status
1411       const int copy = min<int>(data_->num_chars_to_log_,
1412                                 sizeof(fatal_message)-1);
1413       memcpy(fatal_message, data_->message_text_, copy);
1414       fatal_message[copy] = '\0';
1415       fatal_time = data_->timestamp_;
1416     }
1417
1418     if (!FLAGS_logtostderr) {
1419       for (int i = 0; i < NUM_SEVERITIES; ++i) {
1420         if ( LogDestination::log_destinations_[i] )
1421           LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0);
1422       }
1423     }
1424
1425     // release the lock that our caller (directly or indirectly)
1426     // LogMessage::~LogMessage() grabbed so that signal handlers
1427     // can use the logging facility. Alternately, we could add
1428     // an entire unsafe logging interface to bypass locking
1429     // for signal handlers but this seems simpler.
1430     log_mutex.Unlock();
1431     LogDestination::WaitForSinks(data_);
1432
1433     const char* message = "*** Check failure stack trace: ***\n";
1434     if (write(STDERR_FILENO, message, strlen(message)) < 0) {
1435       // Ignore errors.
1436     }
1437     Fail();
1438   }
1439 }
1440
1441 void LogMessage::RecordCrashReason(
1442     glog_internal_namespace_::CrashReason* reason) {
1443   reason->filename = fatal_msg_data_exclusive.fullname_;
1444   reason->line_number = fatal_msg_data_exclusive.line_;
1445   reason->message = fatal_msg_data_exclusive.message_text_ +
1446                     fatal_msg_data_exclusive.num_prefix_chars_;
1447 #ifdef HAVE_STACKTRACE
1448   // Retrieve the stack trace, omitting the logging frames that got us here.
1449   reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4);
1450 #else
1451   reason->depth = 0;
1452 #endif
1453 }
1454
1455 #ifdef HAVE___ATTRIBUTE__
1456 # define ATTRIBUTE_NORETURN __attribute__((noreturn))
1457 #else
1458 # define ATTRIBUTE_NORETURN
1459 #endif
1460
1461 static void logging_fail() ATTRIBUTE_NORETURN;
1462
1463 static void logging_fail() {
1464 #if defined(_DEBUG) && defined(_MSC_VER)
1465   // When debugging on windows, avoid the obnoxious dialog and make
1466   // it possible to continue past a LOG(FATAL) in the debugger
1467   __debugbreak();
1468 #else
1469   abort();
1470 #endif
1471 }
1472
1473 typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN;
1474
1475 GOOGLE_GLOG_DLL_DECL
1476 logging_fail_func_t g_logging_fail_func = &logging_fail;
1477
1478 void InstallFailureFunction(void (*fail_func)()) {
1479   g_logging_fail_func = (logging_fail_func_t)fail_func;
1480 }
1481
1482 void LogMessage::Fail() {
1483   g_logging_fail_func();
1484 }
1485
1486 // L >= log_mutex (callers must hold the log_mutex).
1487 void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1488   if (data_->sink_ != NULL) {
1489     RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1490                data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1491     data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_,
1492                        data_->line_, &data_->tm_time_,
1493                        data_->message_text_ + data_->num_prefix_chars_,
1494                        (data_->num_chars_to_log_ -
1495                         data_->num_prefix_chars_ - 1));
1496   }
1497 }
1498
1499 // L >= log_mutex (callers must hold the log_mutex).
1500 void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1501   SendToSink();
1502   SendToLog();
1503 }
1504
1505 // L >= log_mutex (callers must hold the log_mutex).
1506 void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1507   if (data_->outvec_ != NULL) {
1508     RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1509                data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1510     // Omit prefix of message and trailing newline when recording in outvec_.
1511     const char *start = data_->message_text_ + data_->num_prefix_chars_;
1512     int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1513     data_->outvec_->push_back(string(start, len));
1514   } else {
1515     SendToLog();
1516   }
1517 }
1518
1519 void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
1520   if (data_->message_ != NULL) {
1521     RAW_DCHECK(data_->num_chars_to_log_ > 0 &&
1522                data_->message_text_[data_->num_chars_to_log_-1] == '\n', "");
1523     // Omit prefix of message and trailing newline when writing to message_.
1524     const char *start = data_->message_text_ + data_->num_prefix_chars_;
1525     int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1;
1526     data_->message_->assign(start, len);
1527   }
1528   SendToLog();
1529 }
1530
1531 // L >= log_mutex (callers must hold the log_mutex).
1532 void LogMessage::SendToSyslogAndLog() {
1533 #ifdef HAVE_SYSLOG_H
1534   // Before any calls to syslog(), make a single call to openlog()
1535   static bool openlog_already_called = false;
1536   if (!openlog_already_called) {
1537     openlog(glog_internal_namespace_::ProgramInvocationShortName(),
1538             LOG_CONS | LOG_NDELAY | LOG_PID,
1539             LOG_USER);
1540     openlog_already_called = true;
1541   }
1542
1543   // This array maps Google severity levels to syslog levels
1544   const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG };
1545   syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s",
1546          int(data_->num_chars_to_syslog_),
1547          data_->message_text_ + data_->num_prefix_chars_);
1548   SendToLog();
1549 #else
1550   LOG(ERROR) << "No syslog support: message=" << data_->message_text_;
1551 #endif
1552 }
1553
1554 base::Logger* base::GetLogger(LogSeverity severity) {
1555   MutexLock l(&log_mutex);
1556   return LogDestination::log_destination(severity)->logger_;
1557 }
1558
1559 void base::SetLogger(LogSeverity severity, base::Logger* logger) {
1560   MutexLock l(&log_mutex);
1561   LogDestination::log_destination(severity)->logger_ = logger;
1562 }
1563
1564 // L < log_mutex.  Acquires and releases mutex_.
1565 int64 LogMessage::num_messages(int severity) {
1566   MutexLock l(&log_mutex);
1567   return num_messages_[severity];
1568 }
1569
1570 // Output the COUNTER value. This is only valid if ostream is a
1571 // LogStream.
1572 ostream& operator<<(ostream &os, const PRIVATE_Counter&) {
1573 #ifdef DISABLE_RTTI
1574   LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os);
1575 #else
1576   LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os);
1577 #endif
1578   CHECK(log && log == log->self())
1579       << "You must not use COUNTER with non-glog ostream";
1580   os << log->ctr();
1581   return os;
1582 }
1583
1584 ErrnoLogMessage::ErrnoLogMessage(const char* file, int line,
1585                                  LogSeverity severity, int ctr,
1586                                  void (LogMessage::*send_method)())
1587     : LogMessage(file, line, severity, ctr, send_method) {
1588 }
1589
1590 ErrnoLogMessage::~ErrnoLogMessage() {
1591   // Don't access errno directly because it may have been altered
1592   // while streaming the message.
1593   stream() << ": " << StrError(preserved_errno()) << " ["
1594            << preserved_errno() << "]";
1595 }
1596
1597 void FlushLogFiles(LogSeverity min_severity) {
1598   LogDestination::FlushLogFiles(min_severity);
1599 }
1600
1601 void FlushLogFilesUnsafe(LogSeverity min_severity) {
1602   LogDestination::FlushLogFilesUnsafe(min_severity);
1603 }
1604
1605 void SetLogDestination(LogSeverity severity, const char* base_filename) {
1606   LogDestination::SetLogDestination(severity, base_filename);
1607 }
1608
1609 void SetLogSymlink(LogSeverity severity, const char* symlink_basename) {
1610   LogDestination::SetLogSymlink(severity, symlink_basename);
1611 }
1612
1613 LogSink::~LogSink() {
1614 }
1615
1616 void LogSink::WaitTillSent() {
1617   // noop default
1618 }
1619
1620 string LogSink::ToString(LogSeverity severity, const char* file, int line,
1621                          const struct ::tm* tm_time,
1622                          const char* message, size_t message_len) {
1623   ostringstream stream(string(message, message_len));
1624   stream.fill('0');
1625
1626   // FIXME(jrvb): Updating this to use the correct value for usecs
1627   // requires changing the signature for both this method and
1628   // LogSink::send().  This change needs to be done in a separate CL
1629   // so subclasses of LogSink can be updated at the same time.
1630   int usecs = 0;
1631
1632   stream << LogSeverityNames[severity][0]
1633          << setw(2) << 1+tm_time->tm_mon
1634          << setw(2) << tm_time->tm_mday
1635          << ' '
1636          << setw(2) << tm_time->tm_hour << ':'
1637          << setw(2) << tm_time->tm_min << ':'
1638          << setw(2) << tm_time->tm_sec << '.'
1639          << setw(6) << usecs
1640          << ' '
1641          << setfill(' ') << setw(5) << GetTID() << setfill('0')
1642          << ' '
1643          << file << ':' << line << "] ";
1644
1645   stream << string(message, message_len);
1646   return stream.str();
1647 }
1648
1649 void AddLogSink(LogSink *destination) {
1650   LogDestination::AddLogSink(destination);
1651 }
1652
1653 void RemoveLogSink(LogSink *destination) {
1654   LogDestination::RemoveLogSink(destination);
1655 }
1656
1657 void SetLogFilenameExtension(const char* ext) {
1658   LogDestination::SetLogFilenameExtension(ext);
1659 }
1660
1661 void SetStderrLogging(LogSeverity min_severity) {
1662   LogDestination::SetStderrLogging(min_severity);
1663 }
1664
1665 void SetEmailLogging(LogSeverity min_severity, const char* addresses) {
1666   LogDestination::SetEmailLogging(min_severity, addresses);
1667 }
1668
1669 void LogToStderr() {
1670   LogDestination::LogToStderr();
1671 }
1672
1673 namespace base {
1674 namespace internal {
1675
1676 bool GetExitOnDFatal() {
1677   MutexLock l(&log_mutex);
1678   return exit_on_dfatal;
1679 }
1680
1681 // Determines whether we exit the program for a LOG(DFATAL) message in
1682 // debug mode.  It does this by skipping the call to Fail/FailQuietly.
1683 // This is intended for testing only.
1684 //
1685 // This can have some effects on LOG(FATAL) as well.  Failure messages
1686 // are always allocated (rather than sharing a buffer), the crash
1687 // reason is not recorded, the "gwq" status message is not updated,
1688 // and the stack trace is not recorded.  The LOG(FATAL) *will* still
1689 // exit the program.  Since this function is used only in testing,
1690 // these differences are acceptable.
1691 void SetExitOnDFatal(bool value) {
1692   MutexLock l(&log_mutex);
1693   exit_on_dfatal = value;
1694 }
1695
1696 }  // namespace internal
1697 }  // namespace base
1698
1699 // use_logging controls whether the logging functions LOG/VLOG are used
1700 // to log errors.  It should be set to false when the caller holds the
1701 // log_mutex.
1702 static bool SendEmailInternal(const char*dest, const char *subject,
1703                               const char*body, bool use_logging) {
1704   if (dest && *dest) {
1705     if ( use_logging ) {
1706       VLOG(1) << "Trying to send TITLE:" << subject
1707               << " BODY:" << body << " to " << dest;
1708     } else {
1709       fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n",
1710               subject, body, dest);
1711     }
1712
1713     string cmd =
1714         FLAGS_logmailer + " -s\"" + subject + "\" " + dest;
1715     FILE* pipe = popen(cmd.c_str(), "w");
1716     if (pipe != NULL) {
1717       // Add the body if we have one
1718       if (body)
1719         fwrite(body, sizeof(char), strlen(body), pipe);
1720       bool ok = pclose(pipe) != -1;
1721       if ( !ok ) {
1722         if ( use_logging ) {
1723           LOG(ERROR) << "Problems sending mail to " << dest << ": "
1724                      << StrError(errno);
1725         } else {
1726           fprintf(stderr, "Problems sending mail to %s: %s\n",
1727                   dest, StrError(errno).c_str());
1728         }
1729       }
1730       return ok;
1731     } else {
1732       if ( use_logging ) {
1733         LOG(ERROR) << "Unable to send mail to " << dest;
1734       } else {
1735         fprintf(stderr, "Unable to send mail to %s\n", dest);
1736       }
1737     }
1738   }
1739   return false;
1740 }
1741
1742 bool SendEmail(const char*dest, const char *subject, const char*body){
1743   return SendEmailInternal(dest, subject, body, true);
1744 }
1745
1746 static void GetTempDirectories(vector<string>* list) {
1747   list->clear();
1748 #ifdef OS_WINDOWS
1749   // On windows we'll try to find a directory in this order:
1750   //   C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is)
1751   //   C:/TMP/
1752   //   C:/TEMP/
1753   //   C:/WINDOWS/ or C:/WINNT/
1754   //   .
1755   char tmp[MAX_PATH];
1756   if (GetTempPathA(MAX_PATH, tmp))
1757     list->push_back(tmp);
1758   list->push_back("C:\\tmp\\");
1759   list->push_back("C:\\temp\\");
1760 #else
1761   // Directories, in order of preference. If we find a dir that
1762   // exists, we stop adding other less-preferred dirs
1763   const char * candidates[] = {
1764     // Non-null only during unittest/regtest
1765     getenv("TEST_TMPDIR"),
1766
1767     // Explicitly-supplied temp dirs
1768     getenv("TMPDIR"), getenv("TMP"),
1769
1770     // If all else fails
1771     "/tmp",
1772   };
1773
1774   for (size_t i = 0; i < ARRAYSIZE(candidates); i++) {
1775     const char *d = candidates[i];
1776     if (!d) continue;  // Empty env var
1777
1778     // Make sure we don't surprise anyone who's expecting a '/'
1779     string dstr = d;
1780     if (dstr[dstr.size() - 1] != '/') {
1781       dstr += "/";
1782     }
1783     list->push_back(dstr);
1784
1785     struct stat statbuf;
1786     if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) {
1787       // We found a dir that exists - we're done.
1788       return;
1789     }
1790   }
1791
1792 #endif
1793 }
1794
1795 static vector<string>* logging_directories_list;
1796
1797 const vector<string>& GetLoggingDirectories() {
1798   // Not strictly thread-safe but we're called early in InitGoogle().
1799   if (logging_directories_list == NULL) {
1800     logging_directories_list = new vector<string>;
1801
1802     if ( !FLAGS_log_dir.empty() ) {
1803       // A dir was specified, we should use it
1804       logging_directories_list->push_back(FLAGS_log_dir.c_str());
1805     } else {
1806       GetTempDirectories(logging_directories_list);
1807 #ifdef OS_WINDOWS
1808       char tmp[MAX_PATH];
1809       if (GetWindowsDirectoryA(tmp, MAX_PATH))
1810         logging_directories_list->push_back(tmp);
1811       logging_directories_list->push_back(".\\");
1812 #else
1813       logging_directories_list->push_back("./");
1814 #endif
1815     }
1816   }
1817   return *logging_directories_list;
1818 }
1819
1820 void TestOnly_ClearLoggingDirectoriesList() {
1821   fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be "
1822           "called from test code.\n");
1823   delete logging_directories_list;
1824   logging_directories_list = NULL;
1825 }
1826
1827 void GetExistingTempDirectories(vector<string>* list) {
1828   GetTempDirectories(list);
1829   vector<string>::iterator i_dir = list->begin();
1830   while( i_dir != list->end() ) {
1831     // zero arg to access means test for existence; no constant
1832     // defined on windows
1833     if ( access(i_dir->c_str(), 0) ) {
1834       i_dir = list->erase(i_dir);
1835     } else {
1836       ++i_dir;
1837     }
1838   }
1839 }
1840
1841 void TruncateLogFile(const char *path, int64 limit, int64 keep) {
1842 #ifdef HAVE_UNISTD_H
1843   struct stat statbuf;
1844   const int kCopyBlockSize = 8 << 10;
1845   char copybuf[kCopyBlockSize];
1846   int64 read_offset, write_offset;
1847   // Don't follow symlinks unless they're our own fd symlinks in /proc
1848   int flags = O_RDWR;
1849   // TODO(hamaji): Support other environments.
1850 #ifdef OS_LINUX
1851   const char *procfd_prefix = "/proc/self/fd/";
1852   if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW;
1853 #endif
1854
1855   int fd = open(path, flags);
1856   if (fd == -1) {
1857     if (errno == EFBIG) {
1858       // The log file in question has got too big for us to open. The
1859       // real fix for this would be to compile logging.cc (or probably
1860       // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's
1861       // rather scary.
1862       // Instead just truncate the file to something we can manage
1863       if (truncate(path, 0) == -1) {
1864         PLOG(ERROR) << "Unable to truncate " << path;
1865       } else {
1866         LOG(ERROR) << "Truncated " << path << " due to EFBIG error";
1867       }
1868     } else {
1869       PLOG(ERROR) << "Unable to open " << path;
1870     }
1871     return;
1872   }
1873
1874   if (fstat(fd, &statbuf) == -1) {
1875     PLOG(ERROR) << "Unable to fstat()";
1876     goto out_close_fd;
1877   }
1878
1879   // See if the path refers to a regular file bigger than the
1880   // specified limit
1881   if (!S_ISREG(statbuf.st_mode)) goto out_close_fd;
1882   if (statbuf.st_size <= limit)  goto out_close_fd;
1883   if (statbuf.st_size <= keep) goto out_close_fd;
1884
1885   // This log file is too large - we need to truncate it
1886   LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
1887
1888   // Copy the last "keep" bytes of the file to the beginning of the file
1889   read_offset = statbuf.st_size - keep;
1890   write_offset = 0;
1891   int bytesin, bytesout;
1892   while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
1893     bytesout = pwrite(fd, copybuf, bytesin, write_offset);
1894     if (bytesout == -1) {
1895       PLOG(ERROR) << "Unable to write to " << path;
1896       break;
1897     } else if (bytesout != bytesin) {
1898       LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
1899     }
1900     read_offset += bytesin;
1901     write_offset += bytesout;
1902   }
1903   if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path;
1904
1905   // Truncate the remainder of the file. If someone else writes to the
1906   // end of the file after our last read() above, we lose their latest
1907   // data. Too bad ...
1908   if (ftruncate(fd, write_offset) == -1) {
1909     PLOG(ERROR) << "Unable to truncate " << path;
1910   }
1911
1912  out_close_fd:
1913   close(fd);
1914 #else
1915   LOG(ERROR) << "No log truncation support.";
1916 #endif
1917 }
1918
1919 void TruncateStdoutStderr() {
1920 #ifdef HAVE_UNISTD_H
1921   int64 limit = MaxLogSize() << 20;
1922   int64 keep = 1 << 20;
1923   TruncateLogFile("/proc/self/fd/1", limit, keep);
1924   TruncateLogFile("/proc/self/fd/2", limit, keep);
1925 #else
1926   LOG(ERROR) << "No log truncation support.";
1927 #endif
1928 }
1929
1930
1931 // Helper functions for string comparisons.
1932 #define DEFINE_CHECK_STROP_IMPL(name, func, expected)                   \
1933   string* Check##func##expected##Impl(const char* s1, const char* s2,   \
1934                                       const char* names) {              \
1935     bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2));               \
1936     if (equal == expected) return NULL;                                 \
1937     else {                                                              \
1938       ostringstream ss;                                                 \
1939       if (!s1) s1 = "";                                                 \
1940       if (!s2) s2 = "";                                                 \
1941       ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \
1942       return new string(ss.str());                                      \
1943     }                                                                   \
1944   }
1945 DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true)
1946 DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false)
1947 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true)
1948 DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false)
1949 #undef DEFINE_CHECK_STROP_IMPL
1950
1951 int posix_strerror_r(int err, char *buf, size_t len) {
1952   // Sanity check input parameters
1953   if (buf == NULL || len <= 0) {
1954     errno = EINVAL;
1955     return -1;
1956   }
1957
1958   // Reset buf and errno, and try calling whatever version of strerror_r()
1959   // is implemented by glibc
1960   buf[0] = '\000';
1961   int old_errno = errno;
1962   errno = 0;
1963   char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len));
1964
1965   // Both versions set errno on failure
1966   if (errno) {
1967     // Should already be there, but better safe than sorry
1968     buf[0]     = '\000';
1969     return -1;
1970   }
1971   errno = old_errno;
1972
1973   // POSIX is vague about whether the string will be terminated, although
1974   // is indirectly implies that typically ERANGE will be returned, instead
1975   // of truncating the string. This is different from the GNU implementation.
1976   // We play it safe by always terminating the string explicitly.
1977   buf[len-1] = '\000';
1978
1979   // If the function succeeded, we can use its exit code to determine the
1980   // semantics implemented by glibc
1981   if (!rc) {
1982     return 0;
1983   } else {
1984     // GNU semantics detected
1985     if (rc == buf) {
1986       return 0;
1987     } else {
1988       buf[0] = '\000';
1989 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1990       if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
1991         // This means an error on MacOSX or FreeBSD.
1992         return -1;
1993       }
1994 #endif
1995       strncat(buf, rc, len-1);
1996       return 0;
1997     }
1998   }
1999 }
2000
2001 string StrError(int err) {
2002   char buf[100];
2003   int rc = posix_strerror_r(err, buf, sizeof(buf));
2004   if ((rc < 0) || (buf[0] == '\000')) {
2005     snprintf(buf, sizeof(buf), "Error number %d", err);
2006   }
2007   return buf;
2008 }
2009
2010 LogMessageFatal::LogMessageFatal(const char* file, int line) :
2011     LogMessage(file, line, GLOG_FATAL) {}
2012
2013 LogMessageFatal::LogMessageFatal(const char* file, int line,
2014                                  const CheckOpString& result) :
2015     LogMessage(file, line, result) {}
2016
2017 LogMessageFatal::~LogMessageFatal() {
2018     Flush();
2019     LogMessage::Fail();
2020 }
2021
2022 namespace base {
2023
2024 CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext)
2025     : stream_(new ostringstream) {
2026   *stream_ << exprtext << " (";
2027 }
2028
2029 CheckOpMessageBuilder::~CheckOpMessageBuilder() {
2030   delete stream_;
2031 }
2032
2033 ostream* CheckOpMessageBuilder::ForVar2() {
2034   *stream_ << " vs. ";
2035   return stream_;
2036 }
2037
2038 string* CheckOpMessageBuilder::NewString() {
2039   *stream_ << ")";
2040   return new string(stream_->str());
2041 }
2042
2043 }  // namespace base
2044
2045 template <>
2046 void MakeCheckOpValueString(std::ostream* os, const char& v) {
2047   if (v >= 32 && v <= 126) {
2048     (*os) << "'" << v << "'";
2049   } else {
2050     (*os) << "char value " << (short)v;
2051   }
2052 }
2053
2054 template <>
2055 void MakeCheckOpValueString(std::ostream* os, const signed char& v) {
2056   if (v >= 32 && v <= 126) {
2057     (*os) << "'" << v << "'";
2058   } else {
2059     (*os) << "signed char value " << (short)v;
2060   }
2061 }
2062
2063 template <>
2064 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) {
2065   if (v >= 32 && v <= 126) {
2066     (*os) << "'" << v << "'";
2067   } else {
2068     (*os) << "unsigned char value " << (unsigned short)v;
2069   }
2070 }
2071
2072 void InitGoogleLogging(const char* argv0) {
2073   glog_internal_namespace_::InitGoogleLoggingUtilities(argv0);
2074 }
2075
2076 void ShutdownGoogleLogging() {
2077   glog_internal_namespace_::ShutdownGoogleLoggingUtilities();
2078   LogDestination::DeleteLogDestinations();
2079   delete logging_directories_list;
2080   logging_directories_list = NULL;
2081 }
2082
2083 _END_GOOGLE_NAMESPACE_