blob: ec08d54d4600d7b82238c2500d2ec1135bf39751 [file] [log] [blame]
Tom Cherry8f613462020-05-12 12:46:43 -07001/*
2 * Copyright (C) 2020 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#include "SimpleLogBuffer.h"
18
Tom Cherryf93b4002020-06-03 09:23:49 -070019#include <android-base/logging.h>
20
Tom Cherry8f613462020-05-12 12:46:43 -070021#include "LogBufferElement.h"
22
23SimpleLogBuffer::SimpleLogBuffer(LogReaderList* reader_list, LogTags* tags, LogStatistics* stats)
24 : reader_list_(reader_list), tags_(tags), stats_(stats) {
25 Init();
26}
27
28SimpleLogBuffer::~SimpleLogBuffer() {}
29
30void SimpleLogBuffer::Init() {
31 log_id_for_each(i) {
32 if (SetSize(i, __android_logger_get_buffer_size(i))) {
33 SetSize(i, LOG_BUFFER_MIN_SIZE);
34 }
35 }
36
37 // Release any sleeping reader threads to dump their current content.
38 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
39 for (const auto& reader_thread : reader_list_->reader_threads()) {
40 reader_thread->triggerReader_Locked();
41 }
42}
43
44std::list<LogBufferElement>::iterator SimpleLogBuffer::GetOldest(log_id_t log_id) {
45 auto it = logs().begin();
46 if (oldest_[log_id]) {
47 it = *oldest_[log_id];
48 }
Tom Cherry9787f9a2020-05-19 19:01:16 -070049 while (it != logs().end() && it->log_id() != log_id) {
Tom Cherry8f613462020-05-12 12:46:43 -070050 it++;
51 }
52 if (it != logs().end()) {
53 oldest_[log_id] = it;
54 }
55 return it;
56}
57
58bool SimpleLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
59 if (log_id == LOG_ID_SECURITY) {
60 return true;
61 }
62
63 int prio = ANDROID_LOG_INFO;
64 const char* tag = nullptr;
65 size_t tag_len = 0;
Tom Cherry3dd3ec32020-06-02 15:39:21 -070066 if (IsBinary(log_id)) {
67 int32_t numeric_tag = MsgToTag(msg, len);
Tom Cherry8f613462020-05-12 12:46:43 -070068 tag = tags_->tagToName(numeric_tag);
69 if (tag) {
70 tag_len = strlen(tag);
71 }
72 } else {
73 prio = *msg;
74 tag = msg + 1;
75 tag_len = strnlen(tag, len - 1);
76 }
77 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
78}
79
80int SimpleLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
81 const char* msg, uint16_t len) {
82 if (log_id >= LOG_ID_MAX) {
83 return -EINVAL;
84 }
85
86 if (!ShouldLog(log_id, msg, len)) {
87 // Log traffic received to total
88 stats_->AddTotal(log_id, len);
89 return -EACCES;
90 }
91
92 // Slip the time by 1 nsec if the incoming lands on xxxxxx000 ns.
93 // This prevents any chance that an outside source can request an
94 // exact entry with time specified in ms or us precision.
95 if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
96
97 auto lock = std::lock_guard{lock_};
98 auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
99 LogInternal(LogBufferElement(log_id, realtime, uid, pid, tid, sequence, msg, len));
100 return len;
101}
102
103void SimpleLogBuffer::LogInternal(LogBufferElement&& elem) {
Tom Cherry9787f9a2020-05-19 19:01:16 -0700104 log_id_t log_id = elem.log_id();
Tom Cherry8f613462020-05-12 12:46:43 -0700105
106 logs_.emplace_back(std::move(elem));
Tom Cherry3dd3ec32020-06-02 15:39:21 -0700107 stats_->Add(logs_.back().ToLogStatisticsElement());
Tom Cherry8f613462020-05-12 12:46:43 -0700108 MaybePrune(log_id);
109 reader_list_->NotifyNewLog(1 << log_id);
110}
111
Tom Cherry855c7c82020-05-28 12:38:21 -0700112// These extra parameters are only required for chatty, but since they're a no-op for
113// SimpleLogBuffer, it's easier to include them here, then to duplicate FlushTo() for
114// ChattyLogBuffer.
115class ChattyFlushToState : public FlushToState {
116 public:
117 ChattyFlushToState(uint64_t start, LogMask log_mask) : FlushToState(start, log_mask) {}
118
119 pid_t* last_tid() { return last_tid_; }
120
Tom Cherryb3e16332020-05-28 20:02:42 -0700121 bool drop_chatty_messages() const { return drop_chatty_messages_; }
122 void set_drop_chatty_messages(bool value) { drop_chatty_messages_ = value; }
123
Tom Cherry855c7c82020-05-28 12:38:21 -0700124 private:
125 pid_t last_tid_[LOG_ID_MAX] = {};
Tom Cherryb3e16332020-05-28 20:02:42 -0700126 bool drop_chatty_messages_ = true;
Tom Cherry855c7c82020-05-28 12:38:21 -0700127};
128
129std::unique_ptr<FlushToState> SimpleLogBuffer::CreateFlushToState(uint64_t start,
130 LogMask log_mask) {
131 return std::make_unique<ChattyFlushToState>(start, log_mask);
132}
133
134bool SimpleLogBuffer::FlushTo(
135 LogWriter* writer, FlushToState& abstract_state,
Tom Cherry70fadea2020-05-27 14:43:19 -0700136 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
Tom Cherryb3e16332020-05-28 20:02:42 -0700137 log_time realtime)>& filter) {
Tom Cherry8f613462020-05-12 12:46:43 -0700138 auto shared_lock = SharedLock{lock_};
139
Tom Cherry855c7c82020-05-28 12:38:21 -0700140 auto& state = reinterpret_cast<ChattyFlushToState&>(abstract_state);
141
Tom Cherry8f613462020-05-12 12:46:43 -0700142 std::list<LogBufferElement>::iterator it;
Tom Cherry855c7c82020-05-28 12:38:21 -0700143 if (state.start() <= 1) {
Tom Cherry8f613462020-05-12 12:46:43 -0700144 // client wants to start from the beginning
145 it = logs_.begin();
146 } else {
147 // Client wants to start from some specified time. Chances are
148 // we are better off starting from the end of the time sorted list.
149 for (it = logs_.end(); it != logs_.begin();
150 /* do nothing */) {
151 --it;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700152 if (it->sequence() == state.start()) {
Tom Cherry90e9ce02020-06-01 13:43:50 -0700153 break;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700154 } else if (it->sequence() < state.start()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700155 it++;
156 break;
157 }
158 }
159 }
160
Tom Cherry8f613462020-05-12 12:46:43 -0700161 for (; it != logs_.end(); ++it) {
162 LogBufferElement& element = *it;
163
Tom Cherry9787f9a2020-05-19 19:01:16 -0700164 state.set_start(element.sequence());
Tom Cherry855c7c82020-05-28 12:38:21 -0700165
Tom Cherry9787f9a2020-05-19 19:01:16 -0700166 if (!writer->privileged() && element.uid() != writer->uid()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700167 continue;
168 }
169
Tom Cherry9787f9a2020-05-19 19:01:16 -0700170 if (((1 << element.log_id()) & state.log_mask()) == 0) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700171 continue;
172 }
173
Tom Cherry8f613462020-05-12 12:46:43 -0700174 if (filter) {
Tom Cherryb3e16332020-05-28 20:02:42 -0700175 FilterResult ret =
176 filter(element.log_id(), element.pid(), element.sequence(), element.realtime());
Tom Cherry3e61a132020-05-27 10:46:37 -0700177 if (ret == FilterResult::kSkip) {
Tom Cherry8f613462020-05-12 12:46:43 -0700178 continue;
179 }
Tom Cherry3e61a132020-05-27 10:46:37 -0700180 if (ret == FilterResult::kStop) {
Tom Cherry8f613462020-05-12 12:46:43 -0700181 break;
182 }
183 }
184
Tom Cherryb3e16332020-05-28 20:02:42 -0700185 // drop_chatty_messages is initialized to true, so if the first message that we attempt to
186 // flush is a chatty message, we drop it. Once we see a non-chatty message it gets set to
187 // false to let further chatty messages be printed.
188 if (state.drop_chatty_messages()) {
189 if (element.dropped_count() != 0) {
190 continue;
191 }
192 state.set_drop_chatty_messages(false);
193 }
194
Tom Cherry9787f9a2020-05-19 19:01:16 -0700195 bool same_tid = state.last_tid()[element.log_id()] == element.tid();
Tom Cherry855c7c82020-05-28 12:38:21 -0700196 // Dropped (chatty) immediately following a valid log from the same source in the same log
197 // buffer indicates we have a multiple identical squash. chatty that differs source is due
198 // to spam filter. chatty to chatty of different source is also due to spam filter.
Tom Cherry9787f9a2020-05-19 19:01:16 -0700199 state.last_tid()[element.log_id()] =
200 (element.dropped_count() && !same_tid) ? 0 : element.tid();
Tom Cherry8f613462020-05-12 12:46:43 -0700201
202 shared_lock.unlock();
Tom Cherry8f613462020-05-12 12:46:43 -0700203 // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
204 // `element` pointer is safe here without the lock
Tom Cherry8f613462020-05-12 12:46:43 -0700205 if (!element.FlushTo(writer, stats_, same_tid)) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700206 return false;
Tom Cherry8f613462020-05-12 12:46:43 -0700207 }
Tom Cherry8f613462020-05-12 12:46:43 -0700208 shared_lock.lock_shared();
209 }
210
Tom Cherry855c7c82020-05-28 12:38:21 -0700211 state.set_start(state.start() + 1);
212 return true;
Tom Cherry8f613462020-05-12 12:46:43 -0700213}
214
Tom Cherry8f613462020-05-12 12:46:43 -0700215bool SimpleLogBuffer::Clear(log_id_t id, uid_t uid) {
Tom Cherrya863b1a2020-06-10 14:52:46 -0700216 // Try three times to clear, then disconnect the readers and try one final time.
217 for (int retry = 0; retry < 3; ++retry) {
Tom Cherry8f613462020-05-12 12:46:43 -0700218 {
219 auto lock = std::lock_guard{lock_};
Tom Cherrya863b1a2020-06-10 14:52:46 -0700220 if (Prune(id, ULONG_MAX, uid)) {
221 return true;
222 }
Tom Cherry8f613462020-05-12 12:46:43 -0700223 }
Tom Cherrya863b1a2020-06-10 14:52:46 -0700224 sleep(1);
Tom Cherry8f613462020-05-12 12:46:43 -0700225 }
Tom Cherrya863b1a2020-06-10 14:52:46 -0700226 // Check if it is still busy after the sleep, we try to prune one entry, not another clear run,
227 // so we are looking for the quick side effect of the return value to tell us if we have a
228 // _blocked_ reader.
229 bool busy = false;
230 {
231 auto lock = std::lock_guard{lock_};
232 busy = !Prune(id, 1, uid);
233 }
234 // It is still busy, disconnect all readers.
235 if (busy) {
236 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
237 for (const auto& reader_thread : reader_list_->reader_threads()) {
238 if (reader_thread->IsWatching(id)) {
239 LOG(WARNING) << "Kicking blocked reader, " << reader_thread->name()
240 << ", from LogBuffer::clear()";
241 reader_thread->release_Locked();
242 }
243 }
244 }
245 auto lock = std::lock_guard{lock_};
246 return Prune(id, ULONG_MAX, uid);
Tom Cherry8f613462020-05-12 12:46:43 -0700247}
248
249// get the total space allocated to "id"
250unsigned long SimpleLogBuffer::GetSize(log_id_t id) {
251 auto lock = SharedLock{lock_};
252 size_t retval = max_size_[id];
253 return retval;
254}
255
256// set the total space allocated to "id"
257int SimpleLogBuffer::SetSize(log_id_t id, unsigned long size) {
258 // Reasonable limits ...
259 if (!__android_logger_valid_buffer_size(size)) {
260 return -1;
261 }
262
263 auto lock = std::lock_guard{lock_};
264 max_size_[id] = size;
265 return 0;
266}
267
268void SimpleLogBuffer::MaybePrune(log_id_t id) {
269 unsigned long prune_rows;
270 if (stats_->ShouldPrune(id, max_size_[id], &prune_rows)) {
271 Prune(id, prune_rows, 0);
272 }
273}
274
275bool SimpleLogBuffer::Prune(log_id_t id, unsigned long prune_rows, uid_t caller_uid) {
276 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
277
278 // Don't prune logs that are newer than the point at which any reader threads are reading from.
279 LogReaderThread* oldest = nullptr;
280 for (const auto& reader_thread : reader_list_->reader_threads()) {
281 if (!reader_thread->IsWatching(id)) {
282 continue;
283 }
284 if (!oldest || oldest->start() > reader_thread->start() ||
285 (oldest->start() == reader_thread->start() &&
286 reader_thread->deadline().time_since_epoch().count() != 0)) {
287 oldest = reader_thread.get();
288 }
289 }
290
291 auto it = GetOldest(id);
292
293 while (it != logs_.end()) {
294 LogBufferElement& element = *it;
295
Tom Cherry9787f9a2020-05-19 19:01:16 -0700296 if (element.log_id() != id) {
Tom Cherry8f613462020-05-12 12:46:43 -0700297 ++it;
298 continue;
299 }
300
Tom Cherry9787f9a2020-05-19 19:01:16 -0700301 if (caller_uid != 0 && element.uid() != caller_uid) {
Tom Cherry8f613462020-05-12 12:46:43 -0700302 ++it;
303 continue;
304 }
305
Tom Cherry9787f9a2020-05-19 19:01:16 -0700306 if (oldest && oldest->start() <= element.sequence()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700307 KickReader(oldest, id, prune_rows);
Tom Cherrya863b1a2020-06-10 14:52:46 -0700308 return false;
Tom Cherry8f613462020-05-12 12:46:43 -0700309 }
310
Tom Cherry3dd3ec32020-06-02 15:39:21 -0700311 stats_->Subtract(element.ToLogStatisticsElement());
Tom Cherry8f613462020-05-12 12:46:43 -0700312 it = Erase(it);
313 if (--prune_rows == 0) {
Tom Cherrya863b1a2020-06-10 14:52:46 -0700314 return true;
Tom Cherry8f613462020-05-12 12:46:43 -0700315 }
316 }
Tom Cherrya863b1a2020-06-10 14:52:46 -0700317 return true;
Tom Cherry8f613462020-05-12 12:46:43 -0700318}
319
320std::list<LogBufferElement>::iterator SimpleLogBuffer::Erase(
321 std::list<LogBufferElement>::iterator it) {
322 bool oldest_is_it[LOG_ID_MAX];
323 log_id_for_each(i) { oldest_is_it[i] = oldest_[i] && it == *oldest_[i]; }
324
325 it = logs_.erase(it);
326
327 log_id_for_each(i) {
328 if (oldest_is_it[i]) {
329 if (__predict_false(it == logs().end())) {
330 oldest_[i] = std::nullopt;
331 } else {
332 oldest_[i] = it; // Store the next iterator even if it does not correspond to
333 // the same log_id, as a starting point for GetOldest().
334 }
335 }
336 }
337
338 return it;
339}
340
341// If the selected reader is blocking our pruning progress, decide on
342// what kind of mitigation is necessary to unblock the situation.
343void SimpleLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, unsigned long prune_rows) {
344 if (stats_->Sizes(id) > (2 * max_size_[id])) { // +100%
345 // A misbehaving or slow reader has its connection
346 // dropped if we hit too much memory pressure.
Tom Cherryf93b4002020-06-03 09:23:49 -0700347 LOG(WARNING) << "Kicking blocked reader, " << reader->name()
348 << ", from LogBuffer::kickMe()";
Tom Cherry8f613462020-05-12 12:46:43 -0700349 reader->release_Locked();
350 } else if (reader->deadline().time_since_epoch().count() != 0) {
351 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
352 reader->triggerReader_Locked();
353 } else {
354 // tell slow reader to skip entries to catch up
Tom Cherryf93b4002020-06-03 09:23:49 -0700355 LOG(WARNING) << "Skipping " << prune_rows << " entries from slow reader, " << reader->name()
356 << ", from LogBuffer::kickMe()";
Tom Cherry8f613462020-05-12 12:46:43 -0700357 reader->triggerSkip_Locked(id, prune_rows);
358 }
359}