blob: 744681378f6e54ea6923a5f5c1734a2ac9a81f4f [file] [log] [blame]
Tom Cherryfb150dd2020-05-13 09:28:37 -07001/*
2 * Copyright (C) 2020 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 "SerializedLogBuffer.h"
18
Tom Cherry0a0115f2020-06-22 08:28:45 -070019#include <sys/prctl.h>
20
Tom Cherryfb150dd2020-05-13 09:28:37 -070021#include <limits>
Tom Cherryfb150dd2020-05-13 09:28:37 -070022
23#include <android-base/logging.h>
24#include <android-base/scopeguard.h>
25
Tom Cherry80228952020-08-05 12:14:45 -070026#include "LogSize.h"
Tom Cherryfb150dd2020-05-13 09:28:37 -070027#include "LogStatistics.h"
28#include "SerializedFlushToState.h"
29
30SerializedLogBuffer::SerializedLogBuffer(LogReaderList* reader_list, LogTags* tags,
31 LogStatistics* stats)
32 : reader_list_(reader_list), tags_(tags), stats_(stats) {
33 Init();
34}
35
Tom Cherryfb150dd2020-05-13 09:28:37 -070036void SerializedLogBuffer::Init() {
37 log_id_for_each(i) {
Tom Cherry80228952020-08-05 12:14:45 -070038 if (!SetSize(i, GetBufferSizeFromProperties(i))) {
39 SetSize(i, kLogBufferMinSize);
Tom Cherryfb150dd2020-05-13 09:28:37 -070040 }
41 }
42
43 // Release any sleeping reader threads to dump their current content.
Tom Cherryc5c9eba2020-10-06 10:22:35 -070044 auto lock = std::lock_guard{logd_lock};
Tom Cherryfb150dd2020-05-13 09:28:37 -070045 for (const auto& reader_thread : reader_list_->reader_threads()) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -070046 reader_thread->TriggerReader();
Tom Cherryfb150dd2020-05-13 09:28:37 -070047 }
48}
49
50bool SerializedLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
51 if (log_id == LOG_ID_SECURITY) {
52 return true;
53 }
54
55 int prio = ANDROID_LOG_INFO;
56 const char* tag = nullptr;
57 size_t tag_len = 0;
58 if (IsBinary(log_id)) {
59 int32_t tag_int = MsgToTag(msg, len);
60 tag = tags_->tagToName(tag_int);
61 if (tag) {
62 tag_len = strlen(tag);
63 }
64 } else {
65 prio = *msg;
66 tag = msg + 1;
67 tag_len = strnlen(tag, len - 1);
68 }
69 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
70}
71
72int SerializedLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
73 const char* msg, uint16_t len) {
74 if (log_id >= LOG_ID_MAX || len == 0) {
75 return -EINVAL;
76 }
77
Tom Cherry8c778e62020-08-12 09:36:15 -070078 if (len > LOGGER_ENTRY_MAX_PAYLOAD) {
79 len = LOGGER_ENTRY_MAX_PAYLOAD;
80 }
81
Tom Cherryfb150dd2020-05-13 09:28:37 -070082 if (!ShouldLog(log_id, msg, len)) {
83 stats_->AddTotal(log_id, len);
84 return -EACCES;
85 }
86
87 auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
88
Tom Cherry9169e712020-11-09 14:39:17 +000089 auto lock = std::lock_guard{logd_lock};
Tom Cherryfb150dd2020-05-13 09:28:37 -070090
Tom Cherry9169e712020-11-09 14:39:17 +000091 if (logs_[log_id].empty()) {
92 logs_[log_id].push_back(SerializedLogChunk(max_size_[log_id] / 4));
Tom Cherryfb150dd2020-05-13 09:28:37 -070093 }
94
Tom Cherry9169e712020-11-09 14:39:17 +000095 auto total_len = sizeof(SerializedLogEntry) + len;
96 if (!logs_[log_id].back().CanLog(total_len)) {
97 logs_[log_id].back().FinishWriting();
98 logs_[log_id].push_back(SerializedLogChunk(max_size_[log_id] / 4));
99 }
100
101 auto entry = logs_[log_id].back().Log(sequence, realtime, uid, pid, tid, msg, len);
102 stats_->Add(entry->ToLogStatisticsElement(log_id));
103
104 MaybePrune(log_id);
105
106 reader_list_->NotifyNewLog(1 << log_id);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700107 return len;
108}
109
110void SerializedLogBuffer::MaybePrune(log_id_t log_id) {
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700111 size_t total_size = GetSizeUsed(log_id);
112 size_t after_size = total_size;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700113 if (total_size > max_size_[log_id]) {
114 Prune(log_id, total_size - max_size_[log_id], 0);
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700115 after_size = GetSizeUsed(log_id);
Tom Cherryb5687442020-09-28 13:04:15 -0700116 LOG(VERBOSE) << "Pruned Logs from log_id: " << log_id << ", previous size: " << total_size
117 << " after size: " << after_size;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700118 }
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700119
120 stats_->set_overhead(log_id, after_size);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700121}
122
Tom Cherry4a89fb72020-07-09 12:12:48 -0700123void SerializedLogBuffer::RemoveChunkFromStats(log_id_t log_id, SerializedLogChunk& chunk) {
124 chunk.IncReaderRefCount();
125 int read_offset = 0;
126 while (read_offset < chunk.write_offset()) {
127 auto* entry = chunk.log_entry(read_offset);
128 stats_->Subtract(entry->ToLogStatisticsElement(log_id));
129 read_offset += entry->total_len();
Tom Cherry0a0115f2020-06-22 08:28:45 -0700130 }
Tom Cherryb8c967e2020-07-16 20:46:14 -0700131 chunk.DecReaderRefCount();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700132}
133
Tom Cherry8c778e62020-08-12 09:36:15 -0700134void SerializedLogBuffer::Prune(log_id_t log_id, size_t bytes_to_free, uid_t uid) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700135 auto& log_buffer = logs_[log_id];
Tom Cherryfb150dd2020-05-13 09:28:37 -0700136 auto it = log_buffer.begin();
137 while (it != log_buffer.end()) {
Tom Cherry8c778e62020-08-12 09:36:15 -0700138 for (const auto& reader_thread : reader_list_->reader_threads()) {
139 if (!reader_thread->IsWatching(log_id)) {
140 continue;
141 }
142
143 if (reader_thread->deadline().time_since_epoch().count() != 0) {
144 // Always wake up wrapped readers when pruning. 'Wrapped' readers are an
145 // optimization that allows the reader to wait until logs starting at a specified
146 // time stamp are about to be pruned. This is error-prone however, since if that
147 // timestamp is about to be pruned, the reader is not likely to read the messages
148 // fast enough to not back-up logd. Instead, we can achieve an nearly-as-efficient
149 // but not error-prune batching effect by waking the reader whenever any chunk is
150 // about to be pruned.
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700151 reader_thread->TriggerReader();
Tom Cherry8c778e62020-08-12 09:36:15 -0700152 }
153
154 // Some readers may be still reading from this log chunk, log a warning that they are
155 // about to lose logs.
156 // TODO: We should forcefully disconnect the reader instead, such that the reader itself
157 // has an indication that they've lost logs.
158 if (reader_thread->start() <= it->highest_sequence_number()) {
159 LOG(WARNING) << "Skipping entries from slow reader, " << reader_thread->name()
160 << ", from LogBuffer::Prune()";
161 }
Tom Cherryfb150dd2020-05-13 09:28:37 -0700162 }
163
Tom Cherry4a89fb72020-07-09 12:12:48 -0700164 // Increment ahead of time since we're going to erase this iterator from the list.
Tom Cherryfb150dd2020-05-13 09:28:37 -0700165 auto it_to_prune = it++;
166
Tom Cherry8c778e62020-08-12 09:36:15 -0700167 // Readers may have a reference to the chunk to track their last read log_position.
Tom Cherryfb150dd2020-05-13 09:28:37 -0700168 // Notify them to delete the reference.
Tom Cherry411e2f82020-11-09 13:35:06 -0800169 it_to_prune->NotifyReadersOfPrune(log_id);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700170
171 if (uid != 0) {
172 // Reorder the log buffer to remove logs from the given UID. If there are no logs left
173 // in the buffer after the removal, delete it.
174 if (it_to_prune->ClearUidLogs(uid, log_id, stats_)) {
175 log_buffer.erase(it_to_prune);
176 }
177 } else {
178 size_t buffer_size = it_to_prune->PruneSize();
Tom Cherry4a89fb72020-07-09 12:12:48 -0700179 RemoveChunkFromStats(log_id, *it_to_prune);
180 log_buffer.erase(it_to_prune);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700181 if (buffer_size >= bytes_to_free) {
Tom Cherry8c778e62020-08-12 09:36:15 -0700182 return;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700183 }
184 bytes_to_free -= buffer_size;
185 }
186 }
Tom Cherryfb150dd2020-05-13 09:28:37 -0700187}
188
189std::unique_ptr<FlushToState> SerializedLogBuffer::CreateFlushToState(uint64_t start,
190 LogMask log_mask) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700191 return std::make_unique<SerializedFlushToState>(start, log_mask, logs_);
Tom Cherry154b63a2020-10-05 11:35:59 -0700192}
193
Tom Cherryfb150dd2020-05-13 09:28:37 -0700194bool SerializedLogBuffer::FlushTo(
195 LogWriter* writer, FlushToState& abstract_state,
196 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
197 log_time realtime)>& filter) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700198 auto& state = reinterpret_cast<SerializedFlushToState&>(abstract_state);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700199
Tom Cherry9169e712020-11-09 14:39:17 +0000200 while (state.HasUnreadLogs()) {
Tom Cherry87a17342020-09-18 15:32:32 -0700201 LogWithId top = state.PopNextUnreadLog();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700202 auto* entry = top.entry;
203 auto log_id = top.log_id;
204
205 if (entry->sequence() < state.start()) {
206 continue;
207 }
208 state.set_start(entry->sequence());
209
210 if (!writer->privileged() && entry->uid() != writer->uid()) {
211 continue;
212 }
213
214 if (filter) {
215 auto ret = filter(log_id, entry->pid(), entry->sequence(), entry->realtime());
216 if (ret == FilterResult::kSkip) {
217 continue;
218 }
219 if (ret == FilterResult::kStop) {
220 break;
221 }
222 }
223
Tom Cherry8c778e62020-08-12 09:36:15 -0700224 // We copy the log entry such that we can flush it without the lock. We never block pruning
225 // waiting for this Flush() to complete.
226 constexpr size_t kMaxEntrySize = sizeof(*entry) + LOGGER_ENTRY_MAX_PAYLOAD + 1;
227 unsigned char entry_copy[kMaxEntrySize] __attribute__((uninitialized));
228 CHECK_LT(entry->msg_len(), LOGGER_ENTRY_MAX_PAYLOAD + 1);
229 memcpy(entry_copy, entry, sizeof(*entry) + entry->msg_len());
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700230 logd_lock.unlock();
Tom Cherry8c778e62020-08-12 09:36:15 -0700231
232 if (!reinterpret_cast<SerializedLogEntry*>(entry_copy)->Flush(writer, log_id)) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700233 logd_lock.lock();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700234 return false;
235 }
Tom Cherry8c778e62020-08-12 09:36:15 -0700236
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700237 logd_lock.lock();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700238 }
239
240 state.set_start(state.start() + 1);
241 return true;
242}
243
244bool SerializedLogBuffer::Clear(log_id_t id, uid_t uid) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700245 auto lock = std::lock_guard{logd_lock};
Tom Cherry8c778e62020-08-12 09:36:15 -0700246 Prune(id, ULONG_MAX, uid);
247
248 // Clearing SerializedLogBuffer never waits for readers and therefore is always successful.
249 return true;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700250}
251
Tom Cherry80228952020-08-05 12:14:45 -0700252size_t SerializedLogBuffer::GetSizeUsed(log_id_t id) {
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700253 size_t total_size = 0;
254 for (const auto& chunk : logs_[id]) {
255 total_size += chunk.PruneSize();
256 }
257 return total_size;
258}
259
Tom Cherry80228952020-08-05 12:14:45 -0700260size_t SerializedLogBuffer::GetSize(log_id_t id) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700261 auto lock = std::lock_guard{logd_lock};
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700262 return max_size_[id];
Tom Cherryfb150dd2020-05-13 09:28:37 -0700263}
264
265// New SerializedLogChunk objects will be allocated according to the new size, but older one are
266// unchanged. MaybePrune() is called on the log buffer to reduce it to an appropriate size if the
267// new size is lower.
Tom Cherry80228952020-08-05 12:14:45 -0700268bool SerializedLogBuffer::SetSize(log_id_t id, size_t size) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700269 // Reasonable limits ...
Tom Cherry80228952020-08-05 12:14:45 -0700270 if (!IsValidBufferSize(size)) {
271 return false;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700272 }
273
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700274 auto lock = std::lock_guard{logd_lock};
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700275 max_size_[id] = size;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700276
277 MaybePrune(id);
278
Tom Cherry80228952020-08-05 12:14:45 -0700279 return true;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700280}