blob: de2dc25b8cd0189f19a20edf92a27193501f61e3 [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
99timespec 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 Rouletcd5dd012017-02-13 12:09:28 -0800103 return it.payload<timespec>();
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 Roulet537ad7d2017-03-21 16:24:30 -0700225timespec NBLog::HistogramEntry::timestamp() const {
226 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 }
373 struct timespec ts;
374 if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800375 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800376 }
377}
378
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800379void NBLog::Writer::logTimestamp(const struct timespec &ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800380{
381 if (!mEnabled) {
382 return;
383 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800384 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
385}
386
387void NBLog::Writer::logInteger(const int x)
388{
389 if (!mEnabled) {
390 return;
391 }
392 log(EVENT_INTEGER, &x, sizeof(x));
393}
394
395void NBLog::Writer::logFloat(const float x)
396{
397 if (!mEnabled) {
398 return;
399 }
400 log(EVENT_FLOAT, &x, sizeof(x));
401}
402
403void NBLog::Writer::logPID()
404{
405 if (!mEnabled) {
406 return;
407 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800408 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800409}
410
411void NBLog::Writer::logStart(const char *fmt)
412{
413 if (!mEnabled) {
414 return;
415 }
416 size_t length = strlen(fmt);
417 if (length > Entry::kMaxLength) {
418 length = Entry::kMaxLength;
419 }
420 log(EVENT_START_FMT, fmt, length);
421}
422
423void NBLog::Writer::logEnd()
424{
425 if (!mEnabled) {
426 return;
427 }
428 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
429 log(&entry, true);
430}
431
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700432void NBLog::Writer::logHash(log_hash_t hash)
433{
434 if (!mEnabled) {
435 return;
436 }
437 log(EVENT_HASH, &hash, sizeof(hash));
438}
439
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700440void NBLog::Writer::logHistTS(log_hash_t hash)
441{
442 if (!mEnabled) {
443 return;
444 }
445 HistTsEntry data;
446 data.hash = hash;
447 int error = clock_gettime(CLOCK_MONOTONIC, &data.ts);
448 if (error == 0) {
449 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
450 } else {
451 ALOGE("Failed to get timestamp: error %d", error);
452 }
453}
454
455void NBLog::Writer::logHistFlush(log_hash_t hash)
456{
457 if (!mEnabled) {
458 return;
459 }
460 HistTsEntry data;
461 data.hash = hash;
462 int error = clock_gettime(CLOCK_MONOTONIC, &data.ts);
463 if (error == 0) {
464 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
465 } else {
466 ALOGE("Failed to get timestamp: error %d", error);
467 }
468}
469
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700470void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800471{
472 if (!mEnabled) {
473 return;
474 }
475
476 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700477 va_start(ap, hash);
478 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800479 va_end(ap);
480}
481
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700482void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800483{
484 if (!mEnabled) {
485 return;
486 }
487 Writer::logStart(fmt);
488 int i;
489 double f;
490 char* s;
491 struct timespec t;
492 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700493 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800494 for (const char *p = fmt; *p != '\0'; p++) {
495 // TODO: implement more complex formatting such as %.3f
496 if (*p != '%') {
497 continue;
498 }
499 switch(*++p) {
500 case 's': // string
501 s = va_arg(argp, char *);
502 Writer::log(s);
503 break;
504
505 case 't': // timestamp
506 t = va_arg(argp, struct timespec);
507 Writer::logTimestamp(t);
508 break;
509
510 case 'd': // integer
511 i = va_arg(argp, int);
512 Writer::logInteger(i);
513 break;
514
515 case 'f': // float
516 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
517 Writer::logFloat((float)f);
518 break;
519
520 case 'p': // pid
521 Writer::logPID();
522 break;
523
524 // the "%\0" case finishes parsing
525 case '\0':
526 --p;
527 break;
528
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800529 case '%':
530 break;
531
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800532 default:
533 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
534 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800535 }
536 }
537 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800538}
539
540void NBLog::Writer::log(Event event, const void *data, size_t length)
541{
542 if (!mEnabled) {
543 return;
544 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800545 if (data == NULL || length > Entry::kMaxLength) {
546 // TODO Perhaps it makes sense to display truncated data or at least a
547 // message that the data is too long? The current behavior can create
548 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800549 return;
550 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700551 // Ignore if invalid event
552 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800553 return;
554 }
555 Entry entry(event, data, length);
556 log(&entry, true /*trusted*/);
557}
558
559void NBLog::Writer::log(const NBLog::Entry *entry, bool trusted)
560{
561 if (!mEnabled) {
562 return;
563 }
564 if (!trusted) {
565 log(entry->mEvent, entry->mData, entry->mLength);
566 return;
567 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800568 size_t need = entry->mLength + Entry::kOverhead; // mEvent, mLength, data[length], mLength
569 // need = number of bytes remaining to write
570
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800571 // FIXME optimize this using memcpy for the data part of the Entry.
572 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Glenn Kasten535e1612016-12-05 12:19:36 -0800573 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
574 for (size_t i = 0; i < need; i++) {
575 temp[i] = entry->readAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800576 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800577 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800578}
579
580bool NBLog::Writer::isEnabled() const
581{
582 return mEnabled;
583}
584
585bool NBLog::Writer::setEnabled(bool enabled)
586{
587 bool old = mEnabled;
588 mEnabled = enabled && mShared != NULL;
589 return old;
590}
591
592// ---------------------------------------------------------------------------
593
594NBLog::LockedWriter::LockedWriter()
595 : Writer()
596{
597}
598
Glenn Kasten535e1612016-12-05 12:19:36 -0800599NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
600 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800601{
602}
603
604void NBLog::LockedWriter::log(const char *string)
605{
606 Mutex::Autolock _l(mLock);
607 Writer::log(string);
608}
609
610void NBLog::LockedWriter::logf(const char *fmt, ...)
611{
612 // FIXME should not take the lock until after formatting is done
613 Mutex::Autolock _l(mLock);
614 va_list ap;
615 va_start(ap, fmt);
616 Writer::logvf(fmt, ap);
617 va_end(ap);
618}
619
620void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
621{
622 // FIXME should not take the lock until after formatting is done
623 Mutex::Autolock _l(mLock);
624 Writer::logvf(fmt, ap);
625}
626
627void NBLog::LockedWriter::logTimestamp()
628{
629 // FIXME should not take the lock until after the clock_gettime() syscall
630 Mutex::Autolock _l(mLock);
631 Writer::logTimestamp();
632}
633
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800634void NBLog::LockedWriter::logTimestamp(const struct timespec &ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800635{
636 Mutex::Autolock _l(mLock);
637 Writer::logTimestamp(ts);
638}
639
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800640void NBLog::LockedWriter::logInteger(const int x)
641{
642 Mutex::Autolock _l(mLock);
643 Writer::logInteger(x);
644}
645
646void NBLog::LockedWriter::logFloat(const float x)
647{
648 Mutex::Autolock _l(mLock);
649 Writer::logFloat(x);
650}
651
652void NBLog::LockedWriter::logPID()
653{
654 Mutex::Autolock _l(mLock);
655 Writer::logPID();
656}
657
658void NBLog::LockedWriter::logStart(const char *fmt)
659{
660 Mutex::Autolock _l(mLock);
661 Writer::logStart(fmt);
662}
663
664
665void NBLog::LockedWriter::logEnd()
666{
667 Mutex::Autolock _l(mLock);
668 Writer::logEnd();
669}
670
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700671void NBLog::LockedWriter::logHash(log_hash_t hash)
672{
673 Mutex::Autolock _l(mLock);
674 Writer::logHash(hash);
675}
676
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800677bool NBLog::LockedWriter::isEnabled() const
678{
679 Mutex::Autolock _l(mLock);
680 return Writer::isEnabled();
681}
682
683bool NBLog::LockedWriter::setEnabled(bool enabled)
684{
685 Mutex::Autolock _l(mLock);
686 return Writer::setEnabled(enabled);
687}
688
689// ---------------------------------------------------------------------------
690
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700691const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
692 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
693const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
694 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
695 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800696NBLog::Reader::Reader(const void *shared, size_t size)
697 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
698 mFd(-1), mIndent(0),
699 mFifo(mShared != NULL ?
700 new audio_utils_fifo(size, sizeof(uint8_t),
701 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
702 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800703{
704}
705
Glenn Kasten535e1612016-12-05 12:19:36 -0800706NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
707 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800708{
Glenn Kasten535e1612016-12-05 12:19:36 -0800709 mIMemory = iMemory;
710}
711
712NBLog::Reader::~Reader()
713{
714 delete mFifoReader;
715 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800716}
717
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700718const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
719 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800720 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700721 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
722 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800723 Entry::kOverhead != back) {
724
725 // prev points to an out of limits or inconsistent entry
726 return nullptr;
727 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700728 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800729 return prev;
730 }
731 back = prev;
732 }
733 return nullptr; // no entry found
734}
735
Nicolas Roulet40a44982017-02-03 13:39:57 -0800736std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800737{
Glenn Kasten535e1612016-12-05 12:19:36 -0800738 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800739 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800740 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800741 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800742 size_t capacity = mFifo->capacity();
743
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800744 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
745 // reader index. The index is incremented after handling corruption, to after the last complete
746 // entry of the buffer
747 size_t lost;
748 audio_utils_iovec iovec[2];
749 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
750 if (availToRead <= 0) {
751 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
752 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800753
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800754 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
755 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
756 if (iovec[1].mLength > 0) {
757 memcpy(snapshot->mData + (iovec[0].mLength),
758 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
759 }
760
761 // Handle corrupted buffer
762 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
763 // (due to incomplete format entry). But even if the end format entry is incomplete,
764 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
765 // TODO: handle client corruption (in the middle of a buffer)
766
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700767 const uint8_t *back = snapshot->mData + availToRead;
768 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800769
770 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
771 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700772 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800773 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700774 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800775 } else {
776 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700777 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800778 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700779 const uint8_t *firstStart = nullptr;
780 const uint8_t *firstStartTmp = snapshot->mEnd;
781 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800782 != nullptr) {
783 firstStart = firstStartTmp;
784 }
785 // firstStart is null if no START_FMT entry was found before lastEnd
786 if (firstStart == nullptr) {
787 snapshot->mBegin = snapshot->mEnd;
788 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700789 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800790 }
791 }
792
793 // advance fifo reader index to after last entry read.
794 mFifoReader->release(snapshot->mEnd - front);
795
796 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800797 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800798
Nicolas Roulet40a44982017-02-03 13:39:57 -0800799}
800
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700801int deltaMs(timespec *t1, timespec *t2) {
802 return (t2->tv_sec - t1->tv_sec) * 1000 + t2->tv_nsec / 1000000 - t1->tv_nsec / 1000000;
803}
804
Nicolas Roulet40a44982017-02-03 13:39:57 -0800805void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
806{
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800807#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800808 struct timespec ts;
809 time_t maxSec = -1;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800810 while (entry - start >= (int) Entry::kOverhead) {
811 if (prevEntry - start < 0 || !prevEntry.hasConsistentLength()) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800812 break;
813 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800814 if (prevEntry->type == EVENT_TIMESTAMP) {
815 if (prevEntry->length != sizeof(struct timespec)) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800816 // corrupt
817 break;
818 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800819 prevEntry.copyData((uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800820 if (ts.tv_sec > maxSec) {
821 maxSec = ts.tv_sec;
822 }
823 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800824 --entry;
825 --prevEntry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800826 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800827#endif
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700828 mFd = fd;
829 mIndent = indent;
830 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700831 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700832 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700833 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700834 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
835 // log to push it out. Consider keeping the timestamp/body between calls to readAt().
836 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800837 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800838#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800839 size_t width = 1;
840 while (maxSec >= 10) {
841 ++width;
842 maxSec /= 10;
843 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800844 if (maxSec >= 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700845 timestamp.appendFormat("[%*s]", (int) width + 4, "");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800846 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700847 bool deferredTimestamp = false;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800848#endif
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700849 std::map<std::pair<log_hash_t, int>, std::vector<int>> hists;
850 std::map<std::pair<log_hash_t, int>, timespec*> lastTSs;
851
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800852 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800853 switch (entry->type) {
854#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800855 case EVENT_STRING:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800856 body.appendFormat("%.*s", (int) entry.length(), entry.data());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700857 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800858 case EVENT_TIMESTAMP: {
859 // already checked that length == sizeof(struct timespec);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800860 entry.copyData((const uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800861 long prevNsec = ts.tv_nsec;
862 long deltaMin = LONG_MAX;
863 long deltaMax = -1;
864 long deltaTotal = 0;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800865 auto aux(entry);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800866 for (;;) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800867 ++aux;
868 if (end - aux >= 0 || aux.type() != EVENT_TIMESTAMP) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800869 break;
870 }
871 struct timespec tsNext;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800872 aux.copyData((const uint8_t*) &tsNext);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800873 if (tsNext.tv_sec != ts.tv_sec) {
874 break;
875 }
876 long delta = tsNext.tv_nsec - prevNsec;
877 if (delta < 0) {
878 break;
879 }
880 if (delta < deltaMin) {
881 deltaMin = delta;
882 }
883 if (delta > deltaMax) {
884 deltaMax = delta;
885 }
886 deltaTotal += delta;
887 prevNsec = tsNext.tv_nsec;
888 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800889 size_t n = (aux - entry) / (sizeof(struct timespec) + 3 /*Entry::kOverhead?*/);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700890 if (deferredTimestamp) {
891 dumpLine(timestamp, body);
892 deferredTimestamp = false;
893 }
894 timestamp.clear();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800895 if (n >= kSquashTimestamp) {
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700896 timestamp.appendFormat("[%d.%03d to .%.03d by .%.03d to .%.03d]",
897 (int) ts.tv_sec, (int) (ts.tv_nsec / 1000000),
898 (int) ((ts.tv_nsec + deltaTotal) / 1000000),
899 (int) (deltaMin / 1000000), (int) (deltaMax / 1000000));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800900 entry = aux;
901 // advance = 0;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800902 break;
903 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700904 timestamp.appendFormat("[%d.%03d]", (int) ts.tv_sec,
905 (int) (ts.tv_nsec / 1000000));
906 deferredTimestamp = true;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800907 }
908 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800909 case EVENT_INTEGER:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800910 appendInt(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800911 break;
912 case EVENT_FLOAT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800913 appendFloat(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800914 break;
915 case EVENT_PID:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800916 appendPID(&body, entry.data(), entry.length());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800917 break;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800918#endif
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800919 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800920 // right now, this is the only supported case
921 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800922 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700923 case EVENT_HISTOGRAM_ENTRY_TS: {
924 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
925 // TODO This memcpies are here to avoid unaligned memory access crash.
926 // There's probably a more efficient way to do it
927 log_hash_t hash;
928 memcpy(&hash, &(data->hash), sizeof(hash));
929 const std::pair<log_hash_t, int> key(hash, data->author);
930 if (lastTSs[key] != nullptr) {
931 timespec ts1;
932 memcpy(&ts1, lastTSs[key], sizeof(timespec));
933 timespec ts2;
934 memcpy(&ts2, &data->ts, sizeof(timespec));
935 // TODO might want to filter excessively high outliers, which are usually caused
936 // by the thread being inactive.
937 hists[key].push_back(deltaMs(&ts1, &ts2));
938 }
939 lastTSs[key] = &(data->ts);
940 ++entry;
941 break;
942 }
943 case EVENT_HISTOGRAM_FLUSH:
944 body.appendFormat("Histograms:\n");
945 for (auto const &hist : hists) {
946 body.appendFormat("Histogram %X - ", (int)hist.first.first);
947 handleAuthor(HistogramEntry(entry), &body);
948 drawHistogram(&body, hist.second);
949 }
950 hists.clear();
951 lastTSs.clear();
952 ++entry;
953 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800954 case EVENT_END_FMT:
955 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800956 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800957 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800958 case EVENT_RESERVED:
959 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800960 body.appendFormat("warning: unexpected event %d", entry->type);
961 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800962 break;
963 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700964
965 if (!body.isEmpty()) {
966 dumpLine(timestamp, body);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800967 // deferredTimestamp = false;
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700968 }
969 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800970 // if (deferredTimestamp) {
971 // dumpLine(timestamp, body);
972 // }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800973}
974
Nicolas Roulet40a44982017-02-03 13:39:57 -0800975void NBLog::Reader::dump(int fd, size_t indent)
976{
977 // get a snapshot, dump it
978 std::unique_ptr<Snapshot> snap = getSnapshot();
979 dump(fd, indent, *snap);
980}
981
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800982void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700983{
984 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700985 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700986 } else {
987 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
988 }
989 body.clear();
990}
991
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800992bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
993{
Glenn Kasten481fb672013-09-30 14:39:28 -0700994 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800995}
996
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800997void NBLog::appendTimestamp(String8 *body, const void *data) {
998 struct timespec ts;
999 memcpy(&ts, data, sizeof(struct timespec));
1000 body->appendFormat("[%d.%03d]", (int) ts.tv_sec,
1001 (int) (ts.tv_nsec / 1000000));
1002}
1003
1004void NBLog::appendInt(String8 *body, const void *data) {
1005 int x = *((int*) data);
1006 body->appendFormat("<%d>", x);
1007}
1008
1009void NBLog::appendFloat(String8 *body, const void *data) {
1010 float f;
1011 memcpy(&f, data, sizeof(float));
1012 body->appendFormat("<%f>", f);
1013}
1014
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001015void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001016 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001017 char * name = &((char*) data)[sizeof(pid_t)];
1018 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001019}
1020
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001021NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001022 String8 *timestamp,
1023 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001024 // log timestamp
1025 struct timespec ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001026 timestamp->clear();
1027 timestamp->appendFormat("[%d.%03d]", (int) ts.tv_sec,
1028 (int) (ts.tv_nsec / 1000000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001029
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001030 // log unique hash
1031 log_hash_t hash = fmtEntry.hash();
1032 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1033 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1034
Nicolas Roulet40a44982017-02-03 13:39:57 -08001035 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001036 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001037
1038 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001039 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001040
1041 const char* fmt = fmtEntry.formatString();
1042 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001043
1044 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1045 if (fmt[fmt_offset] != '%') {
1046 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1047 continue;
1048 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001049 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001050 if (fmt[++fmt_offset] == '%') {
1051 body->append("%");
1052 continue;
1053 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001054 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001055 if (fmt_offset == fmt_length) {
1056 continue;
1057 }
1058
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001059 NBLog::Event event = (NBLog::Event) arg->type;
1060 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001061
1062 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001063
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001064 if (event == EVENT_END_FMT) {
1065 break;
1066 }
1067
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001068 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001069 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001070 switch(fmt[fmt_offset])
1071 {
1072 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001073 ALOGW_IF(event != EVENT_STRING,
1074 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001075 body->append((const char*) datum, length);
1076 break;
1077
1078 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001079 ALOGW_IF(event != EVENT_TIMESTAMP,
1080 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001081 appendTimestamp(body, datum);
1082 break;
1083
1084 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001085 ALOGW_IF(event != EVENT_INTEGER,
1086 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001087 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001088 break;
1089
1090 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001091 ALOGW_IF(event != EVENT_FLOAT,
1092 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001093 appendFloat(body, datum);
1094 break;
1095
1096 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001097 ALOGW_IF(event != EVENT_PID,
1098 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001099 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001100 break;
1101
1102 default:
1103 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1104 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001105 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001106 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001107 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1108 ++arg;
1109 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001110}
1111
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001112static int widthOf(int x) {
1113 int width = 0;
1114 while (x > 0) {
1115 ++width;
1116 x /= 10;
1117 }
1118 return width;
1119}
1120
1121static std::map<int, int> buildBuckets(const std::vector<int> &samples) {
1122 // TODO allow buckets of variable resolution
1123 std::map<int, int> buckets;
1124 for (int x : samples) {
1125 ++buckets[x];
1126 }
1127 return buckets;
1128}
1129
1130// TODO put this function in separate file. Make it return a std::string instead of modifying body
1131void NBLog::Reader::drawHistogram(String8 *body, const std::vector<int> &samples, int maxHeight) {
1132 std::map<int, int> buckets = buildBuckets(samples);
1133 // TODO add option for log scale
1134 static const char *underscores = "________________";
1135 static const char *spaces = " ";
1136
1137 auto it = buckets.begin();
1138 int maxLabel = it->first;
1139 int maxVal = it->second;
1140 while (++it != buckets.end()) {
1141 if (it->first > maxLabel) {
1142 maxLabel = it->first;
1143 }
1144 if (it->second > maxVal) {
1145 maxVal = it->second;
1146 }
1147 }
1148 int height = maxVal;
1149 int leftPadding = widthOf(maxVal);
1150 int colWidth = std::max(std::max(widthOf(maxLabel) + 1, 3), leftPadding + 2);
1151 int scalingFactor = 1;
1152 if (height > maxHeight) {
1153 scalingFactor = (height + maxHeight) / maxHeight;
1154 height /= scalingFactor;
1155 }
1156 body->appendFormat("\n");
1157 body->appendFormat("%*s", leftPadding + 2, " ");
1158 for (auto const &x : buckets)
1159 {
1160 body->appendFormat("[%*d]", colWidth - 2, x.second);
1161 }
1162 body->appendFormat("\n");
1163 for (int row = height * scalingFactor; row > 0; row -= scalingFactor)
1164 {
1165 body->appendFormat("%*d|", leftPadding, row);
1166 for (auto const &x : buckets) {
1167 body->appendFormat("%.*s%s", colWidth - 2,
1168 (row == scalingFactor) ? underscores : spaces,
1169 x.second < row ? ((row == scalingFactor) ? "__" : " ") : "[]");
1170 }
1171 body->appendFormat("\n");
1172 }
1173 body->appendFormat("%*s", leftPadding + 1, " ");
1174 for (auto const &x : buckets)
1175 {
1176 body->appendFormat("%*d", colWidth, x.first);
1177 }
1178 body->appendFormat("\n");
1179}
1180
Nicolas Roulet40a44982017-02-03 13:39:57 -08001181// ---------------------------------------------------------------------------
1182
1183NBLog::Merger::Merger(const void *shared, size_t size):
1184 mBuffer(NULL),
1185 mShared((Shared *) shared),
1186 mFifo(mShared != NULL ?
1187 new audio_utils_fifo(size, sizeof(uint8_t),
1188 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1189 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1190 {}
1191
1192void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
1193 mNamedReaders.push_back(reader);
1194}
1195
1196// items placed in priority queue during merge
1197// composed by a timestamp and the index of the snapshot where the timestamp came from
1198struct MergeItem
1199{
1200 struct timespec ts;
1201 int index;
1202 MergeItem(struct timespec ts, int index): ts(ts), index(index) {}
1203};
1204
1205// operators needed for priority queue in merge
1206bool operator>(const struct timespec &t1, const struct timespec &t2) {
1207 return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1208}
1209
1210bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
1211 return i1.ts > i2.ts ||
1212 (i1.ts.tv_sec == i2.ts.tv_sec && i1.ts.tv_nsec == i2.ts.tv_nsec && i1.index > i2.index);
1213}
1214
1215// Merge registered readers, sorted by timestamp
1216void NBLog::Merger::merge() {
1217 int nLogs = mNamedReaders.size();
1218 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001219 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001220 for (int i = 0; i < nLogs; ++i) {
1221 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001222 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001223 }
1224 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001225 // TODO custom heap implementation could allow to update top, improving performance
1226 // for bursty buffers
1227 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1228 for (int i = 0; i < nLogs; ++i)
1229 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001230 if (offsets[i] != snapshots[i]->end()) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001231 timespec ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001232 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001233 }
1234 }
1235
1236 while (!timestamps.empty()) {
1237 // find minimum timestamp
1238 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001239 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001240 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1241 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001242 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001243 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001244 if (offsets[index] != snapshots[index]->end()) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001245 timespec ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001246 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001247 }
1248 }
1249}
1250
1251const std::vector<NBLog::NamedReader> *NBLog::Merger::getNamedReaders() const {
1252 return &mNamedReaders;
1253}
1254
1255NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1256 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1257
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001258void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1259 int author = entry.author();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001260 const char* name = (*mNamedReaders)[author].name();
1261 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001262}
1263
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001264NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1265 : mMerger(merger),
1266 mTimeoutUs(0) {}
1267
1268NBLog::MergeThread::~MergeThread() {
1269 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1270 requestExit();
1271 setTimeoutUs(0);
1272 join();
1273}
1274
1275bool NBLog::MergeThread::threadLoop() {
1276 bool doMerge;
1277 {
1278 AutoMutex _l(mMutex);
1279 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1280 // If it's positive, wait kThreadSleepPeriodUs and then merge
1281 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1282 mCond.waitRelative(mMutex, waitTime);
1283 doMerge = mTimeoutUs > 0;
1284 mTimeoutUs -= kThreadSleepPeriodUs;
1285 }
1286 if (doMerge) {
1287 mMerger.merge();
1288 }
1289 return true;
1290}
1291
1292void NBLog::MergeThread::wakeup() {
1293 setTimeoutUs(kThreadWakeupPeriodUs);
1294}
1295
1296void NBLog::MergeThread::setTimeoutUs(int time) {
1297 AutoMutex _l(mMutex);
1298 mTimeoutUs = time;
1299 mCond.signal();
1300}
1301
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001302} // namespace android