1 /* 2 * Copyright (C) 2021 The Android Open Source Project 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 * http://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 17 #ifndef SRC_BASE_LOG_RING_BUFFER_H_ 18 #define SRC_BASE_LOG_RING_BUFFER_H_ 19 20 #include <stddef.h> 21 #include <stdio.h> 22 23 #include <array> 24 #include <atomic> 25 26 #include "perfetto/ext/base/string_view.h" 27 #include "perfetto/ext/base/thread_annotations.h" 28 29 namespace perfetto { 30 namespace base { 31 32 // Defined out of line because a static constexpr requires static storage if 33 // ODR-used, not worth adding a .cc file just for tests. 34 constexpr size_t kLogRingBufEntries = 8; 35 constexpr size_t kLogRingBufMsgLen = 256; 36 37 // A static non-allocating ring-buffer to hold the most recent log events. 38 // This class is really an implementation detail of logging.cc. The only reason 39 // why is fully defined in a dedicated header is for allowing unittesting, 40 // without leaking extra headers into logging.h (which is a high-fanout header). 41 // This is used to report the last logs in a crash report when a CHECK/FATAL 42 // is encountered. 43 // This class has just an Append() method to insert events into the buffer and 44 // a Read() to read the events in FIFO order. Read() is non-destructive. 45 // 46 // Thread safety considerations: 47 // - The Append() method can be called concurrently by several threads, unless 48 // there are > kLogRingBufEntries concurrent threads. Even if that happens, 49 // case some events will contain a mix of strings but the behavior of 50 // futher Append() and Read() is still defined. 51 // - The Read() method is not thread safe but it's fine in practice. Even if 52 // it's called concurrently with other Append(), it only causes some partial 53 // events to be emitted in output. 54 // In both cases, we never rely purely on \0, all operations are size-bound. 55 // 56 // See logging_unittest.cc for tests. 57 class LogRingBuffer { 58 public: 59 LogRingBuffer() = default; 60 LogRingBuffer(const LogRingBuffer&) = delete; 61 LogRingBuffer& operator=(const LogRingBuffer&) = delete; 62 LogRingBuffer(LogRingBuffer&&) = delete; 63 LogRingBuffer& operator=(LogRingBuffer&&) = delete; 64 65 // This takes three arguments because it fits its only caller (logging.cc). 66 // The args are just concatenated together (plus one space before the msg). Append(StringView tstamp,StringView source,StringView log_msg)67 void Append(StringView tstamp, StringView source, StringView log_msg) { 68 // Reserve atomically a slot in the ring buffer, so any concurrent Append() 69 // won't overlap (unless too many concurrent Append() happen together). 70 // There is no strict synchronization here, |event_slot_| is atomic only for 71 // the sake of avoiding colliding on the same slot but does NOT guarantee 72 // full consistency and integrity of the log messages written in each slot. 73 // A release-store (or acq+rel) won't be enough for full consistency. Two 74 // threads that race on Append() and take the N+1 and N+2 slots could finish 75 // the write in reverse order. So Read() would need to synchronize with 76 // something else (either a per-slot atomic flag or with a second atomic 77 // counter which is incremented after the snprintf). Both options increase 78 // the cost of Append() with no huge benefits (90% of the perfetto services 79 // where we use it is single thread, and the log ring buffer is disabled 80 // on non-standalone builds like the SDK). 81 uint32_t slot = event_slot_.fetch_add(1, std::memory_order_relaxed); 82 slot = slot % kLogRingBufEntries; 83 84 char* const msg = events_[slot]; 85 PERFETTO_ANNOTATE_BENIGN_RACE_SIZED(msg, kLogRingBufMsgLen, 86 "see comments in log_ring_buffer.h") 87 snprintf(msg, kLogRingBufMsgLen, "%.*s%.*s %.*s", 88 static_cast<int>(tstamp.size()), tstamp.data(), 89 static_cast<int>(source.size()), source.data(), 90 static_cast<int>(log_msg.size()), log_msg.data()); 91 } 92 93 // Reads back the buffer in FIFO order, up to |len - 1| characters at most 94 // (the -1 is because a NUL terminator is always appended, unless |len| == 0). 95 // The string written in |dst| is guaranteed to be NUL-terminated, even if 96 // |len| < buffer contents length. 97 // Returns the number of bytes written in output, excluding the \0 terminator. Read(char * dst,size_t len)98 size_t Read(char* dst, size_t len) { 99 if (len == 0) 100 return 0; 101 // This is a relaxed-load because we don't need to fully synchronize on the 102 // writing path for the reasons described in the fetch_add() above. 103 const uint32_t event_slot = event_slot_.load(std::memory_order_relaxed); 104 size_t dst_written = 0; 105 for (uint32_t pos = 0; pos < kLogRingBufEntries; ++pos) { 106 const uint32_t slot = (event_slot + pos) % kLogRingBufEntries; 107 const char* src = events_[slot]; 108 if (*src == '\0') 109 continue; // Empty slot. Skip. 110 char* const wptr = dst + dst_written; 111 // |src| might not be null terminated. This can happen if some 112 // thread-race happened. Limit the copy length. 113 const size_t limit = std::min(len - dst_written, kLogRingBufMsgLen); 114 for (size_t i = 0; i < limit; ++i) { 115 const char c = src[i]; 116 ++dst_written; 117 if (c == '\0' || i == limit - 1) { 118 wptr[i] = '\n'; 119 break; 120 } 121 // Skip non-printable ASCII characters to avoid confusing crash reports. 122 // Note that this deliberately mangles \n. Log messages should not have 123 // a \n in the middle and are NOT \n terminated. The trailing \n between 124 // each line is appended by the if () branch above. 125 const bool is_printable = c >= ' ' && c <= '~'; 126 wptr[i] = is_printable ? c : '?'; 127 } 128 } 129 // Ensure that the output string is null-terminated. 130 PERFETTO_DCHECK(dst_written <= len); 131 if (dst_written == len) { 132 // In case of truncation we replace the last char with \0. But the return 133 // value is the number of chars without \0, hence the --. 134 dst[--dst_written] = '\0'; 135 } else { 136 dst[dst_written] = '\0'; 137 } 138 return dst_written; 139 } 140 141 private: 142 using EventBuf = char[kLogRingBufMsgLen]; 143 EventBuf events_[kLogRingBufEntries]{}; 144 145 static_assert((kLogRingBufEntries & (kLogRingBufEntries - 1)) == 0, 146 "kLogRingBufEntries must be a power of two"); 147 148 // A monotonically increasing counter incremented on each event written. 149 // It determines which of the kLogRingBufEntries indexes in |events_| should 150 // be used next. 151 // It grows >> kLogRingBufEntries, it's supposed to be always used 152 // mod(kLogRingBufEntries). A static_assert in the .cc file ensures that 153 // kLogRingBufEntries is a power of two so wraps are aligned. 154 std::atomic<uint32_t> event_slot_{}; 155 }; 156 157 } // namespace base 158 } // namespace perfetto 159 160 #endif // SRC_BASE_LOG_RING_BUFFER_H_ 161