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