1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/base/internal/raw_logging.h"
16
17 #include <cstdarg>
18 #include <cstddef>
19 #include <cstdio>
20 #include <cstdlib>
21 #include <cstring>
22 #include <string>
23
24 #include "absl/base/attributes.h"
25 #include "absl/base/config.h"
26 #include "absl/base/internal/atomic_hook.h"
27 #include "absl/base/internal/errno_saver.h"
28 #include "absl/base/log_severity.h"
29
30 // We know how to perform low-level writes to stderr in POSIX and Windows. For
31 // these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
32 // Much of raw_logging.cc becomes a no-op when we can't output messages,
33 // although a FATAL ABSL_RAW_LOG message will still abort the process.
34
35 // ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
36 // (as from unistd.h)
37 //
38 // This preprocessor token is also defined in raw_io.cc. If you need to copy
39 // this, consider moving both to config.h instead.
40 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
41 defined(__Fuchsia__) || defined(__native_client__) || \
42 defined(__OpenBSD__) || defined(__EMSCRIPTEN__) || defined(__ASYLO__)
43
44 #include <unistd.h>
45
46 #define ABSL_HAVE_POSIX_WRITE 1
47 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
48 #else
49 #undef ABSL_HAVE_POSIX_WRITE
50 #endif
51
52 // ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
53 // syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
54 // for low level operations that want to avoid libc.
55 #if (defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)) && \
56 !defined(__ANDROID__)
57 #include <sys/syscall.h>
58 #define ABSL_HAVE_SYSCALL_WRITE 1
59 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
60 #else
61 #undef ABSL_HAVE_SYSCALL_WRITE
62 #endif
63
64 #ifdef _WIN32
65 #include <io.h>
66
67 #define ABSL_HAVE_RAW_IO 1
68 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
69 #else
70 #undef ABSL_HAVE_RAW_IO
71 #endif
72
73 namespace absl {
74 ABSL_NAMESPACE_BEGIN
75 namespace raw_log_internal {
76 namespace {
77
78 // TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
79 // Explicitly `#error` out when not `ABSL_LOW_LEVEL_WRITE_SUPPORTED`, except for
80 // a selected set of platforms for which we expect not to be able to raw log.
81
82 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
83 constexpr char kTruncated[] = " ... (message truncated)\n";
84
85 // sprintf the format to the buffer, adjusting *buf and *size to reflect the
86 // consumed bytes, and return whether the message fit without truncation. If
87 // truncation occurred, if possible leave room in the buffer for the message
88 // kTruncated[].
89 bool VADoRawLog(char** buf, int* size, const char* format, va_list ap)
90 ABSL_PRINTF_ATTRIBUTE(3, 0);
VADoRawLog(char ** buf,int * size,const char * format,va_list ap)91 bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) {
92 if (*size < 0)
93 return false;
94 int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
95 bool result = true;
96 if (n < 0 || n > *size) {
97 result = false;
98 if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
99 n = *size - static_cast<int>(sizeof(kTruncated));
100 } else {
101 n = 0; // no room for truncation message
102 }
103 }
104 *size -= n;
105 *buf += n;
106 return result;
107 }
108 #endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED
109
110 constexpr int kLogBufSize = 3000;
111
112 // CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
113 // that invoke malloc() and getenv() that might acquire some locks.
114
115 // Helper for RawLog below.
116 // *DoRawLog writes to *buf of *size and move them past the written portion.
117 // It returns true iff there was no overflow or error.
118 bool DoRawLog(char** buf, int* size, const char* format, ...)
119 ABSL_PRINTF_ATTRIBUTE(3, 4);
DoRawLog(char ** buf,int * size,const char * format,...)120 bool DoRawLog(char** buf, int* size, const char* format, ...) {
121 if (*size < 0)
122 return false;
123 va_list ap;
124 va_start(ap, format);
125 int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
126 va_end(ap);
127 if (n < 0 || n > *size) return false;
128 *size -= n;
129 *buf += n;
130 return true;
131 }
132
DefaultLogFilterAndPrefix(absl::LogSeverity,const char * file,int line,char ** buf,int * buf_size)133 bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line,
134 char** buf, int* buf_size) {
135 DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line);
136 return true;
137 }
138
139 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
140 absl::base_internal::AtomicHook<LogFilterAndPrefixHook>
141 log_filter_and_prefix_hook(DefaultLogFilterAndPrefix);
142 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
143 absl::base_internal::AtomicHook<AbortHook> abort_hook;
144
145 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
146 const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0);
RawLogVA(absl::LogSeverity severity,const char * file,int line,const char * format,va_list ap)147 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
148 const char* format, va_list ap) {
149 char buffer[kLogBufSize];
150 char* buf = buffer;
151 int size = sizeof(buffer);
152 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
153 bool enabled = true;
154 #else
155 bool enabled = false;
156 #endif
157
158 #ifdef ABSL_MIN_LOG_LEVEL
159 if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
160 severity < absl::LogSeverity::kFatal) {
161 enabled = false;
162 }
163 #endif
164
165 enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size);
166 const char* const prefix_end = buf;
167
168 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
169 if (enabled) {
170 bool no_chop = VADoRawLog(&buf, &size, format, ap);
171 if (no_chop) {
172 DoRawLog(&buf, &size, "\n");
173 } else {
174 DoRawLog(&buf, &size, "%s", kTruncated);
175 }
176 AsyncSignalSafeWriteToStderr(buffer, strlen(buffer));
177 }
178 #else
179 static_cast<void>(format);
180 static_cast<void>(ap);
181 static_cast<void>(enabled);
182 #endif
183
184 // Abort the process after logging a FATAL message, even if the output itself
185 // was suppressed.
186 if (severity == absl::LogSeverity::kFatal) {
187 abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
188 abort();
189 }
190 }
191
192 // Non-formatting version of RawLog().
193 //
194 // TODO(gfalcon): When string_view no longer depends on base, change this
195 // interface to take its message as a string_view instead.
DefaultInternalLog(absl::LogSeverity severity,const char * file,int line,const std::string & message)196 void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line,
197 const std::string& message) {
198 RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()),
199 message.data());
200 }
201
202 } // namespace
203
AsyncSignalSafeWriteToStderr(const char * s,size_t len)204 void AsyncSignalSafeWriteToStderr(const char* s, size_t len) {
205 absl::base_internal::ErrnoSaver errno_saver;
206 #if defined(ABSL_HAVE_SYSCALL_WRITE)
207 // We prefer calling write via `syscall` to minimize the risk of libc doing
208 // something "helpful".
209 syscall(SYS_write, STDERR_FILENO, s, len);
210 #elif defined(ABSL_HAVE_POSIX_WRITE)
211 write(STDERR_FILENO, s, len);
212 #elif defined(ABSL_HAVE_RAW_IO)
213 _write(/* stderr */ 2, s, static_cast<unsigned>(len));
214 #else
215 // stderr logging unsupported on this platform
216 (void) s;
217 (void) len;
218 #endif
219 }
220
RawLog(absl::LogSeverity severity,const char * file,int line,const char * format,...)221 void RawLog(absl::LogSeverity severity, const char* file, int line,
222 const char* format, ...) {
223 va_list ap;
224 va_start(ap, format);
225 RawLogVA(severity, file, line, format, ap);
226 va_end(ap);
227 }
228
RawLoggingFullySupported()229 bool RawLoggingFullySupported() {
230 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
231 return true;
232 #else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
233 return false;
234 #endif // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
235 }
236
237 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
238 absl::base_internal::AtomicHook<InternalLogFunction>
239 internal_log_function(DefaultInternalLog);
240
RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func)241 void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) {
242 log_filter_and_prefix_hook.Store(func);
243 }
244
RegisterAbortHook(AbortHook func)245 void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); }
246
RegisterInternalLogFunction(InternalLogFunction func)247 void RegisterInternalLogFunction(InternalLogFunction func) {
248 internal_log_function.Store(func);
249 }
250
251 } // namespace raw_log_internal
252 ABSL_NAMESPACE_END
253 } // namespace absl
254