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