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