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