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