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 #ifdef __EMSCRIPTEN__
25 #include <emscripten/console.h>
26 #endif
27
28 #include "absl/base/attributes.h"
29 #include "absl/base/config.h"
30 #include "absl/base/internal/atomic_hook.h"
31 #include "absl/base/internal/errno_saver.h"
32 #include "absl/base/log_severity.h"
33
34 // We know how to perform low-level writes to stderr in POSIX and Windows. For
35 // these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
36 // Much of raw_logging.cc becomes a no-op when we can't output messages,
37 // although a FATAL ABSL_RAW_LOG message will still abort the process.
38
39 // ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
40 // (as from unistd.h)
41 //
42 // This preprocessor token is also defined in raw_io.cc. If you need to copy
43 // this, consider moving both to config.h instead.
44 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
45 defined(__Fuchsia__) || defined(__native_client__) || \
46 defined(__OpenBSD__) || defined(__EMSCRIPTEN__) || defined(__ASYLO__)
47
48 #include <unistd.h>
49
50 #define ABSL_HAVE_POSIX_WRITE 1
51 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
52 #else
53 #undef ABSL_HAVE_POSIX_WRITE
54 #endif
55
56 // ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
57 // syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
58 // for low level operations that want to avoid libc.
59 #if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__)
60 #include <sys/syscall.h>
61 #define ABSL_HAVE_SYSCALL_WRITE 1
62 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
63 #else
64 #undef ABSL_HAVE_SYSCALL_WRITE
65 #endif
66
67 #ifdef _WIN32
68 #include <io.h>
69
70 #define ABSL_HAVE_RAW_IO 1
71 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
72 #else
73 #undef ABSL_HAVE_RAW_IO
74 #endif
75
76 namespace absl {
77 ABSL_NAMESPACE_BEGIN
78 namespace raw_log_internal {
79 namespace {
80
81 // TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
82 // Explicitly `#error` out when not `ABSL_LOW_LEVEL_WRITE_SUPPORTED`, except for
83 // a selected set of platforms for which we expect not to be able to raw log.
84
85 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
86 constexpr char kTruncated[] = " ... (message truncated)\n";
87
88 // sprintf the format to the buffer, adjusting *buf and *size to reflect the
89 // consumed bytes, and return whether the message fit without truncation. If
90 // truncation occurred, if possible leave room in the buffer for the message
91 // kTruncated[].
92 bool VADoRawLog(char** buf, int* size, const char* format, va_list ap)
93 ABSL_PRINTF_ATTRIBUTE(3, 0);
VADoRawLog(char ** buf,int * size,const char * format,va_list ap)94 bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) {
95 if (*size < 0) return false;
96 int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
97 bool result = true;
98 if (n < 0 || n > *size) {
99 result = false;
100 if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
101 n = *size - static_cast<int>(sizeof(kTruncated));
102 } else {
103 n = 0; // no room for truncation message
104 }
105 }
106 *size -= n;
107 *buf += n;
108 return result;
109 }
110 #endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED
111
112 constexpr int kLogBufSize = 3000;
113
114 // CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
115 // that invoke malloc() and getenv() that might acquire some locks.
116
117 // Helper for RawLog below.
118 // *DoRawLog writes to *buf of *size and move them past the written portion.
119 // It returns true iff there was no overflow or error.
120 bool DoRawLog(char** buf, int* size, const char* format, ...)
121 ABSL_PRINTF_ATTRIBUTE(3, 4);
DoRawLog(char ** buf,int * size,const char * format,...)122 bool DoRawLog(char** buf, int* size, const char* format, ...) {
123 if (*size < 0) return false;
124 va_list ap;
125 va_start(ap, format);
126 int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
127 va_end(ap);
128 if (n < 0 || n > *size) return false;
129 *size -= n;
130 *buf += n;
131 return true;
132 }
133
DefaultLogFilterAndPrefix(absl::LogSeverity,const char * file,int line,char ** buf,int * buf_size)134 bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line,
135 char** buf, int* buf_size) {
136 DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line);
137 return true;
138 }
139
140 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
141 absl::base_internal::AtomicHook<LogFilterAndPrefixHook>
142 log_filter_and_prefix_hook(DefaultLogFilterAndPrefix);
143 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
144 absl::base_internal::AtomicHook<AbortHook> abort_hook;
145
146 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
147 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)148 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
149 const char* format, va_list ap) {
150 char buffer[kLogBufSize];
151 char* buf = buffer;
152 int size = sizeof(buffer);
153 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
154 bool enabled = true;
155 #else
156 bool enabled = false;
157 #endif
158
159 #ifdef ABSL_MIN_LOG_LEVEL
160 if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
161 severity < absl::LogSeverity::kFatal) {
162 enabled = false;
163 }
164 #endif
165
166 enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size);
167 const char* const prefix_end = buf;
168
169 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
170 if (enabled) {
171 bool no_chop = VADoRawLog(&buf, &size, format, ap);
172 if (no_chop) {
173 DoRawLog(&buf, &size, "\n");
174 } else {
175 DoRawLog(&buf, &size, "%s", kTruncated);
176 }
177 AsyncSignalSafeWriteError(buffer, strlen(buffer));
178 }
179 #else
180 static_cast<void>(format);
181 static_cast<void>(ap);
182 static_cast<void>(enabled);
183 #endif
184
185 // Abort the process after logging a FATAL message, even if the output itself
186 // was suppressed.
187 if (severity == absl::LogSeverity::kFatal) {
188 abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
189 abort();
190 }
191 }
192
193 // Non-formatting version of RawLog().
194 //
195 // TODO(gfalcon): When string_view no longer depends on base, change this
196 // interface to take its message as a string_view instead.
DefaultInternalLog(absl::LogSeverity severity,const char * file,int line,const std::string & message)197 void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line,
198 const std::string& message) {
199 RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()),
200 message.data());
201 }
202
203 } // namespace
204
AsyncSignalSafeWriteError(const char * s,size_t len)205 void AsyncSignalSafeWriteError(const char* s, size_t len) {
206 if (!len) return;
207 absl::base_internal::ErrnoSaver errno_saver;
208 #if defined(__EMSCRIPTEN__)
209 // In WebAssembly, bypass filesystem emulation via fwrite.
210 if (s[len - 1] == '\n') {
211 // Skip a trailing newline character as emscripten_errn adds one itself.
212 len--;
213 }
214 // emscripten_errn was introduced in 3.1.41 but broken in standalone mode
215 // until 3.1.43.
216 #if ABSL_INTERNAL_EMSCRIPTEN_VERSION >= 3001043
217 emscripten_errn(s, len);
218 #else
219 char buf[kLogBufSize];
220 if (len >= kLogBufSize) {
221 len = kLogBufSize - 1;
222 constexpr size_t trunc_len = sizeof(kTruncated) - 2;
223 memcpy(buf + len - trunc_len, kTruncated, trunc_len);
224 buf[len] = '\0';
225 len -= trunc_len;
226 } else {
227 buf[len] = '\0';
228 }
229 memcpy(buf, s, len);
230 _emscripten_err(buf);
231 #endif
232 #elif defined(ABSL_HAVE_SYSCALL_WRITE)
233 // We prefer calling write via `syscall` to minimize the risk of libc doing
234 // something "helpful".
235 syscall(SYS_write, STDERR_FILENO, s, len);
236 #elif defined(ABSL_HAVE_POSIX_WRITE)
237 write(STDERR_FILENO, s, len);
238 #elif defined(ABSL_HAVE_RAW_IO)
239 _write(/* stderr */ 2, s, static_cast<unsigned>(len));
240 #else
241 // stderr logging unsupported on this platform
242 (void)s;
243 (void)len;
244 #endif
245 }
246
RawLog(absl::LogSeverity severity,const char * file,int line,const char * format,...)247 void RawLog(absl::LogSeverity severity, const char* file, int line,
248 const char* format, ...) {
249 va_list ap;
250 va_start(ap, format);
251 RawLogVA(severity, file, line, format, ap);
252 va_end(ap);
253 }
254
RawLoggingFullySupported()255 bool RawLoggingFullySupported() {
256 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
257 return true;
258 #else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
259 return false;
260 #endif // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
261 }
262
263 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
264 absl::base_internal::AtomicHook<InternalLogFunction>
265 internal_log_function(DefaultInternalLog);
266
RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func)267 void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) {
268 log_filter_and_prefix_hook.Store(func);
269 }
270
RegisterAbortHook(AbortHook func)271 void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); }
272
RegisterInternalLogFunction(InternalLogFunction func)273 void RegisterInternalLogFunction(InternalLogFunction func) {
274 internal_log_function.Store(func);
275 }
276
277 } // namespace raw_log_internal
278 ABSL_NAMESPACE_END
279 } // namespace absl
280