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