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