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