blob: aa808642d1c42b1e7ab63e28b6ae0aa658259530 [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
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 Cherry8c778e62020-08-12 09:36:15 -0700142void SerializedLogBuffer::Prune(log_id_t log_id, size_t bytes_to_free, uid_t uid) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700143 auto& log_buffer = logs_[log_id];
Tom Cherryfb150dd2020-05-13 09:28:37 -0700144 auto it = log_buffer.begin();
145 while (it != log_buffer.end()) {
Tom Cherry8c778e62020-08-12 09:36:15 -0700146 for (const auto& reader_thread : reader_list_->reader_threads()) {
147 if (!reader_thread->IsWatching(log_id)) {
148 continue;
149 }
150
151 if (reader_thread->deadline().time_since_epoch().count() != 0) {
152 // Always wake up wrapped readers when pruning. 'Wrapped' readers are an
153 // optimization that allows the reader to wait until logs starting at a specified
154 // time stamp are about to be pruned. This is error-prone however, since if that
155 // timestamp is about to be pruned, the reader is not likely to read the messages
156 // fast enough to not back-up logd. Instead, we can achieve an nearly-as-efficient
157 // but not error-prune batching effect by waking the reader whenever any chunk is
158 // about to be pruned.
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700159 reader_thread->TriggerReader();
Tom Cherry8c778e62020-08-12 09:36:15 -0700160 }
161
162 // Some readers may be still reading from this log chunk, log a warning that they are
163 // about to lose logs.
164 // TODO: We should forcefully disconnect the reader instead, such that the reader itself
165 // has an indication that they've lost logs.
166 if (reader_thread->start() <= it->highest_sequence_number()) {
167 LOG(WARNING) << "Skipping entries from slow reader, " << reader_thread->name()
168 << ", from LogBuffer::Prune()";
169 }
Tom Cherryfb150dd2020-05-13 09:28:37 -0700170 }
171
Tom Cherry4a89fb72020-07-09 12:12:48 -0700172 // Increment ahead of time since we're going to erase this iterator from the list.
Tom Cherryfb150dd2020-05-13 09:28:37 -0700173 auto it_to_prune = it++;
174
Tom Cherry8c778e62020-08-12 09:36:15 -0700175 // Readers may have a reference to the chunk to track their last read log_position.
Tom Cherryfb150dd2020-05-13 09:28:37 -0700176 // Notify them to delete the reference.
177 NotifyReadersOfPrune(log_id, it_to_prune);
178
179 if (uid != 0) {
180 // Reorder the log buffer to remove logs from the given UID. If there are no logs left
181 // in the buffer after the removal, delete it.
182 if (it_to_prune->ClearUidLogs(uid, log_id, stats_)) {
183 log_buffer.erase(it_to_prune);
184 }
185 } else {
186 size_t buffer_size = it_to_prune->PruneSize();
Tom Cherry4a89fb72020-07-09 12:12:48 -0700187 RemoveChunkFromStats(log_id, *it_to_prune);
188 log_buffer.erase(it_to_prune);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700189 if (buffer_size >= bytes_to_free) {
Tom Cherry8c778e62020-08-12 09:36:15 -0700190 return;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700191 }
192 bytes_to_free -= buffer_size;
193 }
194 }
Tom Cherryfb150dd2020-05-13 09:28:37 -0700195}
196
197std::unique_ptr<FlushToState> SerializedLogBuffer::CreateFlushToState(uint64_t start,
198 LogMask log_mask) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700199 return std::make_unique<SerializedFlushToState>(start, log_mask, logs_);
Tom Cherry154b63a2020-10-05 11:35:59 -0700200}
201
Tom Cherryfb150dd2020-05-13 09:28:37 -0700202bool SerializedLogBuffer::FlushTo(
203 LogWriter* writer, FlushToState& abstract_state,
204 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
205 log_time realtime)>& filter) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700206 auto& state = reinterpret_cast<SerializedFlushToState&>(abstract_state);
Tom Cherryfb150dd2020-05-13 09:28:37 -0700207
Tom Cherry9169e712020-11-09 14:39:17 +0000208 while (state.HasUnreadLogs()) {
Tom Cherry87a17342020-09-18 15:32:32 -0700209 LogWithId top = state.PopNextUnreadLog();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700210 auto* entry = top.entry;
211 auto log_id = top.log_id;
212
213 if (entry->sequence() < state.start()) {
214 continue;
215 }
216 state.set_start(entry->sequence());
217
218 if (!writer->privileged() && entry->uid() != writer->uid()) {
219 continue;
220 }
221
222 if (filter) {
223 auto ret = filter(log_id, entry->pid(), entry->sequence(), entry->realtime());
224 if (ret == FilterResult::kSkip) {
225 continue;
226 }
227 if (ret == FilterResult::kStop) {
228 break;
229 }
230 }
231
Tom Cherry8c778e62020-08-12 09:36:15 -0700232 // We copy the log entry such that we can flush it without the lock. We never block pruning
233 // waiting for this Flush() to complete.
234 constexpr size_t kMaxEntrySize = sizeof(*entry) + LOGGER_ENTRY_MAX_PAYLOAD + 1;
235 unsigned char entry_copy[kMaxEntrySize] __attribute__((uninitialized));
236 CHECK_LT(entry->msg_len(), LOGGER_ENTRY_MAX_PAYLOAD + 1);
237 memcpy(entry_copy, entry, sizeof(*entry) + entry->msg_len());
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700238 logd_lock.unlock();
Tom Cherry8c778e62020-08-12 09:36:15 -0700239
240 if (!reinterpret_cast<SerializedLogEntry*>(entry_copy)->Flush(writer, log_id)) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700241 logd_lock.lock();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700242 return false;
243 }
Tom Cherry8c778e62020-08-12 09:36:15 -0700244
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700245 logd_lock.lock();
Tom Cherryfb150dd2020-05-13 09:28:37 -0700246 }
247
248 state.set_start(state.start() + 1);
249 return true;
250}
251
252bool SerializedLogBuffer::Clear(log_id_t id, uid_t uid) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700253 auto lock = std::lock_guard{logd_lock};
Tom Cherry8c778e62020-08-12 09:36:15 -0700254 Prune(id, ULONG_MAX, uid);
255
256 // Clearing SerializedLogBuffer never waits for readers and therefore is always successful.
257 return true;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700258}
259
Tom Cherry80228952020-08-05 12:14:45 -0700260size_t SerializedLogBuffer::GetSizeUsed(log_id_t id) {
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700261 size_t total_size = 0;
262 for (const auto& chunk : logs_[id]) {
263 total_size += chunk.PruneSize();
264 }
265 return total_size;
266}
267
Tom Cherry80228952020-08-05 12:14:45 -0700268size_t SerializedLogBuffer::GetSize(log_id_t id) {
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700269 auto lock = std::lock_guard{logd_lock};
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700270 return max_size_[id];
Tom Cherryfb150dd2020-05-13 09:28:37 -0700271}
272
273// New SerializedLogChunk objects will be allocated according to the new size, but older one are
274// unchanged. MaybePrune() is called on the log buffer to reduce it to an appropriate size if the
275// new size is lower.
Tom Cherry80228952020-08-05 12:14:45 -0700276bool SerializedLogBuffer::SetSize(log_id_t id, size_t size) {
Tom Cherryfb150dd2020-05-13 09:28:37 -0700277 // Reasonable limits ...
Tom Cherry80228952020-08-05 12:14:45 -0700278 if (!IsValidBufferSize(size)) {
279 return false;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700280 }
281
Tom Cherryc5c9eba2020-10-06 10:22:35 -0700282 auto lock = std::lock_guard{logd_lock};
Tom Cherrya3d6aa62020-06-19 12:21:21 -0700283 max_size_[id] = size;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700284
285 MaybePrune(id);
286
Tom Cherry80228952020-08-05 12:14:45 -0700287 return true;
Tom Cherryfb150dd2020-05-13 09:28:37 -0700288}