blob: 369c22a849a2cb5a44870c89947f185a4b7ceeff [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// Non-blocking event logger intended for safe communication between processes via shared memory
18
19#ifndef ANDROID_MEDIA_NBLOG_H
20#define ANDROID_MEDIA_NBLOG_H
21
22#include <binder/IMemory.h>
Glenn Kasten535e1612016-12-05 12:19:36 -080023#include <audio_utils/fifo.h>
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080024#include <utils/Mutex.h>
25#include <utils/threads.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080026
Nicolas Roulet40a44982017-02-03 13:39:57 -080027#include <vector>
28
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080029namespace android {
30
Glenn Kasten4e01ef62013-07-11 14:29:59 -070031class String8;
32
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080033class NBLog {
34
35public:
36
37class Writer;
38class Reader;
39
40private:
41
42enum Event {
43 EVENT_RESERVED,
44 EVENT_STRING, // ASCII string, not NUL-terminated
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080045 // TODO: make timestamp optional
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080046 EVENT_TIMESTAMP, // clock_gettime(CLOCK_MONOTONIC)
Nicolas Roulet40a44982017-02-03 13:39:57 -080047 EVENT_INTEGER, // integer value entry
48 EVENT_FLOAT, // floating point value entry
49 EVENT_PID, // process ID and process name
50 EVENT_AUTHOR, // author index (present in merged logs) tracks entry's original log
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080051 EVENT_START_FMT, // logFormat start event: entry includes format string, following
52 // entries contain format arguments
53 EVENT_END_FMT, // end of logFormat argument list
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080054};
55
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080056
57// ---------------------------------------------------------------------------
58// API for handling format entry operations
59
60// a formatted entry has the following structure:
61// * START_FMT entry, containing the format string
62// * author entry of the thread that generated it (optional, present in merged log)
63// * TIMESTAMP entry
64// * format arg1
65// * format arg2
66// * ...
67// * END_FMT entry
68
69class FormatEntry {
70public:
71 // build a Format Entry starting in the given pointer
72 class iterator;
73 explicit FormatEntry(const uint8_t *entry);
74 explicit FormatEntry(const iterator &it);
75
76 // entry representation in memory
77 struct entry {
78 const uint8_t type;
79 const uint8_t length;
80 const uint8_t data[0];
81 };
82
83 // entry tail representation (after data)
84 struct ending {
85 uint8_t length;
86 uint8_t next[0];
87 };
88
89 // entry iterator
90 class iterator {
91 public:
92 iterator(const uint8_t *entry);
93 iterator(const iterator &other);
94
95 // dereference underlying entry
96 const entry& operator*() const;
97 const entry* operator->() const;
98 // advance to next entry
99 iterator& operator++(); // ++i
100 // back to previous entry
101 iterator& operator--(); // --i
102 bool operator!=(const iterator &other) const;
103 int operator-(const iterator &other) const;
104
105 bool hasConsistentLength() const;
106 void copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const;
107 void copyData(uint8_t *dst) const;
108
109 template<typename T>
110 inline const T& payload() {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800111 return *reinterpret_cast<const T *>(ptr + offsetof(entry, data));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800112 }
113
114 private:
115 friend class FormatEntry;
116 const uint8_t *ptr;
117 };
118
119 // Entry's format string
120 const char* formatString() const;
121
122 // Enrty's format string length
123 size_t formatStringLength() const;
124
125 // Format arguments (excluding format string, timestamp and author)
126 iterator args() const;
127
128 // get format entry timestamp
129 timespec timestamp() const;
130
131 // entry's author index (-1 if none present)
132 // a Merger has a vector of Readers, author simply points to the index of the
133 // Reader that originated the entry
134 int author() const;
135
136 // copy entry, adding author before timestamp, returns size of original entry
137 size_t copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const;
138
139 iterator begin() const;
140
141private:
142 // copies ordinary entry from src to dst, and returns length of entry
143 // size_t copyEntry(audio_utils_fifo_writer *dst, const iterator &it);
144 const uint8_t *mEntry;
145};
146
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800147// ---------------------------------------------------------------------------
148
149// representation of a single log entry in private memory
150struct Entry {
151 Entry(Event event, const void *data, size_t length)
152 : mEvent(event), mLength(length), mData(data) { }
153 /*virtual*/ ~Entry() { }
154
155 int readAt(size_t offset) const;
156
157private:
158 friend class Writer;
159 Event mEvent; // event type
Glenn Kasten535e1612016-12-05 12:19:36 -0800160 uint8_t mLength; // length of additional data, 0 <= mLength <= kMaxLength
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800161 const void *mData; // event type-specific data
Glenn Kasten535e1612016-12-05 12:19:36 -0800162 static const size_t kMaxLength = 255;
163public:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800164 // mEvent, mLength, mData[...], duplicate mLength
165 static const size_t kOverhead = sizeof(FormatEntry::entry) + sizeof(FormatEntry::ending);
166 // endind length of previous entry
167 static const size_t kPreviousLengthOffset = - sizeof(FormatEntry::ending) +
168 offsetof(FormatEntry::ending, length);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800169};
170
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800171// representation of a single log entry in shared memory
172// byte[0] mEvent
173// byte[1] mLength
174// byte[2] mData[0]
175// ...
176// byte[2+i] mData[i]
177// ...
178// byte[2+mLength-1] mData[mLength-1]
179// byte[2+mLength] duplicate copy of mLength to permit reverse scan
180// byte[3+mLength] start of next log entry
181
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800182 static void appendInt(String8 *body, const void *data);
183 static void appendFloat(String8 *body, const void *data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800184 static void appendPID(String8 *body, const void *data, size_t length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800185 static void appendTimestamp(String8 *body, const void *data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800186 static size_t fmtEntryLength(const uint8_t *data);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800187
Glenn Kasten535e1612016-12-05 12:19:36 -0800188public:
189
190// Located in shared memory, must be POD.
191// Exactly one process must explicitly call the constructor or use placement new.
192// Since this is a POD, the destructor is empty and unnecessary to call it explicitly.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800193struct Shared {
Glenn Kasten535e1612016-12-05 12:19:36 -0800194 Shared() /* mRear initialized via default constructor */ { }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800195 /*virtual*/ ~Shared() { }
196
Glenn Kasten535e1612016-12-05 12:19:36 -0800197 audio_utils_fifo_index mRear; // index one byte past the end of most recent Entry
198 char mBuffer[0]; // circular buffer for entries
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800199};
200
201public:
202
203// ---------------------------------------------------------------------------
204
205// FIXME Timeline was intended to wrap Writer and Reader, but isn't actually used yet.
206// For now it is just a namespace for sharedSize().
207class Timeline : public RefBase {
208public:
209#if 0
210 Timeline(size_t size, void *shared = NULL);
211 virtual ~Timeline();
212#endif
213
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700214 // Input parameter 'size' is the desired size of the timeline in byte units.
215 // Returns the size rounded up to a power-of-2, plus the constant size overhead for indices.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800216 static size_t sharedSize(size_t size);
217
218#if 0
219private:
220 friend class Writer;
221 friend class Reader;
222
223 const size_t mSize; // circular buffer size in bytes, must be a power of 2
224 bool mOwn; // whether I own the memory at mShared
225 Shared* const mShared; // pointer to shared memory
226#endif
227};
228
229// ---------------------------------------------------------------------------
230
231// Writer is thread-safe with respect to Reader, but not with respect to multiple threads
232// calling Writer methods. If you need multi-thread safety for writing, use LockedWriter.
233class Writer : public RefBase {
234public:
235 Writer(); // dummy nop implementation without shared memory
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700236
237 // Input parameter 'size' is the desired size of the timeline in byte units.
238 // The size of the shared memory must be at least Timeline::sharedSize(size).
Glenn Kasten535e1612016-12-05 12:19:36 -0800239 Writer(void *shared, size_t size);
240 Writer(const sp<IMemory>& iMemory, size_t size);
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700241
Glenn Kasten535e1612016-12-05 12:19:36 -0800242 virtual ~Writer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800243
244 virtual void log(const char *string);
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800245 virtual void logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800246 virtual void logvf(const char *fmt, va_list ap);
247 virtual void logTimestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800248 virtual void logTimestamp(const struct timespec &ts);
249 virtual void logInteger(const int x);
250 virtual void logFloat(const float x);
251 virtual void logPID();
252 virtual void logFormat(const char *fmt, ...);
253 virtual void logVFormat(const char *fmt, va_list ap);
254 virtual void logStart(const char *fmt);
255 virtual void logEnd();
256
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800257
258 virtual bool isEnabled() const;
259
260 // return value for all of these is the previous isEnabled()
261 virtual bool setEnabled(bool enabled); // but won't enable if no shared memory
262 bool enable() { return setEnabled(true); }
263 bool disable() { return setEnabled(false); }
264
265 sp<IMemory> getIMemory() const { return mIMemory; }
266
267private:
Glenn Kasten535e1612016-12-05 12:19:36 -0800268 // 0 <= length <= kMaxLength
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800269 void log(Event event, const void *data, size_t length);
270 void log(const Entry *entry, bool trusted = false);
271
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800272 Shared* const mShared; // raw pointer to shared memory
Glenn Kasten535e1612016-12-05 12:19:36 -0800273 sp<IMemory> mIMemory; // ref-counted version, initialized in constructor and then const
274 audio_utils_fifo * const mFifo; // FIFO itself,
275 // non-NULL unless constructor fails
276 audio_utils_fifo_writer * const mFifoWriter; // used to write to FIFO,
277 // non-NULL unless dummy constructor used
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800278 bool mEnabled; // whether to actually log
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800279
280 // cached pid and process name to use in %p format specifier
281 // total tag length is mPidTagSize and process name is not zero terminated
282 char *mPidTag;
283 size_t mPidTagSize;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800284};
285
286// ---------------------------------------------------------------------------
287
288// Similar to Writer, but safe for multiple threads to call concurrently
289class LockedWriter : public Writer {
290public:
291 LockedWriter();
Glenn Kasten535e1612016-12-05 12:19:36 -0800292 LockedWriter(void *shared, size_t size);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800293
294 virtual void log(const char *string);
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800295 virtual void logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800296 virtual void logvf(const char *fmt, va_list ap);
297 virtual void logTimestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800298 virtual void logTimestamp(const struct timespec &ts);
299 virtual void logInteger(const int x);
300 virtual void logFloat(const float x);
301 virtual void logPID();
302 virtual void logStart(const char *fmt);
303 virtual void logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800304
305 virtual bool isEnabled() const;
306 virtual bool setEnabled(bool enabled);
307
308private:
309 mutable Mutex mLock;
310};
311
312// ---------------------------------------------------------------------------
313
314class Reader : public RefBase {
315public:
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700316
Nicolas Roulet40a44982017-02-03 13:39:57 -0800317 // A snapshot of a readers buffer
318 class Snapshot {
319 public:
320 Snapshot() : mData(NULL), mAvail(0), mLost(0) {}
321
322 Snapshot(size_t bufferSize) : mData(new uint8_t[bufferSize]) {}
323
324 ~Snapshot() { delete[] mData; }
325
326 // copy of the buffer
327 const uint8_t *data() const { return mData; }
328
329 // amount of data available (given by audio_utils_fifo_reader)
330 size_t available() const { return mAvail; }
331
332 // amount of data lost (given by audio_utils_fifo_reader)
333 size_t lost() const { return mLost; }
334
335 private:
336 friend class Reader;
337 const uint8_t *mData;
338 size_t mAvail;
339 size_t mLost;
340 };
341
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700342 // Input parameter 'size' is the desired size of the timeline in byte units.
343 // The size of the shared memory must be at least Timeline::sharedSize(size).
Glenn Kasten535e1612016-12-05 12:19:36 -0800344 Reader(const void *shared, size_t size);
345 Reader(const sp<IMemory>& iMemory, size_t size);
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700346
Glenn Kasten535e1612016-12-05 12:19:36 -0800347 virtual ~Reader();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800348
Nicolas Roulet40a44982017-02-03 13:39:57 -0800349 // get snapshot of readers fifo buffer, effectively consuming the buffer
350 std::unique_ptr<Snapshot> getSnapshot();
351 // dump a particular snapshot of the reader
352 void dump(int fd, size_t indent, Snapshot & snap);
353 // dump the current content of the reader's buffer
354 void dump(int fd, size_t indent = 0);
355 bool isIMemory(const sp<IMemory>& iMemory) const;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800356
357private:
Glenn Kasten535e1612016-12-05 12:19:36 -0800358 /*const*/ Shared* const mShared; // raw pointer to shared memory, actually const but not
359 // declared as const because audio_utils_fifo() constructor
360 sp<IMemory> mIMemory; // ref-counted version, assigned only in constructor
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700361 int mFd; // file descriptor
362 int mIndent; // indentation level
Glenn Kasten535e1612016-12-05 12:19:36 -0800363 audio_utils_fifo * const mFifo; // FIFO itself,
364 // non-NULL unless constructor fails
365 audio_utils_fifo_reader * const mFifoReader; // used to read from FIFO,
366 // non-NULL unless constructor fails
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700367
368 void dumpLine(const String8& timestamp, String8& body);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800369
370 FormatEntry::iterator handleFormat(const FormatEntry &fmtEntry,
371 String8 *timestamp,
372 String8 *body);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800373 // dummy method for handling absent author entry
374 virtual size_t handleAuthor(const FormatEntry &fmtEntry, String8 *body) { return 0; }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800375
376 static const size_t kSquashTimestamp = 5; // squash this many or more adjacent timestamps
377};
378
Nicolas Roulet40a44982017-02-03 13:39:57 -0800379// Wrapper for a reader with a name. Contains a pointer to the reader and a pointer to the name
380class NamedReader {
381public:
382 NamedReader() { mName[0] = '\0'; } // for Vector
383 NamedReader(const sp<NBLog::Reader>& reader, const char *name) :
384 mReader(reader)
385 { strlcpy(mName, name, sizeof(mName)); }
386 ~NamedReader() { }
387 const sp<NBLog::Reader>& reader() const { return mReader; }
388 const char* name() const { return mName; }
389
390private:
391 sp<NBLog::Reader> mReader;
392 static const size_t kMaxName = 32;
393 char mName[kMaxName];
394};
395
396// ---------------------------------------------------------------------------
397
398class Merger : public RefBase {
399public:
400 Merger(const void *shared, size_t size);
401
402 virtual ~Merger() {}
403
404 void addReader(const NamedReader &reader);
405 // TODO add removeReader
406 void merge();
407 const std::vector<NamedReader> *getNamedReaders() const;
408private:
409 // vector of the readers the merger is supposed to merge from.
410 // every reader reads from a writer's buffer
411 std::vector<NamedReader> mNamedReaders;
412 uint8_t *mBuffer;
413 Shared * const mShared;
414 std::unique_ptr<audio_utils_fifo> mFifo;
415 std::unique_ptr<audio_utils_fifo_writer> mFifoWriter;
416
417 static struct timespec getTimestamp(const uint8_t *data);
418};
419
420class MergeReader : public Reader {
421public:
422 MergeReader(const void *shared, size_t size, Merger &merger);
423private:
424 const std::vector<NamedReader> *mNamedReaders;
425 // handle author entry by looking up the author's name and appending it to the body
426 // returns number of bytes read from fmtEntry
427 size_t handleAuthor(const FormatEntry &fmtEntry, String8 *body);
428};
429
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800430// MergeThread is a thread that contains a Merger. It works as a retriggerable one-shot:
431// when triggered, it awakes for a lapse of time, during which it periodically merges; if
432// retriggered, the timeout is reset.
433// The thread is triggered on AudioFlinger binder activity.
434class MergeThread : public Thread {
435public:
436 MergeThread(Merger &merger);
437 virtual ~MergeThread() override;
438
439 // Reset timeout and activate thread to merge periodically if it's idle
440 void wakeup();
441
442 // Set timeout period until the merging thread goes idle again
443 void setTimeoutUs(int time);
444
445private:
446 virtual bool threadLoop() override;
447
448 // the merger who actually does the work of merging the logs
449 Merger& mMerger;
450
451 // mutex for the condition variable
452 Mutex mMutex;
453
454 // condition variable to activate merging on timeout >= 0
455 Condition mCond;
456
457 // time left until the thread blocks again (in microseconds)
458 int mTimeoutUs;
459
460 // merging period when the thread is awake
461 static const int kThreadSleepPeriodUs = 1000000 /*1s*/;
462
463 // initial timeout value when triggered
464 static const int kThreadWakeupPeriodUs = 3000000 /*3s*/;
465};
466
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800467}; // class NBLog
468
469} // namespace android
470
471#endif // ANDROID_MEDIA_NBLOG_H