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