1 /*
2  * Copyright (C) 2018 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 
20 #include <memory>
21 #include <stddef.h>
22 #include <string>
23 #include <unordered_set>
24 
25 #include <audio_utils/fifo.h>
26 #include <binder/IMemory.h>
27 #include <media/nblog/Entry.h>
28 #include <media/nblog/Events.h>
29 #include <media/nblog/Reader.h>
30 #include <media/nblog/Timeline.h>
31 #include <utils/Log.h>
32 #include <utils/String8.h>
33 
34 namespace android {
35 namespace NBLog {
36 
Reader(const void * shared,size_t size,const std::string & name)37 Reader::Reader(const void *shared, size_t size, const std::string &name)
38     : mName(name),
39       mShared((/*const*/ Shared *) shared), /*mIMemory*/
40       mFifo(mShared != NULL ?
41         new audio_utils_fifo(size, sizeof(uint8_t),
42             mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
43       mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
44 {
45 }
46 
Reader(const sp<IMemory> & iMemory,size_t size,const std::string & name)47 Reader::Reader(const sp<IMemory>& iMemory, size_t size, const std::string &name)
48     : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size, name)
49 {
50     mIMemory = iMemory;
51 }
52 
~Reader()53 Reader::~Reader()
54 {
55     delete mFifoReader;
56     delete mFifo;
57 }
58 
59 // Copies content of a Reader FIFO into its Snapshot
60 // The Snapshot has the same raw data, but represented as a sequence of entries
61 // and an EntryIterator making it possible to process the data.
getSnapshot(bool flush)62 std::unique_ptr<Snapshot> Reader::getSnapshot(bool flush)
63 {
64     if (mFifoReader == NULL) {
65         return std::unique_ptr<Snapshot>(new Snapshot());
66     }
67 
68     // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
69     // reader index. The index is incremented after handling corruption, to after the last complete
70     // entry of the buffer
71     size_t lost = 0;
72     audio_utils_iovec iovec[2];
73     const size_t capacity = mFifo->capacity();
74     ssize_t availToRead;
75     // A call to audio_utils_fifo_reader::obtain() places the read pointer one buffer length
76     // before the writer's pointer (since mFifoReader was constructed with flush=false). The
77     // do while loop is an attempt to read all of the FIFO's contents regardless of how behind
78     // the reader is with respect to the writer. However, the following scheduling sequence is
79     // possible and can lead to a starvation situation:
80     // - Writer T1 writes, overrun with respect to Reader T2
81     // - T2 calls obtain() and gets EOVERFLOW, T2 ptr placed one buffer size behind T1 ptr
82     // - T1 write, overrun
83     // - T2 obtain(), EOVERFLOW (and so on...)
84     // To address this issue, we limit the number of tries for the reader to catch up with
85     // the writer.
86     int tries = 0;
87     size_t lostTemp;
88     do {
89         availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lostTemp);
90         lost += lostTemp;
91     } while (availToRead < 0 || ++tries <= kMaxObtainTries);
92 
93     if (availToRead <= 0) {
94         ALOGW_IF(availToRead < 0, "NBLog Reader %s failed to catch up with Writer", mName.c_str());
95         return std::unique_ptr<Snapshot>(new Snapshot());
96     }
97 
98     // Change to #if 1 for debugging. This statement is useful for checking buffer fullness levels
99     // (as seen by reader) and how much data was lost. If you find that the fullness level is
100     // getting close to full, or that data loss is happening to often, then you should
101     // probably try some of the following:
102     // - log less data
103     // - log less often
104     // - increase the initial shared memory allocation for the buffer
105 #if 0
106     ALOGD("getSnapshot name=%s, availToRead=%zd, capacity=%zu, fullness=%.3f, lost=%zu",
107             name().c_str(), availToRead, capacity, (double)availToRead / (double)capacity, lost);
108 #endif
109     std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
110     memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
111     if (iovec[1].mLength > 0) {
112         memcpy(snapshot->mData + (iovec[0].mLength),
113                 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
114     }
115 
116     // Handle corrupted buffer
117     // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
118     // (due to incomplete format entry). But even if the end format entry is incomplete,
119     // it ends in a complete entry (which is not an FMT_END). So is safe to traverse backwards.
120     // TODO: handle client corruption (in the middle of a buffer)
121 
122     const uint8_t *back = snapshot->mData + availToRead;
123     const uint8_t *front = snapshot->mData;
124 
125     // Find last FMT_END. <back> is sitting on an entry which might be the middle of a FormatEntry.
126     // We go backwards until we find an EVENT_FMT_END.
127     const uint8_t *lastEnd = findLastValidEntry(front, back, invalidEndTypes);
128     if (lastEnd == nullptr) {
129         snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
130     } else {
131         // end of snapshot points to after last FMT_END entry
132         snapshot->mEnd = EntryIterator(lastEnd).next();
133         // find first FMT_START
134         const uint8_t *firstStart = nullptr;
135         const uint8_t *firstStartTmp = snapshot->mEnd;
136         while ((firstStartTmp = findLastValidEntry(front, firstStartTmp, invalidBeginTypes))
137                 != nullptr) {
138             firstStart = firstStartTmp;
139         }
140         // firstStart is null if no FMT_START entry was found before lastEnd
141         if (firstStart == nullptr) {
142             snapshot->mBegin = snapshot->mEnd;
143         } else {
144             snapshot->mBegin = EntryIterator(firstStart);
145         }
146     }
147 
148     // advance fifo reader index to after last entry read.
149     if (flush) {
150         mFifoReader->release(snapshot->mEnd - front);
151     }
152 
153     snapshot->mLost = lost;
154     return snapshot;
155 }
156 
isIMemory(const sp<IMemory> & iMemory) const157 bool Reader::isIMemory(const sp<IMemory>& iMemory) const
158 {
159     return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
160 }
161 
162 // We make a set of the invalid types rather than the valid types when aligning
163 // Snapshot EntryIterators to valid entries during log corruption checking.
164 // This is done in order to avoid the maintenance overhead of adding a new Event
165 // type to the two sets below whenever a new Event type is created, as it is
166 // very likely that new types added will be valid types.
167 // Currently, invalidBeginTypes and invalidEndTypes are used to handle the special
168 // case of a Format Entry, which consists of a variable number of simple log entries.
169 // If a new Event is added that consists of a variable number of simple log entries,
170 // then these sets need to be updated.
171 
172 // We want the beginning of a Snapshot to point to an entry that is not in
173 // the middle of a formatted entry and not an FMT_END.
174 const std::unordered_set<Event> Reader::invalidBeginTypes {
175     EVENT_FMT_AUTHOR,
176     EVENT_FMT_END,
177     EVENT_FMT_FLOAT,
178     EVENT_FMT_HASH,
179     EVENT_FMT_INTEGER,
180     EVENT_FMT_PID,
181     EVENT_FMT_STRING,
182     EVENT_FMT_TIMESTAMP,
183 };
184 
185 // We want the end of a Snapshot to point to an entry that is not in
186 // the middle of a formatted entry and not a FMT_START.
187 const std::unordered_set<Event> Reader::invalidEndTypes {
188     EVENT_FMT_AUTHOR,
189     EVENT_FMT_FLOAT,
190     EVENT_FMT_HASH,
191     EVENT_FMT_INTEGER,
192     EVENT_FMT_PID,
193     EVENT_FMT_START,
194     EVENT_FMT_STRING,
195     EVENT_FMT_TIMESTAMP,
196 };
197 
findLastValidEntry(const uint8_t * front,const uint8_t * back,const std::unordered_set<Event> & invalidTypes)198 const uint8_t *Reader::findLastValidEntry(const uint8_t *front, const uint8_t *back,
199                                           const std::unordered_set<Event> &invalidTypes) {
200     if (front == nullptr || back == nullptr) {
201         return nullptr;
202     }
203     while (back + Entry::kPreviousLengthOffset >= front) {
204         const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
205         const Event type = (const Event)prev[offsetof(entry, type)];
206         if (prev < front
207                 || prev + prev[offsetof(entry, length)] + Entry::kOverhead != back
208                 || type <= EVENT_RESERVED || type >= EVENT_UPPER_BOUND) {
209             // prev points to an out of limits or inconsistent entry
210             return nullptr;
211         }
212         // if invalidTypes does not contain the type, then the type is valid.
213         if (invalidTypes.find(type) == invalidTypes.end()) {
214             return prev;
215         }
216         back = prev;
217     }
218     return nullptr; // no entry found
219 }
220 
221 // TODO for future compatibility, would prefer to have a dump() go to string, and then go
222 // to fd only when invoked through binder.
dump(int fd,size_t indent)223 void DumpReader::dump(int fd, size_t indent)
224 {
225     if (fd < 0) return;
226     std::unique_ptr<Snapshot> snapshot = getSnapshot(false /*flush*/);
227     if (snapshot == nullptr) {
228         return;
229     }
230     String8 timestamp, body;
231 
232     // TODO all logged types should have a printable format.
233     // TODO can we make the printing generic?
234     for (EntryIterator it = snapshot->begin(); it != snapshot->end(); ++it) {
235         switch (it->type) {
236         case EVENT_FMT_START:
237             it = handleFormat(FormatEntry(it), &timestamp, &body);
238             break;
239         case EVENT_LATENCY: {
240             const double latencyMs = it.payload<double>();
241             body.appendFormat("EVENT_LATENCY,%.3f", latencyMs);
242         } break;
243         case EVENT_OVERRUN: {
244             const int64_t ts = it.payload<int64_t>();
245             body.appendFormat("EVENT_OVERRUN,%lld", static_cast<long long>(ts));
246         } break;
247         case EVENT_THREAD_INFO: {
248             const thread_info_t info = it.payload<thread_info_t>();
249             body.appendFormat("EVENT_THREAD_INFO,%d,%s", static_cast<int>(info.id),
250                     threadTypeToString(info.type));
251         } break;
252         case EVENT_UNDERRUN: {
253             const int64_t ts = it.payload<int64_t>();
254             body.appendFormat("EVENT_UNDERRUN,%lld", static_cast<long long>(ts));
255         } break;
256         case EVENT_WARMUP_TIME: {
257             const double timeMs = it.payload<double>();
258             body.appendFormat("EVENT_WARMUP_TIME,%.3f", timeMs);
259         } break;
260         case EVENT_WORK_TIME: {
261             const int64_t monotonicNs = it.payload<int64_t>();
262             body.appendFormat("EVENT_WORK_TIME,%lld", static_cast<long long>(monotonicNs));
263         } break;
264         case EVENT_THREAD_PARAMS: {
265             const thread_params_t params = it.payload<thread_params_t>();
266             body.appendFormat("EVENT_THREAD_PARAMS,%zu,%u", params.frameCount, params.sampleRate);
267         } break;
268         case EVENT_FMT_END:
269         case EVENT_RESERVED:
270         case EVENT_UPPER_BOUND:
271             body.appendFormat("warning: unexpected event %d", it->type);
272             break;
273         default:
274             break;
275         }
276         if (!body.isEmpty()) {
277             dprintf(fd, "%.*s%s %s\n", (int)indent, "", timestamp.string(), body.string());
278             body.clear();
279         }
280         timestamp.clear();
281     }
282 }
283 
handleFormat(const FormatEntry & fmtEntry,String8 * timestamp,String8 * body)284 EntryIterator DumpReader::handleFormat(const FormatEntry &fmtEntry,
285         String8 *timestamp, String8 *body)
286 {
287     String8 timestampLocal;
288     String8 bodyLocal;
289     if (timestamp == nullptr) {
290         timestamp = &timestampLocal;
291     }
292     if (body == nullptr) {
293         body = &bodyLocal;
294     }
295 
296     // log timestamp
297     const int64_t ts = fmtEntry.timestamp();
298     timestamp->clear();
299     timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
300                     (int) ((ts / (1000 * 1000)) % 1000));
301 
302     // log unique hash
303     log_hash_t hash = fmtEntry.hash();
304     // print only lower 16bit of hash as hex and line as int to reduce spam in the log
305     body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
306 
307     // log author (if present)
308     handleAuthor(fmtEntry, body);
309 
310     // log string
311     EntryIterator arg = fmtEntry.args();
312 
313     const char* fmt = fmtEntry.formatString();
314     size_t fmt_length = fmtEntry.formatStringLength();
315 
316     for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
317         if (fmt[fmt_offset] != '%') {
318             body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
319             continue;
320         }
321         // case "%%""
322         if (fmt[++fmt_offset] == '%') {
323             body->append("%");
324             continue;
325         }
326         // case "%\0"
327         if (fmt_offset == fmt_length) {
328             continue;
329         }
330 
331         Event event = (Event) arg->type;
332         size_t length = arg->length;
333 
334         // TODO check length for event type is correct
335 
336         if (event == EVENT_FMT_END) {
337             break;
338         }
339 
340         // TODO: implement more complex formatting such as %.3f
341         const uint8_t *datum = arg->data; // pointer to the current event args
342         switch(fmt[fmt_offset])
343         {
344         case 's': // string
345             ALOGW_IF(event != EVENT_FMT_STRING,
346                 "NBLog Reader incompatible event for string specifier: %d", event);
347             body->append((const char*) datum, length);
348             break;
349 
350         case 't': // timestamp
351             ALOGW_IF(event != EVENT_FMT_TIMESTAMP,
352                 "NBLog Reader incompatible event for timestamp specifier: %d", event);
353             appendTimestamp(body, datum);
354             break;
355 
356         case 'd': // integer
357             ALOGW_IF(event != EVENT_FMT_INTEGER,
358                 "NBLog Reader incompatible event for integer specifier: %d", event);
359             appendInt(body, datum);
360             break;
361 
362         case 'f': // float
363             ALOGW_IF(event != EVENT_FMT_FLOAT,
364                 "NBLog Reader incompatible event for float specifier: %d", event);
365             appendFloat(body, datum);
366             break;
367 
368         case 'p': // pid
369             ALOGW_IF(event != EVENT_FMT_PID,
370                 "NBLog Reader incompatible event for pid specifier: %d", event);
371             appendPID(body, datum, length);
372             break;
373 
374         default:
375             ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
376         }
377         ++arg;
378     }
379     ALOGW_IF(arg->type != EVENT_FMT_END, "Expected end of format, got %d", arg->type);
380     return arg;
381 }
382 
appendInt(String8 * body,const void * data)383 void DumpReader::appendInt(String8 *body, const void *data)
384 {
385     if (body == nullptr || data == nullptr) {
386         return;
387     }
388     //int x = *((int*) data);
389     int x;
390     memcpy(&x, data, sizeof(x));
391     body->appendFormat("<%d>", x);
392 }
393 
appendFloat(String8 * body,const void * data)394 void DumpReader::appendFloat(String8 *body, const void *data)
395 {
396     if (body == nullptr || data == nullptr) {
397         return;
398     }
399     float f;
400     memcpy(&f, data, sizeof(f));
401     body->appendFormat("<%f>", f);
402 }
403 
appendPID(String8 * body,const void * data,size_t length)404 void DumpReader::appendPID(String8 *body, const void* data, size_t length)
405 {
406     if (body == nullptr || data == nullptr) {
407         return;
408     }
409     pid_t id = *((pid_t*) data);
410     char * name = &((char*) data)[sizeof(pid_t)];
411     body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
412 }
413 
appendTimestamp(String8 * body,const void * data)414 void DumpReader::appendTimestamp(String8 *body, const void *data)
415 {
416     if (body == nullptr || data == nullptr) {
417         return;
418     }
419     int64_t ts;
420     memcpy(&ts, data, sizeof(ts));
421     body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
422                     (int) ((ts / (1000 * 1000)) % 1000));
423 }
424 
bufferDump(const uint8_t * buffer,size_t size)425 String8 DumpReader::bufferDump(const uint8_t *buffer, size_t size)
426 {
427     String8 str;
428     if (buffer == nullptr) {
429         return str;
430     }
431     str.append("[ ");
432     for(size_t i = 0; i < size; i++) {
433         str.appendFormat("%d ", buffer[i]);
434     }
435     str.append("]");
436     return str;
437 }
438 
bufferDump(const EntryIterator & it)439 String8 DumpReader::bufferDump(const EntryIterator &it)
440 {
441     return bufferDump(it, it->length + Entry::kOverhead);
442 }
443 
444 }   // namespace NBLog
445 }   // namespace android
446