blob: 26584584a9a38b242f77a2c47988213ea0d02881 [file] [log] [blame]
Mark Salyzyn0175b072014-02-26 09:50:16 -08001/*
2 * Copyright (C) 2012-2014 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 */
Tom Cherryd5b38382020-05-12 13:16:41 -070016// for manual checking of stale entries during ChattyLogBuffer::erase()
Mark Salyzyn60636fa2016-10-24 16:22:17 -070017//#define DEBUG_CHECK_FOR_STALE_ENTRIES
Mark Salyzyn0175b072014-02-26 09:50:16 -080018
Tom Cherryd5b38382020-05-12 13:16:41 -070019#include "ChattyLogBuffer.h"
20
Mark Salyzyn671e3432014-05-06 07:34:59 -070021#include <ctype.h>
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -080022#include <endian.h>
Mark Salyzyn202e1532015-02-09 08:21:05 -080023#include <errno.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080024#include <stdio.h>
25#include <string.h>
Mark Salyzyn8fcfd852016-10-24 08:20:26 -070026#include <sys/cdefs.h>
Mark Salyzyn57a0af92014-05-09 17:44:18 -070027#include <sys/user.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080028#include <time.h>
29#include <unistd.h>
30
Tom Cherryb398a7c2020-05-20 12:09:22 -070031#include <limits>
Mark Salyzyn511338d2015-05-19 09:12:30 -070032#include <unordered_map>
Tom Cherry10d086e2019-08-21 14:16:34 -070033#include <utility>
Mark Salyzyn511338d2015-05-19 09:12:30 -070034
Mark Salyzynf10e2732016-09-27 13:08:23 -070035#include <private/android_logger.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080036
Mark Salyzyna2c02222016-12-13 10:31:29 -080037#include "LogUtils.h"
Mark Salyzyn0175b072014-02-26 09:50:16 -080038
Mark Salyzyn8fcfd852016-10-24 08:20:26 -070039#ifndef __predict_false
40#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
41#endif
42
Mark Salyzyndfa7a072014-02-11 12:29:31 -080043// Default
Mark Salyzyndfa7a072014-02-11 12:29:31 -080044#define log_buffer_size(id) mMaxSize[id]
Mark Salyzyn671e3432014-05-06 07:34:59 -070045
Tom Cherryd5b38382020-05-12 13:16:41 -070046void ChattyLogBuffer::Init() {
Mark Salyzyndfa7a072014-02-11 12:29:31 -080047 log_id_for_each(i) {
Tom Cherryd5b38382020-05-12 13:16:41 -070048 if (SetSize(i, __android_logger_get_buffer_size(i))) {
49 SetSize(i, LOG_BUFFER_MIN_SIZE);
Mark Salyzyn57a0af92014-05-09 17:44:18 -070050 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -080051 }
Tom Cherrye170d1a2020-05-01 16:45:25 -070052 // Release any sleeping reader threads to dump their current content.
Tom Cherry68630a02020-05-11 16:29:29 -070053 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
54 for (const auto& reader_thread : reader_list_->reader_threads()) {
55 reader_thread->triggerReader_Locked();
Mark Salyzynb6bee332015-09-08 08:56:32 -070056 }
Mark Salyzyn0175b072014-02-26 09:50:16 -080057}
58
Tom Cherryd5b38382020-05-12 13:16:41 -070059ChattyLogBuffer::ChattyLogBuffer(LogReaderList* reader_list, LogTags* tags, PruneList* prune,
60 LogStatistics* stats)
Tom Cherry68630a02020-05-11 16:29:29 -070061 : reader_list_(reader_list), tags_(tags), prune_(prune), stats_(stats) {
Tom Cherryd5b38382020-05-12 13:16:41 -070062 Init();
Mark Salyzyn11e55cb2015-03-10 16:45:17 -070063}
64
Tom Cherrya26f7df2020-05-19 17:48:42 -070065ChattyLogBuffer::~ChattyLogBuffer() {}
Mark Salyzyna2c02222016-12-13 10:31:29 -080066
Tom Cherryd5b38382020-05-12 13:16:41 -070067LogBufferElementCollection::iterator ChattyLogBuffer::GetOldest(log_id_t log_id) {
Tom Cherry385c2c92020-04-29 17:58:18 -070068 auto it = mLogElements.begin();
Tom Cherry20118ee2020-05-04 10:17:42 -070069 if (oldest_[log_id]) {
70 it = *oldest_[log_id];
Tom Cherry385c2c92020-04-29 17:58:18 -070071 }
72 while (it != mLogElements.end() && (*it)->getLogId() != log_id) {
73 it++;
74 }
75 if (it != mLogElements.end()) {
Tom Cherry20118ee2020-05-04 10:17:42 -070076 oldest_[log_id] = it;
Tom Cherry385c2c92020-04-29 17:58:18 -070077 }
78 return it;
79}
80
Mark Salyzyn501c3732017-03-10 14:31:54 -080081enum match_type { DIFFERENT, SAME, SAME_LIBLOG };
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -080082
Tom Cherryd5b38382020-05-12 13:16:41 -070083static enum match_type identical(LogBufferElement* elem, LogBufferElement* last) {
Mark Salyzyna2c02222016-12-13 10:31:29 -080084 // is it mostly identical?
Mark Salyzyn501c3732017-03-10 14:31:54 -080085 // if (!elem) return DIFFERENT;
Mark Salyzyn0484b3b2016-08-11 08:02:06 -070086 ssize_t lenl = elem->getMsgLen();
87 if (lenl <= 0) return DIFFERENT; // value if this represents a chatty elem
Mark Salyzyn501c3732017-03-10 14:31:54 -080088 // if (!last) return DIFFERENT;
Mark Salyzyn0484b3b2016-08-11 08:02:06 -070089 ssize_t lenr = last->getMsgLen();
90 if (lenr <= 0) return DIFFERENT; // value if this represents a chatty elem
Mark Salyzyn501c3732017-03-10 14:31:54 -080091 // if (elem->getLogId() != last->getLogId()) return DIFFERENT;
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -080092 if (elem->getUid() != last->getUid()) return DIFFERENT;
93 if (elem->getPid() != last->getPid()) return DIFFERENT;
94 if (elem->getTid() != last->getTid()) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -080095
96 // last is more than a minute old, stop squashing identical messages
Tom Cherryd5b38382020-05-12 13:16:41 -070097 if (elem->getRealTime().nsec() > (last->getRealTime().nsec() + 60 * NS_PER_SEC))
Mark Salyzyn501c3732017-03-10 14:31:54 -080098 return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -080099
100 // Identical message
101 const char* msgl = elem->getMsg();
102 const char* msgr = last->getMsg();
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800103 if (lenl == lenr) {
104 if (!fastcmp<memcmp>(msgl, msgr, lenl)) return SAME;
105 // liblog tagged messages (content gets summed)
Tom Cherryd5b38382020-05-12 13:16:41 -0700106 if (elem->getLogId() == LOG_ID_EVENTS && lenl == sizeof(android_log_event_int_t) &&
107 !fastcmp<memcmp>(msgl, msgr, sizeof(android_log_event_int_t) - sizeof(int32_t)) &&
108 elem->getTag() == LIBLOG_LOG_TAG) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800109 return SAME_LIBLOG;
Mark Salyzyn1598fe02017-03-13 15:41:59 -0700110 }
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800111 }
Mark Salyzyna2c02222016-12-13 10:31:29 -0800112
113 // audit message (except sequence number) identical?
Tom Cherryd5b38382020-05-12 13:16:41 -0700114 if (last->isBinary() && lenl > static_cast<ssize_t>(sizeof(android_log_event_string_t)) &&
115 lenr > static_cast<ssize_t>(sizeof(android_log_event_string_t))) {
116 if (fastcmp<memcmp>(msgl, msgr, sizeof(android_log_event_string_t) - sizeof(int32_t))) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800117 return DIFFERENT;
Mark Salyzyn1598fe02017-03-13 15:41:59 -0700118 }
Mark Salyzyna2c02222016-12-13 10:31:29 -0800119 msgl += sizeof(android_log_event_string_t);
120 lenl -= sizeof(android_log_event_string_t);
121 msgr += sizeof(android_log_event_string_t);
122 lenr -= sizeof(android_log_event_string_t);
123 }
Mark Salyzyn0484b3b2016-08-11 08:02:06 -0700124 static const char avc[] = "): avc: ";
Mark Salyzyn501c3732017-03-10 14:31:54 -0800125 const char* avcl = android::strnstr(msgl, lenl, avc);
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800126 if (!avcl) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800127 lenl -= avcl - msgl;
Mark Salyzyn501c3732017-03-10 14:31:54 -0800128 const char* avcr = android::strnstr(msgr, lenr, avc);
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800129 if (!avcr) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800130 lenr -= avcr - msgr;
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800131 if (lenl != lenr) return DIFFERENT;
Tom Cherryd5b38382020-05-12 13:16:41 -0700132 if (fastcmp<memcmp>(avcl + strlen(avc), avcr + strlen(avc), lenl - strlen(avc))) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800133 return DIFFERENT;
Mark Salyzyn1598fe02017-03-13 15:41:59 -0700134 }
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800135 return SAME;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800136}
137
Tom Cherrya26f7df2020-05-19 17:48:42 -0700138bool ChattyLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
Tom Cherry2ac86de2020-02-20 13:21:51 -0800139 if (log_id == LOG_ID_SECURITY) {
Tom Cherrya26f7df2020-05-19 17:48:42 -0700140 return true;
Tom Cherry2ac86de2020-02-20 13:21:51 -0800141 }
142
143 int prio = ANDROID_LOG_INFO;
144 const char* tag = nullptr;
145 size_t tag_len = 0;
146 if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
Tom Cherrya26f7df2020-05-19 17:48:42 -0700147 if (len < sizeof(android_event_header_t)) {
148 return false;
149 }
150 int32_t numeric_tag = reinterpret_cast<const android_event_header_t*>(msg)->tag;
151 tag = tags_->tagToName(numeric_tag);
Tom Cherry2ac86de2020-02-20 13:21:51 -0800152 if (tag) {
153 tag_len = strlen(tag);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800154 }
Tom Cherry2ac86de2020-02-20 13:21:51 -0800155 } else {
156 prio = *msg;
157 tag = msg + 1;
158 tag_len = strnlen(tag, len - 1);
159 }
Tom Cherrya26f7df2020-05-19 17:48:42 -0700160 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
161}
162
163int ChattyLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
164 const char* msg, uint16_t len) {
165 if (log_id >= LOG_ID_MAX) {
166 return -EINVAL;
167 }
168
169 if (!ShouldLog(log_id, msg, len)) {
Tom Cherry2ac86de2020-02-20 13:21:51 -0800170 // Log traffic received to total
Tom Cherrya26f7df2020-05-19 17:48:42 -0700171 stats_->AddTotal(log_id, len);
Tom Cherry2ac86de2020-02-20 13:21:51 -0800172 return -EACCES;
Mark Salyzyne59c4692014-10-02 13:07:05 -0700173 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800174
Tom Cherrya26f7df2020-05-19 17:48:42 -0700175 // Slip the time by 1 nsec if the incoming lands on xxxxxx000 ns.
176 // This prevents any chance that an outside source can request an
177 // exact entry with time specified in ms or us precision.
178 if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800179
Tom Cherrya26f7df2020-05-19 17:48:42 -0700180 std::unique_ptr<LogBufferElement> elem(
181 new LogBufferElement(log_id, realtime, uid, pid, tid, msg, len));
182
183 // b/137093665: don't coalesce security messages.
184 if (log_id == LOG_ID_SECURITY) {
185 auto lock = std::lock_guard{lock_};
186 Log(std::move(elem));
187 return len;
188 }
189
190 auto lock = std::lock_guard{lock_};
191 // Initialize last_logged_elements_ to a copy of elem if logging the first element for a log_id.
192 if (!last_logged_elements_[log_id]) {
193 last_logged_elements_[log_id].reset(new LogBufferElement(*elem));
194 Log(std::move(elem));
195 return len;
196 }
197
198 std::unique_ptr<LogBufferElement> current_last = std::move(last_logged_elements_[log_id]);
199 enum match_type match = identical(elem.get(), current_last.get());
200
201 if (match == DIFFERENT) {
202 if (duplicate_elements_[log_id]) {
203 auto dropped_element = std::move(duplicate_elements_[log_id]);
204 // If we previously had 3+ identical messages, log the chatty message.
205 if (dropped_element && dropped_element->getDropped() > 0) {
206 Log(std::move(dropped_element));
Mark Salyzyna2c02222016-12-13 10:31:29 -0800207 }
Tom Cherrya26f7df2020-05-19 17:48:42 -0700208 // Log the saved copy of the last identical message seen.
209 Log(std::move(current_last));
210 }
211 last_logged_elements_[log_id].reset(new LogBufferElement(*elem));
212 Log(std::move(elem));
213 return len;
214 }
215
216 // 2 identical message: set duplicate_elements_ appropriately.
217 if (!duplicate_elements_[log_id]) {
218 duplicate_elements_[log_id] = std::move(current_last);
219 last_logged_elements_[log_id] = std::move(elem);
220 return len;
221 }
222
223 // 3+ identical LIBLOG event messages: coalesce them into last_logged_elements_.
224 if (match == SAME_LIBLOG) {
225 const android_log_event_int_t* current_last_event =
226 reinterpret_cast<const android_log_event_int_t*>(current_last->getMsg());
227 int64_t current_last_count = current_last_event->payload.data;
228 android_log_event_int_t* elem_event =
229 reinterpret_cast<android_log_event_int_t*>(const_cast<char*>(elem->getMsg()));
230 int64_t elem_count = elem_event->payload.data;
231
232 int64_t total = current_last_count + elem_count;
233 if (total > std::numeric_limits<int32_t>::max()) {
234 last_logged_elements_[log_id] = std::move(elem);
235 Log(std::move(current_last));
Mark Salyzyna2c02222016-12-13 10:31:29 -0800236 return len;
237 }
Tom Cherrya26f7df2020-05-19 17:48:42 -0700238 stats_->AddTotal(current_last->getLogId(), current_last->getMsgLen());
239 elem_event->payload.data = total;
240 last_logged_elements_[log_id] = std::move(elem);
241 return len;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800242 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800243
Tom Cherrya26f7df2020-05-19 17:48:42 -0700244 // 3+ identical messages (not LIBLOG) messages: increase the drop count.
245 uint16_t dropped_count = duplicate_elements_[log_id]->getDropped();
246 if (dropped_count == std::numeric_limits<uint16_t>::max()) {
247 Log(std::move(duplicate_elements_[log_id]));
248 dropped_count = 0;
249 }
250 // We're dropping the current_last log so add its stats to the total.
251 stats_->AddTotal(current_last->getLogId(), current_last->getMsgLen());
252 // Use current_last for tracking the dropped count to always use the latest timestamp.
253 current_last->setDropped(dropped_count + 1);
254 duplicate_elements_[log_id] = std::move(current_last);
255 last_logged_elements_[log_id] = std::move(elem);
Mark Salyzyna2c02222016-12-13 10:31:29 -0800256 return len;
257}
258
Tom Cherrya26f7df2020-05-19 17:48:42 -0700259void ChattyLogBuffer::Log(std::unique_ptr<LogBufferElement> elem) {
260 log_id_t log_id = elem->getLogId();
261 mLogElements.push_back(elem.release());
262 stats_->Add(mLogElements.back());
263 maybePrune(log_id);
264 reader_list_->NotifyNewLog(1 << log_id);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800265}
266
Tom Cherryd5b38382020-05-12 13:16:41 -0700267void ChattyLogBuffer::maybePrune(log_id_t id) {
Tom Cherry64e90162020-05-07 14:44:43 -0700268 unsigned long prune_rows;
269 if (stats_->ShouldPrune(id, log_buffer_size(id), &prune_rows)) {
270 prune(id, prune_rows);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800271 }
272}
273
Tom Cherryd5b38382020-05-12 13:16:41 -0700274LogBufferElementCollection::iterator ChattyLogBuffer::erase(LogBufferElementCollection::iterator it,
275 bool coalesce) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800276 LogBufferElement* element = *it;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700277 log_id_t id = element->getLogId();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700278
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700279 // Remove iterator references in the various lists that will become stale
280 // after the element is erased from the main logging list.
281
Mark Salyzyn501c3732017-03-10 14:31:54 -0800282 { // start of scope for found iterator
Tom Cherryd5b38382020-05-12 13:16:41 -0700283 int key = (id == LOG_ID_EVENTS || id == LOG_ID_SECURITY) ? element->getTag()
284 : element->getUid();
Mark Salyzyn6a066942016-07-14 15:34:30 -0700285 LogBufferIteratorMap::iterator found = mLastWorst[id].find(key);
286 if ((found != mLastWorst[id].end()) && (it == found->second)) {
287 mLastWorst[id].erase(found);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700288 }
Mark Salyzync892ea32015-08-19 17:06:11 -0700289 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700290
Mark Salyzyn501c3732017-03-10 14:31:54 -0800291 { // start of scope for pid found iterator
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700292 // element->getUid() may not be AID_SYSTEM for next-best-watermark.
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700293 // will not assume id != LOG_ID_EVENTS or LOG_ID_SECURITY for KISS and
294 // long term code stability, find() check should be fast for those ids.
Tom Cherryd5b38382020-05-12 13:16:41 -0700295 LogBufferPidIteratorMap::iterator found = mLastWorstPidOfSystem[id].find(element->getPid());
296 if (found != mLastWorstPidOfSystem[id].end() && it == found->second) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700297 mLastWorstPidOfSystem[id].erase(found);
298 }
299 }
300
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800301 bool setLast[LOG_ID_MAX];
302 bool doSetLast = false;
Tom Cherry20118ee2020-05-04 10:17:42 -0700303 log_id_for_each(i) { doSetLast |= setLast[i] = oldest_[i] && it == *oldest_[i]; }
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700304#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
305 LogBufferElementCollection::iterator bad = it;
Tom Cherryd5b38382020-05-12 13:16:41 -0700306 int key =
307 (id == LOG_ID_EVENTS || id == LOG_ID_SECURITY) ? element->getTag() : element->getUid();
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700308#endif
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700309 it = mLogElements.erase(it);
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800310 if (doSetLast) {
311 log_id_for_each(i) {
312 if (setLast[i]) {
Tom Cherry385c2c92020-04-29 17:58:18 -0700313 if (__predict_false(it == mLogElements.end())) {
Tom Cherry20118ee2020-05-04 10:17:42 -0700314 oldest_[i] = std::nullopt;
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800315 } else {
Tom Cherry20118ee2020-05-04 10:17:42 -0700316 oldest_[i] = it; // Store the next iterator even if it does not correspond to
Tom Cherry385c2c92020-04-29 17:58:18 -0700317 // the same log_id, as a starting point for GetOldest().
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800318 }
319 }
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800320 }
321 }
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700322#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
323 log_id_for_each(i) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800324 for (auto b : mLastWorst[i]) {
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700325 if (bad == b.second) {
Tom Cherryd5b38382020-05-12 13:16:41 -0700326 android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n", i, b.first, key);
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700327 }
328 }
Mark Salyzyn501c3732017-03-10 14:31:54 -0800329 for (auto b : mLastWorstPidOfSystem[i]) {
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700330 if (bad == b.second) {
Tom Cherryd5b38382020-05-12 13:16:41 -0700331 android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n", i, b.first);
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700332 }
333 }
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700334 }
335#endif
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700336 if (coalesce) {
Tom Cherry64e90162020-05-07 14:44:43 -0700337 stats_->Erase(element);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700338 } else {
Tom Cherry64e90162020-05-07 14:44:43 -0700339 stats_->Subtract(element);
Mark Salyzyn831aa292015-09-03 16:08:50 -0700340 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700341 delete element;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700342
343 return it;
344}
345
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700346// Define a temporary mechanism to report the last LogBufferElement pointer
347// for the specified uid, pid and tid. Used below to help merge-sort when
348// pruning for worst UID.
Mark Salyzyn511338d2015-05-19 09:12:30 -0700349class LogBufferElementLast {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800350 typedef std::unordered_map<uint64_t, LogBufferElement*> LogBufferElementMap;
Mark Salyzyn511338d2015-05-19 09:12:30 -0700351 LogBufferElementMap map;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700352
Tom Cherryd5b38382020-05-12 13:16:41 -0700353 public:
Chih-Hung Hsieh08d470b2018-08-13 14:22:56 -0700354 bool coalesce(LogBufferElement* element, uint16_t dropped) {
Tom Cherrya5151972020-05-15 11:39:58 -0700355 uint64_t key = LogBufferElementKey(element->getUid(), element->getPid(), element->getTid());
356 LogBufferElementMap::iterator it = map.find(key);
Mark Salyzyn511338d2015-05-19 09:12:30 -0700357 if (it != map.end()) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800358 LogBufferElement* found = it->second;
Chih-Hung Hsieh08d470b2018-08-13 14:22:56 -0700359 uint16_t moreDropped = found->getDropped();
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700360 if ((dropped + moreDropped) > USHRT_MAX) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700361 map.erase(it);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700362 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700363 found->setDropped(dropped + moreDropped);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700364 return true;
365 }
366 }
367 return false;
368 }
369
Mark Salyzyn501c3732017-03-10 14:31:54 -0800370 void add(LogBufferElement* element) {
Tom Cherrya5151972020-05-15 11:39:58 -0700371 uint64_t key = LogBufferElementKey(element->getUid(), element->getPid(), element->getTid());
372 map[key] = element;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700373 }
374
Tom Cherryd5b38382020-05-12 13:16:41 -0700375 void clear() { map.clear(); }
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700376
Mark Salyzyn501c3732017-03-10 14:31:54 -0800377 void clear(LogBufferElement* element) {
Tom Cherry10d086e2019-08-21 14:16:34 -0700378 uint64_t current = element->getRealTime().nsec() - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn501c3732017-03-10 14:31:54 -0800379 for (LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
380 LogBufferElement* mapElement = it->second;
Tom Cherry10d086e2019-08-21 14:16:34 -0700381 if (mapElement->getDropped() >= EXPIRE_THRESHOLD &&
382 current > mapElement->getRealTime().nsec()) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700383 it = map.erase(it);
384 } else {
385 ++it;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700386 }
387 }
388 }
Tom Cherrya5151972020-05-15 11:39:58 -0700389
390 private:
391 uint64_t LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid) {
392 return uint64_t(uid) << 32 | uint64_t(pid) << 16 | uint64_t(tid);
393 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700394};
395
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700396// If the selected reader is blocking our pruning progress, decide on
397// what kind of mitigation is necessary to unblock the situation.
Tom Cherryd5b38382020-05-12 13:16:41 -0700398void ChattyLogBuffer::kickMe(LogReaderThread* me, log_id_t id, unsigned long pruneRows) {
Tom Cherry64e90162020-05-07 14:44:43 -0700399 if (stats_->Sizes(id) > (2 * log_buffer_size(id))) { // +100%
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700400 // A misbehaving or slow reader has its connection
401 // dropped if we hit too much memory pressure.
Tom Cherry283c9a12020-05-14 19:25:05 -0700402 android::prdebug("Kicking blocked reader, %s, from ChattyLogBuffer::kickMe()\n",
403 me->name().c_str());
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700404 me->release_Locked();
Tom Cherry68630a02020-05-11 16:29:29 -0700405 } else if (me->deadline().time_since_epoch().count() != 0) {
406 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700407 me->triggerReader_Locked();
408 } else {
409 // tell slow reader to skip entries to catch up
Tom Cherry21f16a02019-11-15 17:37:03 -0800410 android::prdebug(
Tom Cherry283c9a12020-05-14 19:25:05 -0700411 "Skipping %lu entries from slow reader, %s, from ChattyLogBuffer::kickMe()\n",
412 pruneRows, me->name().c_str());
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700413 me->triggerSkip_Locked(id, pruneRows);
414 }
415}
416
Mark Salyzyn0175b072014-02-26 09:50:16 -0800417// prune "pruneRows" of type "id" from the buffer.
418//
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700419// This garbage collection task is used to expire log entries. It is called to
420// remove all logs (clear), all UID logs (unprivileged clear), or every
421// 256 or 10% of the total logs (whichever is less) to prune the logs.
422//
423// First there is a prep phase where we discover the reader region lock that
424// acts as a backstop to any pruning activity to stop there and go no further.
425//
426// There are three major pruning loops that follow. All expire from the oldest
427// entries. Since there are multiple log buffers, the Android logging facility
428// will appear to drop entries 'in the middle' when looking at multiple log
429// sources and buffers. This effect is slightly more prominent when we prune
430// the worst offender by logging source. Thus the logs slowly loose content
431// and value as you move back in time. This is preferred since chatty sources
432// invariably move the logs value down faster as less chatty sources would be
433// expired in the noise.
434//
435// The first loop performs blacklisting and worst offender pruning. Falling
436// through when there are no notable worst offenders and have not hit the
437// region lock preventing further worst offender pruning. This loop also looks
438// after managing the chatty log entries and merging to help provide
439// statistical basis for blame. The chatty entries are not a notification of
440// how much logs you may have, but instead represent how much logs you would
441// have had in a virtual log buffer that is extended to cover all the in-memory
442// logs without loss. They last much longer than the represented pruned logs
443// since they get multiplied by the gains in the non-chatty log sources.
444//
445// The second loop get complicated because an algorithm of watermarks and
446// history is maintained to reduce the order and keep processing time
447// down to a minimum at scale. These algorithms can be costly in the face
448// of larger log buffers, or severly limited processing time granted to a
449// background task at lowest priority.
450//
451// This second loop does straight-up expiration from the end of the logs
452// (again, remember for the specified log buffer id) but does some whitelist
453// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
454// spam filtration all take priority. This second loop also checks if a region
455// lock is causing us to buffer too much in the logs to help the reader(s),
456// and will tell the slowest reader thread to skip log entries, and if
457// persistent and hits a further threshold, kill the reader thread.
458//
459// The third thread is optional, and only gets hit if there was a whitelist
460// and more needs to be pruned against the backstop of the region lock.
461//
Tom Cherryd5b38382020-05-12 13:16:41 -0700462bool ChattyLogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Tom Cherry6ec71e92020-05-04 12:53:36 -0700463 LogReaderThread* oldest = nullptr;
Mark Salyzync5dc9702015-09-16 15:34:00 -0700464 bool busy = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700465 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800466
Tom Cherry68630a02020-05-11 16:29:29 -0700467 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
Mark Salyzyn0175b072014-02-26 09:50:16 -0800468
469 // Region locked?
Tom Cherry68630a02020-05-11 16:29:29 -0700470 for (const auto& reader_thread : reader_list_->reader_threads()) {
471 if (!reader_thread->IsWatching(id)) {
472 continue;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800473 }
Tom Cherry68630a02020-05-11 16:29:29 -0700474 if (!oldest || oldest->start() > reader_thread->start() ||
475 (oldest->start() == reader_thread->start() &&
476 reader_thread->deadline().time_since_epoch().count() != 0)) {
477 oldest = reader_thread.get();
478 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800479 }
480
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800481 LogBufferElementCollection::iterator it;
482
Mark Salyzyn501c3732017-03-10 14:31:54 -0800483 if (__predict_false(caller_uid != AID_ROOT)) { // unlikely
Mark Salyzyn43a5f312016-09-01 15:48:36 -0700484 // Only here if clear all request from non system source, so chatty
485 // filter logistics is not required.
Tom Cherry385c2c92020-04-29 17:58:18 -0700486 it = GetOldest(id);
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800487 while (it != mLogElements.end()) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800488 LogBufferElement* element = *it;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700489
Tom Cherryd5b38382020-05-12 13:16:41 -0700490 if (element->getLogId() != id || element->getUid() != caller_uid) {
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700491 ++it;
492 continue;
493 }
494
Tom Cherrycef47bb2020-05-04 17:10:16 -0700495 if (oldest && oldest->start() <= element->getSequence()) {
Tom Cherry5e266552020-04-08 10:47:26 -0700496 busy = true;
497 kickMe(oldest, id, pruneRows);
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700498 break;
499 }
500
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700501 it = erase(it);
Mark Salyzyn43a5f312016-09-01 15:48:36 -0700502 if (--pruneRows == 0) {
503 break;
504 }
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700505 }
Mark Salyzync5dc9702015-09-16 15:34:00 -0700506 return busy;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700507 }
508
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700509 // prune by worst offenders; by blacklist, UID, and by PID of system UID
Tom Cherry5a3db392020-05-01 17:03:20 -0700510 bool hasBlacklist = (id != LOG_ID_SECURITY) && prune_->naughty();
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700511 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800512 // recalculate the worst offender on every batched pass
Mark Salyzyn501c3732017-03-10 14:31:54 -0800513 int worst = -1; // not valid for getUid() or getKey()
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800514 size_t worst_sizes = 0;
515 size_t second_worst_sizes = 0;
Mark Salyzyn501c3732017-03-10 14:31:54 -0800516 pid_t worstPid = 0; // POSIX guarantees PID != 0
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800517
Tom Cherry5a3db392020-05-01 17:03:20 -0700518 if (worstUidEnabledForLogid(id) && prune_->worstUidEnabled()) {
Mark Salyzyn6a066942016-07-14 15:34:30 -0700519 // Calculate threshold as 12.5% of available storage
520 size_t threshold = log_buffer_size(id) / 8;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700521
Tom Cherryb6b78e92020-05-07 09:13:12 -0700522 if (id == LOG_ID_EVENTS || id == LOG_ID_SECURITY) {
Tom Cherry64e90162020-05-07 14:44:43 -0700523 stats_->WorstTwoTags(threshold, &worst, &worst_sizes, &second_worst_sizes);
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700524 // per-pid filter for AID_SYSTEM sources is too complex
Mark Salyzyn6a066942016-07-14 15:34:30 -0700525 } else {
Tom Cherry64e90162020-05-07 14:44:43 -0700526 stats_->WorstTwoUids(id, threshold, &worst, &worst_sizes, &second_worst_sizes);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700527
Tom Cherryb6b78e92020-05-07 09:13:12 -0700528 if (worst == AID_SYSTEM && prune_->worstPidOfSystemEnabled()) {
Tom Cherry64e90162020-05-07 14:44:43 -0700529 stats_->WorstTwoSystemPids(id, worst_sizes, &worstPid, &second_worst_sizes);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700530 }
531 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800532 }
533
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700534 // skip if we have neither worst nor naughty filters
Mark Salyzyn6a066942016-07-14 15:34:30 -0700535 if ((worst == -1) && !hasBlacklist) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700536 break;
537 }
538
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800539 bool kick = false;
Tom Cherry385c2c92020-04-29 17:58:18 -0700540 bool leading = true; // true if starting from the oldest log entry, false if starting from
541 // a specific chatty entry.
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700542 // Perform at least one mandatory garbage collection cycle in following
543 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700544 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700545 // - check age-out of preserved logs
546 bool gc = pruneRows <= 1;
Mark Salyzyn6a066942016-07-14 15:34:30 -0700547 if (!gc && (worst != -1)) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800548 { // begin scope for worst found iterator
Tom Cherryd5b38382020-05-12 13:16:41 -0700549 LogBufferIteratorMap::iterator found = mLastWorst[id].find(worst);
550 if (found != mLastWorst[id].end() && found->second != mLogElements.end()) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700551 leading = false;
552 it = found->second;
553 }
554 }
Mark Salyzyn501c3732017-03-10 14:31:54 -0800555 if (worstPid) { // begin scope for pid worst found iterator
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700556 // FYI: worstPid only set if !LOG_ID_EVENTS and
557 // !LOG_ID_SECURITY, not going to make that assumption ...
Tom Cherryd5b38382020-05-12 13:16:41 -0700558 LogBufferPidIteratorMap::iterator found = mLastWorstPidOfSystem[id].find(worstPid);
559 if (found != mLastWorstPidOfSystem[id].end() &&
560 found->second != mLogElements.end()) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700561 leading = false;
562 it = found->second;
563 }
Mark Salyzync892ea32015-08-19 17:06:11 -0700564 }
565 }
Tom Cherry385c2c92020-04-29 17:58:18 -0700566 if (leading) {
567 it = GetOldest(id);
568 }
Tom Cherrybd80e562020-05-18 08:58:50 -0700569 static const log_time too_old{EXPIRE_HOUR_THRESHOLD * 60 * 60, 0};
Mark Salyzynccfe8442015-08-24 13:43:27 -0700570 LogBufferElementCollection::iterator lastt;
571 lastt = mLogElements.end();
572 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700573 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700574 while (it != mLogElements.end()) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800575 LogBufferElement* element = *it;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800576
Tom Cherrycef47bb2020-05-04 17:10:16 -0700577 if (oldest && oldest->start() <= element->getSequence()) {
Tom Cherry5e266552020-04-08 10:47:26 -0700578 busy = true;
Mark Salyzyn0878a7c2017-05-11 13:28:33 -0700579 // Do not let chatty eliding trigger any reader mitigation
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800580 break;
581 }
582
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700583 if (element->getLogId() != id) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800584 ++it;
585 continue;
586 }
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700587 // below this point element->getLogId() == id
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800588
Chih-Hung Hsieh08d470b2018-08-13 14:22:56 -0700589 uint16_t dropped = element->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800590
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700591 // remove any leading drops
592 if (leading && dropped) {
593 it = erase(it);
594 continue;
595 }
596
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700597 if (dropped && last.coalesce(element, dropped)) {
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700598 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700599 continue;
600 }
601
Tom Cherryd5b38382020-05-12 13:16:41 -0700602 int key = (id == LOG_ID_EVENTS || id == LOG_ID_SECURITY) ? element->getTag()
603 : element->getUid();
Mark Salyzyn6a066942016-07-14 15:34:30 -0700604
Tom Cherry5a3db392020-05-01 17:03:20 -0700605 if (hasBlacklist && prune_->naughty(element)) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700606 last.clear(element);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700607 it = erase(it);
608 if (dropped) {
609 continue;
610 }
611
612 pruneRows--;
613 if (pruneRows == 0) {
614 break;
615 }
616
Mark Salyzyn6a066942016-07-14 15:34:30 -0700617 if (key == worst) {
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700618 kick = true;
619 if (worst_sizes < second_worst_sizes) {
620 break;
621 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700622 worst_sizes -= element->getMsgLen();
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700623 }
624 continue;
625 }
626
Mark Salyzyn501c3732017-03-10 14:31:54 -0800627 if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old)) ||
628 (element->getRealTime() > (*lastt)->getRealTime())) {
Mark Salyzynccfe8442015-08-24 13:43:27 -0700629 break;
630 }
631
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700632 if (dropped) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700633 last.add(element);
Tom Cherryd5b38382020-05-12 13:16:41 -0700634 if (worstPid && ((!gc && element->getPid() == worstPid) ||
635 mLastWorstPidOfSystem[id].find(element->getPid()) ==
636 mLastWorstPidOfSystem[id].end())) {
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700637 // element->getUid() may not be AID_SYSTEM, next best
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700638 // watermark if current one empty. id is not LOG_ID_EVENTS
639 // or LOG_ID_SECURITY because of worstPid check.
Mark Salyzyn1eefca22016-09-01 07:28:44 -0700640 mLastWorstPidOfSystem[id][element->getPid()] = it;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700641 }
Mark Salyzyn501c3732017-03-10 14:31:54 -0800642 if ((!gc && !worstPid && (key == worst)) ||
643 (mLastWorst[id].find(key) == mLastWorst[id].end())) {
Mark Salyzyn6a066942016-07-14 15:34:30 -0700644 mLastWorst[id][key] = it;
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700645 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800646 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700647 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800648 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700649
Tom Cherryd5b38382020-05-12 13:16:41 -0700650 if (key != worst || (worstPid && element->getPid() != worstPid)) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700651 leading = false;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700652 last.clear(element);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700653 ++it;
654 continue;
655 }
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700656 // key == worst below here
657 // If worstPid set, then element->getPid() == worstPid below here
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700658
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700659 pruneRows--;
660 if (pruneRows == 0) {
661 break;
662 }
663
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700664 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700665
Chih-Hung Hsieh08d470b2018-08-13 14:22:56 -0700666 uint16_t len = element->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700667
668 // do not create any leading drops
669 if (leading) {
670 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700671 } else {
Tom Cherry64e90162020-05-07 14:44:43 -0700672 stats_->Drop(element);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700673 element->setDropped(1);
674 if (last.coalesce(element, 1)) {
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700675 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700676 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700677 last.add(element);
Tom Cherryd5b38382020-05-12 13:16:41 -0700678 if (worstPid && (!gc || mLastWorstPidOfSystem[id].find(worstPid) ==
679 mLastWorstPidOfSystem[id].end())) {
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700680 // element->getUid() may not be AID_SYSTEM, next best
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700681 // watermark if current one empty. id is not
682 // LOG_ID_EVENTS or LOG_ID_SECURITY because of worstPid.
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700683 mLastWorstPidOfSystem[id][worstPid] = it;
684 }
Tom Cherryd5b38382020-05-12 13:16:41 -0700685 if ((!gc && !worstPid) || mLastWorst[id].find(worst) == mLastWorst[id].end()) {
Mark Salyzyn6a066942016-07-14 15:34:30 -0700686 mLastWorst[id][worst] = it;
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700687 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700688 ++it;
689 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700690 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700691 if (worst_sizes < second_worst_sizes) {
692 break;
693 }
694 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800695 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700696 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800697
Tom Cherry5a3db392020-05-01 17:03:20 -0700698 if (!kick || !prune_->worstUidEnabled()) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800699 break; // the following loop will ask bad clients to skip/drop
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800700 }
701 }
702
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800703 bool whitelist = false;
Tom Cherry5a3db392020-05-01 17:03:20 -0700704 bool hasWhitelist = (id != LOG_ID_SECURITY) && prune_->nice() && !clearAll;
Tom Cherry385c2c92020-04-29 17:58:18 -0700705 it = GetOldest(id);
Mark Salyzyn501c3732017-03-10 14:31:54 -0800706 while ((pruneRows > 0) && (it != mLogElements.end())) {
707 LogBufferElement* element = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700708
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700709 if (element->getLogId() != id) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700710 it++;
711 continue;
712 }
713
Tom Cherrycef47bb2020-05-04 17:10:16 -0700714 if (oldest && oldest->start() <= element->getSequence()) {
Tom Cherry5e266552020-04-08 10:47:26 -0700715 busy = true;
716 if (!whitelist) kickMe(oldest, id, pruneRows);
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700717 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800718 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700719
Tom Cherry5a3db392020-05-01 17:03:20 -0700720 if (hasWhitelist && !element->getDropped() && prune_->nice(element)) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700721 // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700722 whitelist = true;
723 it++;
724 continue;
725 }
726
727 it = erase(it);
728 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800729 }
730
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700731 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800732 if (whitelist && (pruneRows > 0)) {
Tom Cherry385c2c92020-04-29 17:58:18 -0700733 it = GetOldest(id);
Mark Salyzyn501c3732017-03-10 14:31:54 -0800734 while ((it != mLogElements.end()) && (pruneRows > 0)) {
735 LogBufferElement* element = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700736
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700737 if (element->getLogId() != id) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700738 ++it;
739 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800740 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700741
Tom Cherrycef47bb2020-05-04 17:10:16 -0700742 if (oldest && oldest->start() <= element->getSequence()) {
Tom Cherry5e266552020-04-08 10:47:26 -0700743 busy = true;
744 kickMe(oldest, id, pruneRows);
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700745 break;
746 }
747
748 it = erase(it);
749 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800750 }
751 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800752
Mark Salyzync5dc9702015-09-16 15:34:00 -0700753 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800754}
755
756// clear all rows of type "id" from the buffer.
Tom Cherryd5b38382020-05-12 13:16:41 -0700757bool ChattyLogBuffer::Clear(log_id_t id, uid_t uid) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700758 bool busy = true;
759 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
760 for (int retry = 4;;) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800761 if (retry == 1) { // last pass
Mark Salyzync5dc9702015-09-16 15:34:00 -0700762 // Check if it is still busy after the sleep, we say prune
763 // one entry, not another clear run, so we are looking for
764 // the quick side effect of the return value to tell us if
765 // we have a _blocked_ reader.
Tom Cherry0b01ff02020-05-21 10:37:22 -0700766 {
767 auto lock = std::lock_guard{lock_};
768 busy = prune(id, 1, uid);
769 }
Mark Salyzync5dc9702015-09-16 15:34:00 -0700770 // It is still busy, blocked reader(s), lets kill them all!
771 // otherwise, lets be a good citizen and preserve the slow
772 // readers and let the clear run (below) deal with determining
773 // if we are still blocked and return an error code to caller.
774 if (busy) {
Tom Cherry68630a02020-05-11 16:29:29 -0700775 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
776 for (const auto& reader_thread : reader_list_->reader_threads()) {
777 if (reader_thread->IsWatching(id)) {
Tom Cherry21f16a02019-11-15 17:37:03 -0800778 android::prdebug(
Tom Cherry283c9a12020-05-14 19:25:05 -0700779 "Kicking blocked reader, %s, from ChattyLogBuffer::clear()\n",
780 reader_thread->name().c_str());
Tom Cherry68630a02020-05-11 16:29:29 -0700781 reader_thread->release_Locked();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700782 }
Mark Salyzync5dc9702015-09-16 15:34:00 -0700783 }
Mark Salyzync5dc9702015-09-16 15:34:00 -0700784 }
785 }
Tom Cherry0b01ff02020-05-21 10:37:22 -0700786 {
787 auto lock = std::lock_guard{lock_};
788 busy = prune(id, ULONG_MAX, uid);
789 }
Mark Salyzync5dc9702015-09-16 15:34:00 -0700790 if (!busy || !--retry) {
791 break;
792 }
Mark Salyzyn501c3732017-03-10 14:31:54 -0800793 sleep(1); // Let reader(s) catch up after notification
Mark Salyzync5dc9702015-09-16 15:34:00 -0700794 }
795 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800796}
797
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800798// set the total space allocated to "id"
Tom Cherryd5b38382020-05-12 13:16:41 -0700799int ChattyLogBuffer::SetSize(log_id_t id, unsigned long size) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800800 // Reasonable limits ...
Mark Salyzynf10e2732016-09-27 13:08:23 -0700801 if (!__android_logger_valid_buffer_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800802 return -1;
803 }
Tom Cherry0b01ff02020-05-21 10:37:22 -0700804 auto lock = std::lock_guard{lock_};
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800805 log_buffer_size(id) = size;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800806 return 0;
807}
808
809// get the total space allocated to "id"
Tom Cherryd5b38382020-05-12 13:16:41 -0700810unsigned long ChattyLogBuffer::GetSize(log_id_t id) {
Tom Cherry0b01ff02020-05-21 10:37:22 -0700811 auto shared_lock = SharedLock{lock_};
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800812 size_t retval = log_buffer_size(id);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800813 return retval;
814}
815
Tom Cherryd5b38382020-05-12 13:16:41 -0700816uint64_t ChattyLogBuffer::FlushTo(
Tom Cherry283c9a12020-05-14 19:25:05 -0700817 LogWriter* writer, uint64_t start, pid_t* lastTid,
Tom Cherry68630a02020-05-11 16:29:29 -0700818 const std::function<FlushToResult(const LogBufferElement* element)>& filter) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800819 LogBufferElementCollection::iterator it;
Tom Cherry283c9a12020-05-14 19:25:05 -0700820 uid_t uid = writer->uid();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800821
Tom Cherry0b01ff02020-05-21 10:37:22 -0700822 auto shared_lock = SharedLock{lock_};
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600823
Tom Cherry10d086e2019-08-21 14:16:34 -0700824 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600825 // client wants to start from the beginning
826 it = mLogElements.begin();
827 } else {
828 // Client wants to start from some specified time. Chances are
829 // we are better off starting from the end of the time sorted list.
Tom Cherry10d086e2019-08-21 14:16:34 -0700830 for (it = mLogElements.end(); it != mLogElements.begin();
Mark Salyzyn501c3732017-03-10 14:31:54 -0800831 /* do nothing */) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600832 --it;
Mark Salyzyn501c3732017-03-10 14:31:54 -0800833 LogBufferElement* element = *it;
Tom Cherry10d086e2019-08-21 14:16:34 -0700834 if (element->getSequence() <= start) {
835 it++;
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600836 break;
837 }
838 }
839 }
840
Tom Cherry10d086e2019-08-21 14:16:34 -0700841 uint64_t curr = start;
Mark Salyzynb5b87962017-01-23 14:20:31 -0800842
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600843 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn501c3732017-03-10 14:31:54 -0800844 LogBufferElement* element = *it;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800845
Tom Cherry283c9a12020-05-14 19:25:05 -0700846 if (!writer->privileged() && element->getUid() != uid) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800847 continue;
848 }
849
Tom Cherry283c9a12020-05-14 19:25:05 -0700850 if (!writer->can_read_security_logs() && element->getLogId() == LOG_ID_SECURITY) {
Mark Salyzyn8fa88962016-01-26 14:32:35 -0800851 continue;
852 }
853
Mark Salyzyn3c501b52017-04-18 14:09:45 -0700854 // NB: calling out to another object with wrlock() held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800855 if (filter) {
Tom Cherry68630a02020-05-11 16:29:29 -0700856 FlushToResult ret = filter(element);
857 if (ret == FlushToResult::kSkip) {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800858 continue;
859 }
Tom Cherry68630a02020-05-11 16:29:29 -0700860 if (ret == FlushToResult::kStop) {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800861 break;
862 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800863 }
864
Mark Salyzynae2abf12017-03-31 10:48:39 -0700865 bool sameTid = false;
866 if (lastTid) {
867 sameTid = lastTid[element->getLogId()] == element->getTid();
868 // Dropped (chatty) immediately following a valid log from the
869 // same source in the same log buffer indicates we have a
870 // multiple identical squash. chatty that differs source
871 // is due to spam filter. chatty to chatty of different
872 // source is also due to spam filter.
873 lastTid[element->getLogId()] =
Tom Cherryd5b38382020-05-12 13:16:41 -0700874 (element->getDropped() && !sameTid) ? 0 : element->getTid();
Mark Salyzynae2abf12017-03-31 10:48:39 -0700875 }
Mark Salyzynb5b87962017-01-23 14:20:31 -0800876
Tom Cherry0b01ff02020-05-21 10:37:22 -0700877 shared_lock.unlock();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800878
Tom Cherry283c9a12020-05-14 19:25:05 -0700879 curr = element->getSequence();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800880 // range locking in LastLogTimes looks after us
Tom Cherry283c9a12020-05-14 19:25:05 -0700881 if (!element->FlushTo(writer, stats_, sameTid)) {
882 return FLUSH_ERROR;
Mark Salyzyneb45db22017-05-17 19:55:12 +0000883 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800884
Tom Cherry0b01ff02020-05-21 10:37:22 -0700885 shared_lock.lock_shared();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800886 }
Mark Salyzyn206ed8e2017-05-18 10:06:00 -0700887 return curr;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800888}