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