1 /*
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 */
16
17 #include <ctype.h>
18 #include <errno.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <sys/user.h>
22 #include <time.h>
23 #include <unistd.h>
24
25 #include <unordered_map>
26
27 #include <cutils/properties.h>
28 #include <log/logger.h>
29
30 #include "LogBuffer.h"
31 #include "LogReader.h"
32
33 // Default
34 #define LOG_BUFFER_SIZE (256 * 1024) // Tuned on a per-platform basis here?
35 #define log_buffer_size(id) mMaxSize[id]
36 #define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
37 #define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
38
valid_size(unsigned long value)39 static bool valid_size(unsigned long value) {
40 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
41 return false;
42 }
43
44 long pages = sysconf(_SC_PHYS_PAGES);
45 if (pages < 1) {
46 return true;
47 }
48
49 long pagesize = sysconf(_SC_PAGESIZE);
50 if (pagesize <= 1) {
51 pagesize = PAGE_SIZE;
52 }
53
54 // maximum memory impact a somewhat arbitrary ~3%
55 pages = (pages + 31) / 32;
56 unsigned long maximum = pages * pagesize;
57
58 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
59 return true;
60 }
61
62 return value <= maximum;
63 }
64
property_get_size(const char * key)65 static unsigned long property_get_size(const char *key) {
66 char property[PROPERTY_VALUE_MAX];
67 property_get(key, property, "");
68
69 char *cp;
70 unsigned long value = strtoul(property, &cp, 10);
71
72 switch(*cp) {
73 case 'm':
74 case 'M':
75 value *= 1024;
76 /* FALLTHRU */
77 case 'k':
78 case 'K':
79 value *= 1024;
80 /* FALLTHRU */
81 case '\0':
82 break;
83
84 default:
85 value = 0;
86 }
87
88 if (!valid_size(value)) {
89 value = 0;
90 }
91
92 return value;
93 }
94
init()95 void LogBuffer::init() {
96 static const char global_tuneable[] = "persist.logd.size"; // Settings App
97 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk
98
99 unsigned long default_size = property_get_size(global_tuneable);
100 if (!default_size) {
101 default_size = property_get_size(global_default);
102 }
103
104 log_id_for_each(i) {
105 char key[PROP_NAME_MAX];
106
107 snprintf(key, sizeof(key), "%s.%s",
108 global_tuneable, android_log_id_to_name(i));
109 unsigned long property_size = property_get_size(key);
110
111 if (!property_size) {
112 snprintf(key, sizeof(key), "%s.%s",
113 global_default, android_log_id_to_name(i));
114 property_size = property_get_size(key);
115 }
116
117 if (!property_size) {
118 property_size = default_size;
119 }
120
121 if (!property_size) {
122 property_size = LOG_BUFFER_SIZE;
123 }
124
125 if (setSize(i, property_size)) {
126 setSize(i, LOG_BUFFER_MIN_SIZE);
127 }
128 }
129 }
130
LogBuffer(LastLogTimes * times)131 LogBuffer::LogBuffer(LastLogTimes *times) : mTimes(*times) {
132 pthread_mutex_init(&mLogElementsLock, NULL);
133
134 init();
135 }
136
log(log_id_t log_id,log_time realtime,uid_t uid,pid_t pid,pid_t tid,const char * msg,unsigned short len)137 int LogBuffer::log(log_id_t log_id, log_time realtime,
138 uid_t uid, pid_t pid, pid_t tid,
139 const char *msg, unsigned short len) {
140 if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
141 return -EINVAL;
142 }
143
144 LogBufferElement *elem = new LogBufferElement(log_id, realtime,
145 uid, pid, tid, msg, len);
146 int prio = ANDROID_LOG_INFO;
147 const char *tag = NULL;
148 if (log_id == LOG_ID_EVENTS) {
149 tag = android::tagToName(elem->getTag());
150 } else {
151 prio = *msg;
152 tag = msg + 1;
153 }
154 if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
155 // Log traffic received to total
156 pthread_mutex_lock(&mLogElementsLock);
157 stats.add(elem);
158 stats.subtract(elem);
159 pthread_mutex_unlock(&mLogElementsLock);
160 delete elem;
161 return -EACCES;
162 }
163
164 pthread_mutex_lock(&mLogElementsLock);
165
166 // Insert elements in time sorted order if possible
167 // NB: if end is region locked, place element at end of list
168 LogBufferElementCollection::iterator it = mLogElements.end();
169 LogBufferElementCollection::iterator last = it;
170 while (last != mLogElements.begin()) {
171 --it;
172 if ((*it)->getRealTime() <= realtime) {
173 break;
174 }
175 last = it;
176 }
177
178 if (last == mLogElements.end()) {
179 mLogElements.push_back(elem);
180 } else {
181 uint64_t end = 1;
182 bool end_set = false;
183 bool end_always = false;
184
185 LogTimeEntry::lock();
186
187 LastLogTimes::iterator t = mTimes.begin();
188 while(t != mTimes.end()) {
189 LogTimeEntry *entry = (*t);
190 if (entry->owned_Locked()) {
191 if (!entry->mNonBlock) {
192 end_always = true;
193 break;
194 }
195 if (!end_set || (end <= entry->mEnd)) {
196 end = entry->mEnd;
197 end_set = true;
198 }
199 }
200 t++;
201 }
202
203 if (end_always
204 || (end_set && (end >= (*last)->getSequence()))) {
205 mLogElements.push_back(elem);
206 } else {
207 mLogElements.insert(last,elem);
208 }
209
210 LogTimeEntry::unlock();
211 }
212
213 stats.add(elem);
214 maybePrune(log_id);
215 pthread_mutex_unlock(&mLogElementsLock);
216
217 return len;
218 }
219
220 // Prune at most 10% of the log entries or 256, whichever is less.
221 //
222 // mLogElementsLock must be held when this function is called.
maybePrune(log_id_t id)223 void LogBuffer::maybePrune(log_id_t id) {
224 size_t sizes = stats.sizes(id);
225 unsigned long maxSize = log_buffer_size(id);
226 if (sizes > maxSize) {
227 size_t sizeOver = sizes - ((maxSize * 9) / 10);
228 size_t elements = stats.elements(id);
229 size_t minElements = elements / 10;
230 unsigned long pruneRows = elements * sizeOver / sizes;
231 if (pruneRows <= minElements) {
232 pruneRows = minElements;
233 }
234 if (pruneRows > 256) {
235 pruneRows = 256;
236 }
237 prune(id, pruneRows);
238 }
239 }
240
erase(LogBufferElementCollection::iterator it,bool engageStats)241 LogBufferElementCollection::iterator LogBuffer::erase(
242 LogBufferElementCollection::iterator it, bool engageStats) {
243 LogBufferElement *e = *it;
244 log_id_t id = e->getLogId();
245
246 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(e->getUid());
247 if ((f != mLastWorstUid[id].end()) && (it == f->second)) {
248 mLastWorstUid[id].erase(f);
249 }
250 it = mLogElements.erase(it);
251 if (engageStats) {
252 stats.subtract(e);
253 } else {
254 stats.erase(e);
255 }
256 delete e;
257
258 return it;
259 }
260
261 // Define a temporary mechanism to report the last LogBufferElement pointer
262 // for the specified uid, pid and tid. Used below to help merge-sort when
263 // pruning for worst UID.
264 class LogBufferElementKey {
265 const union {
266 struct {
267 uint16_t uid;
268 uint16_t pid;
269 uint16_t tid;
270 uint16_t padding;
271 } __packed;
272 uint64_t value;
273 } __packed;
274
275 public:
LogBufferElementKey(uid_t u,pid_t p,pid_t t)276 LogBufferElementKey(uid_t u, pid_t p, pid_t t):uid(u),pid(p),tid(t),padding(0) { }
LogBufferElementKey(uint64_t k)277 LogBufferElementKey(uint64_t k):value(k) { }
278
getKey()279 uint64_t getKey() { return value; }
280 };
281
282 class LogBufferElementLast {
283
284 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
285 LogBufferElementMap map;
286
287 public:
288
merge(LogBufferElement * e,unsigned short dropped)289 bool merge(LogBufferElement *e, unsigned short dropped) {
290 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
291 LogBufferElementMap::iterator it = map.find(key.getKey());
292 if (it != map.end()) {
293 LogBufferElement *l = it->second;
294 unsigned short d = l->getDropped();
295 if ((dropped + d) > USHRT_MAX) {
296 map.erase(it);
297 } else {
298 l->setDropped(dropped + d);
299 return true;
300 }
301 }
302 return false;
303 }
304
add(LogBufferElement * e)305 void add(LogBufferElement *e) {
306 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
307 map[key.getKey()] = e;
308 }
309
clear()310 inline void clear() {
311 map.clear();
312 }
313
clear(LogBufferElement * e)314 void clear(LogBufferElement *e) {
315 uint64_t current = e->getRealTime().nsec()
316 - (EXPIRE_RATELIMIT * NS_PER_SEC);
317 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
318 LogBufferElement *l = it->second;
319 if ((l->getDropped() >= EXPIRE_THRESHOLD)
320 && (current > l->getRealTime().nsec())) {
321 it = map.erase(it);
322 } else {
323 ++it;
324 }
325 }
326 }
327
328 };
329
330 // prune "pruneRows" of type "id" from the buffer.
331 //
332 // This garbage collection task is used to expire log entries. It is called to
333 // remove all logs (clear), all UID logs (unprivileged clear), or every
334 // 256 or 10% of the total logs (whichever is less) to prune the logs.
335 //
336 // First there is a prep phase where we discover the reader region lock that
337 // acts as a backstop to any pruning activity to stop there and go no further.
338 //
339 // There are three major pruning loops that follow. All expire from the oldest
340 // entries. Since there are multiple log buffers, the Android logging facility
341 // will appear to drop entries 'in the middle' when looking at multiple log
342 // sources and buffers. This effect is slightly more prominent when we prune
343 // the worst offender by logging source. Thus the logs slowly loose content
344 // and value as you move back in time. This is preferred since chatty sources
345 // invariably move the logs value down faster as less chatty sources would be
346 // expired in the noise.
347 //
348 // The first loop performs blacklisting and worst offender pruning. Falling
349 // through when there are no notable worst offenders and have not hit the
350 // region lock preventing further worst offender pruning. This loop also looks
351 // after managing the chatty log entries and merging to help provide
352 // statistical basis for blame. The chatty entries are not a notification of
353 // how much logs you may have, but instead represent how much logs you would
354 // have had in a virtual log buffer that is extended to cover all the in-memory
355 // logs without loss. They last much longer than the represented pruned logs
356 // since they get multiplied by the gains in the non-chatty log sources.
357 //
358 // The second loop get complicated because an algorithm of watermarks and
359 // history is maintained to reduce the order and keep processing time
360 // down to a minimum at scale. These algorithms can be costly in the face
361 // of larger log buffers, or severly limited processing time granted to a
362 // background task at lowest priority.
363 //
364 // This second loop does straight-up expiration from the end of the logs
365 // (again, remember for the specified log buffer id) but does some whitelist
366 // preservation. Thus whitelist is a Hail Mary low priority, blacklists and
367 // spam filtration all take priority. This second loop also checks if a region
368 // lock is causing us to buffer too much in the logs to help the reader(s),
369 // and will tell the slowest reader thread to skip log entries, and if
370 // persistent and hits a further threshold, kill the reader thread.
371 //
372 // The third thread is optional, and only gets hit if there was a whitelist
373 // and more needs to be pruned against the backstop of the region lock.
374 //
375 // mLogElementsLock must be held when this function is called.
376 //
prune(log_id_t id,unsigned long pruneRows,uid_t caller_uid)377 void LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
378 LogTimeEntry *oldest = NULL;
379
380 LogTimeEntry::lock();
381
382 // Region locked?
383 LastLogTimes::iterator t = mTimes.begin();
384 while(t != mTimes.end()) {
385 LogTimeEntry *entry = (*t);
386 if (entry->owned_Locked() && entry->isWatching(id)
387 && (!oldest || (oldest->mStart > entry->mStart))) {
388 oldest = entry;
389 }
390 t++;
391 }
392
393 LogBufferElementCollection::iterator it;
394
395 if (caller_uid != AID_ROOT) {
396 for(it = mLogElements.begin(); it != mLogElements.end();) {
397 LogBufferElement *e = *it;
398
399 if (oldest && (oldest->mStart <= e->getSequence())) {
400 break;
401 }
402
403 if (e->getLogId() != id) {
404 ++it;
405 continue;
406 }
407
408 if (e->getUid() == caller_uid) {
409 it = erase(it);
410 pruneRows--;
411 if (pruneRows == 0) {
412 break;
413 }
414 } else {
415 ++it;
416 }
417 }
418 LogTimeEntry::unlock();
419 return;
420 }
421
422 // prune by worst offender by uid
423 bool hasBlacklist = mPrune.naughty();
424 while (pruneRows > 0) {
425 // recalculate the worst offender on every batched pass
426 uid_t worst = (uid_t) -1;
427 size_t worst_sizes = 0;
428 size_t second_worst_sizes = 0;
429
430 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
431 std::unique_ptr<const UidEntry *[]> sorted = stats.sort(2, id);
432
433 if (sorted.get()) {
434 if (sorted[0] && sorted[1]) {
435 worst_sizes = sorted[0]->getSizes();
436 // Calculate threshold as 12.5% of available storage
437 size_t threshold = log_buffer_size(id) / 8;
438 if ((worst_sizes > threshold)
439 // Allow time horizon to extend roughly tenfold, assume
440 // average entry length is 100 characters.
441 && (worst_sizes > (10 * sorted[0]->getDropped()))) {
442 worst = sorted[0]->getKey();
443 second_worst_sizes = sorted[1]->getSizes();
444 if (second_worst_sizes < threshold) {
445 second_worst_sizes = threshold;
446 }
447 }
448 }
449 }
450 }
451
452 // skip if we have neither worst nor naughty filters
453 if ((worst == (uid_t) -1) && !hasBlacklist) {
454 break;
455 }
456
457 bool kick = false;
458 bool leading = true;
459 it = mLogElements.begin();
460 // Perform at least one mandatory garbage collection cycle in following
461 // - clear leading chatty tags
462 // - merge chatty tags
463 // - check age-out of preserved logs
464 bool gc = pruneRows <= 1;
465 if (!gc && (worst != (uid_t) -1)) {
466 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
467 if ((f != mLastWorstUid[id].end())
468 && (f->second != mLogElements.end())) {
469 leading = false;
470 it = f->second;
471 }
472 }
473 static const timespec too_old = {
474 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
475 };
476 LogBufferElementCollection::iterator lastt;
477 lastt = mLogElements.end();
478 --lastt;
479 LogBufferElementLast last;
480 while (it != mLogElements.end()) {
481 LogBufferElement *e = *it;
482
483 if (oldest && (oldest->mStart <= e->getSequence())) {
484 break;
485 }
486
487 if (e->getLogId() != id) {
488 ++it;
489 continue;
490 }
491
492 unsigned short dropped = e->getDropped();
493
494 // remove any leading drops
495 if (leading && dropped) {
496 it = erase(it);
497 continue;
498 }
499
500 // merge any drops
501 if (dropped && last.merge(e, dropped)) {
502 it = erase(it, false);
503 continue;
504 }
505
506 if (hasBlacklist && mPrune.naughty(e)) {
507 last.clear(e);
508 it = erase(it);
509 if (dropped) {
510 continue;
511 }
512
513 pruneRows--;
514 if (pruneRows == 0) {
515 break;
516 }
517
518 if (e->getUid() == worst) {
519 kick = true;
520 if (worst_sizes < second_worst_sizes) {
521 break;
522 }
523 worst_sizes -= e->getMsgLen();
524 }
525 continue;
526 }
527
528 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
529 || (e->getRealTime() > (*lastt)->getRealTime())) {
530 break;
531 }
532
533 // unmerged drop message
534 if (dropped) {
535 last.add(e);
536 if ((!gc && (e->getUid() == worst))
537 || (mLastWorstUid[id].find(e->getUid())
538 == mLastWorstUid[id].end())) {
539 mLastWorstUid[id][e->getUid()] = it;
540 }
541 ++it;
542 continue;
543 }
544
545 if (e->getUid() != worst) {
546 leading = false;
547 last.clear(e);
548 ++it;
549 continue;
550 }
551
552 pruneRows--;
553 if (pruneRows == 0) {
554 break;
555 }
556
557 kick = true;
558
559 unsigned short len = e->getMsgLen();
560
561 // do not create any leading drops
562 if (leading) {
563 it = erase(it);
564 } else {
565 stats.drop(e);
566 e->setDropped(1);
567 if (last.merge(e, 1)) {
568 it = erase(it, false);
569 } else {
570 last.add(e);
571 if (!gc || (mLastWorstUid[id].find(worst)
572 == mLastWorstUid[id].end())) {
573 mLastWorstUid[id][worst] = it;
574 }
575 ++it;
576 }
577 }
578 if (worst_sizes < second_worst_sizes) {
579 break;
580 }
581 worst_sizes -= len;
582 }
583 last.clear();
584
585 if (!kick || !mPrune.worstUidEnabled()) {
586 break; // the following loop will ask bad clients to skip/drop
587 }
588 }
589
590 bool whitelist = false;
591 bool hasWhitelist = mPrune.nice();
592 it = mLogElements.begin();
593 while((pruneRows > 0) && (it != mLogElements.end())) {
594 LogBufferElement *e = *it;
595
596 if (e->getLogId() != id) {
597 it++;
598 continue;
599 }
600
601 if (oldest && (oldest->mStart <= e->getSequence())) {
602 if (whitelist) {
603 break;
604 }
605
606 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
607 // kick a misbehaving log reader client off the island
608 oldest->release_Locked();
609 } else {
610 oldest->triggerSkip_Locked(id, pruneRows);
611 }
612 break;
613 }
614
615 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
616 whitelist = true;
617 it++;
618 continue;
619 }
620
621 it = erase(it);
622 pruneRows--;
623 }
624
625 // Do not save the whitelist if we are reader range limited
626 if (whitelist && (pruneRows > 0)) {
627 it = mLogElements.begin();
628 while((it != mLogElements.end()) && (pruneRows > 0)) {
629 LogBufferElement *e = *it;
630
631 if (e->getLogId() != id) {
632 ++it;
633 continue;
634 }
635
636 if (oldest && (oldest->mStart <= e->getSequence())) {
637 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
638 // kick a misbehaving log reader client off the island
639 oldest->release_Locked();
640 } else {
641 oldest->triggerSkip_Locked(id, pruneRows);
642 }
643 break;
644 }
645
646 it = erase(it);
647 pruneRows--;
648 }
649 }
650
651 LogTimeEntry::unlock();
652 }
653
654 // clear all rows of type "id" from the buffer.
clear(log_id_t id,uid_t uid)655 void LogBuffer::clear(log_id_t id, uid_t uid) {
656 pthread_mutex_lock(&mLogElementsLock);
657 prune(id, ULONG_MAX, uid);
658 pthread_mutex_unlock(&mLogElementsLock);
659 }
660
661 // get the used space associated with "id".
getSizeUsed(log_id_t id)662 unsigned long LogBuffer::getSizeUsed(log_id_t id) {
663 pthread_mutex_lock(&mLogElementsLock);
664 size_t retval = stats.sizes(id);
665 pthread_mutex_unlock(&mLogElementsLock);
666 return retval;
667 }
668
669 // set the total space allocated to "id"
setSize(log_id_t id,unsigned long size)670 int LogBuffer::setSize(log_id_t id, unsigned long size) {
671 // Reasonable limits ...
672 if (!valid_size(size)) {
673 return -1;
674 }
675 pthread_mutex_lock(&mLogElementsLock);
676 log_buffer_size(id) = size;
677 pthread_mutex_unlock(&mLogElementsLock);
678 return 0;
679 }
680
681 // get the total space allocated to "id"
getSize(log_id_t id)682 unsigned long LogBuffer::getSize(log_id_t id) {
683 pthread_mutex_lock(&mLogElementsLock);
684 size_t retval = log_buffer_size(id);
685 pthread_mutex_unlock(&mLogElementsLock);
686 return retval;
687 }
688
flushTo(SocketClient * reader,const uint64_t start,bool privileged,int (* filter)(const LogBufferElement * element,void * arg),void * arg)689 uint64_t LogBuffer::flushTo(
690 SocketClient *reader, const uint64_t start, bool privileged,
691 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
692 LogBufferElementCollection::iterator it;
693 uint64_t max = start;
694 uid_t uid = reader->getUid();
695
696 pthread_mutex_lock(&mLogElementsLock);
697
698 if (start <= 1) {
699 // client wants to start from the beginning
700 it = mLogElements.begin();
701 } else {
702 // Client wants to start from some specified time. Chances are
703 // we are better off starting from the end of the time sorted list.
704 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
705 --it;
706 LogBufferElement *element = *it;
707 if (element->getSequence() <= start) {
708 it++;
709 break;
710 }
711 }
712 }
713
714 for (; it != mLogElements.end(); ++it) {
715 LogBufferElement *element = *it;
716
717 if (!privileged && (element->getUid() != uid)) {
718 continue;
719 }
720
721 if (element->getSequence() <= start) {
722 continue;
723 }
724
725 // NB: calling out to another object with mLogElementsLock held (safe)
726 if (filter) {
727 int ret = (*filter)(element, arg);
728 if (ret == false) {
729 continue;
730 }
731 if (ret != true) {
732 break;
733 }
734 }
735
736 pthread_mutex_unlock(&mLogElementsLock);
737
738 // range locking in LastLogTimes looks after us
739 max = element->flushTo(reader, this);
740
741 if (max == element->FLUSH_ERROR) {
742 return max;
743 }
744
745 pthread_mutex_lock(&mLogElementsLock);
746 }
747 pthread_mutex_unlock(&mLogElementsLock);
748
749 return max;
750 }
751
formatStatistics(char ** strp,uid_t uid,unsigned int logMask)752 void LogBuffer::formatStatistics(char **strp, uid_t uid, unsigned int logMask) {
753 pthread_mutex_lock(&mLogElementsLock);
754
755 stats.format(strp, uid, logMask);
756
757 pthread_mutex_unlock(&mLogElementsLock);
758 }
759