blob: b4b354636c9e4de0ce6c3feb45a157a105ba2883 [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;
Tom Cherry3dd3ec32020-06-02 15:39:21 -070064 if (IsBinary(log_id)) {
65 int32_t numeric_tag = MsgToTag(msg, len);
Tom Cherry8f613462020-05-12 12:46:43 -070066 tag = tags_->tagToName(numeric_tag);
67 if (tag) {
68 tag_len = strlen(tag);
69 }
70 } else {
71 prio = *msg;
72 tag = msg + 1;
73 tag_len = strnlen(tag, len - 1);
74 }
75 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
76}
77
78int SimpleLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
79 const char* msg, uint16_t len) {
80 if (log_id >= LOG_ID_MAX) {
81 return -EINVAL;
82 }
83
84 if (!ShouldLog(log_id, msg, len)) {
85 // Log traffic received to total
86 stats_->AddTotal(log_id, len);
87 return -EACCES;
88 }
89
90 // Slip the time by 1 nsec if the incoming lands on xxxxxx000 ns.
91 // This prevents any chance that an outside source can request an
92 // exact entry with time specified in ms or us precision.
93 if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
94
95 auto lock = std::lock_guard{lock_};
96 auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
97 LogInternal(LogBufferElement(log_id, realtime, uid, pid, tid, sequence, msg, len));
98 return len;
99}
100
101void SimpleLogBuffer::LogInternal(LogBufferElement&& elem) {
Tom Cherry9787f9a2020-05-19 19:01:16 -0700102 log_id_t log_id = elem.log_id();
Tom Cherry8f613462020-05-12 12:46:43 -0700103
104 logs_.emplace_back(std::move(elem));
Tom Cherry3dd3ec32020-06-02 15:39:21 -0700105 stats_->Add(logs_.back().ToLogStatisticsElement());
Tom Cherry8f613462020-05-12 12:46:43 -0700106 MaybePrune(log_id);
107 reader_list_->NotifyNewLog(1 << log_id);
108}
109
Tom Cherry855c7c82020-05-28 12:38:21 -0700110// These extra parameters are only required for chatty, but since they're a no-op for
111// SimpleLogBuffer, it's easier to include them here, then to duplicate FlushTo() for
112// ChattyLogBuffer.
113class ChattyFlushToState : public FlushToState {
114 public:
115 ChattyFlushToState(uint64_t start, LogMask log_mask) : FlushToState(start, log_mask) {}
116
117 pid_t* last_tid() { return last_tid_; }
118
Tom Cherryb3e16332020-05-28 20:02:42 -0700119 bool drop_chatty_messages() const { return drop_chatty_messages_; }
120 void set_drop_chatty_messages(bool value) { drop_chatty_messages_ = value; }
121
Tom Cherry855c7c82020-05-28 12:38:21 -0700122 private:
123 pid_t last_tid_[LOG_ID_MAX] = {};
Tom Cherryb3e16332020-05-28 20:02:42 -0700124 bool drop_chatty_messages_ = true;
Tom Cherry855c7c82020-05-28 12:38:21 -0700125};
126
127std::unique_ptr<FlushToState> SimpleLogBuffer::CreateFlushToState(uint64_t start,
128 LogMask log_mask) {
129 return std::make_unique<ChattyFlushToState>(start, log_mask);
130}
131
132bool SimpleLogBuffer::FlushTo(
133 LogWriter* writer, FlushToState& abstract_state,
Tom Cherry70fadea2020-05-27 14:43:19 -0700134 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
Tom Cherryb3e16332020-05-28 20:02:42 -0700135 log_time realtime)>& filter) {
Tom Cherry8f613462020-05-12 12:46:43 -0700136 auto shared_lock = SharedLock{lock_};
137
Tom Cherry855c7c82020-05-28 12:38:21 -0700138 auto& state = reinterpret_cast<ChattyFlushToState&>(abstract_state);
139
Tom Cherry8f613462020-05-12 12:46:43 -0700140 std::list<LogBufferElement>::iterator it;
Tom Cherry855c7c82020-05-28 12:38:21 -0700141 if (state.start() <= 1) {
Tom Cherry8f613462020-05-12 12:46:43 -0700142 // client wants to start from the beginning
143 it = logs_.begin();
144 } else {
145 // Client wants to start from some specified time. Chances are
146 // we are better off starting from the end of the time sorted list.
147 for (it = logs_.end(); it != logs_.begin();
148 /* do nothing */) {
149 --it;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700150 if (it->sequence() == state.start()) {
Tom Cherry90e9ce02020-06-01 13:43:50 -0700151 break;
Tom Cherry9787f9a2020-05-19 19:01:16 -0700152 } else if (it->sequence() < state.start()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700153 it++;
154 break;
155 }
156 }
157 }
158
Tom Cherry8f613462020-05-12 12:46:43 -0700159 for (; it != logs_.end(); ++it) {
160 LogBufferElement& element = *it;
161
Tom Cherry9787f9a2020-05-19 19:01:16 -0700162 state.set_start(element.sequence());
Tom Cherry855c7c82020-05-28 12:38:21 -0700163
Tom Cherry9787f9a2020-05-19 19:01:16 -0700164 if (!writer->privileged() && element.uid() != writer->uid()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700165 continue;
166 }
167
Tom Cherry9787f9a2020-05-19 19:01:16 -0700168 if (((1 << element.log_id()) & state.log_mask()) == 0) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700169 continue;
170 }
171
Tom Cherry8f613462020-05-12 12:46:43 -0700172 if (filter) {
Tom Cherryb3e16332020-05-28 20:02:42 -0700173 FilterResult ret =
174 filter(element.log_id(), element.pid(), element.sequence(), element.realtime());
Tom Cherry3e61a132020-05-27 10:46:37 -0700175 if (ret == FilterResult::kSkip) {
Tom Cherry8f613462020-05-12 12:46:43 -0700176 continue;
177 }
Tom Cherry3e61a132020-05-27 10:46:37 -0700178 if (ret == FilterResult::kStop) {
Tom Cherry8f613462020-05-12 12:46:43 -0700179 break;
180 }
181 }
182
Tom Cherryb3e16332020-05-28 20:02:42 -0700183 // drop_chatty_messages is initialized to true, so if the first message that we attempt to
184 // flush is a chatty message, we drop it. Once we see a non-chatty message it gets set to
185 // false to let further chatty messages be printed.
186 if (state.drop_chatty_messages()) {
187 if (element.dropped_count() != 0) {
188 continue;
189 }
190 state.set_drop_chatty_messages(false);
191 }
192
Tom Cherry9787f9a2020-05-19 19:01:16 -0700193 bool same_tid = state.last_tid()[element.log_id()] == element.tid();
Tom Cherry855c7c82020-05-28 12:38:21 -0700194 // Dropped (chatty) immediately following a valid log from the same source in the same log
195 // buffer indicates we have a multiple identical squash. chatty that differs source is due
196 // to spam filter. chatty to chatty of different source is also due to spam filter.
Tom Cherry9787f9a2020-05-19 19:01:16 -0700197 state.last_tid()[element.log_id()] =
198 (element.dropped_count() && !same_tid) ? 0 : element.tid();
Tom Cherry8f613462020-05-12 12:46:43 -0700199
200 shared_lock.unlock();
Tom Cherry8f613462020-05-12 12:46:43 -0700201 // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
202 // `element` pointer is safe here without the lock
Tom Cherry8f613462020-05-12 12:46:43 -0700203 if (!element.FlushTo(writer, stats_, same_tid)) {
Tom Cherry855c7c82020-05-28 12:38:21 -0700204 return false;
Tom Cherry8f613462020-05-12 12:46:43 -0700205 }
Tom Cherry8f613462020-05-12 12:46:43 -0700206 shared_lock.lock_shared();
207 }
208
Tom Cherry855c7c82020-05-28 12:38:21 -0700209 state.set_start(state.start() + 1);
210 return true;
Tom Cherry8f613462020-05-12 12:46:43 -0700211}
212
213// clear all rows of type "id" from the buffer.
214bool SimpleLogBuffer::Clear(log_id_t id, uid_t uid) {
215 bool busy = true;
216 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
217 for (int retry = 4;;) {
218 if (retry == 1) { // last pass
219 // Check if it is still busy after the sleep, we say prune
220 // one entry, not another clear run, so we are looking for
221 // the quick side effect of the return value to tell us if
222 // we have a _blocked_ reader.
223 {
224 auto lock = std::lock_guard{lock_};
225 busy = Prune(id, 1, uid);
226 }
227 // It is still busy, blocked reader(s), lets kill them all!
228 // otherwise, lets be a good citizen and preserve the slow
229 // readers and let the clear run (below) deal with determining
230 // if we are still blocked and return an error code to caller.
231 if (busy) {
232 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
233 for (const auto& reader_thread : reader_list_->reader_threads()) {
234 if (reader_thread->IsWatching(id)) {
235 android::prdebug("Kicking blocked reader, %s, from LogBuffer::clear()\n",
236 reader_thread->name().c_str());
237 reader_thread->release_Locked();
238 }
239 }
240 }
241 }
242 {
243 auto lock = std::lock_guard{lock_};
244 busy = Prune(id, ULONG_MAX, uid);
245 }
246
247 if (!busy || !--retry) {
248 break;
249 }
250 sleep(1); // Let reader(s) catch up after notification
251 }
252 return busy;
253}
254
255// get the total space allocated to "id"
256unsigned long SimpleLogBuffer::GetSize(log_id_t id) {
257 auto lock = SharedLock{lock_};
258 size_t retval = max_size_[id];
259 return retval;
260}
261
262// set the total space allocated to "id"
263int SimpleLogBuffer::SetSize(log_id_t id, unsigned long size) {
264 // Reasonable limits ...
265 if (!__android_logger_valid_buffer_size(size)) {
266 return -1;
267 }
268
269 auto lock = std::lock_guard{lock_};
270 max_size_[id] = size;
271 return 0;
272}
273
274void SimpleLogBuffer::MaybePrune(log_id_t id) {
275 unsigned long prune_rows;
276 if (stats_->ShouldPrune(id, max_size_[id], &prune_rows)) {
277 Prune(id, prune_rows, 0);
278 }
279}
280
281bool SimpleLogBuffer::Prune(log_id_t id, unsigned long prune_rows, uid_t caller_uid) {
282 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
283
284 // Don't prune logs that are newer than the point at which any reader threads are reading from.
285 LogReaderThread* oldest = nullptr;
286 for (const auto& reader_thread : reader_list_->reader_threads()) {
287 if (!reader_thread->IsWatching(id)) {
288 continue;
289 }
290 if (!oldest || oldest->start() > reader_thread->start() ||
291 (oldest->start() == reader_thread->start() &&
292 reader_thread->deadline().time_since_epoch().count() != 0)) {
293 oldest = reader_thread.get();
294 }
295 }
296
297 auto it = GetOldest(id);
298
299 while (it != logs_.end()) {
300 LogBufferElement& element = *it;
301
Tom Cherry9787f9a2020-05-19 19:01:16 -0700302 if (element.log_id() != id) {
Tom Cherry8f613462020-05-12 12:46:43 -0700303 ++it;
304 continue;
305 }
306
Tom Cherry9787f9a2020-05-19 19:01:16 -0700307 if (caller_uid != 0 && element.uid() != caller_uid) {
Tom Cherry8f613462020-05-12 12:46:43 -0700308 ++it;
309 continue;
310 }
311
Tom Cherry9787f9a2020-05-19 19:01:16 -0700312 if (oldest && oldest->start() <= element.sequence()) {
Tom Cherry8f613462020-05-12 12:46:43 -0700313 KickReader(oldest, id, prune_rows);
314 return true;
315 }
316
Tom Cherry3dd3ec32020-06-02 15:39:21 -0700317 stats_->Subtract(element.ToLogStatisticsElement());
Tom Cherry8f613462020-05-12 12:46:43 -0700318 it = Erase(it);
319 if (--prune_rows == 0) {
320 return false;
321 }
322 }
323 return false;
324}
325
326std::list<LogBufferElement>::iterator SimpleLogBuffer::Erase(
327 std::list<LogBufferElement>::iterator it) {
328 bool oldest_is_it[LOG_ID_MAX];
329 log_id_for_each(i) { oldest_is_it[i] = oldest_[i] && it == *oldest_[i]; }
330
331 it = logs_.erase(it);
332
333 log_id_for_each(i) {
334 if (oldest_is_it[i]) {
335 if (__predict_false(it == logs().end())) {
336 oldest_[i] = std::nullopt;
337 } else {
338 oldest_[i] = it; // Store the next iterator even if it does not correspond to
339 // the same log_id, as a starting point for GetOldest().
340 }
341 }
342 }
343
344 return it;
345}
346
347// If the selected reader is blocking our pruning progress, decide on
348// what kind of mitigation is necessary to unblock the situation.
349void SimpleLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, unsigned long prune_rows) {
350 if (stats_->Sizes(id) > (2 * max_size_[id])) { // +100%
351 // A misbehaving or slow reader has its connection
352 // dropped if we hit too much memory pressure.
353 android::prdebug("Kicking blocked reader, %s, from LogBuffer::kickMe()\n",
354 reader->name().c_str());
355 reader->release_Locked();
356 } else if (reader->deadline().time_since_epoch().count() != 0) {
357 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
358 reader->triggerReader_Locked();
359 } else {
360 // tell slow reader to skip entries to catch up
361 android::prdebug("Skipping %lu entries from slow reader, %s, from LogBuffer::kickMe()\n",
362 prune_rows, reader->name().c_str());
363 reader->triggerSkip_Locked(id, prune_rows);
364 }
365}