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