blob: efe6e7d53cfddcca1025881e7f404caea024c83a [file] [log] [blame]
Austin Schuh906616c2019-01-21 20:25:11 -08001// Copyright (c) 2006, 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// Author: Maxim Lifantsev
31//
32// logging_unittest.cc covers the functionality herein
33
34#include "utilities.h"
35
36#include <stdarg.h>
37#include <stdio.h>
38#include <errno.h>
39#ifdef HAVE_UNISTD_H
40# include <unistd.h> // for close() and write()
41#endif
42#include <fcntl.h> // for open()
43#include <time.h>
44#include "config.h"
45#include "glog/logging.h" // To pick up flag settings etc.
46#include "glog/raw_logging.h"
47#include "base/commandlineflags.h"
48
49#ifdef HAVE_STACKTRACE
50# include "stacktrace.h"
51#endif
52
53#if defined(HAVE_SYSCALL_H)
54#include <syscall.h> // for syscall()
55#elif defined(HAVE_SYS_SYSCALL_H)
56#include <sys/syscall.h> // for syscall()
57#endif
58#ifdef HAVE_UNISTD_H
59# include <unistd.h>
60#endif
61
62#if defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)
63# define safe_write(fd, s, len) syscall(SYS_write, fd, s, len)
64#else
65 // Not so safe, but what can you do?
66# define safe_write(fd, s, len) write(fd, s, len)
67#endif
68
Austin Schuh61226052022-06-20 09:40:08 -070069namespace aos {
70void FatalUnsetRealtimePriority() __attribute__((weak));
71}
72
73static void MaybeUnsetRealtime() {
74 if (&aos::FatalUnsetRealtimePriority != nullptr) {
75 aos::FatalUnsetRealtimePriority();
76 }
77}
78
Austin Schuh906616c2019-01-21 20:25:11 -080079_START_GOOGLE_NAMESPACE_
80
81// Data for RawLog__ below. We simply pick up the latest
82// time data created by a normal log message to avoid calling
83// localtime_r which can allocate memory.
84static struct ::tm last_tm_time_for_raw_log;
85static int last_usecs_for_raw_log;
86
87void RawLog__SetLastTime(const struct ::tm& t, int usecs) {
88 memcpy(&last_tm_time_for_raw_log, &t, sizeof(last_tm_time_for_raw_log));
89 last_usecs_for_raw_log = usecs;
90}
91
92// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
93// that invoke malloc() and getenv() that might acquire some locks.
94// If this becomes a problem we should reimplement a subset of vsnprintf
95// that does not need locks and malloc.
96
97// Helper for RawLog__ below.
98// *DoRawLog writes to *buf of *size and move them past the written portion.
99// It returns true iff there was no overflow or error.
100static bool DoRawLog(char** buf, int* size, const char* format, ...) {
101 va_list ap;
102 va_start(ap, format);
103 int n = vsnprintf(*buf, *size, format, ap);
104 va_end(ap);
105 if (n < 0 || n > *size) return false;
106 *size -= n;
107 *buf += n;
108 return true;
109}
110
111// Helper for RawLog__ below.
112inline static bool VADoRawLog(char** buf, int* size,
113 const char* format, va_list ap) {
114 int n = vsnprintf(*buf, *size, format, ap);
115 if (n < 0 || n > *size) return false;
116 *size -= n;
117 *buf += n;
118 return true;
119}
120
121static const int kLogBufSize = 3000;
122static bool crashed = false;
123static CrashReason crash_reason;
124static char crash_buf[kLogBufSize + 1] = { 0 }; // Will end in '\0'
125
126void RawLog__(LogSeverity severity, const char* file, int line,
127 const char* format, ...) {
128 if (!(FLAGS_logtostderr || severity >= FLAGS_stderrthreshold ||
129 FLAGS_alsologtostderr || !IsGoogleLoggingInitialized())) {
130 return; // this stderr log message is suppressed
131 }
132 // can't call localtime_r here: it can allocate
133 struct ::tm& t = last_tm_time_for_raw_log;
134 char buffer[kLogBufSize];
135 char* buf = buffer;
136 int size = sizeof(buffer);
137
138 // NOTE: this format should match the specification in base/logging.h
139 DoRawLog(&buf, &size, "%c%02d%02d %02d:%02d:%02d.%06d %5u %s:%d] RAW: ",
140 LogSeverityNames[severity][0],
141 1 + t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
142 last_usecs_for_raw_log,
143 static_cast<unsigned int>(GetTID()),
144 const_basename(const_cast<char *>(file)), line);
145
146 // Record the position and size of the buffer after the prefix
147 const char* msg_start = buf;
148 const int msg_size = size;
149
150 va_list ap;
151 va_start(ap, format);
152 bool no_chop = VADoRawLog(&buf, &size, format, ap);
153 va_end(ap);
154 if (no_chop) {
155 DoRawLog(&buf, &size, "\n");
156 } else {
157 DoRawLog(&buf, &size, "RAW_LOG ERROR: The Message was too long!\n");
158 }
159 // We make a raw syscall to write directly to the stderr file descriptor,
160 // avoiding FILE buffering (to avoid invoking malloc()), and bypassing
161 // libc (to side-step any libc interception).
162 // We write just once to avoid races with other invocations of RawLog__.
163 safe_write(STDERR_FILENO, buffer, strlen(buffer));
164 if (severity == GLOG_FATAL) {
Austin Schuh61226052022-06-20 09:40:08 -0700165 MaybeUnsetRealtime();
Austin Schuh906616c2019-01-21 20:25:11 -0800166 if (!sync_val_compare_and_swap(&crashed, false, true)) {
167 crash_reason.filename = file;
168 crash_reason.line_number = line;
169 memcpy(crash_buf, msg_start, msg_size); // Don't include prefix
170 crash_reason.message = crash_buf;
171#ifdef HAVE_STACKTRACE
172 crash_reason.depth =
173 GetStackTrace(crash_reason.stack, ARRAYSIZE(crash_reason.stack), 1);
174#else
175 crash_reason.depth = 0;
176#endif
177 SetCrashReason(&crash_reason);
178 }
179 LogMessage::Fail(); // abort()
180 }
181}
182
183_END_GOOGLE_NAMESPACE_