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