raw_logging.cc 8.0 KB

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