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