raw_logging.cc 8.9 KB

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