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 #pragma once
18 
19 #include <sys/types.h>
20 
21 #include <list>
22 #include <optional>
23 #include <string>
24 
25 #include <android-base/thread_annotations.h>
26 #include <android/log.h>
27 #include <private/android_filesystem_config.h>
28 
29 #include "LogBuffer.h"
30 #include "LogBufferElement.h"
31 #include "LogReaderList.h"
32 #include "LogReaderThread.h"
33 #include "LogStatistics.h"
34 #include "LogTags.h"
35 #include "LogWriter.h"
36 #include "LogdLock.h"
37 #include "PruneList.h"
38 #include "SimpleLogBuffer.h"
39 
40 typedef std::list<LogBufferElement> LogBufferElementCollection;
41 
42 class ChattyLogBuffer : public SimpleLogBuffer {
43     // watermark of any worst/chatty uid processing
44     typedef std::unordered_map<uid_t, LogBufferElementCollection::iterator> LogBufferIteratorMap;
45     LogBufferIteratorMap mLastWorst[LOG_ID_MAX] GUARDED_BY(logd_lock);
46     // watermark of any worst/chatty pid of system processing
47     typedef std::unordered_map<pid_t, LogBufferElementCollection::iterator> LogBufferPidIteratorMap;
48     LogBufferPidIteratorMap mLastWorstPidOfSystem[LOG_ID_MAX] GUARDED_BY(logd_lock);
49 
50   public:
51     ChattyLogBuffer(LogReaderList* reader_list, LogTags* tags, PruneList* prune,
52                     LogStatistics* stats);
53     ~ChattyLogBuffer();
54 
55   protected:
56     bool Prune(log_id_t id, unsigned long pruneRows, uid_t uid) REQUIRES(logd_lock) override;
57     void LogInternal(LogBufferElement&& elem) REQUIRES(logd_lock) override;
58 
59   private:
60     LogBufferElementCollection::iterator Erase(LogBufferElementCollection::iterator it,
61                                                bool coalesce = false) REQUIRES(logd_lock);
62 
63     PruneList* prune_;
64 
65     // This always contains a copy of the last message logged, for deduplication.
66     std::optional<LogBufferElement> last_logged_elements_[LOG_ID_MAX] GUARDED_BY(logd_lock);
67     // This contains an element if duplicate messages are seen.
68     // Its `dropped` count is `duplicates seen - 1`.
69     std::optional<LogBufferElement> duplicate_elements_[LOG_ID_MAX] GUARDED_BY(logd_lock);
70 };
71