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