blob: acd093b2551af924fd33c4f76fc1f92fd203bd8a [file] [log] [blame]
Tom Cherry1a796bc2020-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 Cherry1fdbdbe2020-06-22 08:28:45 -070019#include <sys/prctl.h>
20
Tom Cherry1a796bc2020-05-13 09:28:37 -070021#include <limits>
Tom Cherry1a796bc2020-05-13 09:28:37 -070022
23#include <android-base/logging.h>
24#include <android-base/scopeguard.h>
25
Tom Cherry39dc2212020-08-05 12:14:45 -070026#include "LogSize.h"
Tom Cherry1a796bc2020-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 Cherry1a796bc2020-05-13 09:28:37 -070036void SerializedLogBuffer::Init() {
37 log_id_for_each(i) {
Tom Cherry39dc2212020-08-05 12:14:45 -070038 if (!SetSize(i, GetBufferSizeFromProperties(i))) {
39 SetSize(i, kLogBufferMinSize);
Tom Cherry1a796bc2020-05-13 09:28:37 -070040 }
41 }
42
43 // Release any sleeping reader threads to dump their current content.
44 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
45 for (const auto& reader_thread : reader_list_->reader_threads()) {
46 reader_thread->triggerReader_Locked();
47 }
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 Cherry3932a9c2020-08-12 09:36:15 -070078 if (len > LOGGER_ENTRY_MAX_PAYLOAD) {
79 len = LOGGER_ENTRY_MAX_PAYLOAD;
80 }
81
Tom Cherry1a796bc2020-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
89 auto lock = std::lock_guard{lock_};
90
91 if (logs_[log_id].empty()) {
92 logs_[log_id].push_back(SerializedLogChunk(max_size_[log_id] / 4));
93 }
94
95 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);
107 return len;
108}
109
110void SerializedLogBuffer::MaybePrune(log_id_t log_id) {
Tom Cherryf74503d2020-06-19 12:21:21 -0700111 size_t total_size = GetSizeUsed(log_id);
112 size_t after_size = total_size;
Tom Cherry1a796bc2020-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 Cherryf74503d2020-06-19 12:21:21 -0700115 after_size = GetSizeUsed(log_id);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700116 LOG(INFO) << "Pruned Logs from log_id: " << log_id << ", previous size: " << total_size
Tom Cherryf74503d2020-06-19 12:21:21 -0700117 << " after size: " << after_size;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700118 }
Tom Cherryf74503d2020-06-19 12:21:21 -0700119
120 stats_->set_overhead(log_id, after_size);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700121}
122
Tom Cherry4f8125a2020-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 Cherry1fdbdbe2020-06-22 08:28:45 -0700130 }
Tom Cherry59caa7a2020-07-16 20:46:14 -0700131 chunk.DecReaderRefCount();
Tom Cherry1a796bc2020-05-13 09:28:37 -0700132}
133
134void SerializedLogBuffer::NotifyReadersOfPrune(
135 log_id_t log_id, const std::list<SerializedLogChunk>::iterator& chunk) {
136 for (const auto& reader_thread : reader_list_->reader_threads()) {
137 auto& state = reinterpret_cast<SerializedFlushToState&>(reader_thread->flush_to_state());
138 state.Prune(log_id, chunk);
139 }
140}
141
Tom Cherry3932a9c2020-08-12 09:36:15 -0700142void SerializedLogBuffer::Prune(log_id_t log_id, size_t bytes_to_free, uid_t uid) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700143 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
Tom Cherry1a796bc2020-05-13 09:28:37 -0700144
145 auto& log_buffer = logs_[log_id];
Tom Cherry1a796bc2020-05-13 09:28:37 -0700146 auto it = log_buffer.begin();
147 while (it != log_buffer.end()) {
Tom Cherry3932a9c2020-08-12 09:36:15 -0700148 for (const auto& reader_thread : reader_list_->reader_threads()) {
149 if (!reader_thread->IsWatching(log_id)) {
150 continue;
151 }
152
153 if (reader_thread->deadline().time_since_epoch().count() != 0) {
154 // Always wake up wrapped readers when pruning. 'Wrapped' readers are an
155 // optimization that allows the reader to wait until logs starting at a specified
156 // time stamp are about to be pruned. This is error-prone however, since if that
157 // timestamp is about to be pruned, the reader is not likely to read the messages
158 // fast enough to not back-up logd. Instead, we can achieve an nearly-as-efficient
159 // but not error-prune batching effect by waking the reader whenever any chunk is
160 // about to be pruned.
161 reader_thread->triggerReader_Locked();
162 }
163
164 // Some readers may be still reading from this log chunk, log a warning that they are
165 // about to lose logs.
166 // TODO: We should forcefully disconnect the reader instead, such that the reader itself
167 // has an indication that they've lost logs.
168 if (reader_thread->start() <= it->highest_sequence_number()) {
169 LOG(WARNING) << "Skipping entries from slow reader, " << reader_thread->name()
170 << ", from LogBuffer::Prune()";
171 }
Tom Cherry1a796bc2020-05-13 09:28:37 -0700172 }
173
Tom Cherry4f8125a2020-07-09 12:12:48 -0700174 // Increment ahead of time since we're going to erase this iterator from the list.
Tom Cherry1a796bc2020-05-13 09:28:37 -0700175 auto it_to_prune = it++;
176
Tom Cherry3932a9c2020-08-12 09:36:15 -0700177 // Readers may have a reference to the chunk to track their last read log_position.
Tom Cherry1a796bc2020-05-13 09:28:37 -0700178 // Notify them to delete the reference.
179 NotifyReadersOfPrune(log_id, it_to_prune);
180
181 if (uid != 0) {
182 // Reorder the log buffer to remove logs from the given UID. If there are no logs left
183 // in the buffer after the removal, delete it.
184 if (it_to_prune->ClearUidLogs(uid, log_id, stats_)) {
185 log_buffer.erase(it_to_prune);
186 }
187 } else {
188 size_t buffer_size = it_to_prune->PruneSize();
Tom Cherry4f8125a2020-07-09 12:12:48 -0700189 RemoveChunkFromStats(log_id, *it_to_prune);
190 log_buffer.erase(it_to_prune);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700191 if (buffer_size >= bytes_to_free) {
Tom Cherry3932a9c2020-08-12 09:36:15 -0700192 return;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700193 }
194 bytes_to_free -= buffer_size;
195 }
196 }
Tom Cherry1a796bc2020-05-13 09:28:37 -0700197}
198
199std::unique_ptr<FlushToState> SerializedLogBuffer::CreateFlushToState(uint64_t start,
200 LogMask log_mask) {
201 return std::make_unique<SerializedFlushToState>(start, log_mask);
202}
203
204bool SerializedLogBuffer::FlushTo(
205 LogWriter* writer, FlushToState& abstract_state,
206 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
207 log_time realtime)>& filter) {
208 auto lock = std::unique_lock{lock_};
209
210 auto& state = reinterpret_cast<SerializedFlushToState&>(abstract_state);
211 state.InitializeLogs(logs_);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700212
213 while (state.HasUnreadLogs()) {
Tom Cherry6533fff2020-09-18 15:32:32 -0700214 LogWithId top = state.PopNextUnreadLog();
Tom Cherry1a796bc2020-05-13 09:28:37 -0700215 auto* entry = top.entry;
216 auto log_id = top.log_id;
217
218 if (entry->sequence() < state.start()) {
219 continue;
220 }
221 state.set_start(entry->sequence());
222
223 if (!writer->privileged() && entry->uid() != writer->uid()) {
224 continue;
225 }
226
227 if (filter) {
228 auto ret = filter(log_id, entry->pid(), entry->sequence(), entry->realtime());
229 if (ret == FilterResult::kSkip) {
230 continue;
231 }
232 if (ret == FilterResult::kStop) {
233 break;
234 }
235 }
236
Tom Cherry3932a9c2020-08-12 09:36:15 -0700237 // We copy the log entry such that we can flush it without the lock. We never block pruning
238 // waiting for this Flush() to complete.
239 constexpr size_t kMaxEntrySize = sizeof(*entry) + LOGGER_ENTRY_MAX_PAYLOAD + 1;
240 unsigned char entry_copy[kMaxEntrySize] __attribute__((uninitialized));
241 CHECK_LT(entry->msg_len(), LOGGER_ENTRY_MAX_PAYLOAD + 1);
242 memcpy(entry_copy, entry, sizeof(*entry) + entry->msg_len());
Tom Cherry1a796bc2020-05-13 09:28:37 -0700243 lock.unlock();
Tom Cherry3932a9c2020-08-12 09:36:15 -0700244
245 if (!reinterpret_cast<SerializedLogEntry*>(entry_copy)->Flush(writer, log_id)) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700246 return false;
247 }
Tom Cherry3932a9c2020-08-12 09:36:15 -0700248
Tom Cherry1a796bc2020-05-13 09:28:37 -0700249 lock.lock();
Tom Cherry1a796bc2020-05-13 09:28:37 -0700250 }
251
252 state.set_start(state.start() + 1);
253 return true;
254}
255
256bool SerializedLogBuffer::Clear(log_id_t id, uid_t uid) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700257 auto lock = std::lock_guard{lock_};
Tom Cherry3932a9c2020-08-12 09:36:15 -0700258 Prune(id, ULONG_MAX, uid);
259
260 // Clearing SerializedLogBuffer never waits for readers and therefore is always successful.
261 return true;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700262}
263
Tom Cherry39dc2212020-08-05 12:14:45 -0700264size_t SerializedLogBuffer::GetSizeUsed(log_id_t id) {
Tom Cherryf74503d2020-06-19 12:21:21 -0700265 size_t total_size = 0;
266 for (const auto& chunk : logs_[id]) {
267 total_size += chunk.PruneSize();
268 }
269 return total_size;
270}
271
Tom Cherry39dc2212020-08-05 12:14:45 -0700272size_t SerializedLogBuffer::GetSize(log_id_t id) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700273 auto lock = std::lock_guard{lock_};
Tom Cherryf74503d2020-06-19 12:21:21 -0700274 return max_size_[id];
Tom Cherry1a796bc2020-05-13 09:28:37 -0700275}
276
277// New SerializedLogChunk objects will be allocated according to the new size, but older one are
278// unchanged. MaybePrune() is called on the log buffer to reduce it to an appropriate size if the
279// new size is lower.
Tom Cherry39dc2212020-08-05 12:14:45 -0700280bool SerializedLogBuffer::SetSize(log_id_t id, size_t size) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700281 // Reasonable limits ...
Tom Cherry39dc2212020-08-05 12:14:45 -0700282 if (!IsValidBufferSize(size)) {
283 return false;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700284 }
285
286 auto lock = std::lock_guard{lock_};
Tom Cherryf74503d2020-06-19 12:21:21 -0700287 max_size_[id] = size;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700288
289 MaybePrune(id);
290
Tom Cherry39dc2212020-08-05 12:14:45 -0700291 return true;
Tom Cherry1a796bc2020-05-13 09:28:37 -0700292}