blob: 7613c1e98cac6afa52ac47a46e5ca6bf5f26a3cb [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 */
Mark Salyzyn60636fa2016-10-24 16:22:17 -070016// for manual checking of stale entries during LogBuffer::erase()
17//#define DEBUG_CHECK_FOR_STALE_ENTRIES
Mark Salyzyn0175b072014-02-26 09:50:16 -080018
Mark Salyzyn671e3432014-05-06 07:34:59 -070019#include <ctype.h>
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -080020#include <endian.h>
Mark Salyzyn202e1532015-02-09 08:21:05 -080021#include <errno.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080022#include <stdio.h>
23#include <string.h>
Mark Salyzyn8fcfd852016-10-24 08:20:26 -070024#include <sys/cdefs.h>
Mark Salyzyn57a0af92014-05-09 17:44:18 -070025#include <sys/user.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080026#include <time.h>
27#include <unistd.h>
28
Mark Salyzyn511338d2015-05-19 09:12:30 -070029#include <unordered_map>
30
Mark Salyzyn671e3432014-05-06 07:34:59 -070031#include <cutils/properties.h>
Mark Salyzynf10e2732016-09-27 13:08:23 -070032#include <private/android_logger.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080033
34#include "LogBuffer.h"
Mark Salyzynb6bee332015-09-08 08:56:32 -070035#include "LogKlog.h"
Mark Salyzyn671e3432014-05-06 07:34:59 -070036#include "LogReader.h"
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
Mark Salyzyn11e55cb2015-03-10 16:45:17 -070046void LogBuffer::init() {
Mark Salyzyndfa7a072014-02-11 12:29:31 -080047 log_id_for_each(i) {
Mark Salyzyn507eb9f2016-01-11 10:58:09 -080048 mLastSet[i] = false;
49 mLast[i] = mLogElements.begin();
50
Mark Salyzynf10e2732016-09-27 13:08:23 -070051 if (setSize(i, __android_logger_get_buffer_size(i))) {
Mark Salyzyn57a0af92014-05-09 17:44:18 -070052 setSize(i, LOG_BUFFER_MIN_SIZE);
53 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -080054 }
Mark Salyzynb6bee332015-09-08 08:56:32 -070055 bool lastMonotonic = monotonic;
Mark Salyzynba7a9a02015-12-01 15:57:25 -080056 monotonic = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzynb75cce02015-11-30 11:35:56 -080057 if (lastMonotonic != monotonic) {
58 //
59 // Fixup all timestamps, may not be 100% accurate, but better than
60 // throwing what we have away when we get 'surprised' by a change.
61 // In-place element fixup so no need to check reader-lock. Entries
62 // should already be in timestamp order, but we could end up with a
63 // few out-of-order entries if new monotonics come in before we
64 // are notified of the reinit change in status. A Typical example would
65 // be:
66 // --------- beginning of system
67 // 10.494082 184 201 D Cryptfs : Just triggered post_fs_data
68 // --------- beginning of kernel
69 // 0.000000 0 0 I : Initializing cgroup subsys
70 // as the act of mounting /data would trigger persist.logd.timestamp to
71 // be corrected. 1/30 corner case YMMV.
72 //
73 pthread_mutex_lock(&mLogElementsLock);
74 LogBufferElementCollection::iterator it = mLogElements.begin();
75 while((it != mLogElements.end())) {
76 LogBufferElement *e = *it;
77 if (monotonic) {
78 if (!android::isMonotonic(e->mRealTime)) {
79 LogKlog::convertRealToMonotonic(e->mRealTime);
80 }
81 } else {
82 if (android::isMonotonic(e->mRealTime)) {
83 LogKlog::convertMonotonicToReal(e->mRealTime);
84 }
85 }
86 ++it;
87 }
88 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzynb6bee332015-09-08 08:56:32 -070089 }
90
Mark Salyzynb75cce02015-11-30 11:35:56 -080091 // We may have been triggered by a SIGHUP. Release any sleeping reader
92 // threads to dump their current content.
Mark Salyzynb6bee332015-09-08 08:56:32 -070093 //
Mark Salyzynb75cce02015-11-30 11:35:56 -080094 // NB: this is _not_ performed in the context of a SIGHUP, it is
95 // performed during startup, and in context of reinit administrative thread
96 LogTimeEntry::lock();
97
98 LastLogTimes::iterator times = mTimes.begin();
99 while(times != mTimes.end()) {
100 LogTimeEntry *entry = (*times);
101 if (entry->owned_Locked()) {
102 entry->triggerReader_Locked();
Mark Salyzynb6bee332015-09-08 08:56:32 -0700103 }
Mark Salyzynb75cce02015-11-30 11:35:56 -0800104 times++;
Mark Salyzynb6bee332015-09-08 08:56:32 -0700105 }
Mark Salyzynb75cce02015-11-30 11:35:56 -0800106
107 LogTimeEntry::unlock();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800108}
109
Mark Salyzynb6bee332015-09-08 08:56:32 -0700110LogBuffer::LogBuffer(LastLogTimes *times):
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800111 monotonic(android_log_clockid() == CLOCK_MONOTONIC),
Mark Salyzynb6bee332015-09-08 08:56:32 -0700112 mTimes(*times) {
Mark Salyzyn11e55cb2015-03-10 16:45:17 -0700113 pthread_mutex_init(&mLogElementsLock, NULL);
114
Mark Salyzyna2c02222016-12-13 10:31:29 -0800115 log_id_for_each(i) {
116 lastLoggedElements[i] = NULL;
117 droppedElements[i] = NULL;
118 }
119
Mark Salyzyn11e55cb2015-03-10 16:45:17 -0700120 init();
121}
122
Mark Salyzyna2c02222016-12-13 10:31:29 -0800123LogBuffer::~LogBuffer() {
124 log_id_for_each(i) {
125 delete lastLoggedElements[i];
126 delete droppedElements[i];
127 }
128}
129
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800130enum match_type {
131 DIFFERENT,
132 SAME,
133 SAME_LIBLOG
134};
135
136static enum match_type identical(LogBufferElement* elem, LogBufferElement* last) {
Mark Salyzyna2c02222016-12-13 10:31:29 -0800137 // is it mostly identical?
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800138// if (!elem) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800139 unsigned short lenl = elem->getMsgLen();
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800140 if (!lenl) return DIFFERENT;
141// if (!last) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800142 unsigned short lenr = last->getMsgLen();
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800143 if (!lenr) return DIFFERENT;
144// if (elem->getLogId() != last->getLogId()) return DIFFERENT;
145 if (elem->getUid() != last->getUid()) return DIFFERENT;
146 if (elem->getPid() != last->getPid()) return DIFFERENT;
147 if (elem->getTid() != last->getTid()) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800148
149 // last is more than a minute old, stop squashing identical messages
150 if (elem->getRealTime().nsec() >
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800151 (last->getRealTime().nsec() + 60 * NS_PER_SEC)) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800152
153 // Identical message
154 const char* msgl = elem->getMsg();
155 const char* msgr = last->getMsg();
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800156 if (lenl == lenr) {
157 if (!fastcmp<memcmp>(msgl, msgr, lenl)) return SAME;
158 // liblog tagged messages (content gets summed)
159 if ((elem->getLogId() == LOG_ID_EVENTS) &&
160 (lenl == sizeof(android_log_event_int_t)) &&
161 !fastcmp<memcmp>(msgl, msgr,
162 sizeof(android_log_event_int_t) - sizeof(int32_t)) &&
163 (elem->getTag() == LIBLOG_LOG_TAG)) return SAME_LIBLOG;
164 }
Mark Salyzyna2c02222016-12-13 10:31:29 -0800165
166 // audit message (except sequence number) identical?
167 static const char avc[] = "): avc: ";
168
169 if (last->isBinary()) {
170 if (fastcmp<memcmp>(msgl, msgr,
171 sizeof(android_log_event_string_t) -
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800172 sizeof(int32_t))) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800173 msgl += sizeof(android_log_event_string_t);
174 lenl -= sizeof(android_log_event_string_t);
175 msgr += sizeof(android_log_event_string_t);
176 lenr -= sizeof(android_log_event_string_t);
177 }
178 const char *avcl = android::strnstr(msgl, lenl, avc);
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800179 if (!avcl) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800180 lenl -= avcl - msgl;
181 const char *avcr = android::strnstr(msgr, lenr, avc);
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800182 if (!avcr) return DIFFERENT;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800183 lenr -= avcr - msgr;
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800184 if (lenl != lenr) return DIFFERENT;
185 if (fastcmp<memcmp>(avcl + strlen(avc),
186 avcr + strlen(avc), lenl)) return DIFFERENT;
187 return SAME;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800188}
189
Mark Salyzyn202e1532015-02-09 08:21:05 -0800190int LogBuffer::log(log_id_t log_id, log_time realtime,
191 uid_t uid, pid_t pid, pid_t tid,
192 const char *msg, unsigned short len) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800193 if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
Mark Salyzyn202e1532015-02-09 08:21:05 -0800194 return -EINVAL;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800195 }
Mark Salyzyne59c4692014-10-02 13:07:05 -0700196
Mark Salyzyn0175b072014-02-26 09:50:16 -0800197 LogBufferElement *elem = new LogBufferElement(log_id, realtime,
Mark Salyzynb992d0d2014-03-20 16:09:38 -0700198 uid, pid, tid, msg, len);
Mark Salyzyn0ee8de32016-01-06 21:17:43 +0000199 if (log_id != LOG_ID_SECURITY) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800200 int prio = ANDROID_LOG_INFO;
Mark Salyzyn0ee8de32016-01-06 21:17:43 +0000201 const char *tag = NULL;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800202 if (log_id == LOG_ID_EVENTS) {
Mark Salyzyn61e9ce62016-09-12 14:51:54 -0700203 tag = tagToName(elem->getTag());
Mark Salyzyn083b0372015-12-04 10:59:45 -0800204 } else {
205 prio = *msg;
206 tag = msg + 1;
207 }
Mark Salyzyn61e9ce62016-09-12 14:51:54 -0700208 if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800209 // Log traffic received to total
210 pthread_mutex_lock(&mLogElementsLock);
211 stats.add(elem);
212 stats.subtract(elem);
213 pthread_mutex_unlock(&mLogElementsLock);
214 delete elem;
215 return -EACCES;
216 }
Mark Salyzyne59c4692014-10-02 13:07:05 -0700217 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800218
219 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyna2c02222016-12-13 10:31:29 -0800220 LogBufferElement* currentLast = lastLoggedElements[log_id];
221 if (currentLast) {
222 LogBufferElement *dropped = droppedElements[log_id];
223 unsigned short count = dropped ? dropped->getDropped() : 0;
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800224 //
225 // State Init
226 // incoming:
227 // dropped = NULL
228 // currentLast = NULL;
229 // elem = incoming message
230 // outgoing:
231 // dropped = NULL -> State 0
232 // currentLast = copy of elem
233 // log elem
234 // State 0
235 // incoming:
236 // count = 0
237 // dropped = NULL
238 // currentLast = copy of last message
239 // elem = incoming message
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800240 // outgoing: if match != DIFFERENT
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800241 // dropped = copy of first identical message -> State 1
242 // currentLast = reference to elem
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800243 // break: if match == DIFFERENT
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800244 // dropped = NULL -> State 0
245 // delete copy of last message (incoming currentLast)
246 // currentLast = copy of elem
247 // log elem
248 // State 1
249 // incoming:
250 // count = 0
251 // dropped = copy of first identical message
252 // currentLast = reference to last held-back incoming
253 // message
254 // elem = incoming message
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800255 // outgoing: if match == SAME
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800256 // delete copy of first identical message (dropped)
257 // dropped = reference to last held-back incoming
258 // message set to chatty count of 1 -> State 2
259 // currentLast = reference to elem
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800260 // outgoing: if match == SAME_LIBLOG
261 // dropped = copy of first identical message -> State 1
262 // take sum of currentLast and elem
263 // if sum overflows:
264 // log currentLast
265 // currentLast = reference to elem
266 // else
267 // delete currentLast
268 // currentLast = reference to elem, sum liblog.
269 // break: if match == DIFFERENT
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800270 // delete dropped
271 // dropped = NULL -> State 0
272 // log reference to last held-back (currentLast)
273 // currentLast = copy of elem
274 // log elem
275 // State 2
276 // incoming:
277 // count = chatty count
278 // dropped = chatty message holding count
279 // currentLast = reference to last held-back incoming
280 // message.
281 // dropped = chatty message holding count
282 // elem = incoming message
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800283 // outgoing: if match != DIFFERENT
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800284 // delete chatty message holding count
285 // dropped = reference to last held-back incoming
286 // message, set to chatty count + 1
287 // currentLast = reference to elem
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800288 // break: if match == DIFFERENT
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800289 // log dropped (chatty message)
290 // dropped = NULL -> State 0
291 // log reference to last held-back (currentLast)
292 // currentLast = copy of elem
293 // log elem
294 //
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800295 enum match_type match = identical(elem, currentLast);
296 if (match != DIFFERENT) {
Mark Salyzyna2c02222016-12-13 10:31:29 -0800297 if (dropped) {
Mark Salyzyn1dfb4de2016-12-16 16:09:15 -0800298 // Sum up liblog tag messages?
299 if ((count == 0) /* at Pass 1 */ && (match == SAME_LIBLOG)) {
300 android_log_event_int_t* event =
301 reinterpret_cast<android_log_event_int_t*>(
302 const_cast<char*>(currentLast->getMsg()));
303 //
304 // To unit test, differentiate with something like:
305 // event->header.tag = htole32(CHATTY_LOG_TAG);
306 // here, then instead of delete currentLast below,
307 // log(currentLast) to see the incremental sums form.
308 //
309 uint32_t swab = event->payload.data;
310 unsigned long long total = htole32(swab);
311 event = reinterpret_cast<android_log_event_int_t*>(
312 const_cast<char*>(elem->getMsg()));
313 swab = event->payload.data;
314
315 lastLoggedElements[LOG_ID_EVENTS] = elem;
316 total += htole32(swab);
317 // check for overflow
318 if (total >= UINT32_MAX) {
319 log(currentLast);
320 pthread_mutex_unlock(&mLogElementsLock);
321 return len;
322 }
323 stats.add(currentLast);
324 stats.subtract(currentLast);
325 delete currentLast;
326 swab = total;
327 event->payload.data = htole32(swab);
328 pthread_mutex_unlock(&mLogElementsLock);
329 return len;
330 }
Mark Salyzyna2c02222016-12-13 10:31:29 -0800331 if (count == USHRT_MAX) {
332 log(dropped);
333 count = 1;
334 } else {
335 delete dropped;
336 ++count;
337 }
338 }
339 if (count) {
340 stats.add(currentLast);
341 stats.subtract(currentLast);
342 currentLast->setDropped(count);
343 }
344 droppedElements[log_id] = currentLast;
345 lastLoggedElements[log_id] = elem;
346 pthread_mutex_unlock(&mLogElementsLock);
347 return len;
348 }
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800349 if (dropped) { // State 1 or 2
350 if (count) { // State 2
351 log(dropped); // report chatty
352 } else { // State 1
353 delete dropped;
354 }
Mark Salyzyna2c02222016-12-13 10:31:29 -0800355 droppedElements[log_id] = NULL;
Mark Salyzyn8f83a352016-12-16 16:09:15 -0800356 log(currentLast); // report last message in the series
357 } else { // State 0
Mark Salyzyna2c02222016-12-13 10:31:29 -0800358 delete currentLast;
359 }
360 }
361 lastLoggedElements[log_id] = new LogBufferElement(*elem);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800362
Mark Salyzyna2c02222016-12-13 10:31:29 -0800363 log(elem);
364 pthread_mutex_unlock(&mLogElementsLock);
365
366 return len;
367}
368
369// assumes mLogElementsLock held, owns elem, will look after garbage collection
370void LogBuffer::log(LogBufferElement* elem) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800371 // Insert elements in time sorted order if possible
372 // NB: if end is region locked, place element at end of list
373 LogBufferElementCollection::iterator it = mLogElements.end();
374 LogBufferElementCollection::iterator last = it;
Mark Salyzyneae155e2014-10-13 16:49:47 -0700375 while (last != mLogElements.begin()) {
376 --it;
Mark Salyzyna2c02222016-12-13 10:31:29 -0800377 if ((*it)->getRealTime() <= elem->getRealTime()) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800378 break;
379 }
380 last = it;
381 }
Mark Salyzync03e72c2014-02-18 11:23:53 -0800382
Mark Salyzyn0175b072014-02-26 09:50:16 -0800383 if (last == mLogElements.end()) {
384 mLogElements.push_back(elem);
385 } else {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800386 uint64_t end = 1;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800387 bool end_set = false;
388 bool end_always = false;
389
390 LogTimeEntry::lock();
391
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700392 LastLogTimes::iterator times = mTimes.begin();
393 while(times != mTimes.end()) {
Mark Salyzyna2c02222016-12-13 10:31:29 -0800394 LogTimeEntry* entry = (*times);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800395 if (entry->owned_Locked()) {
396 if (!entry->mNonBlock) {
397 end_always = true;
398 break;
399 }
400 if (!end_set || (end <= entry->mEnd)) {
401 end = entry->mEnd;
402 end_set = true;
403 }
404 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700405 times++;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800406 }
407
408 if (end_always
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800409 || (end_set && (end >= (*last)->getSequence()))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800410 mLogElements.push_back(elem);
411 } else {
Mark Salyzyna2c02222016-12-13 10:31:29 -0800412 mLogElements.insert(last, elem);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800413 }
414
415 LogTimeEntry::unlock();
416 }
417
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700418 stats.add(elem);
Mark Salyzyna2c02222016-12-13 10:31:29 -0800419 maybePrune(elem->getLogId());
Mark Salyzyn0175b072014-02-26 09:50:16 -0800420}
421
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700422// Prune at most 10% of the log entries or maxPrune, whichever is less.
Mark Salyzyn0175b072014-02-26 09:50:16 -0800423//
424// mLogElementsLock must be held when this function is called.
425void LogBuffer::maybePrune(log_id_t id) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800426 size_t sizes = stats.sizes(id);
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700427 unsigned long maxSize = log_buffer_size(id);
428 if (sizes > maxSize) {
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700429 size_t sizeOver = sizes - ((maxSize * 9) / 10);
Mark Salyzyn58b8be82015-09-30 07:40:09 -0700430 size_t elements = stats.realElements(id);
431 size_t minElements = elements / 100;
432 if (minElements < minPrune) {
433 minElements = minPrune;
434 }
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700435 unsigned long pruneRows = elements * sizeOver / sizes;
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700436 if (pruneRows < minElements) {
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700437 pruneRows = minElements;
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800438 }
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700439 if (pruneRows > maxPrune) {
440 pruneRows = maxPrune;
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700441 }
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800442 prune(id, pruneRows);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800443 }
444}
445
Mark Salyzyn831aa292015-09-03 16:08:50 -0700446LogBufferElementCollection::iterator LogBuffer::erase(
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700447 LogBufferElementCollection::iterator it, bool coalesce) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700448 LogBufferElement *element = *it;
449 log_id_t id = element->getLogId();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700450
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700451 // Remove iterator references in the various lists that will become stale
452 // after the element is erased from the main logging list.
453
Mark Salyzyn6a066942016-07-14 15:34:30 -0700454 { // start of scope for found iterator
455 int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ?
456 element->getTag() : element->getUid();
457 LogBufferIteratorMap::iterator found = mLastWorst[id].find(key);
458 if ((found != mLastWorst[id].end()) && (it == found->second)) {
459 mLastWorst[id].erase(found);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700460 }
Mark Salyzync892ea32015-08-19 17:06:11 -0700461 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700462
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700463 { // start of scope for pid found iterator
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700464 // element->getUid() may not be AID_SYSTEM for next-best-watermark.
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700465 // will not assume id != LOG_ID_EVENTS or LOG_ID_SECURITY for KISS and
466 // long term code stability, find() check should be fast for those ids.
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700467 LogBufferPidIteratorMap::iterator found =
468 mLastWorstPidOfSystem[id].find(element->getPid());
469 if ((found != mLastWorstPidOfSystem[id].end())
470 && (it == found->second)) {
471 mLastWorstPidOfSystem[id].erase(found);
472 }
473 }
474
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800475 bool setLast[LOG_ID_MAX];
476 bool doSetLast = false;
477 log_id_for_each(i) {
478 doSetLast |= setLast[i] = mLastSet[i] && (it == mLast[i]);
479 }
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700480#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
481 LogBufferElementCollection::iterator bad = it;
482 int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ?
483 element->getTag() : element->getUid();
484#endif
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700485 it = mLogElements.erase(it);
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800486 if (doSetLast) {
487 log_id_for_each(i) {
488 if (setLast[i]) {
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700489 if (__predict_false(it == mLogElements.end())) { // impossible
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800490 mLastSet[i] = false;
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700491 mLast[i] = mLogElements.begin();
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800492 } else {
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700493 mLast[i] = it; // push down the road as next-best-watermark
Mark Salyzyn7fd6c5c2016-01-19 16:04:41 -0800494 }
495 }
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800496 }
497 }
Mark Salyzyn60636fa2016-10-24 16:22:17 -0700498#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
499 log_id_for_each(i) {
500 for(auto b : mLastWorst[i]) {
501 if (bad == b.second) {
502 android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n",
503 i, b.first, key);
504 }
505 }
506 for(auto b : mLastWorstPidOfSystem[i]) {
507 if (bad == b.second) {
508 android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n",
509 i, b.first);
510 }
511 }
512 if (mLastSet[i] && (bad == mLast[i])) {
513 android::prdebug("stale mLast[%d]\n", i);
514 mLastSet[i] = false;
515 mLast[i] = mLogElements.begin();
516 }
517 }
518#endif
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700519 if (coalesce) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700520 stats.erase(element);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700521 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700522 stats.subtract(element);
Mark Salyzyn831aa292015-09-03 16:08:50 -0700523 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700524 delete element;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700525
526 return it;
527}
528
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700529// Define a temporary mechanism to report the last LogBufferElement pointer
530// for the specified uid, pid and tid. Used below to help merge-sort when
531// pruning for worst UID.
532class LogBufferElementKey {
533 const union {
534 struct {
Mark Salyzyn684bdb52016-12-13 12:44:20 -0800535 uint32_t uid;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700536 uint16_t pid;
537 uint16_t tid;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700538 } __packed;
539 uint64_t value;
540 } __packed;
541
542public:
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700543 LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid):
544 uid(uid),
545 pid(pid),
Mark Salyzyn684bdb52016-12-13 12:44:20 -0800546 tid(tid)
547 {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700548 }
Chih-Hung Hsieh1cc82ce2016-04-25 13:49:46 -0700549 explicit LogBufferElementKey(uint64_t key):value(key) { }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700550
551 uint64_t getKey() { return value; }
552};
553
Mark Salyzyn511338d2015-05-19 09:12:30 -0700554class LogBufferElementLast {
555
556 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
557 LogBufferElementMap map;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700558
559public:
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700560
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700561 bool coalesce(LogBufferElement *element, unsigned short dropped) {
562 LogBufferElementKey key(element->getUid(),
563 element->getPid(),
564 element->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700565 LogBufferElementMap::iterator it = map.find(key.getKey());
566 if (it != map.end()) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700567 LogBufferElement *found = it->second;
568 unsigned short moreDropped = found->getDropped();
569 if ((dropped + moreDropped) > USHRT_MAX) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700570 map.erase(it);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700571 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700572 found->setDropped(dropped + moreDropped);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700573 return true;
574 }
575 }
576 return false;
577 }
578
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700579 void add(LogBufferElement *element) {
580 LogBufferElementKey key(element->getUid(),
581 element->getPid(),
582 element->getTid());
583 map[key.getKey()] = element;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700584 }
585
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700586 inline void clear() {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700587 map.clear();
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700588 }
589
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700590 void clear(LogBufferElement *element) {
591 uint64_t current = element->getRealTime().nsec()
Mark Salyzyn047cc072015-06-04 13:35:30 -0700592 - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn511338d2015-05-19 09:12:30 -0700593 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700594 LogBufferElement *mapElement = it->second;
595 if ((mapElement->getDropped() >= EXPIRE_THRESHOLD)
596 && (current > mapElement->getRealTime().nsec())) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700597 it = map.erase(it);
598 } else {
599 ++it;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700600 }
601 }
602 }
603
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700604};
605
Mark Salyzyn0175b072014-02-26 09:50:16 -0800606// prune "pruneRows" of type "id" from the buffer.
607//
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700608// This garbage collection task is used to expire log entries. It is called to
609// remove all logs (clear), all UID logs (unprivileged clear), or every
610// 256 or 10% of the total logs (whichever is less) to prune the logs.
611//
612// First there is a prep phase where we discover the reader region lock that
613// acts as a backstop to any pruning activity to stop there and go no further.
614//
615// There are three major pruning loops that follow. All expire from the oldest
616// entries. Since there are multiple log buffers, the Android logging facility
617// will appear to drop entries 'in the middle' when looking at multiple log
618// sources and buffers. This effect is slightly more prominent when we prune
619// the worst offender by logging source. Thus the logs slowly loose content
620// and value as you move back in time. This is preferred since chatty sources
621// invariably move the logs value down faster as less chatty sources would be
622// expired in the noise.
623//
624// The first loop performs blacklisting and worst offender pruning. Falling
625// through when there are no notable worst offenders and have not hit the
626// region lock preventing further worst offender pruning. This loop also looks
627// after managing the chatty log entries and merging to help provide
628// statistical basis for blame. The chatty entries are not a notification of
629// how much logs you may have, but instead represent how much logs you would
630// have had in a virtual log buffer that is extended to cover all the in-memory
631// logs without loss. They last much longer than the represented pruned logs
632// since they get multiplied by the gains in the non-chatty log sources.
633//
634// The second loop get complicated because an algorithm of watermarks and
635// history is maintained to reduce the order and keep processing time
636// down to a minimum at scale. These algorithms can be costly in the face
637// of larger log buffers, or severly limited processing time granted to a
638// background task at lowest priority.
639//
640// This second loop does straight-up expiration from the end of the logs
641// (again, remember for the specified log buffer id) but does some whitelist
642// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
643// spam filtration all take priority. This second loop also checks if a region
644// lock is causing us to buffer too much in the logs to help the reader(s),
645// and will tell the slowest reader thread to skip log entries, and if
646// persistent and hits a further threshold, kill the reader thread.
647//
648// The third thread is optional, and only gets hit if there was a whitelist
649// and more needs to be pruned against the backstop of the region lock.
650//
Mark Salyzyn0175b072014-02-26 09:50:16 -0800651// mLogElementsLock must be held when this function is called.
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700652//
Mark Salyzync5dc9702015-09-16 15:34:00 -0700653bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800654 LogTimeEntry *oldest = NULL;
Mark Salyzync5dc9702015-09-16 15:34:00 -0700655 bool busy = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700656 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800657
658 LogTimeEntry::lock();
659
660 // Region locked?
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700661 LastLogTimes::iterator times = mTimes.begin();
662 while(times != mTimes.end()) {
663 LogTimeEntry *entry = (*times);
TraianX Schiauda6495d2014-12-17 10:53:41 +0200664 if (entry->owned_Locked() && entry->isWatching(id)
Mark Salyzynb75cce02015-11-30 11:35:56 -0800665 && (!oldest ||
666 (oldest->mStart > entry->mStart) ||
667 ((oldest->mStart == entry->mStart) &&
668 (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800669 oldest = entry;
670 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700671 times++;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800672 }
673
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800674 LogBufferElementCollection::iterator it;
675
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700676 if (__predict_false(caller_uid != AID_ROOT)) { // unlikely
Mark Salyzyn43a5f312016-09-01 15:48:36 -0700677 // Only here if clear all request from non system source, so chatty
678 // filter logistics is not required.
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800679 it = mLastSet[id] ? mLast[id] : mLogElements.begin();
680 while (it != mLogElements.end()) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700681 LogBufferElement *element = *it;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700682
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700683 if ((element->getLogId() != id) || (element->getUid() != caller_uid)) {
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700684 ++it;
685 continue;
686 }
687
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800688 if (!mLastSet[id] || ((*mLast[id])->getLogId() != id)) {
689 mLast[id] = it;
690 mLastSet[id] = true;
691 }
692
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700693 if (oldest && (oldest->mStart <= element->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700694 busy = true;
Mark Salyzynb75cce02015-11-30 11:35:56 -0800695 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
696 oldest->triggerReader_Locked();
697 } else {
698 oldest->triggerSkip_Locked(id, pruneRows);
699 }
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700700 break;
701 }
702
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700703 it = erase(it);
Mark Salyzyn43a5f312016-09-01 15:48:36 -0700704 if (--pruneRows == 0) {
705 break;
706 }
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700707 }
708 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700709 return busy;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700710 }
711
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700712 // prune by worst offenders; by blacklist, UID, and by PID of system UID
Mark Salyzyn083b0372015-12-04 10:59:45 -0800713 bool hasBlacklist = (id != LOG_ID_SECURITY) && mPrune.naughty();
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700714 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800715 // recalculate the worst offender on every batched pass
Mark Salyzyn6a066942016-07-14 15:34:30 -0700716 int worst = -1; // not valid for getUid() or getKey()
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800717 size_t worst_sizes = 0;
718 size_t second_worst_sizes = 0;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700719 pid_t worstPid = 0; // POSIX guarantees PID != 0
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800720
Mark Salyzynae769232015-03-17 17:17:25 -0700721 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
Mark Salyzyn6a066942016-07-14 15:34:30 -0700722 // Calculate threshold as 12.5% of available storage
723 size_t threshold = log_buffer_size(id) / 8;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700724
Mark Salyzyn6a066942016-07-14 15:34:30 -0700725 if ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) {
726 stats.sortTags(AID_ROOT, (pid_t)0, 2, id).findWorst(
727 worst, worst_sizes, second_worst_sizes, threshold);
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700728 // per-pid filter for AID_SYSTEM sources is too complex
Mark Salyzyn6a066942016-07-14 15:34:30 -0700729 } else {
730 stats.sort(AID_ROOT, (pid_t)0, 2, id).findWorst(
731 worst, worst_sizes, second_worst_sizes, threshold);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700732
Mark Salyzyn6a066942016-07-14 15:34:30 -0700733 if ((worst == AID_SYSTEM) && mPrune.worstPidOfSystemEnabled()) {
734 stats.sortPids(worst, (pid_t)0, 2, id).findWorst(
735 worstPid, worst_sizes, second_worst_sizes);
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700736 }
737 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800738 }
739
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700740 // skip if we have neither worst nor naughty filters
Mark Salyzyn6a066942016-07-14 15:34:30 -0700741 if ((worst == -1) && !hasBlacklist) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700742 break;
743 }
744
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800745 bool kick = false;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700746 bool leading = true;
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800747 it = mLastSet[id] ? mLast[id] : mLogElements.begin();
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700748 // Perform at least one mandatory garbage collection cycle in following
749 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700750 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700751 // - check age-out of preserved logs
752 bool gc = pruneRows <= 1;
Mark Salyzyn6a066942016-07-14 15:34:30 -0700753 if (!gc && (worst != -1)) {
754 { // begin scope for worst found iterator
755 LogBufferIteratorMap::iterator found = mLastWorst[id].find(worst);
756 if ((found != mLastWorst[id].end())
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700757 && (found->second != mLogElements.end())) {
758 leading = false;
759 it = found->second;
760 }
761 }
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700762 if (worstPid) { // begin scope for pid worst found iterator
763 // FYI: worstPid only set if !LOG_ID_EVENTS and
764 // !LOG_ID_SECURITY, not going to make that assumption ...
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700765 LogBufferPidIteratorMap::iterator found
766 = mLastWorstPidOfSystem[id].find(worstPid);
767 if ((found != mLastWorstPidOfSystem[id].end())
768 && (found->second != mLogElements.end())) {
769 leading = false;
770 it = found->second;
771 }
Mark Salyzync892ea32015-08-19 17:06:11 -0700772 }
773 }
Mark Salyzynccfe8442015-08-24 13:43:27 -0700774 static const timespec too_old = {
775 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
776 };
777 LogBufferElementCollection::iterator lastt;
778 lastt = mLogElements.end();
779 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700780 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700781 while (it != mLogElements.end()) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700782 LogBufferElement *element = *it;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800783
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700784 if (oldest && (oldest->mStart <= element->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700785 busy = true;
Mark Salyzynb75cce02015-11-30 11:35:56 -0800786 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
787 oldest->triggerReader_Locked();
788 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800789 break;
790 }
791
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700792 if (element->getLogId() != id) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800793 ++it;
794 continue;
795 }
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700796 // below this point element->getLogId() == id
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800797
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800798 if (leading && (!mLastSet[id] || ((*mLast[id])->getLogId() != id))) {
799 mLast[id] = it;
800 mLastSet[id] = true;
801 }
802
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700803 unsigned short dropped = element->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800804
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700805 // remove any leading drops
806 if (leading && dropped) {
807 it = erase(it);
808 continue;
809 }
810
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700811 if (dropped && last.coalesce(element, dropped)) {
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700812 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700813 continue;
814 }
815
Mark Salyzyn6a066942016-07-14 15:34:30 -0700816 int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ?
817 element->getTag() :
818 element->getUid();
819
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700820 if (hasBlacklist && mPrune.naughty(element)) {
821 last.clear(element);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700822 it = erase(it);
823 if (dropped) {
824 continue;
825 }
826
827 pruneRows--;
828 if (pruneRows == 0) {
829 break;
830 }
831
Mark Salyzyn6a066942016-07-14 15:34:30 -0700832 if (key == worst) {
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700833 kick = true;
834 if (worst_sizes < second_worst_sizes) {
835 break;
836 }
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700837 worst_sizes -= element->getMsgLen();
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700838 }
839 continue;
840 }
841
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700842 if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old))
843 || (element->getRealTime() > (*lastt)->getRealTime())) {
Mark Salyzynccfe8442015-08-24 13:43:27 -0700844 break;
845 }
846
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700847 if (dropped) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700848 last.add(element);
849 if (worstPid
850 && ((!gc && (element->getPid() == worstPid))
Mark Salyzyn6a066942016-07-14 15:34:30 -0700851 || (mLastWorstPidOfSystem[id].find(element->getPid())
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700852 == mLastWorstPidOfSystem[id].end()))) {
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700853 // element->getUid() may not be AID_SYSTEM, next best
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700854 // watermark if current one empty. id is not LOG_ID_EVENTS
855 // or LOG_ID_SECURITY because of worstPid check.
Mark Salyzyn1eefca22016-09-01 07:28:44 -0700856 mLastWorstPidOfSystem[id][element->getPid()] = it;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700857 }
Mark Salyzyn6a066942016-07-14 15:34:30 -0700858 if ((!gc && !worstPid && (key == worst))
859 || (mLastWorst[id].find(key) == mLastWorst[id].end())) {
860 mLastWorst[id][key] = it;
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700861 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800862 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700863 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800864 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700865
Mark Salyzyn6a066942016-07-14 15:34:30 -0700866 if ((key != worst)
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700867 || (worstPid && (element->getPid() != worstPid))) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700868 leading = false;
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700869 last.clear(element);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700870 ++it;
871 continue;
872 }
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700873 // key == worst below here
874 // If worstPid set, then element->getPid() == worstPid below here
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700875
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700876 pruneRows--;
877 if (pruneRows == 0) {
878 break;
879 }
880
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700881 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700882
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700883 unsigned short len = element->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700884
885 // do not create any leading drops
886 if (leading) {
887 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700888 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700889 stats.drop(element);
890 element->setDropped(1);
891 if (last.coalesce(element, 1)) {
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700892 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700893 } else {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700894 last.add(element);
895 if (worstPid && (!gc
896 || (mLastWorstPidOfSystem[id].find(worstPid)
897 == mLastWorstPidOfSystem[id].end()))) {
Mark Salyzynfa07f9d2016-10-21 09:46:42 -0700898 // element->getUid() may not be AID_SYSTEM, next best
Mark Salyzyn8fcfd852016-10-24 08:20:26 -0700899 // watermark if current one empty. id is not
900 // LOG_ID_EVENTS or LOG_ID_SECURITY because of worstPid.
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700901 mLastWorstPidOfSystem[id][worstPid] = it;
902 }
Mark Salyzyn6a066942016-07-14 15:34:30 -0700903 if ((!gc && !worstPid) ||
904 (mLastWorst[id].find(worst) == mLastWorst[id].end())) {
905 mLastWorst[id][worst] = it;
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700906 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700907 ++it;
908 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700909 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700910 if (worst_sizes < second_worst_sizes) {
911 break;
912 }
913 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800914 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700915 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800916
Mark Salyzyn1c950472014-04-01 17:19:47 -0700917 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800918 break; // the following loop will ask bad clients to skip/drop
919 }
920 }
921
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800922 bool whitelist = false;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800923 bool hasWhitelist = (id != LOG_ID_SECURITY) && mPrune.nice() && !clearAll;
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800924 it = mLastSet[id] ? mLast[id] : mLogElements.begin();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800925 while((pruneRows > 0) && (it != mLogElements.end())) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700926 LogBufferElement *element = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700927
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700928 if (element->getLogId() != id) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700929 it++;
930 continue;
931 }
932
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800933 if (!mLastSet[id] || ((*mLast[id])->getLogId() != id)) {
934 mLast[id] = it;
935 mLastSet[id] = true;
936 }
937
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700938 if (oldest && (oldest->mStart <= element->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700939 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700940 if (whitelist) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800941 break;
942 }
Mark Salyzyn1c950472014-04-01 17:19:47 -0700943
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700944 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
945 // kick a misbehaving log reader client off the island
946 oldest->release_Locked();
Mark Salyzynb75cce02015-11-30 11:35:56 -0800947 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
948 oldest->triggerReader_Locked();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700949 } else {
950 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800951 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700952 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800953 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700954
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700955 if (hasWhitelist && !element->getDropped() && mPrune.nice(element)) {
956 // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700957 whitelist = true;
958 it++;
959 continue;
960 }
961
962 it = erase(it);
963 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800964 }
965
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700966 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800967 if (whitelist && (pruneRows > 0)) {
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800968 it = mLastSet[id] ? mLast[id] : mLogElements.begin();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800969 while((it != mLogElements.end()) && (pruneRows > 0)) {
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700970 LogBufferElement *element = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700971
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700972 if (element->getLogId() != id) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700973 ++it;
974 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800975 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700976
Mark Salyzyn507eb9f2016-01-11 10:58:09 -0800977 if (!mLastSet[id] || ((*mLast[id])->getLogId() != id)) {
978 mLast[id] = it;
979 mLastSet[id] = true;
980 }
981
Mark Salyzynbec3c3d2015-08-28 08:02:59 -0700982 if (oldest && (oldest->mStart <= element->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700983 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700984 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
985 // kick a misbehaving log reader client off the island
986 oldest->release_Locked();
Mark Salyzynb75cce02015-11-30 11:35:56 -0800987 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
988 oldest->triggerReader_Locked();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700989 } else {
990 oldest->triggerSkip_Locked(id, pruneRows);
991 }
992 break;
993 }
994
995 it = erase(it);
996 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800997 }
998 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800999
Mark Salyzyn0175b072014-02-26 09:50:16 -08001000 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -07001001
1002 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -08001003}
1004
1005// clear all rows of type "id" from the buffer.
Mark Salyzync5dc9702015-09-16 15:34:00 -07001006bool LogBuffer::clear(log_id_t id, uid_t uid) {
1007 bool busy = true;
1008 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
1009 for (int retry = 4;;) {
1010 if (retry == 1) { // last pass
1011 // Check if it is still busy after the sleep, we say prune
1012 // one entry, not another clear run, so we are looking for
1013 // the quick side effect of the return value to tell us if
1014 // we have a _blocked_ reader.
1015 pthread_mutex_lock(&mLogElementsLock);
1016 busy = prune(id, 1, uid);
1017 pthread_mutex_unlock(&mLogElementsLock);
1018 // It is still busy, blocked reader(s), lets kill them all!
1019 // otherwise, lets be a good citizen and preserve the slow
1020 // readers and let the clear run (below) deal with determining
1021 // if we are still blocked and return an error code to caller.
1022 if (busy) {
1023 LogTimeEntry::lock();
1024 LastLogTimes::iterator times = mTimes.begin();
1025 while (times != mTimes.end()) {
1026 LogTimeEntry *entry = (*times);
1027 // Killer punch
1028 if (entry->owned_Locked() && entry->isWatching(id)) {
1029 entry->release_Locked();
1030 }
1031 times++;
1032 }
1033 LogTimeEntry::unlock();
1034 }
1035 }
1036 pthread_mutex_lock(&mLogElementsLock);
1037 busy = prune(id, ULONG_MAX, uid);
1038 pthread_mutex_unlock(&mLogElementsLock);
1039 if (!busy || !--retry) {
1040 break;
1041 }
1042 sleep (1); // Let reader(s) catch up after notification
1043 }
1044 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -08001045}
1046
1047// get the used space associated with "id".
1048unsigned long LogBuffer::getSizeUsed(log_id_t id) {
1049 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001050 size_t retval = stats.sizes(id);
Mark Salyzyn0175b072014-02-26 09:50:16 -08001051 pthread_mutex_unlock(&mLogElementsLock);
1052 return retval;
1053}
1054
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001055// set the total space allocated to "id"
1056int LogBuffer::setSize(log_id_t id, unsigned long size) {
1057 // Reasonable limits ...
Mark Salyzynf10e2732016-09-27 13:08:23 -07001058 if (!__android_logger_valid_buffer_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001059 return -1;
1060 }
1061 pthread_mutex_lock(&mLogElementsLock);
1062 log_buffer_size(id) = size;
1063 pthread_mutex_unlock(&mLogElementsLock);
1064 return 0;
1065}
1066
1067// get the total space allocated to "id"
1068unsigned long LogBuffer::getSize(log_id_t id) {
1069 pthread_mutex_lock(&mLogElementsLock);
1070 size_t retval = log_buffer_size(id);
1071 pthread_mutex_unlock(&mLogElementsLock);
1072 return retval;
1073}
1074
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001075uint64_t LogBuffer::flushTo(
Mark Salyzyn8fa88962016-01-26 14:32:35 -08001076 SocketClient *reader, const uint64_t start,
1077 bool privileged, bool security,
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001078 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn0175b072014-02-26 09:50:16 -08001079 LogBufferElementCollection::iterator it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001080 uint64_t max = start;
Mark Salyzyn0175b072014-02-26 09:50:16 -08001081 uid_t uid = reader->getUid();
1082
1083 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -06001084
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001085 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -06001086 // client wants to start from the beginning
1087 it = mLogElements.begin();
1088 } else {
1089 // Client wants to start from some specified time. Chances are
1090 // we are better off starting from the end of the time sorted list.
1091 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
1092 --it;
1093 LogBufferElement *element = *it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001094 if (element->getSequence() <= start) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -06001095 it++;
1096 break;
1097 }
1098 }
1099 }
1100
Mark Salyzynb5b87962017-01-23 14:20:31 -08001101 // Help detect if the valid message before is from the same source so
1102 // we can differentiate chatty filter types.
1103 pid_t lastTid[LOG_ID_MAX] = { 0 };
1104
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -06001105 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn0175b072014-02-26 09:50:16 -08001106 LogBufferElement *element = *it;
1107
1108 if (!privileged && (element->getUid() != uid)) {
1109 continue;
1110 }
1111
Mark Salyzyn8fa88962016-01-26 14:32:35 -08001112 if (!security && (element->getLogId() == LOG_ID_SECURITY)) {
1113 continue;
1114 }
1115
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001116 if (element->getSequence() <= start) {
Mark Salyzyn0175b072014-02-26 09:50:16 -08001117 continue;
1118 }
1119
1120 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -08001121 if (filter) {
1122 int ret = (*filter)(element, arg);
1123 if (ret == false) {
1124 continue;
1125 }
1126 if (ret != true) {
1127 break;
1128 }
Mark Salyzyn0175b072014-02-26 09:50:16 -08001129 }
1130
Mark Salyzynb5b87962017-01-23 14:20:31 -08001131 bool sameTid = lastTid[element->getLogId()] == element->getTid();
1132 // Dropped (chatty) immediately following a valid log from the
1133 // same source in the same log buffer indicates we have a
1134 // multiple identical squash. chatty that differs source
1135 // is due to spam filter. chatty to chatty of different
1136 // source is also due to spam filter.
1137 lastTid[element->getLogId()] = (element->getDropped() && !sameTid) ?
1138 0 : element->getTid();
1139
Mark Salyzyn0175b072014-02-26 09:50:16 -08001140 pthread_mutex_unlock(&mLogElementsLock);
1141
1142 // range locking in LastLogTimes looks after us
Mark Salyzynb5b87962017-01-23 14:20:31 -08001143 max = element->flushTo(reader, this, privileged, sameTid);
Mark Salyzyn0175b072014-02-26 09:50:16 -08001144
1145 if (max == element->FLUSH_ERROR) {
1146 return max;
1147 }
1148
1149 pthread_mutex_lock(&mLogElementsLock);
1150 }
1151 pthread_mutex_unlock(&mLogElementsLock);
1152
1153 return max;
1154}
Mark Salyzyn34facab2014-02-06 14:48:50 -08001155
Mark Salyzynee3b8382015-12-17 09:58:43 -08001156std::string LogBuffer::formatStatistics(uid_t uid, pid_t pid,
1157 unsigned int logMask) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001158 pthread_mutex_lock(&mLogElementsLock);
1159
Mark Salyzynee3b8382015-12-17 09:58:43 -08001160 std::string ret = stats.format(uid, pid, logMask);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001161
1162 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn73160ac2015-08-20 10:01:44 -07001163
1164 return ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001165}