• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_logging_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   int n = vsnprintf(*buf, *size, format, ap);
93   bool result = true;
94   if (n < 0 || n > *size) {
95     result = false;
96     if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
97       n = *size - sizeof(kTruncated);  // room for truncation message
98     } else {
99       n = 0;  // no room for truncation message
100     }
101   }
102   *size -= n;
103   *buf += n;
104   return result;
105 }
106 #endif  // ABSL_LOW_LEVEL_WRITE_SUPPORTED
107 
108 constexpr int kLogBufSize = 3000;
109 
110 // CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
111 // that invoke malloc() and getenv() that might acquire some locks.
112 
113 // Helper for RawLog below.
114 // *DoRawLog writes to *buf of *size and move them past the written portion.
115 // It returns true iff there was no overflow or error.
116 bool DoRawLog(char** buf, int* size, const char* format, ...)
117     ABSL_PRINTF_ATTRIBUTE(3, 4);
DoRawLog(char ** buf,int * size,const char * format,...)118 bool DoRawLog(char** buf, int* size, const char* format, ...) {
119   va_list ap;
120   va_start(ap, format);
121   int n = vsnprintf(*buf, *size, format, ap);
122   va_end(ap);
123   if (n < 0 || n > *size) return false;
124   *size -= n;
125   *buf += n;
126   return true;
127 }
128 
DefaultLogFilterAndPrefix(absl::LogSeverity,const char * file,int line,char ** buf,int * buf_size)129 bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line,
130                                char** buf, int* buf_size) {
131   DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line);
132   return true;
133 }
134 
135 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
136 absl::base_internal::AtomicHook<LogFilterAndPrefixHook>
137     log_filter_and_prefix_hook(DefaultLogFilterAndPrefix);
138 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
139 absl::base_internal::AtomicHook<AbortHook> abort_hook;
140 
141 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
142               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)143 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
144               const char* format, va_list ap) {
145   char buffer[kLogBufSize];
146   char* buf = buffer;
147   int size = sizeof(buffer);
148 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
149   bool enabled = true;
150 #else
151   bool enabled = false;
152 #endif
153 
154 #ifdef ABSL_MIN_LOG_LEVEL
155   if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
156       severity < absl::LogSeverity::kFatal) {
157     enabled = false;
158   }
159 #endif
160 
161   enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size);
162   const char* const prefix_end = buf;
163 
164 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
165   if (enabled) {
166     bool no_chop = VADoRawLog(&buf, &size, format, ap);
167     if (no_chop) {
168       DoRawLog(&buf, &size, "\n");
169     } else {
170       DoRawLog(&buf, &size, "%s", kTruncated);
171     }
172     AsyncSignalSafeWriteToStderr(buffer, strlen(buffer));
173   }
174 #else
175   static_cast<void>(format);
176   static_cast<void>(ap);
177   static_cast<void>(enabled);
178 #endif
179 
180   // Abort the process after logging a FATAL message, even if the output itself
181   // was suppressed.
182   if (severity == absl::LogSeverity::kFatal) {
183     abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
184     abort();
185   }
186 }
187 
188 // Non-formatting version of RawLog().
189 //
190 // TODO(gfalcon): When string_view no longer depends on base, change this
191 // interface to take its message as a string_view instead.
DefaultInternalLog(absl::LogSeverity severity,const char * file,int line,const std::string & message)192 void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line,
193                         const std::string& message) {
194   RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()),
195          message.data());
196 }
197 
198 }  // namespace
199 
AsyncSignalSafeWriteToStderr(const char * s,size_t len)200 void AsyncSignalSafeWriteToStderr(const char* s, size_t len) {
201   absl::base_internal::ErrnoSaver errno_saver;
202 #if defined(ABSL_HAVE_SYSCALL_WRITE)
203   // We prefer calling write via `syscall` to minimize the risk of libc doing
204   // something "helpful".
205   syscall(SYS_write, STDERR_FILENO, s, len);
206 #elif defined(ABSL_HAVE_POSIX_WRITE)
207   write(STDERR_FILENO, s, len);
208 #elif defined(ABSL_HAVE_RAW_IO)
209   _write(/* stderr */ 2, s, len);
210 #else
211   // stderr logging unsupported on this platform
212   (void) s;
213   (void) len;
214 #endif
215 }
216 
RawLog(absl::LogSeverity severity,const char * file,int line,const char * format,...)217 void RawLog(absl::LogSeverity severity, const char* file, int line,
218             const char* format, ...) {
219   va_list ap;
220   va_start(ap, format);
221   RawLogVA(severity, file, line, format, ap);
222   va_end(ap);
223 }
224 
RawLoggingFullySupported()225 bool RawLoggingFullySupported() {
226 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
227   return true;
228 #else  // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
229   return false;
230 #endif  // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
231 }
232 
233 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
234     absl::base_internal::AtomicHook<InternalLogFunction>
235         internal_log_function(DefaultInternalLog);
236 
RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func)237 void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) {
238   log_filter_and_prefix_hook.Store(func);
239 }
240 
RegisterAbortHook(AbortHook func)241 void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); }
242 
RegisterInternalLogFunction(InternalLogFunction func)243 void RegisterInternalLogFunction(InternalLogFunction func) {
244   internal_log_function.Store(func);
245 }
246 
247 }  // namespace raw_logging_internal
248 ABSL_NAMESPACE_END
249 }  // namespace absl
250