blob: 5ab8e0983bafd042f2326008c689540cdc749fba [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
19#include "LogBufferElement.h"
20
21SimpleLogBuffer::SimpleLogBuffer(LogReaderList* reader_list, LogTags* tags, LogStatistics* stats)
22 : reader_list_(reader_list), tags_(tags), stats_(stats) {
23 Init();
24}
25
26SimpleLogBuffer::~SimpleLogBuffer() {}
27
28void SimpleLogBuffer::Init() {
29 log_id_for_each(i) {
30 if (SetSize(i, __android_logger_get_buffer_size(i))) {
31 SetSize(i, LOG_BUFFER_MIN_SIZE);
32 }
33 }
34
35 // Release any sleeping reader threads to dump their current content.
36 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
37 for (const auto& reader_thread : reader_list_->reader_threads()) {
38 reader_thread->triggerReader_Locked();
39 }
40}
41
42std::list<LogBufferElement>::iterator SimpleLogBuffer::GetOldest(log_id_t log_id) {
43 auto it = logs().begin();
44 if (oldest_[log_id]) {
45 it = *oldest_[log_id];
46 }
Tom Cherry9787f9a2020-05-19 19:01:16 -070047 while (it != logs().end() && it->log_id() != log_id) {
Tom Cherry8f613462020-05-12 12:46:43 -070048 it++;
49 }
50 if (it != logs().end()) {
51 oldest_[log_id] = it;
52 }
53 return it;
54}
55
56bool SimpleLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
57 if (log_id == LOG_ID_SECURITY) {
58 return true;
59 }
60
61 int prio = ANDROID_LOG_INFO;
62 const char* tag = nullptr;
63 size_t tag_len = 0;
64 if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
65 if (len < sizeof(android_event_header_t)) {
66 return false;
67 }
68 int32_t numeric_tag = reinterpret_cast<const android_event_header_t*>(msg)->tag;
69 tag = tags_->tagToName(numeric_tag);
70 if (tag) {
71 tag_len = strlen(tag);
72 }
73 } else {
74 prio = *msg;
75 tag = msg + 1;
76 tag_len = strnlen(tag, len - 1);
77 }
78 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
79}
80
81int SimpleLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
82 const char* msg, uint16_t len) {
83 if (log_id >= LOG_ID_MAX) {
84 return -EINVAL;
85 }
86
87 if (!ShouldLog(log_id, msg, len)) {
88 // Log traffic received to total
89 stats_->AddTotal(log_id, len);
90 return -EACCES;
91 }
92
93 // Slip the time by 1 nsec if the incoming lands on xxxxxx000 ns.
94 // This prevents any chance that an outside source can request an
95 // exact entry with time specified in ms or us precision.
96 if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
97
98 auto lock = std::lock_guard{lock_};
99 auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
100 LogInternal(LogBufferElement(log_id, realtime, uid, pid, tid, sequence, msg, len));
101 return len;
102}
103
104void SimpleLogBuffer::LogInternal(LogBufferElement&& elem) {
Tom Cherry9787f9a2020-05-19 19:01:16 -0700105 log_id_t log_id = elem.log_id();
Tom Cherry8f613462020-05-12 12:46:43 -0700106
107 logs_.emplace_back(std::move(elem));
Tom Cherry9787f9a2020-05-19 19:01:16 -0700108 stats_->Add(logs_.back());
Tom Cherry8f613462020-05-12 12:46:43 -0700109 MaybePrune(log_id);
110 reader_list_->NotifyNewLog(1 << log_id);
111}
112
Tom Cherry855c7c82020-05-28 12:38:21 -0700113// These extra parameters are only required for chatty, but since they're a no-op for
114// SimpleLogBuffer, it's easier to include them here, then to duplicate FlushTo() for
115// ChattyLogBuffer.
116class ChattyFlushToState : public FlushToState {
117 public:
118 ChattyFlushToState(uint64_t start, LogMask log_mask) : FlushToState(start, log_mask) {}
119
120 pid_t* last_tid() { return last_tid_; }
121
Tom Cherryb3e16332020-05-28 20:02:42 -0700122 bool drop_chatty_messages() const { return drop_chatty_messages_; }
123 void set_drop_chatty_messages(bool value) { drop_chatty_messages_ = value; }
124
Tom Cherry855c7c82020-05-28 12:38:21 -0700125 private:
126 pid_t last_tid_[LOG_ID_MAX] = {};
Tom Cherryb3e16332020-05-28 20:02:42 -0700127 bool drop_chatty_messages_ = true;
Tom Cherry855c7c82020-05-28 12:38:21 -0700128};
129
130std::unique_ptr<FlushToState> SimpleLogBuffer::CreateFlushToState(uint64_t start,
131 LogMask log_mask) {
132 return std::make_unique<ChattyFlushToState>(start, log_mask);
133}
134
135bool SimpleLogBuffer::FlushTo(
136 LogWriter* writer, FlushToState& abstract_state,
Tom Cherry70fadea2020-05-27 14:43:19 -0700137 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
Tom Cherryb3e16332020-05-28 20:02:42 -0700138 log_time realtime)>& filter) {
Tom Cherry8f613462020-05-12 12:46:43 -0700139 auto shared_lock = SharedLock{lock_};
140
Tom Cherry855c7c82020-05-28 12:38:21 -0700141 auto& state = reinterpret_cast<ChattyFlushToState&>(abstract_state);
142
Tom Cherry8f613462020-05-12 12:46:43 -0700143 std::list<LogBufferElement>::iterator it;
Tom Cherry855c7c82020-05-28 12:38:21 -0700144 if (state.start() <= 1) {
Tom Cherry8f613462020-05-12 12:46:43 -0700145 // client wants to start from the beginning
146 it = logs_.begin();
147 } else {
148 // Client wants to start from some specified time. Chances are
149 // we are better off starting from the end of the time sorted list.
150 for (it = logs_.end(); it != logs_.begin();
151 /* do nothing */) {
152 --it;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700153 if (it->sequence() == state.start()) {
Tom Cherry90e9ce02020-06-01 13:43:50 -0700154 break;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700155 } else if (it->sequence() < state.start()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700156 it++;
157 break;
158 }
159 }
160 }
161
Tom Cherry8f613462020-05-12 12:46:43 -0700162 for (; it != logs_.end(); ++it) {
163 LogBufferElement& element = *it;
164
Tom Cherry9787f9a2020-05-19 19:01:16 -0700165 state.set_start(element.sequence());
Tom Cherry855c7c82020-05-28 12:38:21 -0700166
Tom Cherry9787f9a2020-05-19 19:01:16 -0700167 if (!writer->privileged() && element.uid() != writer->uid()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700168 continue;
169 }
170
Tom Cherry9787f9a2020-05-19 19:01:16 -0700171 if (((1 << element.log_id()) & state.log_mask()) == 0) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700172 continue;
173 }
174
Tom Cherry8f613462020-05-12 12:46:43 -0700175 if (filter) {
Tom Cherryb3e16332020-05-28 20:02:42 -0700176 FilterResult ret =
177 filter(element.log_id(), element.pid(), element.sequence(), element.realtime());
Tom Cherry3e61a132020-05-27 10:46:37 -0700178 if (ret == FilterResult::kSkip) {
Tom Cherry8f613462020-05-12 12:46:43 -0700179 continue;
180 }
Tom Cherry3e61a132020-05-27 10:46:37 -0700181 if (ret == FilterResult::kStop) {
Tom Cherry8f613462020-05-12 12:46:43 -0700182 break;
183 }
184 }
185
Tom Cherryb3e16332020-05-28 20:02:42 -0700186 // drop_chatty_messages is initialized to true, so if the first message that we attempt to
187 // flush is a chatty message, we drop it. Once we see a non-chatty message it gets set to
188 // false to let further chatty messages be printed.
189 if (state.drop_chatty_messages()) {
190 if (element.dropped_count() != 0) {
191 continue;
192 }
193 state.set_drop_chatty_messages(false);
194 }
195
Tom Cherry9787f9a2020-05-19 19:01:16 -0700196 bool same_tid = state.last_tid()[element.log_id()] == element.tid();
Tom Cherry855c7c82020-05-28 12:38:21 -0700197 // Dropped (chatty) immediately following a valid log from the same source in the same log
198 // buffer indicates we have a multiple identical squash. chatty that differs source is due
199 // to spam filter. chatty to chatty of different source is also due to spam filter.
Tom Cherry9787f9a2020-05-19 19:01:16 -0700200 state.last_tid()[element.log_id()] =
201 (element.dropped_count() && !same_tid) ? 0 : element.tid();
Tom Cherry8f613462020-05-12 12:46:43 -0700202
203 shared_lock.unlock();
Tom Cherry8f613462020-05-12 12:46:43 -0700204 // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
205 // `element` pointer is safe here without the lock
Tom Cherry8f613462020-05-12 12:46:43 -0700206 if (!element.FlushTo(writer, stats_, same_tid)) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700207 return false;
Tom Cherry8f613462020-05-12 12:46:43 -0700208 }
Tom Cherry8f613462020-05-12 12:46:43 -0700209 shared_lock.lock_shared();
210 }
211
Tom Cherry855c7c82020-05-28 12:38:21 -0700212 state.set_start(state.start() + 1);
213 return true;
Tom Cherry8f613462020-05-12 12:46:43 -0700214}
215
216// clear all rows of type "id" from the buffer.
217bool SimpleLogBuffer::Clear(log_id_t id, uid_t uid) {
218 bool busy = true;
219 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
220 for (int retry = 4;;) {
221 if (retry == 1) { // last pass
222 // Check if it is still busy after the sleep, we say prune
223 // one entry, not another clear run, so we are looking for
224 // the quick side effect of the return value to tell us if
225 // we have a _blocked_ reader.
226 {
227 auto lock = std::lock_guard{lock_};
228 busy = Prune(id, 1, uid);
229 }
230 // It is still busy, blocked reader(s), lets kill them all!
231 // otherwise, lets be a good citizen and preserve the slow
232 // readers and let the clear run (below) deal with determining
233 // if we are still blocked and return an error code to caller.
234 if (busy) {
235 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
236 for (const auto& reader_thread : reader_list_->reader_threads()) {
237 if (reader_thread->IsWatching(id)) {
238 android::prdebug("Kicking blocked reader, %s, from LogBuffer::clear()\n",
239 reader_thread->name().c_str());
240 reader_thread->release_Locked();
241 }
242 }
243 }
244 }
245 {
246 auto lock = std::lock_guard{lock_};
247 busy = Prune(id, ULONG_MAX, uid);
248 }
249
250 if (!busy || !--retry) {
251 break;
252 }
253 sleep(1); // Let reader(s) catch up after notification
254 }
255 return busy;
256}
257
258// get the total space allocated to "id"
259unsigned long SimpleLogBuffer::GetSize(log_id_t id) {
260 auto lock = SharedLock{lock_};
261 size_t retval = max_size_[id];
262 return retval;
263}
264
265// set the total space allocated to "id"
266int SimpleLogBuffer::SetSize(log_id_t id, unsigned long size) {
267 // Reasonable limits ...
268 if (!__android_logger_valid_buffer_size(size)) {
269 return -1;
270 }
271
272 auto lock = std::lock_guard{lock_};
273 max_size_[id] = size;
274 return 0;
275}
276
277void SimpleLogBuffer::MaybePrune(log_id_t id) {
278 unsigned long prune_rows;
279 if (stats_->ShouldPrune(id, max_size_[id], &prune_rows)) {
280 Prune(id, prune_rows, 0);
281 }
282}
283
284bool SimpleLogBuffer::Prune(log_id_t id, unsigned long prune_rows, uid_t caller_uid) {
285 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
286
287 // Don't prune logs that are newer than the point at which any reader threads are reading from.
288 LogReaderThread* oldest = nullptr;
289 for (const auto& reader_thread : reader_list_->reader_threads()) {
290 if (!reader_thread->IsWatching(id)) {
291 continue;
292 }
293 if (!oldest || oldest->start() > reader_thread->start() ||
294 (oldest->start() == reader_thread->start() &&
295 reader_thread->deadline().time_since_epoch().count() != 0)) {
296 oldest = reader_thread.get();
297 }
298 }
299
300 auto it = GetOldest(id);
301
302 while (it != logs_.end()) {
303 LogBufferElement& element = *it;
304
Tom Cherry9787f9a2020-05-19 19:01:16 -0700305 if (element.log_id() != id) {
Tom Cherry8f613462020-05-12 12:46:43 -0700306 ++it;
307 continue;
308 }
309
Tom Cherry9787f9a2020-05-19 19:01:16 -0700310 if (caller_uid != 0 && element.uid() != caller_uid) {
Tom Cherry8f613462020-05-12 12:46:43 -0700311 ++it;
312 continue;
313 }
314
Tom Cherry9787f9a2020-05-19 19:01:16 -0700315 if (oldest && oldest->start() <= element.sequence()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700316 KickReader(oldest, id, prune_rows);
317 return true;
318 }
319
Tom Cherry9787f9a2020-05-19 19:01:16 -0700320 stats_->Subtract(element);
Tom Cherry8f613462020-05-12 12:46:43 -0700321 it = Erase(it);
322 if (--prune_rows == 0) {
323 return false;
324 }
325 }
326 return false;
327}
328
329std::list<LogBufferElement>::iterator SimpleLogBuffer::Erase(
330 std::list<LogBufferElement>::iterator it) {
331 bool oldest_is_it[LOG_ID_MAX];
332 log_id_for_each(i) { oldest_is_it[i] = oldest_[i] && it == *oldest_[i]; }
333
334 it = logs_.erase(it);
335
336 log_id_for_each(i) {
337 if (oldest_is_it[i]) {
338 if (__predict_false(it == logs().end())) {
339 oldest_[i] = std::nullopt;
340 } else {
341 oldest_[i] = it; // Store the next iterator even if it does not correspond to
342 // the same log_id, as a starting point for GetOldest().
343 }
344 }
345 }
346
347 return it;
348}
349
350// If the selected reader is blocking our pruning progress, decide on
351// what kind of mitigation is necessary to unblock the situation.
352void SimpleLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, unsigned long prune_rows) {
353 if (stats_->Sizes(id) > (2 * max_size_[id])) { // +100%
354 // A misbehaving or slow reader has its connection
355 // dropped if we hit too much memory pressure.
356 android::prdebug("Kicking blocked reader, %s, from LogBuffer::kickMe()\n",
357 reader->name().c_str());
358 reader->release_Locked();
359 } else if (reader->deadline().time_since_epoch().count() != 0) {
360 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
361 reader->triggerReader_Locked();
362 } else {
363 // tell slow reader to skip entries to catch up
364 android::prdebug("Skipping %lu entries from slow reader, %s, from LogBuffer::kickMe()\n",
365 prune_rows, reader->name().c_str());
366 reader->triggerSkip_Locked(id, prune_rows);
367 }
368}