blob: ceecc6d1087a0ad2b03003873fdbfb84c196c879 [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 }
47 while (it != logs().end() && it->getLogId() != log_id) {
48 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) {
105 log_id_t log_id = elem.getLogId();
106
107 logs_.emplace_back(std::move(elem));
108 stats_->Add(&logs_.back());
109 MaybePrune(log_id);
110 reader_list_->NotifyNewLog(1 << log_id);
111}
112
113uint64_t SimpleLogBuffer::FlushTo(
114 LogWriter* writer, uint64_t start, pid_t* last_tid,
Tom Cherry70fadea2020-05-27 14:43:19 -0700115 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
116 log_time realtime, uint16_t dropped_count)>& filter) {
Tom Cherry8f613462020-05-12 12:46:43 -0700117 auto shared_lock = SharedLock{lock_};
118
119 std::list<LogBufferElement>::iterator it;
120 if (start <= 1) {
121 // client wants to start from the beginning
122 it = logs_.begin();
123 } else {
124 // Client wants to start from some specified time. Chances are
125 // we are better off starting from the end of the time sorted list.
126 for (it = logs_.end(); it != logs_.begin();
127 /* do nothing */) {
128 --it;
Tom Cherry90e9ce02020-06-01 13:43:50 -0700129 if (it->getSequence() == start) {
130 break;
131 } else if (it->getSequence() < start) {
Tom Cherry8f613462020-05-12 12:46:43 -0700132 it++;
133 break;
134 }
135 }
136 }
137
138 uint64_t curr = start;
139
140 for (; it != logs_.end(); ++it) {
141 LogBufferElement& element = *it;
142
143 if (!writer->privileged() && element.getUid() != writer->uid()) {
144 continue;
145 }
146
147 if (!writer->can_read_security_logs() && element.getLogId() == LOG_ID_SECURITY) {
148 continue;
149 }
150
151 if (filter) {
Tom Cherry70fadea2020-05-27 14:43:19 -0700152 FilterResult ret = filter(element.getLogId(), element.getPid(), element.getSequence(),
153 element.getRealTime(), element.getDropped());
Tom Cherry3e61a132020-05-27 10:46:37 -0700154 if (ret == FilterResult::kSkip) {
Tom Cherry8f613462020-05-12 12:46:43 -0700155 continue;
156 }
Tom Cherry3e61a132020-05-27 10:46:37 -0700157 if (ret == FilterResult::kStop) {
Tom Cherry8f613462020-05-12 12:46:43 -0700158 break;
159 }
160 }
161
162 bool same_tid = false;
163 if (last_tid) {
164 same_tid = last_tid[element.getLogId()] == element.getTid();
165 // Dropped (chatty) immediately following a valid log from the
166 // same source in the same log buffer indicates we have a
167 // multiple identical squash. chatty that differs source
168 // is due to spam filter. chatty to chatty of different
169 // source is also due to spam filter.
170 last_tid[element.getLogId()] =
171 (element.getDropped() && !same_tid) ? 0 : element.getTid();
172 }
173
174 shared_lock.unlock();
175
176 // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
177 // `element` pointer is safe here without the lock
178 curr = element.getSequence();
179 if (!element.FlushTo(writer, stats_, same_tid)) {
180 return FLUSH_ERROR;
181 }
182
183 shared_lock.lock_shared();
184 }
185
186 return curr;
187}
188
189// clear all rows of type "id" from the buffer.
190bool SimpleLogBuffer::Clear(log_id_t id, uid_t uid) {
191 bool busy = true;
192 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
193 for (int retry = 4;;) {
194 if (retry == 1) { // last pass
195 // Check if it is still busy after the sleep, we say prune
196 // one entry, not another clear run, so we are looking for
197 // the quick side effect of the return value to tell us if
198 // we have a _blocked_ reader.
199 {
200 auto lock = std::lock_guard{lock_};
201 busy = Prune(id, 1, uid);
202 }
203 // It is still busy, blocked reader(s), lets kill them all!
204 // otherwise, lets be a good citizen and preserve the slow
205 // readers and let the clear run (below) deal with determining
206 // if we are still blocked and return an error code to caller.
207 if (busy) {
208 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
209 for (const auto& reader_thread : reader_list_->reader_threads()) {
210 if (reader_thread->IsWatching(id)) {
211 android::prdebug("Kicking blocked reader, %s, from LogBuffer::clear()\n",
212 reader_thread->name().c_str());
213 reader_thread->release_Locked();
214 }
215 }
216 }
217 }
218 {
219 auto lock = std::lock_guard{lock_};
220 busy = Prune(id, ULONG_MAX, uid);
221 }
222
223 if (!busy || !--retry) {
224 break;
225 }
226 sleep(1); // Let reader(s) catch up after notification
227 }
228 return busy;
229}
230
231// get the total space allocated to "id"
232unsigned long SimpleLogBuffer::GetSize(log_id_t id) {
233 auto lock = SharedLock{lock_};
234 size_t retval = max_size_[id];
235 return retval;
236}
237
238// set the total space allocated to "id"
239int SimpleLogBuffer::SetSize(log_id_t id, unsigned long size) {
240 // Reasonable limits ...
241 if (!__android_logger_valid_buffer_size(size)) {
242 return -1;
243 }
244
245 auto lock = std::lock_guard{lock_};
246 max_size_[id] = size;
247 return 0;
248}
249
250void SimpleLogBuffer::MaybePrune(log_id_t id) {
251 unsigned long prune_rows;
252 if (stats_->ShouldPrune(id, max_size_[id], &prune_rows)) {
253 Prune(id, prune_rows, 0);
254 }
255}
256
257bool SimpleLogBuffer::Prune(log_id_t id, unsigned long prune_rows, uid_t caller_uid) {
258 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
259
260 // Don't prune logs that are newer than the point at which any reader threads are reading from.
261 LogReaderThread* oldest = nullptr;
262 for (const auto& reader_thread : reader_list_->reader_threads()) {
263 if (!reader_thread->IsWatching(id)) {
264 continue;
265 }
266 if (!oldest || oldest->start() > reader_thread->start() ||
267 (oldest->start() == reader_thread->start() &&
268 reader_thread->deadline().time_since_epoch().count() != 0)) {
269 oldest = reader_thread.get();
270 }
271 }
272
273 auto it = GetOldest(id);
274
275 while (it != logs_.end()) {
276 LogBufferElement& element = *it;
277
278 if (element.getLogId() != id) {
279 ++it;
280 continue;
281 }
282
283 if (caller_uid != 0 && element.getUid() != caller_uid) {
284 ++it;
285 continue;
286 }
287
288 if (oldest && oldest->start() <= element.getSequence()) {
289 KickReader(oldest, id, prune_rows);
290 return true;
291 }
292
293 stats_->Subtract(&element);
294 it = Erase(it);
295 if (--prune_rows == 0) {
296 return false;
297 }
298 }
299 return false;
300}
301
302std::list<LogBufferElement>::iterator SimpleLogBuffer::Erase(
303 std::list<LogBufferElement>::iterator it) {
304 bool oldest_is_it[LOG_ID_MAX];
305 log_id_for_each(i) { oldest_is_it[i] = oldest_[i] && it == *oldest_[i]; }
306
307 it = logs_.erase(it);
308
309 log_id_for_each(i) {
310 if (oldest_is_it[i]) {
311 if (__predict_false(it == logs().end())) {
312 oldest_[i] = std::nullopt;
313 } else {
314 oldest_[i] = it; // Store the next iterator even if it does not correspond to
315 // the same log_id, as a starting point for GetOldest().
316 }
317 }
318 }
319
320 return it;
321}
322
323// If the selected reader is blocking our pruning progress, decide on
324// what kind of mitigation is necessary to unblock the situation.
325void SimpleLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, unsigned long prune_rows) {
326 if (stats_->Sizes(id) > (2 * max_size_[id])) { // +100%
327 // A misbehaving or slow reader has its connection
328 // dropped if we hit too much memory pressure.
329 android::prdebug("Kicking blocked reader, %s, from LogBuffer::kickMe()\n",
330 reader->name().c_str());
331 reader->release_Locked();
332 } else if (reader->deadline().time_since_epoch().count() != 0) {
333 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
334 reader->triggerReader_Locked();
335 } else {
336 // tell slow reader to skip entries to catch up
337 android::prdebug("Skipping %lu entries from slow reader, %s, from LogBuffer::kickMe()\n",
338 prune_rows, reader->name().c_str());
339 reader->triggerSkip_Locked(id, prune_rows);
340 }
341}