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 #pragma once
18 
19 #include "config/ConfigKey.h"
20 #include "config/ConfigListener.h"
21 #include "packages/PackageInfoListener.h"
22 #include "stats_util.h"
23 
24 #include <gtest/gtest_prod.h>
25 #include <stdio.h>
26 #include <utils/RefBase.h>
27 #include <utils/String16.h>
28 
29 #include <list>
30 #include <mutex>
31 #include <set>
32 #include <string>
33 #include <unordered_map>
34 
35 using namespace android;
36 using namespace std;
37 
38 using android::util::ProtoOutputStream;
39 
40 namespace android {
41 namespace os {
42 namespace statsd {
43 
44 struct AppData {
45     int64_t versionCode;
46     string versionString;
47     string installer;
48     bool deleted;
49 
50     // Empty constructor needed for unordered map.
AppDataAppData51     AppData() {
52     }
53 
AppDataAppData54     AppData(const int64_t v, const string& versionString, const string& installer)
55         : versionCode(v), versionString(versionString), installer(installer), deleted(false){};
56 };
57 
58 // When calling appendUidMap, we retrieve all the ChangeRecords since the last
59 // timestamp we called appendUidMap for this configuration key.
60 struct ChangeRecord {
61     const bool deletion;
62     const int64_t timestampNs;
63     const string package;
64     const int32_t uid;
65     const int64_t version;
66     const int64_t prevVersion;
67     const string versionString;
68     const string prevVersionString;
69 
ChangeRecordChangeRecord70     ChangeRecord(const bool isDeletion, const int64_t timestampNs, const string& package,
71                  const int32_t uid, const int64_t version, const string versionString,
72                  const int64_t prevVersion, const string prevVersionString)
73         : deletion(isDeletion),
74           timestampNs(timestampNs),
75           package(package),
76           uid(uid),
77           version(version),
78           prevVersion(prevVersion),
79           versionString(versionString),
80           prevVersionString(prevVersionString) {
81     }
82 };
83 
84 const unsigned int kBytesChangeRecord = sizeof(struct ChangeRecord);
85 
86 // UidMap keeps track of what the corresponding app name (APK name) and version code for every uid
87 // at any given moment. This map must be updated by StatsCompanionService.
88 class UidMap : public virtual android::RefBase {
89 public:
90     UidMap();
91     ~UidMap();
92     static const std::map<std::string, uint32_t> sAidToUidMapping;
93 
94     static sp<UidMap> getInstance();
95     /*
96      * All three inputs must be the same size, and the jth element in each array refers to the same
97      * tuple, ie. uid[j] corresponds to packageName[j] with versionCode[j].
98      */
99     void updateMap(const int64_t& timestamp, const vector<int32_t>& uid,
100                    const vector<int64_t>& versionCode, const vector<String16>& versionString,
101                    const vector<String16>& packageName, const vector<String16>& installer);
102 
103     void updateApp(const int64_t& timestamp, const String16& packageName, const int32_t& uid,
104                    const int64_t& versionCode, const String16& versionString,
105                    const String16& installer);
106     void removeApp(const int64_t& timestamp, const String16& packageName, const int32_t& uid);
107 
108     // Returns true if the given uid contains the specified app (eg. com.google.android.gms).
109     bool hasApp(int uid, const string& packageName) const;
110 
111     // Returns the app names from uid.
112     std::set<string> getAppNamesFromUid(const int32_t& uid, bool returnNormalized) const;
113 
114     int64_t getAppVersion(int uid, const string& packageName) const;
115 
116     // Helper for debugging contents of this uid map. Can be triggered with:
117     // adb shell cmd stats print-uid-map
118     void printUidMap(int outFd) const;
119 
120     // Command for indicating to the map that StatsLogProcessor should be notified if an app is
121     // updated. This allows metric producers and managers to distinguish when the same uid or app
122     // represents a different version of an app.
123     void setListener(wp<PackageInfoListener> listener);
124 
125     // Informs uid map that a config is added/updated. Used for keeping mConfigKeys up to date.
126     void OnConfigUpdated(const ConfigKey& key);
127 
128     // Informs uid map that a config is removed. Used for keeping mConfigKeys up to date.
129     void OnConfigRemoved(const ConfigKey& key);
130 
131     void assignIsolatedUid(int isolatedUid, int parentUid);
132     void removeIsolatedUid(int isolatedUid);
133 
134     // Returns the host uid if it exists. Otherwise, returns the same uid that was passed-in.
135     virtual int getHostUidOrSelf(int uid) const;
136 
137     // Gets all snapshots and changes that have occurred since the last output.
138     // If every config key has received a change or snapshot record, then this
139     // record is deleted.
140     void appendUidMap(const int64_t& timestamp, const ConfigKey& key, std::set<string>* str_set,
141                       bool includeVersionStrings, bool includeInstaller,
142                       ProtoOutputStream* proto);
143 
144     // Forces the output to be cleared. We still generate a snapshot based on the current state.
145     // This results in extra data uploaded but helps us reconstruct the uid mapping on the server
146     // in case we lose a previous upload.
147     void clearOutput();
148 
149     // Get currently cached value of memory used by UID map.
150     size_t getBytesUsed() const;
151 
152     virtual std::set<int32_t> getAppUid(const string& package) const;
153 
154     // Write current PackageInfoSnapshot to ProtoOutputStream.
155     // interestingUids: If not empty, only write the package info for these uids. If empty, write
156     //                  package info for all uids.
157     // str_set: if not null, add new string to the set and write str_hash to proto
158     //          if null, write string to proto.
159     void writeUidMapSnapshot(int64_t timestamp, bool includeVersionStrings, bool includeInstaller,
160                              const std::set<int32_t>& interestingUids, std::set<string>* str_set,
161                              ProtoOutputStream* proto);
162 
163 private:
164     std::set<string> getAppNamesFromUidLocked(const int32_t& uid, bool returnNormalized) const;
165     string normalizeAppName(const string& appName) const;
166 
167     void writeUidMapSnapshotLocked(int64_t timestamp, bool includeVersionStrings,
168                                    bool includeInstaller, const std::set<int32_t>& interestingUids,
169                                    std::set<string>* str_set, ProtoOutputStream* proto);
170 
171     mutable mutex mMutex;
172     mutable mutex mIsolatedMutex;
173 
174     struct PairHash {
operatorPairHash175         size_t operator()(std::pair<int, string> p) const noexcept {
176             std::hash<std::string> hash_fn;
177             return hash_fn(std::to_string(p.first) + p.second);
178         }
179     };
180     // Maps uid and package name to application data.
181     std::unordered_map<std::pair<int, string>, AppData, PairHash> mMap;
182 
183     // Maps isolated uid to the parent uid. Any metrics for an isolated uid will instead contribute
184     // to the parent uid.
185     std::unordered_map<int, int> mIsolatedUidMap;
186 
187     // Record the changes that can be provided with the uploads.
188     std::list<ChangeRecord> mChanges;
189 
190     // Store which uid and apps represent deleted ones.
191     std::list<std::pair<int, string>> mDeletedApps;
192 
193     // Notify StatsLogProcessor if there's an upgrade/removal in any app.
194     wp<PackageInfoListener> mSubscriber;
195 
196     // Mapping of config keys we're aware of to the epoch time they last received an update. This
197     // lets us know it's safe to delete events older than the oldest update. The value is nanosec.
198     // Value of -1 denotes this config key has never received an upload.
199     std::unordered_map<ConfigKey, int64_t> mLastUpdatePerConfigKey;
200 
201     // Returns the minimum value from mConfigKeys.
202     int64_t getMinimumTimestampNs();
203 
204     // If our current used bytes is above the limit, then we clear out the earliest snapshot. If
205     // there are no more snapshots, then we clear out the earliest delta. We repeat the deletions
206     // until the memory consumed by mOutput is below the specified limit.
207     void ensureBytesUsedBelowLimit();
208 
209     // Override used for testing the max memory allowed by uid map. 0 means we use the value
210     // specified in StatsdStats.h with the rest of the guardrails.
211     size_t maxBytesOverride = 0;
212 
213     // Cache the size of mOutput;
214     size_t mBytesUsed;
215 
216     // Allows unit-test to access private methods.
217     FRIEND_TEST(UidMapTest, TestClearingOutput);
218     FRIEND_TEST(UidMapTest, TestRemovedAppRetained);
219     FRIEND_TEST(UidMapTest, TestRemovedAppOverGuardrail);
220     FRIEND_TEST(UidMapTest, TestOutputIncludesAtLeastOneSnapshot);
221     FRIEND_TEST(UidMapTest, TestMemoryComputed);
222     FRIEND_TEST(UidMapTest, TestMemoryGuardrail);
223 };
224 
225 }  // namespace statsd
226 }  // namespace os
227 }  // namespace android
228