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