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