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