1 /*
2 * Copyright (C) 2017 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_NDEBUG 0
18 #define LOG_TAG "MediaMetricsService"
19 #include <utils/Log.h>
20
21 #include "MediaMetricsService.h"
22 #include "iface_statsd.h"
23
24 #include <pwd.h> //getpwuid
25
26 #include <android-base/stringprintf.h>
27 #include <android/content/pm/IPackageManagerNative.h> // package info
28 #include <audio_utils/clock.h> // clock conversions
29 #include <binder/IPCThreadState.h> // get calling uid
30 #include <binder/IServiceManager.h> // checkCallingPermission
31 #include <cutils/properties.h> // for property_get
32 #include <mediautils/MemoryLeakTrackUtil.h>
33 #include <memunreachable/memunreachable.h>
34 #include <private/android_filesystem_config.h> // UID
35 #include <statslog.h>
36
37 #include <set>
38
39 namespace android {
40
41 using base::StringPrintf;
42 using mediametrics::Item;
43 using mediametrics::startsWith;
44
45 // individual records kept in memory: age or count
46 // age: <= 28 hours (1 1/6 days)
47 // count: hard limit of # records
48 // (0 for either of these disables that threshold)
49 //
50 static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
51 // 2019/6: average daily per device is currently 375-ish;
52 // setting this to 2000 is large enough to catch most devices
53 // we'll lose some data on very very media-active devices, but only for
54 // the gms collection; statsd will have already covered those for us.
55 // This also retains enough information to help with bugreports
56 static constexpr size_t kMaxRecords = 2000;
57
58 // max we expire in a single call, to constrain how long we hold the
59 // mutex, which also constrains how long a client might wait.
60 static constexpr size_t kMaxExpiredAtOnce = 50;
61
62 // TODO: need to look at tuning kMaxRecords and friends for low-memory devices
63
64 /* static */
roundTime(nsecs_t timeNs)65 nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
66 {
67 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
68 }
69
70 /* static */
useUidForPackage(const std::string & package,const std::string & installer)71 bool MediaMetricsService::useUidForPackage(
72 const std::string& package, const std::string& installer)
73 {
74 if (strchr(package.c_str(), '.') == nullptr) {
75 return false; // not of form 'com.whatever...'; assume internal and ok
76 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
77 return false; // android.* packages are assumed fine
78 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
79 return false; // from play store
80 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
81 return false; // some google source
82 } else if (strcmp(installer.c_str(), "preload") == 0) {
83 return false; // preloads
84 } else {
85 return true; // we're not sure where it came from, use uid only.
86 }
87 }
88
89 /* static */
90 std::pair<std::string, int64_t>
getSanitizedPackageNameAndVersionCode(uid_t uid)91 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
92 // Meyer's singleton, initialized on first access.
93 // mUidInfo is locked internally.
94 static mediautils::UidInfo uidInfo;
95
96 // get info.
97 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
98 if (useUidForPackage(info.package, info.installer)) {
99 return { std::to_string(uid), /* versionCode */ 0 };
100 } else {
101 return { info.package, info.versionCode };
102 }
103 }
104
MediaMetricsService()105 MediaMetricsService::MediaMetricsService()
106 : mMaxRecords(kMaxRecords),
107 mMaxRecordAgeNs(kMaxRecordAgeNs),
108 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
109 {
110 ALOGD("%s", __func__);
111 }
112
~MediaMetricsService()113 MediaMetricsService::~MediaMetricsService()
114 {
115 ALOGD("%s", __func__);
116 // the class destructor clears anyhow, but we enforce clearing items first.
117 mItemsDiscarded += (int64_t)mItems.size();
118 mItems.clear();
119 }
120
submitInternal(mediametrics::Item * item,bool release)121 status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
122 {
123 // calling PID is 0 for one-way calls.
124 const pid_t pid = IPCThreadState::self()->getCallingPid();
125 const pid_t pid_given = item->getPid();
126 const uid_t uid = IPCThreadState::self()->getCallingUid();
127 const uid_t uid_given = item->getUid();
128
129 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
130 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
131
132 bool isTrusted;
133 switch (uid) {
134 case AID_AUDIOSERVER:
135 case AID_BLUETOOTH:
136 case AID_CAMERA:
137 case AID_DRM:
138 case AID_MEDIA:
139 case AID_MEDIA_CODEC:
140 case AID_MEDIA_EX:
141 case AID_MEDIA_DRM:
142 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
143 case AID_SYSTEM:
144 // trusted source, only override default values
145 isTrusted = true;
146 if (uid_given == (uid_t)-1) {
147 item->setUid(uid);
148 }
149 if (pid_given == (pid_t)-1) {
150 item->setPid(pid); // if one-way then this is 0.
151 }
152 break;
153 default:
154 isTrusted = false;
155 item->setPid(pid); // always use calling pid, if one-way then this is 0.
156 item->setUid(uid);
157 break;
158 }
159
160 // Overwrite package name and version if the caller was untrusted or empty
161 if (!isTrusted || item->getPkgName().empty()) {
162 const uid_t uidItem = item->getUid();
163 const auto [ pkgName, version ] =
164 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
165 item->setPkgName(pkgName);
166 item->setPkgVersionCode(version);
167 }
168
169 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
170 "sanitized pkg version: %lld",
171 __func__,
172 (int)isTrusted,
173 uid_given, item->getUid(),
174 item->getPkgName().c_str(),
175 (long long)item->getPkgVersionCode());
176
177 mItemsSubmitted++;
178
179 // validate the record; we discard if we don't like it
180 if (isContentValid(item, isTrusted) == false) {
181 if (release) delete item;
182 return PERMISSION_DENIED;
183 }
184
185 // XXX: if we have a sessionid in the new record, look to make
186 // sure it doesn't appear in the finalized list.
187
188 if (item->count() == 0) {
189 ALOGV("%s: dropping empty record...", __func__);
190 if (release) delete item;
191 return BAD_VALUE;
192 }
193
194 if (!isTrusted || item->getTimestamp() == 0) {
195 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
196 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
197 //
198 // For consistency and correlation with other logging mechanisms
199 // we use REALTIME here.
200 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
201 item->setTimestamp(now);
202 }
203
204 // now attach either the item or its dup to a const shared pointer
205 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
206
207 (void)mAudioAnalytics.submit(sitem, isTrusted);
208
209 (void)dump2Statsd(sitem, mStatsdLog); // failure should be logged in function.
210 saveItem(sitem);
211 return NO_ERROR;
212 }
213
dump(int fd,const Vector<String16> & args)214 status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
215 {
216 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
217 const std::string result = StringPrintf("Permission Denial: "
218 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
219 IPCThreadState::self()->getCallingPid(),
220 IPCThreadState::self()->getCallingUid());
221 write(fd, result.c_str(), result.size());
222 return NO_ERROR;
223 }
224
225 static const String16 allOption("--all");
226 static const String16 clearOption("--clear");
227 static const String16 heapOption("--heap");
228 static const String16 helpOption("--help");
229 static const String16 prefixOption("--prefix");
230 static const String16 sinceOption("--since");
231 static const String16 unreachableOption("--unreachable");
232
233 bool all = false;
234 bool clear = false;
235 bool heap = false;
236 bool unreachable = false;
237 int64_t sinceNs = 0;
238 std::string prefix;
239
240 const size_t n = args.size();
241 for (size_t i = 0; i < n; i++) {
242 if (args[i] == allOption) {
243 all = true;
244 } else if (args[i] == clearOption) {
245 clear = true;
246 } else if (args[i] == heapOption) {
247 heap = true;
248 } else if (args[i] == helpOption) {
249 // TODO: consider function area dumping.
250 // dumpsys media.metrics audiotrack,codec
251 // or dumpsys media.metrics audiotrack codec
252
253 static constexpr char result[] =
254 "Recognized parameters:\n"
255 "--all show all records\n"
256 "--clear clear out saved records\n"
257 "--heap show heap usage (top 100)\n"
258 "--help display help\n"
259 "--prefix X process records for component X\n"
260 "--since X X < 0: records from -X seconds in the past\n"
261 " X = 0: ignore\n"
262 " X > 0: records from X seconds since Unix epoch\n"
263 "--unreachable show unreachable memory (leaks)\n";
264 write(fd, result, std::size(result));
265 return NO_ERROR;
266 } else if (args[i] == prefixOption) {
267 ++i;
268 if (i < n) {
269 prefix = String8(args[i]).string();
270 }
271 } else if (args[i] == sinceOption) {
272 ++i;
273 if (i < n) {
274 String8 value(args[i]);
275 char *endp;
276 const char *p = value.string();
277 const auto sec = (int64_t)strtoll(p, &endp, 10);
278 if (endp == p || *endp != '\0' || sec == 0) {
279 sinceNs = 0;
280 } else if (sec < 0) {
281 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
282 } else {
283 sinceNs = sec * NANOS_PER_SECOND;
284 }
285 }
286 } else if (args[i] == unreachableOption) {
287 unreachable = true;
288 }
289 }
290 std::stringstream result;
291 {
292 std::lock_guard _l(mLock);
293
294 if (clear) {
295 mItemsDiscarded += (int64_t)mItems.size();
296 mItems.clear();
297 mAudioAnalytics.clear();
298 } else {
299 result << StringPrintf("Dump of the %s process:\n", kServiceName);
300 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
301 result << dumpHeaders(sinceNs, prefixptr);
302 result << dumpQueue(sinceNs, prefixptr);
303
304 // TODO: maybe consider a better way of dumping audio analytics info.
305 const int32_t linesToDump = all ? INT32_MAX : 1000;
306 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
307 result << dumpString;
308 if (lines == linesToDump) {
309 result << "-- some lines may be truncated --\n";
310 }
311
312 // Dump the statsd atoms we sent out.
313 result << "Statsd atoms:\n"
314 << mStatsdLog->dumpToString(" " /* prefix */,
315 all ? STATSD_LOG_LINES_MAX : STATSD_LOG_LINES_DUMP);
316 }
317 }
318 const std::string str = result.str();
319 write(fd, str.c_str(), str.size());
320
321 // Check heap and unreachable memory outside of lock.
322 if (heap) {
323 dprintf(fd, "\nDumping heap:\n");
324 std::string s = dumpMemoryAddresses(100 /* limit */);
325 write(fd, s.c_str(), s.size());
326 }
327 if (unreachable) {
328 dprintf(fd, "\nDumping unreachable memory:\n");
329 // TODO - should limit be an argument parameter?
330 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
331 write(fd, s.c_str(), s.size());
332 }
333 return NO_ERROR;
334 }
335
336 // dump headers
dumpHeaders(int64_t sinceNs,const char * prefix)337 std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
338 {
339 std::stringstream result;
340 if (mediametrics::Item::isEnabled()) {
341 result << "Metrics gathering: enabled\n";
342 } else {
343 result << "Metrics gathering: DISABLED via property\n";
344 }
345 result << StringPrintf(
346 "Since Boot: Submissions: %lld Accepted: %lld\n",
347 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
348 result << StringPrintf(
349 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
350 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
351 (long long)mItemsDiscardedExpire);
352 if (prefix != nullptr) {
353 result << "Restricting to prefix " << prefix << "\n";
354 }
355 if (sinceNs != 0) {
356 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
357 }
358 return result.str();
359 }
360
361 // TODO: should prefix be a set<string>?
dumpQueue(int64_t sinceNs,const char * prefix)362 std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
363 {
364 if (mItems.empty()) {
365 return "empty\n";
366 }
367 std::stringstream result;
368 int slot = 0;
369 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
370 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
371 continue;
372 }
373 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
374 ALOGV("%s: omit '%s', it's not '%s'",
375 __func__, item->getKey().c_str(), prefix);
376 continue;
377 }
378 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
379 slot++;
380 }
381 return result.str();
382 }
383
384 //
385 // Our Cheap in-core, non-persistent records management.
386
387 // if item != NULL, it's the item we just inserted
388 // true == more items eligible to be recovered
expirations(const std::shared_ptr<const mediametrics::Item> & item)389 bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
390 {
391 bool more = false;
392
393 // check queue size
394 size_t overlimit = 0;
395 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
396 overlimit = mItems.size() - mMaxRecords;
397 if (overlimit > mMaxRecordsExpiredAtOnce) {
398 more = true;
399 overlimit = mMaxRecordsExpiredAtOnce;
400 }
401 }
402
403 // check queue times
404 size_t expired = 0;
405 if (!more && mMaxRecordAgeNs > 0) {
406 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
407 // we check one at a time, skip search would be more efficient.
408 size_t i = overlimit;
409 for (; i < mItems.size(); ++i) {
410 auto &oitem = mItems[i];
411 nsecs_t when = oitem->getTimestamp();
412 if (oitem.get() == item.get()) {
413 break;
414 }
415 if (now > when && (now - when) <= mMaxRecordAgeNs) {
416 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
417 }
418 if (i >= mMaxRecordsExpiredAtOnce) {
419 // this represents "one too many"; tell caller there are
420 // more to be reclaimed.
421 more = true;
422 break;
423 }
424 }
425 expired = i - overlimit;
426 }
427
428 if (const size_t toErase = overlimit + expired;
429 toErase > 0) {
430 mItemsDiscardedCount += (int64_t)overlimit;
431 mItemsDiscardedExpire += (int64_t)expired;
432 mItemsDiscarded += (int64_t)toErase;
433 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
434 }
435 return more;
436 }
437
processExpirations()438 void MediaMetricsService::processExpirations()
439 {
440 bool more;
441 do {
442 sleep(1);
443 std::lock_guard _l(mLock);
444 more = expirations(nullptr);
445 } while (more);
446 }
447
saveItem(const std::shared_ptr<const mediametrics::Item> & item)448 void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
449 {
450 std::lock_guard _l(mLock);
451 // we assume the items are roughly in time order.
452 mItems.emplace_back(item);
453 if (isPullable(item->getKey())) {
454 registerStatsdCallbacksIfNeeded();
455 mPullableItems[item->getKey()].emplace_back(item);
456 }
457 ++mItemsFinalized;
458 if (expirations(item)
459 && (!mExpireFuture.valid()
460 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
461 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
462 }
463 }
464
465 /* static */
isContentValid(const mediametrics::Item * item,bool isTrusted)466 bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
467 {
468 if (isTrusted) return true;
469 // untrusted uids can only send us a limited set of keys
470 const std::string &key = item->getKey();
471 if (startsWith(key, "audio.")) return true;
472 if (startsWith(key, "drm.vendor.")) return true;
473 // the list of allowedKey uses statsd_handlers
474 // in iface_statsd.cpp as reference
475 // drmmanager is from a trusted uid, therefore not needed here
476 for (const char *allowedKey : {
477 // legacy audio
478 "audiopolicy",
479 "audiorecord",
480 "audiothread",
481 "audiotrack",
482 // other media
483 "codec",
484 "extractor",
485 "mediadrm",
486 "mediaparser",
487 "nuplayer",
488 }) {
489 if (key == allowedKey) {
490 return true;
491 }
492 }
493 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
494 return false;
495 }
496
497 // are we rate limited, normally false
isRateLimited(mediametrics::Item *) const498 bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
499 {
500 return false;
501 }
502
registerStatsdCallbacksIfNeeded()503 void MediaMetricsService::registerStatsdCallbacksIfNeeded()
504 {
505 if (mStatsdRegistered.test_and_set()) {
506 return;
507 }
508 auto tag = android::util::MEDIA_DRM_ACTIVITY_INFO;
509 auto cb = MediaMetricsService::pullAtomCallback;
510 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
511 }
512
513 /* static */
isPullable(const std::string & key)514 bool MediaMetricsService::isPullable(const std::string &key)
515 {
516 static const std::set<std::string> pullableKeys{
517 "mediadrm",
518 };
519 return pullableKeys.count(key);
520 }
521
522 /* static */
atomTagToKey(int32_t atomTag)523 std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
524 {
525 switch (atomTag) {
526 case android::util::MEDIA_DRM_ACTIVITY_INFO:
527 return "mediadrm";
528 }
529 return {};
530 }
531
532 /* static */
pullAtomCallback(int32_t atomTag,AStatsEventList * data,void * cookie)533 AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
534 int32_t atomTag, AStatsEventList* data, void* cookie)
535 {
536 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
537 return svc->pullItems(atomTag, data);
538 }
539
pullItems(int32_t atomTag,AStatsEventList * data)540 AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
541 int32_t atomTag, AStatsEventList* data)
542 {
543 const std::string key(atomTagToKey(atomTag));
544 if (key.empty()) {
545 return AStatsManager_PULL_SKIP;
546 }
547 std::lock_guard _l(mLock);
548 bool dumped = false;
549 for (auto &item : mPullableItems[key]) {
550 if (const auto sitem = item.lock()) {
551 dumped |= dump2Statsd(sitem, data, mStatsdLog);
552 }
553 }
554 mPullableItems[key].clear();
555 return dumped ? AStatsManager_PULL_SUCCESS : AStatsManager_PULL_SKIP;
556 }
557 } // namespace android
558