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