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 <stddef.h>
18 #include <cstdarg>
19 #include <cstdio>
20 #include <cstdlib>
21 #include <cstring>
22 
23 #include "absl/base/attributes.h"
24 #include "absl/base/config.h"
25 #include "absl/base/internal/atomic_hook.h"
26 #include "absl/base/log_severity.h"
27 
28 // We know how to perform low-level writes to stderr in POSIX and Windows.  For
29 // these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
30 // Much of raw_logging.cc becomes a no-op when we can't output messages,
31 // although a FATAL ABSL_RAW_LOG message will still abort the process.
32 
33 // ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
34 // (as from unistd.h)
35 //
36 // This preprocessor token is also defined in raw_io.cc.  If you need to copy
37 // this, consider moving both to config.h instead.
38 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
39     defined(__Fuchsia__) || defined(__native_client__) || \
40     defined(__EMSCRIPTEN__) || defined(__ASYLO__)
41 
42 #include <unistd.h>
43 
44 #define ABSL_HAVE_POSIX_WRITE 1
45 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
46 #else
47 #undef ABSL_HAVE_POSIX_WRITE
48 #endif
49 
50 // ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
51 //   syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
52 // for low level operations that want to avoid libc.
53 #if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__)
54 #include <sys/syscall.h>
55 #define ABSL_HAVE_SYSCALL_WRITE 1
56 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
57 #else
58 #undef ABSL_HAVE_SYSCALL_WRITE
59 #endif
60 
61 #ifdef _WIN32
62 #include <io.h>
63 
64 #define ABSL_HAVE_RAW_IO 1
65 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
66 #else
67 #undef ABSL_HAVE_RAW_IO
68 #endif
69 
70 // TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
71 // Explicitly #error out when not ABSL_LOW_LEVEL_WRITE_SUPPORTED, except for a
72 // selected set of platforms for which we expect not to be able to raw log.
73 
74 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static absl::base_internal::AtomicHook<
75     absl::raw_logging_internal::LogPrefixHook>
76     log_prefix_hook;
77 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static absl::base_internal::AtomicHook<
78     absl::raw_logging_internal::AbortHook>
79     abort_hook;
80 
81 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
82 static const char kTruncated[] = " ... (message truncated)\n";
83 
84 // sprintf the format to the buffer, adjusting *buf and *size to reflect the
85 // consumed bytes, and return whether the message fit without truncation.  If
86 // truncation occurred, if possible leave room in the buffer for the message
87 // kTruncated[].
88 inline static bool VADoRawLog(char** buf, int* size, const char* format,
89                               va_list ap) ABSL_PRINTF_ATTRIBUTE(3, 0);
VADoRawLog(char ** buf,int * size,const char * format,va_list ap)90 inline static bool VADoRawLog(char** buf, int* size,
91                               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 static constexpr int kLogBufSize = 3000;
109 
110 namespace {
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   va_list ap;
122   va_start(ap, format);
123   int n = vsnprintf(*buf, *size, format, ap);
124   va_end(ap);
125   if (n < 0 || n > *size) return false;
126   *size -= n;
127   *buf += n;
128   return true;
129 }
130 
131 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
132               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)133 void RawLogVA(absl::LogSeverity severity, const char* file, int line,
134               const char* format, va_list ap) {
135   char buffer[kLogBufSize];
136   char* buf = buffer;
137   int size = sizeof(buffer);
138 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
139   bool enabled = true;
140 #else
141   bool enabled = false;
142 #endif
143 
144 #ifdef ABSL_MIN_LOG_LEVEL
145   if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
146       severity < absl::LogSeverity::kFatal) {
147     enabled = false;
148   }
149 #endif
150 
151   auto log_prefix_hook_ptr = log_prefix_hook.Load();
152   if (log_prefix_hook_ptr) {
153     enabled = log_prefix_hook_ptr(severity, file, line, &buf, &size);
154   } else {
155     if (enabled) {
156       DoRawLog(&buf, &size, "[%s : %d] RAW: ", file, line);
157     }
158   }
159   const char* const prefix_end = buf;
160 
161 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
162   if (enabled) {
163     bool no_chop = VADoRawLog(&buf, &size, format, ap);
164     if (no_chop) {
165       DoRawLog(&buf, &size, "\n");
166     } else {
167       DoRawLog(&buf, &size, "%s", kTruncated);
168     }
169     absl::raw_logging_internal::SafeWriteToStderr(buffer, strlen(buffer));
170   }
171 #else
172   static_cast<void>(format);
173   static_cast<void>(ap);
174 #endif
175 
176   // Abort the process after logging a FATAL message, even if the output itself
177   // was suppressed.
178   if (severity == absl::LogSeverity::kFatal) {
179     abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
180     abort();
181   }
182 }
183 
184 }  // namespace
185 
186 namespace absl {
187 ABSL_NAMESPACE_BEGIN
188 namespace raw_logging_internal {
SafeWriteToStderr(const char * s,size_t len)189 void SafeWriteToStderr(const char *s, size_t len) {
190 #if defined(ABSL_HAVE_SYSCALL_WRITE)
191   syscall(SYS_write, STDERR_FILENO, s, len);
192 #elif defined(ABSL_HAVE_POSIX_WRITE)
193   write(STDERR_FILENO, s, len);
194 #elif defined(ABSL_HAVE_RAW_IO)
195   _write(/* stderr */ 2, s, len);
196 #else
197   // stderr logging unsupported on this platform
198   (void) s;
199   (void) len;
200 #endif
201 }
202 
203 void RawLog(absl::LogSeverity severity, const char* file, int line,
204             const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
RawLog(absl::LogSeverity severity,const char * file,int line,const char * format,...)205 void RawLog(absl::LogSeverity severity, const char* file, int line,
206             const char* format, ...) {
207   va_list ap;
208   va_start(ap, format);
209   RawLogVA(severity, file, line, format, ap);
210   va_end(ap);
211 }
212 
213 // Non-formatting version of RawLog().
214 //
215 // TODO(gfalcon): When string_view no longer depends on base, change this
216 // interface to take its message as a string_view instead.
DefaultInternalLog(absl::LogSeverity severity,const char * file,int line,const std::string & message)217 static void DefaultInternalLog(absl::LogSeverity severity, const char* file,
218                                int line, const std::string& message) {
219   RawLog(severity, file, line, "%s", message.c_str());
220 }
221 
RawLoggingFullySupported()222 bool RawLoggingFullySupported() {
223 #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
224   return true;
225 #else  // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
226   return false;
227 #endif  // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
228 }
229 
230 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
231     absl::base_internal::AtomicHook<InternalLogFunction>
232         internal_log_function(DefaultInternalLog);
233 
RegisterInternalLogFunction(InternalLogFunction func)234 void RegisterInternalLogFunction(InternalLogFunction func) {
235   internal_log_function.Store(func);
236 }
237 
238 }  // namespace raw_logging_internal
239 ABSL_NAMESPACE_END
240 }  // namespace absl
241