blob: 18c0b50547047c836a76d535591a2884e378cb21 [file] [log] [blame]
Ray Essick3938dc62016-11-01 08:56:56 -07001/*
Ray Essick2e9c63b2017-03-29 15:16:44 -07002 * Copyright (C) 2017 The Android Open Source Project
Ray Essick3938dc62016-11-01 08:56:56 -07003 *
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
Ray Essick3938dc62016-11-01 08:56:56 -070017//#define LOG_NDEBUG 0
Ray Essickf27e9872019-12-07 06:28:46 -080018#define LOG_TAG "MediaMetricsService"
Ray Essick3938dc62016-11-01 08:56:56 -070019#include <utils/Log.h>
20
Ray Essick40e8e5e2019-12-05 20:19:40 -080021#include "MediaMetricsService.h"
Andy Hungc9b6f8b2021-07-08 10:17:55 -070022#include "ValidateId.h"
Robert Shih2e15aed2021-03-16 18:30:35 -070023#include "iface_statsd.h"
Ray Essick3938dc62016-11-01 08:56:56 -070024
Andy Hung17dbaf22019-10-11 14:06:31 -070025#include <pwd.h> //getpwuid
26
Andy Hung54c73ce2021-03-30 14:25:54 -070027#include <android-base/stringprintf.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070028#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080029#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070030#include <binder/IPCThreadState.h> // get calling uid
Andy Hung49ca44e2020-11-10 22:14:58 -080031#include <binder/IServiceManager.h> // checkCallingPermission
Andy Hung17dbaf22019-10-11 14:06:31 -070032#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070033#include <mediautils/MemoryLeakTrackUtil.h>
34#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070035#include <private/android_filesystem_config.h> // UID
Robert Shih2e15aed2021-03-16 18:30:35 -070036#include <statslog.h>
37
38#include <set>
Andy Hung17dbaf22019-10-11 14:06:31 -070039
Ray Essick3938dc62016-11-01 08:56:56 -070040namespace android {
41
Andy Hung54c73ce2021-03-30 14:25:54 -070042using base::StringPrintf;
Andy Hung3ab1b322020-05-18 10:47:31 -070043using mediametrics::Item;
44using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080045
Ray Essickf65f4212017-08-31 11:41:19 -070046// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070047// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070048// count: hard limit of # records
49// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070050//
Andy Hung17dbaf22019-10-11 14:06:31 -070051static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070052// 2019/6: average daily per device is currently 375-ish;
53// setting this to 2000 is large enough to catch most devices
54// we'll lose some data on very very media-active devices, but only for
55// the gms collection; statsd will have already covered those for us.
56// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070057static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070058
59// max we expire in a single call, to constrain how long we hold the
60// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070061static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070062
63// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070064
Andy Hung55aaf522019-12-03 15:07:51 -080065/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080066nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080067{
68 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
69}
70
Andy Hunga85efab2019-12-23 11:41:29 -080071/* static */
72bool MediaMetricsService::useUidForPackage(
73 const std::string& package, const std::string& installer)
74{
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070075 // NOLINTBEGIN(bugprone-branch-clone)
Andy Hung3ab1b322020-05-18 10:47:31 -070076 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080077 return false; // not of form 'com.whatever...'; assume internal and ok
78 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
79 return false; // android.* packages are assumed fine
80 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
81 return false; // from play store
82 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
83 return false; // some google source
84 } else if (strcmp(installer.c_str(), "preload") == 0) {
85 return false; // preloads
86 } else {
87 return true; // we're not sure where it came from, use uid only.
88 }
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070089 // NOLINTEND(bugprone-branch-clone)
Andy Hunga85efab2019-12-23 11:41:29 -080090}
91
Andy Hungce9b6632020-04-28 20:15:17 -070092/* static */
93std::pair<std::string, int64_t>
94MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
95 // Meyer's singleton, initialized on first access.
96 // mUidInfo is locked internally.
97 static mediautils::UidInfo uidInfo;
98
99 // get info.
100 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
101 if (useUidForPackage(info.package, info.installer)) {
102 return { std::to_string(uid), /* versionCode */ 0 };
103 } else {
104 return { info.package, info.versionCode };
105 }
106}
107
Ray Essickf27e9872019-12-07 06:28:46 -0800108MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700109 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700110 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800111 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700112{
113 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700114}
115
Ray Essickf27e9872019-12-07 06:28:46 -0800116MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700117{
118 ALOGD("%s", __func__);
119 // the class destructor clears anyhow, but we enforce clearing items first.
Andy Hungc14ee142021-03-10 16:39:02 -0800120 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700121 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700122}
123
Ray Essickf27e9872019-12-07 06:28:46 -0800124status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800125{
Andy Hung55aaf522019-12-03 15:07:51 -0800126 // calling PID is 0 for one-way calls.
127 const pid_t pid = IPCThreadState::self()->getCallingPid();
128 const pid_t pid_given = item->getPid();
129 const uid_t uid = IPCThreadState::self()->getCallingUid();
130 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800131
Andy Hung55aaf522019-12-03 15:07:51 -0800132 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
133 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800134
Andy Hung17dbaf22019-10-11 14:06:31 -0700135 bool isTrusted;
136 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800137 case AID_AUDIOSERVER:
138 case AID_BLUETOOTH:
139 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700140 case AID_DRM:
141 case AID_MEDIA:
142 case AID_MEDIA_CODEC:
143 case AID_MEDIA_EX:
144 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800145 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800146 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700147 // trusted source, only override default values
148 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800149 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800150 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700151 }
Andy Hung55aaf522019-12-03 15:07:51 -0800152 if (pid_given == (pid_t)-1) {
153 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700154 }
155 break;
156 default:
157 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800158 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700159 item->setUid(uid);
160 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800161 }
162
Andy Hunga85efab2019-12-23 11:41:29 -0800163 // Overwrite package name and version if the caller was untrusted or empty
164 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700165 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700166 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700167 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700168 item->setPkgName(pkgName);
169 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700170 }
171
Andy Hung5d3f2d12020-03-04 19:55:03 -0800172 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700173 "sanitized pkg version: %lld",
174 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800175 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700176 uid_given, item->getUid(),
177 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700178 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700179
180 mItemsSubmitted++;
181
182 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700183 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700184 if (release) delete item;
185 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700186 }
187
Ray Essick92d23b42018-01-29 12:10:30 -0800188 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700189 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700190
Ray Essick92d23b42018-01-29 12:10:30 -0800191 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700192 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700193 if (release) delete item;
194 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700195 }
Ray Essick92d23b42018-01-29 12:10:30 -0800196
Andy Hung55aaf522019-12-03 15:07:51 -0800197 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700198 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800199 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800200 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800201 // For consistency and correlation with other logging mechanisms
202 // we use REALTIME here.
203 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800204 item->setTimestamp(now);
205 }
206
Andy Hung82a074b2019-12-03 14:16:45 -0800207 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800208 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800209
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700210 // register log session ids with singleton.
211 if (startsWith(item->getKey(), "metrics.manager")) {
212 std::string logSessionId;
213 if (item->get("logSessionId", &logSessionId)
214 && mediametrics::stringutils::isLogSessionId(logSessionId.c_str())) {
215 mediametrics::ValidateId::get()->registerId(logSessionId);
216 }
217 }
218
Andy Hung06f3aba2019-12-03 16:36:42 -0800219 (void)mAudioAnalytics.submit(sitem, isTrusted);
220
Andy Hung5be90c82021-03-30 14:30:20 -0700221 (void)dump2Statsd(sitem, mStatsdLog); // failure should be logged in function.
Andy Hung82a074b2019-12-03 14:16:45 -0800222 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700223 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700224}
225
Ray Essickf27e9872019-12-07 06:28:46 -0800226status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700227{
Ray Essick3938dc62016-11-01 08:56:56 -0700228 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700229 const std::string result = StringPrintf("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800230 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700231 IPCThreadState::self()->getCallingPid(),
232 IPCThreadState::self()->getCallingUid());
Andy Hung54c73ce2021-03-30 14:25:54 -0700233 write(fd, result.c_str(), result.size());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800234 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700235 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800236
Andy Hung709b91e2020-04-04 14:23:36 -0700237 static const String16 allOption("--all");
238 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700239 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700240 static const String16 helpOption("--help");
241 static const String16 prefixOption("--prefix");
242 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700243 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700244
245 bool all = false;
246 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700247 bool heap = false;
248 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700249 int64_t sinceNs = 0;
250 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700251
Andy Hung709b91e2020-04-04 14:23:36 -0700252 const size_t n = args.size();
253 for (size_t i = 0; i < n; i++) {
254 if (args[i] == allOption) {
255 all = true;
256 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800257 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700258 } else if (args[i] == heapOption) {
259 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800260 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700261 // TODO: consider function area dumping.
262 // dumpsys media.metrics audiotrack,codec
263 // or dumpsys media.metrics audiotrack codec
264
Andy Hung54c73ce2021-03-30 14:25:54 -0700265 static constexpr char result[] =
266 "Recognized parameters:\n"
267 "--all show all records\n"
268 "--clear clear out saved records\n"
269 "--heap show heap usage (top 100)\n"
270 "--help display help\n"
271 "--prefix X process records for component X\n"
272 "--since X X < 0: records from -X seconds in the past\n"
273 " X = 0: ignore\n"
274 " X > 0: records from X seconds since Unix epoch\n"
275 "--unreachable show unreachable memory (leaks)\n";
276 write(fd, result, std::size(result));
Ray Essick35ad27f2017-01-30 14:04:11 -0800277 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700278 } else if (args[i] == prefixOption) {
279 ++i;
280 if (i < n) {
281 prefix = String8(args[i]).string();
282 }
283 } else if (args[i] == sinceOption) {
284 ++i;
285 if (i < n) {
286 String8 value(args[i]);
287 char *endp;
288 const char *p = value.string();
Andy Hung3ab1b322020-05-18 10:47:31 -0700289 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700290 if (endp == p || *endp != '\0' || sec == 0) {
291 sinceNs = 0;
292 } else if (sec < 0) {
293 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
294 } else {
295 sinceNs = sec * NANOS_PER_SECOND;
296 }
297 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700298 } else if (args[i] == unreachableOption) {
299 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800300 }
301 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700302 std::stringstream result;
Andy Hung17dbaf22019-10-11 14:06:31 -0700303 {
304 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800305
Andy Hung17dbaf22019-10-11 14:06:31 -0700306 if (clear) {
Andy Hungc14ee142021-03-10 16:39:02 -0800307 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700308 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700309 mAudioAnalytics.clear();
310 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700311 result << StringPrintf("Dump of the %s process:\n", kServiceName);
Andy Hung709b91e2020-04-04 14:23:36 -0700312 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hung54c73ce2021-03-30 14:25:54 -0700313 result << dumpHeaders(sinceNs, prefixptr);
314 result << dumpQueue(sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700315
316 // TODO: maybe consider a better way of dumping audio analytics info.
317 const int32_t linesToDump = all ? INT32_MAX : 1000;
318 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
Andy Hung54c73ce2021-03-30 14:25:54 -0700319 result << dumpString;
Andy Hung709b91e2020-04-04 14:23:36 -0700320 if (lines == linesToDump) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700321 result << "-- some lines may be truncated --\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700322 }
Andy Hung5be90c82021-03-30 14:30:20 -0700323
Andy Hungf1a23832021-12-13 09:31:55 -0800324 const int32_t heatLinesToDump = all ? INT32_MAX : 20;
325 const auto [ heatDumpString, heatLines] =
326 mAudioAnalytics.dumpHeatMap(heatLinesToDump);
327 result << "\n" << heatDumpString;
328 if (heatLines == heatLinesToDump) {
329 result << "-- some lines may be truncated --\n";
330 }
331
Andy Hungf4eaa462022-03-09 21:53:09 -0800332 const int32_t healthLinesToDump = all ? INT32_MAX : 15;
333 result << "\nHealth Message Log:";
334 const auto [ healthDumpString, healthLines ] =
335 mAudioAnalytics.dumpHealth(healthLinesToDump);
336 result << "\n" << healthDumpString;
337 if (healthLines == healthLinesToDump) {
338 result << "-- some lines may be truncated --\n";
339 }
340
Andy Hung93424642022-08-18 19:20:48 -0700341 const int32_t spatializerLinesToDump = all ? INT32_MAX : 15;
342 result << "\nSpatializer Message Log:";
343 const auto [ spatializerDumpString, spatializerLines ] =
344 mAudioAnalytics.dumpSpatializer(spatializerLinesToDump);
345 result << "\n" << spatializerDumpString;
346 if (spatializerLines == spatializerLinesToDump) {
347 result << "-- some lines may be truncated --\n";
348 }
349
Andy Hungf1a23832021-12-13 09:31:55 -0800350 result << "\nLogSessionId:\n"
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700351 << mediametrics::ValidateId::get()->dump();
352
Andy Hung5be90c82021-03-30 14:30:20 -0700353 // Dump the statsd atoms we sent out.
Andy Hungf1a23832021-12-13 09:31:55 -0800354 result << "\nStatsd atoms:\n"
Andy Hung5be90c82021-03-30 14:30:20 -0700355 << mStatsdLog->dumpToString(" " /* prefix */,
356 all ? STATSD_LOG_LINES_MAX : STATSD_LOG_LINES_DUMP);
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800357 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700358 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700359 const std::string str = result.str();
360 write(fd, str.c_str(), str.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700361
362 // Check heap and unreachable memory outside of lock.
363 if (heap) {
364 dprintf(fd, "\nDumping heap:\n");
365 std::string s = dumpMemoryAddresses(100 /* limit */);
366 write(fd, s.c_str(), s.size());
367 }
368 if (unreachable) {
369 dprintf(fd, "\nDumping unreachable memory:\n");
370 // TODO - should limit be an argument parameter?
371 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
372 write(fd, s.c_str(), s.size());
373 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700374 return NO_ERROR;
375}
376
377// dump headers
Andy Hung54c73ce2021-03-30 14:25:54 -0700378std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800379{
Andy Hung54c73ce2021-03-30 14:25:54 -0700380 std::stringstream result;
Ray Essickf27e9872019-12-07 06:28:46 -0800381 if (mediametrics::Item::isEnabled()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700382 result << "Metrics gathering: enabled\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800383 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700384 result << "Metrics gathering: DISABLED via property\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800385 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700386 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700387 "Since Boot: Submissions: %lld Accepted: %lld\n",
388 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
Andy Hung54c73ce2021-03-30 14:25:54 -0700389 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700390 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
391 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
392 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700393 if (prefix != nullptr) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700394 result << "Restricting to prefix " << prefix << "\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700395 }
396 if (sinceNs != 0) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700397 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800398 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700399 return result.str();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700400}
401
Andy Hung709b91e2020-04-04 14:23:36 -0700402// TODO: should prefix be a set<string>?
Andy Hung54c73ce2021-03-30 14:25:54 -0700403std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800404{
Ray Essick92d23b42018-01-29 12:10:30 -0800405 if (mItems.empty()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700406 return "empty\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700407 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700408 std::stringstream result;
Andy Hung709b91e2020-04-04 14:23:36 -0700409 int slot = 0;
410 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
411 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
412 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700413 }
Andy Hung709b91e2020-04-04 14:23:36 -0700414 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
415 ALOGV("%s: omit '%s', it's not '%s'",
416 __func__, item->getKey().c_str(), prefix);
417 continue;
418 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700419 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
Andy Hung709b91e2020-04-04 14:23:36 -0700420 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700421 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700422 return result.str();
Ray Essick3938dc62016-11-01 08:56:56 -0700423}
424
425//
426// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700427
Ray Essick72a436b2018-06-14 15:08:13 -0700428// if item != NULL, it's the item we just inserted
429// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700430bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800431{
Ray Essick72a436b2018-06-14 15:08:13 -0700432 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800433
Andy Hung17dbaf22019-10-11 14:06:31 -0700434 // check queue size
435 size_t overlimit = 0;
436 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
437 overlimit = mItems.size() - mMaxRecords;
438 if (overlimit > mMaxRecordsExpiredAtOnce) {
439 more = true;
440 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700441 }
442 }
443
Andy Hung17dbaf22019-10-11 14:06:31 -0700444 // check queue times
445 size_t expired = 0;
446 if (!more && mMaxRecordAgeNs > 0) {
447 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
448 // we check one at a time, skip search would be more efficient.
449 size_t i = overlimit;
450 for (; i < mItems.size(); ++i) {
451 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700452 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800453 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800454 break;
455 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700456 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800457 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700458 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700459 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700460 // this represents "one too many"; tell caller there are
461 // more to be reclaimed.
462 more = true;
463 break;
464 }
Ray Essick3938dc62016-11-01 08:56:56 -0700465 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700466 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700467 }
Ray Essick72a436b2018-06-14 15:08:13 -0700468
Andy Hung17dbaf22019-10-11 14:06:31 -0700469 if (const size_t toErase = overlimit + expired;
470 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800471 mItemsDiscardedCount += (int64_t)overlimit;
472 mItemsDiscardedExpire += (int64_t)expired;
473 mItemsDiscarded += (int64_t)toErase;
474 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700475 }
Ray Essick72a436b2018-06-14 15:08:13 -0700476 return more;
477}
478
Ray Essickf27e9872019-12-07 06:28:46 -0800479void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700480{
481 bool more;
482 do {
483 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700484 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700485 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700486 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700487}
488
Ray Essickf27e9872019-12-07 06:28:46 -0800489void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700490{
Andy Hung17dbaf22019-10-11 14:06:31 -0700491 std::lock_guard _l(mLock);
492 // we assume the items are roughly in time order.
493 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700494 if (isPullable(item->getKey())) {
495 registerStatsdCallbacksIfNeeded();
496 mPullableItems[item->getKey()].emplace_back(item);
497 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700498 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700499 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700500 && (!mExpireFuture.valid()
501 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
502 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700503 }
Ray Essick3938dc62016-11-01 08:56:56 -0700504}
505
Andy Hung17dbaf22019-10-11 14:06:31 -0700506/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800507bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800508{
Andy Hung17dbaf22019-10-11 14:06:31 -0700509 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800510 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700511 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800512 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800513 if (startsWith(key, "drm.vendor.")) return true;
Robert Shih27914962023-01-12 21:00:16 +0000514 if (startsWith(key, "mediadrm.")) return true;
515
Edwin Wong8d188352020-02-11 11:59:34 -0800516 // the list of allowedKey uses statsd_handlers
517 // in iface_statsd.cpp as reference
518 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700519 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800520 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700521 "audiopolicy",
522 "audiorecord",
523 "audiothread",
524 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800525 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700526 "codec",
527 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800528 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100529 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700530 "nuplayer",
531 }) {
532 if (key == allowedKey) {
533 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800534 }
535 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700536 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700537 return false;
538}
539
Andy Hung17dbaf22019-10-11 14:06:31 -0700540// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800541bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700542{
543 return false;
544}
545
Robert Shih2e15aed2021-03-16 18:30:35 -0700546void MediaMetricsService::registerStatsdCallbacksIfNeeded()
547{
548 if (mStatsdRegistered.test_and_set()) {
549 return;
550 }
551 auto tag = android::util::MEDIA_DRM_ACTIVITY_INFO;
552 auto cb = MediaMetricsService::pullAtomCallback;
553 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
554}
555
556/* static */
557bool MediaMetricsService::isPullable(const std::string &key)
558{
559 static const std::set<std::string> pullableKeys{
560 "mediadrm",
561 };
562 return pullableKeys.count(key);
563}
564
565/* static */
566std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
567{
568 switch (atomTag) {
569 case android::util::MEDIA_DRM_ACTIVITY_INFO:
570 return "mediadrm";
571 }
572 return {};
573}
574
575/* static */
576AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
577 int32_t atomTag, AStatsEventList* data, void* cookie)
578{
579 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
580 return svc->pullItems(atomTag, data);
581}
582
583AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
584 int32_t atomTag, AStatsEventList* data)
585{
586 const std::string key(atomTagToKey(atomTag));
587 if (key.empty()) {
588 return AStatsManager_PULL_SKIP;
589 }
590 std::lock_guard _l(mLock);
Robert Shih58a37f82021-04-19 10:18:50 -0700591 bool dumped = false;
Robert Shih2e15aed2021-03-16 18:30:35 -0700592 for (auto &item : mPullableItems[key]) {
593 if (const auto sitem = item.lock()) {
Robert Shih58a37f82021-04-19 10:18:50 -0700594 dumped |= dump2Statsd(sitem, data, mStatsdLog);
Robert Shih2e15aed2021-03-16 18:30:35 -0700595 }
596 }
597 mPullableItems[key].clear();
Robert Shih58a37f82021-04-19 10:18:50 -0700598 return dumped ? AStatsManager_PULL_SUCCESS : AStatsManager_PULL_SKIP;
Robert Shih2e15aed2021-03-16 18:30:35 -0700599}
Ray Essick3938dc62016-11-01 08:56:56 -0700600} // namespace android