blob: 1d1d61b3746e0fa0e5ecc186819cae8754582c3f [file] [log] [blame]
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001/*
2 * Copyright (C) 2013 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#define LOG_TAG "NBLog"
18//#define LOG_NDEBUG 0
19
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080020#include <climits>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080021#include <stdarg.h>
22#include <stdint.h>
23#include <stdio.h>
24#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -080025#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080026#include <time.h>
27#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -080028#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080029#include <media/nbaio/NBLog.h>
30#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -070031#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080032
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070033#include <map>
Nicolas Roulet40a44982017-02-03 13:39:57 -080034#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070035#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -080036
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080037namespace android {
38
39int NBLog::Entry::readAt(size_t offset) const
40{
41 // FIXME This is too slow, despite the name it is used during writing
42 if (offset == 0)
43 return mEvent;
44 else if (offset == 1)
45 return mLength;
46 else if (offset < (size_t) (mLength + 2))
47 return ((char *) mData)[offset - 2];
48 else if (offset == (size_t) (mLength + 2))
49 return mLength;
50 else
51 return 0;
52}
53
54// ---------------------------------------------------------------------------
55
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070056/*static*/
57std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
58 uint8_t type = EntryIterator(ptr)->type;
59 switch (type) {
60 case EVENT_START_FMT:
61 return std::make_unique<FormatEntry>(FormatEntry(ptr));
62 case EVENT_HISTOGRAM_FLUSH:
63 case EVENT_HISTOGRAM_ENTRY_TS:
64 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
65 default:
66 ALOGW("Tried to create AbstractEntry of type %d", type);
67 return nullptr;
68 }
Nicolas Roulet40a44982017-02-03 13:39:57 -080069}
70
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070071NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
72}
73
74// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080075
Nicolas Roulet40a44982017-02-03 13:39:57 -080076const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080077 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -080078}
79
80size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080081 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -080082}
83
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070084NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080085 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -070086 // skip start fmt
87 ++it;
88 // skip timestamp
89 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -070090 // skip hash
91 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -070092 // Skip author if present
93 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080094 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080095 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -070096 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080097}
98
Nicolas Rouletf42f1562017-03-30 19:16:22 -070099int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800100 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700101 // skip start fmt
102 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700103 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800104}
105
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700106NBLog::log_hash_t NBLog::FormatEntry::hash() const {
107 auto it = begin();
108 // skip start fmt
109 ++it;
110 // skip timestamp
111 ++it;
112 // unaligned 64-bit read not supported
113 log_hash_t hash;
114 memcpy(&hash, it->data, sizeof(hash));
115 return hash;
116}
117
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700118int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800119 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700120 // skip start fmt
121 ++it;
122 // skip timestamp
123 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700124 // skip hash
125 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700126 // if there is an author entry, return it, return -1 otherwise
127 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800128 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800129 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800130 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800131}
132
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700133NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800134 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
135 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800136 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800137 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700138 // copy timestamp
139 (++it).copyTo(dst);
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700140 // copy hash
141 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800142 // insert author entry
143 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
144 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800145 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
146 authorEntry[offsetof(entry, length)] =
147 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
148 sizeof(author);
149 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800150 dst->write(authorEntry, authorEntrySize);
151 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800152 while ((++it)->type != EVENT_END_FMT) {
153 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800154 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800155 it.copyTo(dst);
156 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800157 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800158}
159
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700160void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800161 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
162 dst->write(ptr, length);
163}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700165void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800166 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
167}
168
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700169NBLog::EntryIterator NBLog::FormatEntry::begin() const {
170 return EntryIterator(mEntry);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800171}
172
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700173NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800174 : ptr(nullptr) {}
175
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700176NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800177 : ptr(entry) {}
178
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700179NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800180 : ptr(other.ptr) {}
181
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700182const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800183 return *(entry*) ptr;
184}
185
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700186const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800187 return (entry*) ptr;
188}
189
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700190NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800191 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
192 return *this;
193}
194
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700195NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800196 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
197 return *this;
198}
199
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700200NBLog::EntryIterator NBLog::EntryIterator::next() const {
201 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800202 return ++aux;
203}
204
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700205NBLog::EntryIterator NBLog::EntryIterator::prev() const {
206 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800207 return --aux;
208}
209
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700210int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800211 return ptr - other.ptr;
212}
213
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700214bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800215 return ptr != other.ptr;
216}
217
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700218bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800219 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
220 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800221}
222
223// ---------------------------------------------------------------------------
224
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700225int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700226 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
227}
228
229NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
230 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
231}
232
233int NBLog::HistogramEntry::author() const {
234 EntryIterator it(mEntry);
235 if (it->length == sizeof(HistTsEntryWithAuthor)) {
236 return it.payload<HistTsEntryWithAuthor>().author;
237 } else {
238 return -1;
239 }
240}
241
242NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
243 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
244 // Current histogram entry has {type, length, struct HistTsEntry, length}.
245 // We now want {type, length, struct HistTsEntryWithAuthor, length}
246 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
247 // Copy content until the point we want to add the author
248 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
249 // Copy the author
250 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
251 // Update lengths
252 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
253 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
254 // Write new buffer into FIFO
255 dst->write(buffer, sizeof(buffer));
256 return EntryIterator(mEntry).next();
257}
258
259// ---------------------------------------------------------------------------
260
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800261#if 0 // FIXME see note in NBLog.h
262NBLog::Timeline::Timeline(size_t size, void *shared)
263 : mSize(roundup(size)), mOwn(shared == NULL),
264 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
265{
266 new (mShared) Shared;
267}
268
269NBLog::Timeline::~Timeline()
270{
271 mShared->~Shared();
272 if (mOwn) {
273 delete[] (char *) mShared;
274 }
275}
276#endif
277
278/*static*/
279size_t NBLog::Timeline::sharedSize(size_t size)
280{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800281 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800282 return sizeof(Shared) + roundup(size);
283}
284
285// ---------------------------------------------------------------------------
286
287NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800288 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800289{
290}
291
Glenn Kasten535e1612016-12-05 12:19:36 -0800292NBLog::Writer::Writer(void *shared, size_t size)
293 : mShared((Shared *) shared),
294 mFifo(mShared != NULL ?
295 new audio_utils_fifo(size, sizeof(uint8_t),
296 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
297 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
298 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800299{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800300 // caching pid and process name
301 pid_t id = ::getpid();
302 char procName[16];
303 int status = prctl(PR_GET_NAME, procName);
304 if (status) { // error getting process name
305 procName[0] = '\0';
306 }
307 size_t length = strlen(procName);
308 mPidTagSize = length + sizeof(pid_t);
309 mPidTag = new char[mPidTagSize];
310 memcpy(mPidTag, &id, sizeof(pid_t));
311 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800312}
313
Glenn Kasten535e1612016-12-05 12:19:36 -0800314NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
315 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800316{
Glenn Kasten535e1612016-12-05 12:19:36 -0800317 mIMemory = iMemory;
318}
319
320NBLog::Writer::~Writer()
321{
322 delete mFifoWriter;
323 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800324 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800325}
326
327void NBLog::Writer::log(const char *string)
328{
329 if (!mEnabled) {
330 return;
331 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800332 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800333 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800334 if (length > Entry::kMaxLength) {
335 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800336 }
337 log(EVENT_STRING, string, length);
338}
339
340void NBLog::Writer::logf(const char *fmt, ...)
341{
342 if (!mEnabled) {
343 return;
344 }
345 va_list ap;
346 va_start(ap, fmt);
347 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
348 va_end(ap);
349}
350
351void NBLog::Writer::logvf(const char *fmt, va_list ap)
352{
353 if (!mEnabled) {
354 return;
355 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800356 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800357 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
358 if (length >= (int) sizeof(buffer)) {
359 length = sizeof(buffer) - 1;
360 // NUL termination is not required
361 // buffer[length] = '\0';
362 }
363 if (length >= 0) {
364 log(EVENT_STRING, buffer, length);
365 }
366}
367
368void NBLog::Writer::logTimestamp()
369{
370 if (!mEnabled) {
371 return;
372 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700373 int64_t ts = get_monotonic_ns();
374 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800375 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700376 } else {
377 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800378 }
379}
380
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700381void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800382{
383 if (!mEnabled) {
384 return;
385 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800386 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
387}
388
389void NBLog::Writer::logInteger(const int x)
390{
391 if (!mEnabled) {
392 return;
393 }
394 log(EVENT_INTEGER, &x, sizeof(x));
395}
396
397void NBLog::Writer::logFloat(const float x)
398{
399 if (!mEnabled) {
400 return;
401 }
402 log(EVENT_FLOAT, &x, sizeof(x));
403}
404
405void NBLog::Writer::logPID()
406{
407 if (!mEnabled) {
408 return;
409 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800410 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800411}
412
413void NBLog::Writer::logStart(const char *fmt)
414{
415 if (!mEnabled) {
416 return;
417 }
418 size_t length = strlen(fmt);
419 if (length > Entry::kMaxLength) {
420 length = Entry::kMaxLength;
421 }
422 log(EVENT_START_FMT, fmt, length);
423}
424
425void NBLog::Writer::logEnd()
426{
427 if (!mEnabled) {
428 return;
429 }
430 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
431 log(&entry, true);
432}
433
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700434void NBLog::Writer::logHash(log_hash_t hash)
435{
436 if (!mEnabled) {
437 return;
438 }
439 log(EVENT_HASH, &hash, sizeof(hash));
440}
441
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700442void NBLog::Writer::logHistTS(log_hash_t hash)
443{
444 if (!mEnabled) {
445 return;
446 }
447 HistTsEntry data;
448 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700449 data.ts = get_monotonic_ns();
450 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700451 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
452 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700453 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700454 }
455}
456
457void NBLog::Writer::logHistFlush(log_hash_t hash)
458{
459 if (!mEnabled) {
460 return;
461 }
462 HistTsEntry data;
463 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700464 data.ts = get_monotonic_ns();
465 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700466 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
467 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700468 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700469 }
470}
471
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700472void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800473{
474 if (!mEnabled) {
475 return;
476 }
477
478 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700479 va_start(ap, hash);
480 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800481 va_end(ap);
482}
483
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700484void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800485{
486 if (!mEnabled) {
487 return;
488 }
489 Writer::logStart(fmt);
490 int i;
491 double f;
492 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700493 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800494 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700495 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800496 for (const char *p = fmt; *p != '\0'; p++) {
497 // TODO: implement more complex formatting such as %.3f
498 if (*p != '%') {
499 continue;
500 }
501 switch(*++p) {
502 case 's': // string
503 s = va_arg(argp, char *);
504 Writer::log(s);
505 break;
506
507 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700508 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800509 Writer::logTimestamp(t);
510 break;
511
512 case 'd': // integer
513 i = va_arg(argp, int);
514 Writer::logInteger(i);
515 break;
516
517 case 'f': // float
518 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
519 Writer::logFloat((float)f);
520 break;
521
522 case 'p': // pid
523 Writer::logPID();
524 break;
525
526 // the "%\0" case finishes parsing
527 case '\0':
528 --p;
529 break;
530
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800531 case '%':
532 break;
533
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800534 default:
535 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
536 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800537 }
538 }
539 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800540}
541
542void NBLog::Writer::log(Event event, const void *data, size_t length)
543{
544 if (!mEnabled) {
545 return;
546 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800547 if (data == NULL || length > Entry::kMaxLength) {
548 // TODO Perhaps it makes sense to display truncated data or at least a
549 // message that the data is too long? The current behavior can create
550 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800551 return;
552 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700553 // Ignore if invalid event
554 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800555 return;
556 }
557 Entry entry(event, data, length);
558 log(&entry, true /*trusted*/);
559}
560
561void NBLog::Writer::log(const NBLog::Entry *entry, bool trusted)
562{
563 if (!mEnabled) {
564 return;
565 }
566 if (!trusted) {
567 log(entry->mEvent, entry->mData, entry->mLength);
568 return;
569 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800570 size_t need = entry->mLength + Entry::kOverhead; // mEvent, mLength, data[length], mLength
571 // need = number of bytes remaining to write
572
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800573 // FIXME optimize this using memcpy for the data part of the Entry.
574 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Glenn Kasten535e1612016-12-05 12:19:36 -0800575 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
576 for (size_t i = 0; i < need; i++) {
577 temp[i] = entry->readAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800578 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800579 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800580}
581
582bool NBLog::Writer::isEnabled() const
583{
584 return mEnabled;
585}
586
587bool NBLog::Writer::setEnabled(bool enabled)
588{
589 bool old = mEnabled;
590 mEnabled = enabled && mShared != NULL;
591 return old;
592}
593
594// ---------------------------------------------------------------------------
595
596NBLog::LockedWriter::LockedWriter()
597 : Writer()
598{
599}
600
Glenn Kasten535e1612016-12-05 12:19:36 -0800601NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
602 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800603{
604}
605
606void NBLog::LockedWriter::log(const char *string)
607{
608 Mutex::Autolock _l(mLock);
609 Writer::log(string);
610}
611
612void NBLog::LockedWriter::logf(const char *fmt, ...)
613{
614 // FIXME should not take the lock until after formatting is done
615 Mutex::Autolock _l(mLock);
616 va_list ap;
617 va_start(ap, fmt);
618 Writer::logvf(fmt, ap);
619 va_end(ap);
620}
621
622void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
623{
624 // FIXME should not take the lock until after formatting is done
625 Mutex::Autolock _l(mLock);
626 Writer::logvf(fmt, ap);
627}
628
629void NBLog::LockedWriter::logTimestamp()
630{
631 // FIXME should not take the lock until after the clock_gettime() syscall
632 Mutex::Autolock _l(mLock);
633 Writer::logTimestamp();
634}
635
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700636void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800637{
638 Mutex::Autolock _l(mLock);
639 Writer::logTimestamp(ts);
640}
641
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800642void NBLog::LockedWriter::logInteger(const int x)
643{
644 Mutex::Autolock _l(mLock);
645 Writer::logInteger(x);
646}
647
648void NBLog::LockedWriter::logFloat(const float x)
649{
650 Mutex::Autolock _l(mLock);
651 Writer::logFloat(x);
652}
653
654void NBLog::LockedWriter::logPID()
655{
656 Mutex::Autolock _l(mLock);
657 Writer::logPID();
658}
659
660void NBLog::LockedWriter::logStart(const char *fmt)
661{
662 Mutex::Autolock _l(mLock);
663 Writer::logStart(fmt);
664}
665
666
667void NBLog::LockedWriter::logEnd()
668{
669 Mutex::Autolock _l(mLock);
670 Writer::logEnd();
671}
672
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700673void NBLog::LockedWriter::logHash(log_hash_t hash)
674{
675 Mutex::Autolock _l(mLock);
676 Writer::logHash(hash);
677}
678
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800679bool NBLog::LockedWriter::isEnabled() const
680{
681 Mutex::Autolock _l(mLock);
682 return Writer::isEnabled();
683}
684
685bool NBLog::LockedWriter::setEnabled(bool enabled)
686{
687 Mutex::Autolock _l(mLock);
688 return Writer::setEnabled(enabled);
689}
690
691// ---------------------------------------------------------------------------
692
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700693const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
694 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
695const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
696 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
697 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800698NBLog::Reader::Reader(const void *shared, size_t size)
699 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
700 mFd(-1), mIndent(0),
701 mFifo(mShared != NULL ?
702 new audio_utils_fifo(size, sizeof(uint8_t),
703 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
704 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800705{
706}
707
Glenn Kasten535e1612016-12-05 12:19:36 -0800708NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
709 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800710{
Glenn Kasten535e1612016-12-05 12:19:36 -0800711 mIMemory = iMemory;
712}
713
714NBLog::Reader::~Reader()
715{
716 delete mFifoReader;
717 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800718}
719
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700720const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
721 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800722 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700723 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
724 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800725 Entry::kOverhead != back) {
726
727 // prev points to an out of limits or inconsistent entry
728 return nullptr;
729 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700730 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800731 return prev;
732 }
733 back = prev;
734 }
735 return nullptr; // no entry found
736}
737
Nicolas Roulet40a44982017-02-03 13:39:57 -0800738std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800739{
Glenn Kasten535e1612016-12-05 12:19:36 -0800740 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800741 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800742 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800743 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800744 size_t capacity = mFifo->capacity();
745
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800746 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
747 // reader index. The index is incremented after handling corruption, to after the last complete
748 // entry of the buffer
749 size_t lost;
750 audio_utils_iovec iovec[2];
751 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
752 if (availToRead <= 0) {
753 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
754 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800755
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800756 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
757 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
758 if (iovec[1].mLength > 0) {
759 memcpy(snapshot->mData + (iovec[0].mLength),
760 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
761 }
762
763 // Handle corrupted buffer
764 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
765 // (due to incomplete format entry). But even if the end format entry is incomplete,
766 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
767 // TODO: handle client corruption (in the middle of a buffer)
768
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700769 const uint8_t *back = snapshot->mData + availToRead;
770 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800771
772 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
773 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700774 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800775 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700776 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800777 } else {
778 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700779 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800780 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700781 const uint8_t *firstStart = nullptr;
782 const uint8_t *firstStartTmp = snapshot->mEnd;
783 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800784 != nullptr) {
785 firstStart = firstStartTmp;
786 }
787 // firstStart is null if no START_FMT entry was found before lastEnd
788 if (firstStart == nullptr) {
789 snapshot->mBegin = snapshot->mEnd;
790 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700791 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800792 }
793 }
794
795 // advance fifo reader index to after last entry read.
796 mFifoReader->release(snapshot->mEnd - front);
797
798 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800799 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800800
Nicolas Roulet40a44982017-02-03 13:39:57 -0800801}
802
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700803inline static int deltaMs(int64_t t1, int64_t t2) {
804 return (t2 - t1) / (1000 * 1000);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700805}
806
Nicolas Roulet40a44982017-02-03 13:39:57 -0800807void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
808{
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800809#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800810 struct timespec ts;
811 time_t maxSec = -1;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800812 while (entry - start >= (int) Entry::kOverhead) {
813 if (prevEntry - start < 0 || !prevEntry.hasConsistentLength()) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800814 break;
815 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800816 if (prevEntry->type == EVENT_TIMESTAMP) {
817 if (prevEntry->length != sizeof(struct timespec)) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800818 // corrupt
819 break;
820 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800821 prevEntry.copyData((uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800822 if (ts.tv_sec > maxSec) {
823 maxSec = ts.tv_sec;
824 }
825 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800826 --entry;
827 --prevEntry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800828 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800829#endif
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700830 mFd = fd;
831 mIndent = indent;
832 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700833 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700834 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700835 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700836 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
837 // log to push it out. Consider keeping the timestamp/body between calls to readAt().
838 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800839 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800840#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800841 size_t width = 1;
842 while (maxSec >= 10) {
843 ++width;
844 maxSec /= 10;
845 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800846 if (maxSec >= 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700847 timestamp.appendFormat("[%*s]", (int) width + 4, "");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800848 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700849 bool deferredTimestamp = false;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800850#endif
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700851 std::map<std::pair<log_hash_t, int>, std::vector<int>> hists;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700852 std::map<std::pair<log_hash_t, int>, int64_t*> lastTSs;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700853
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800854 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800855 switch (entry->type) {
856#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800857 case EVENT_STRING:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800858 body.appendFormat("%.*s", (int) entry.length(), entry.data());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700859 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800860 case EVENT_TIMESTAMP: {
861 // already checked that length == sizeof(struct timespec);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800862 entry.copyData((const uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800863 long prevNsec = ts.tv_nsec;
864 long deltaMin = LONG_MAX;
865 long deltaMax = -1;
866 long deltaTotal = 0;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800867 auto aux(entry);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800868 for (;;) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800869 ++aux;
870 if (end - aux >= 0 || aux.type() != EVENT_TIMESTAMP) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800871 break;
872 }
873 struct timespec tsNext;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800874 aux.copyData((const uint8_t*) &tsNext);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800875 if (tsNext.tv_sec != ts.tv_sec) {
876 break;
877 }
878 long delta = tsNext.tv_nsec - prevNsec;
879 if (delta < 0) {
880 break;
881 }
882 if (delta < deltaMin) {
883 deltaMin = delta;
884 }
885 if (delta > deltaMax) {
886 deltaMax = delta;
887 }
888 deltaTotal += delta;
889 prevNsec = tsNext.tv_nsec;
890 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800891 size_t n = (aux - entry) / (sizeof(struct timespec) + 3 /*Entry::kOverhead?*/);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700892 if (deferredTimestamp) {
893 dumpLine(timestamp, body);
894 deferredTimestamp = false;
895 }
896 timestamp.clear();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800897 if (n >= kSquashTimestamp) {
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700898 timestamp.appendFormat("[%d.%03d to .%.03d by .%.03d to .%.03d]",
899 (int) ts.tv_sec, (int) (ts.tv_nsec / 1000000),
900 (int) ((ts.tv_nsec + deltaTotal) / 1000000),
901 (int) (deltaMin / 1000000), (int) (deltaMax / 1000000));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800902 entry = aux;
903 // advance = 0;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800904 break;
905 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700906 timestamp.appendFormat("[%d.%03d]", (int) ts.tv_sec,
907 (int) (ts.tv_nsec / 1000000));
908 deferredTimestamp = true;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800909 }
910 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800911 case EVENT_INTEGER:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800912 appendInt(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800913 break;
914 case EVENT_FLOAT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800915 appendFloat(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800916 break;
917 case EVENT_PID:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800918 appendPID(&body, entry.data(), entry.length());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800919 break;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800920#endif
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800921 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800922 // right now, this is the only supported case
923 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800924 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700925 case EVENT_HISTOGRAM_ENTRY_TS: {
926 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
927 // TODO This memcpies are here to avoid unaligned memory access crash.
928 // There's probably a more efficient way to do it
929 log_hash_t hash;
930 memcpy(&hash, &(data->hash), sizeof(hash));
931 const std::pair<log_hash_t, int> key(hash, data->author);
932 if (lastTSs[key] != nullptr) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700933 int64_t ts1;
934 memcpy(&ts1, lastTSs[key], sizeof(ts1));
935 int64_t ts2;
936 memcpy(&ts2, &data->ts, sizeof(ts2));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700937 // TODO might want to filter excessively high outliers, which are usually caused
938 // by the thread being inactive.
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700939 hists[key].push_back(deltaMs(ts1, ts2));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700940 }
941 lastTSs[key] = &(data->ts);
942 ++entry;
943 break;
944 }
945 case EVENT_HISTOGRAM_FLUSH:
946 body.appendFormat("Histograms:\n");
947 for (auto const &hist : hists) {
948 body.appendFormat("Histogram %X - ", (int)hist.first.first);
949 handleAuthor(HistogramEntry(entry), &body);
950 drawHistogram(&body, hist.second);
951 }
952 hists.clear();
953 lastTSs.clear();
954 ++entry;
955 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800956 case EVENT_END_FMT:
957 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800958 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800959 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800960 case EVENT_RESERVED:
961 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800962 body.appendFormat("warning: unexpected event %d", entry->type);
963 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800964 break;
965 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700966
967 if (!body.isEmpty()) {
968 dumpLine(timestamp, body);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800969 // deferredTimestamp = false;
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700970 }
971 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800972 // if (deferredTimestamp) {
973 // dumpLine(timestamp, body);
974 // }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800975}
976
Nicolas Roulet40a44982017-02-03 13:39:57 -0800977void NBLog::Reader::dump(int fd, size_t indent)
978{
979 // get a snapshot, dump it
980 std::unique_ptr<Snapshot> snap = getSnapshot();
981 dump(fd, indent, *snap);
982}
983
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800984void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700985{
986 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700987 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700988 } else {
989 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
990 }
991 body.clear();
992}
993
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800994bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
995{
Glenn Kasten481fb672013-09-30 14:39:28 -0700996 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800997}
998
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800999void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001000 int64_t ts;
1001 memcpy(&ts, data, sizeof(ts));
1002 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1003 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001004}
1005
1006void NBLog::appendInt(String8 *body, const void *data) {
1007 int x = *((int*) data);
1008 body->appendFormat("<%d>", x);
1009}
1010
1011void NBLog::appendFloat(String8 *body, const void *data) {
1012 float f;
1013 memcpy(&f, data, sizeof(float));
1014 body->appendFormat("<%f>", f);
1015}
1016
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001017void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001018 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001019 char * name = &((char*) data)[sizeof(pid_t)];
1020 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001021}
1022
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001023String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001024{
1025 String8 str;
1026 str.append("[ ");
1027 for(size_t i = 0; i < size; i++)
1028 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001029 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001030 }
1031 str.append("]");
1032 return str;
1033}
1034
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001035String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001036{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001037 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001038}
1039
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001040NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001041 String8 *timestamp,
1042 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001043 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001044 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001045 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001046 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1047 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001048
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001049 // log unique hash
1050 log_hash_t hash = fmtEntry.hash();
1051 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1052 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1053
Nicolas Roulet40a44982017-02-03 13:39:57 -08001054 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001055 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001056
1057 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001058 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001059
1060 const char* fmt = fmtEntry.formatString();
1061 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001062
1063 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1064 if (fmt[fmt_offset] != '%') {
1065 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1066 continue;
1067 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001068 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001069 if (fmt[++fmt_offset] == '%') {
1070 body->append("%");
1071 continue;
1072 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001073 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001074 if (fmt_offset == fmt_length) {
1075 continue;
1076 }
1077
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001078 NBLog::Event event = (NBLog::Event) arg->type;
1079 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001080
1081 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001082
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001083 if (event == EVENT_END_FMT) {
1084 break;
1085 }
1086
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001087 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001088 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001089 switch(fmt[fmt_offset])
1090 {
1091 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001092 ALOGW_IF(event != EVENT_STRING,
1093 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001094 body->append((const char*) datum, length);
1095 break;
1096
1097 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001098 ALOGW_IF(event != EVENT_TIMESTAMP,
1099 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001100 appendTimestamp(body, datum);
1101 break;
1102
1103 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001104 ALOGW_IF(event != EVENT_INTEGER,
1105 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001106 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001107 break;
1108
1109 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001110 ALOGW_IF(event != EVENT_FLOAT,
1111 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001112 appendFloat(body, datum);
1113 break;
1114
1115 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001116 ALOGW_IF(event != EVENT_PID,
1117 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001118 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001119 break;
1120
1121 default:
1122 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1123 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001124 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001125 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001126 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1127 ++arg;
1128 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001129}
1130
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001131static int widthOf(int x) {
1132 int width = 0;
1133 while (x > 0) {
1134 ++width;
1135 x /= 10;
1136 }
1137 return width;
1138}
1139
1140static std::map<int, int> buildBuckets(const std::vector<int> &samples) {
1141 // TODO allow buckets of variable resolution
1142 std::map<int, int> buckets;
1143 for (int x : samples) {
1144 ++buckets[x];
1145 }
1146 return buckets;
1147}
1148
1149// TODO put this function in separate file. Make it return a std::string instead of modifying body
1150void NBLog::Reader::drawHistogram(String8 *body, const std::vector<int> &samples, int maxHeight) {
1151 std::map<int, int> buckets = buildBuckets(samples);
1152 // TODO add option for log scale
1153 static const char *underscores = "________________";
1154 static const char *spaces = " ";
1155
1156 auto it = buckets.begin();
1157 int maxLabel = it->first;
1158 int maxVal = it->second;
1159 while (++it != buckets.end()) {
1160 if (it->first > maxLabel) {
1161 maxLabel = it->first;
1162 }
1163 if (it->second > maxVal) {
1164 maxVal = it->second;
1165 }
1166 }
1167 int height = maxVal;
1168 int leftPadding = widthOf(maxVal);
1169 int colWidth = std::max(std::max(widthOf(maxLabel) + 1, 3), leftPadding + 2);
1170 int scalingFactor = 1;
1171 if (height > maxHeight) {
1172 scalingFactor = (height + maxHeight) / maxHeight;
1173 height /= scalingFactor;
1174 }
1175 body->appendFormat("\n");
1176 body->appendFormat("%*s", leftPadding + 2, " ");
1177 for (auto const &x : buckets)
1178 {
1179 body->appendFormat("[%*d]", colWidth - 2, x.second);
1180 }
1181 body->appendFormat("\n");
1182 for (int row = height * scalingFactor; row > 0; row -= scalingFactor)
1183 {
1184 body->appendFormat("%*d|", leftPadding, row);
1185 for (auto const &x : buckets) {
1186 body->appendFormat("%.*s%s", colWidth - 2,
1187 (row == scalingFactor) ? underscores : spaces,
1188 x.second < row ? ((row == scalingFactor) ? "__" : " ") : "[]");
1189 }
1190 body->appendFormat("\n");
1191 }
1192 body->appendFormat("%*s", leftPadding + 1, " ");
1193 for (auto const &x : buckets)
1194 {
1195 body->appendFormat("%*d", colWidth, x.first);
1196 }
1197 body->appendFormat("\n");
1198}
1199
Nicolas Roulet40a44982017-02-03 13:39:57 -08001200// ---------------------------------------------------------------------------
1201
1202NBLog::Merger::Merger(const void *shared, size_t size):
1203 mBuffer(NULL),
1204 mShared((Shared *) shared),
1205 mFifo(mShared != NULL ?
1206 new audio_utils_fifo(size, sizeof(uint8_t),
1207 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1208 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1209 {}
1210
1211void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
1212 mNamedReaders.push_back(reader);
1213}
1214
1215// items placed in priority queue during merge
1216// composed by a timestamp and the index of the snapshot where the timestamp came from
1217struct MergeItem
1218{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001219 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001220 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001221 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001222};
1223
1224// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001225// bool operator>(const int64_t &t1, const int64_t &t2) {
1226// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1227// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001228
1229bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001230 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001231}
1232
1233// Merge registered readers, sorted by timestamp
1234void NBLog::Merger::merge() {
1235 int nLogs = mNamedReaders.size();
1236 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001237 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001238 for (int i = 0; i < nLogs; ++i) {
1239 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001240 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001241 }
1242 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001243 // TODO custom heap implementation could allow to update top, improving performance
1244 // for bursty buffers
1245 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1246 for (int i = 0; i < nLogs; ++i)
1247 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001248 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001249 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001250 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001251 }
1252 }
1253
1254 while (!timestamps.empty()) {
1255 // find minimum timestamp
1256 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001257 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001258 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1259 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001260 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001261 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001262 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001263 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001264 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001265 }
1266 }
1267}
1268
1269const std::vector<NBLog::NamedReader> *NBLog::Merger::getNamedReaders() const {
1270 return &mNamedReaders;
1271}
1272
1273NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1274 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1275
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001276void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1277 int author = entry.author();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001278 const char* name = (*mNamedReaders)[author].name();
1279 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001280}
1281
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001282NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1283 : mMerger(merger),
1284 mTimeoutUs(0) {}
1285
1286NBLog::MergeThread::~MergeThread() {
1287 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1288 requestExit();
1289 setTimeoutUs(0);
1290 join();
1291}
1292
1293bool NBLog::MergeThread::threadLoop() {
1294 bool doMerge;
1295 {
1296 AutoMutex _l(mMutex);
1297 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1298 // If it's positive, wait kThreadSleepPeriodUs and then merge
1299 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1300 mCond.waitRelative(mMutex, waitTime);
1301 doMerge = mTimeoutUs > 0;
1302 mTimeoutUs -= kThreadSleepPeriodUs;
1303 }
1304 if (doMerge) {
1305 mMerger.merge();
1306 }
1307 return true;
1308}
1309
1310void NBLog::MergeThread::wakeup() {
1311 setTimeoutUs(kThreadWakeupPeriodUs);
1312}
1313
1314void NBLog::MergeThread::setTimeoutUs(int time) {
1315 AutoMutex _l(mMutex);
1316 mTimeoutUs = time;
1317 mCond.signal();
1318}
1319
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001320} // namespace android