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