blob: 48d0073425a8264c1f87179635e469a463e4ea49 [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 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
Svet Ganov8455ba22019-01-02 13:05:56 -080017package com.android.server.appop;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080018
Svet Ganovaf189e32019-02-15 18:45:29 -080019import static android.app.AppOpsManager.MAX_PRIORITY_UID_STATE;
20import static android.app.AppOpsManager.MIN_PRIORITY_UID_STATE;
21import static android.app.AppOpsManager.OP_FLAGS_ALL;
Svet Ganov8455ba22019-01-02 13:05:56 -080022import static android.app.AppOpsManager.OP_NONE;
Philip P. Moltmanndde07852019-01-25 16:42:36 -080023import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Hai Zhang2b98fb32018-09-21 15:18:46 -070024import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
25import static android.app.AppOpsManager.UID_STATE_CACHED;
26import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
27import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
Amith Yamasania0a30a12019-01-22 11:38:06 -080028import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION;
Svet Ganovaf189e32019-02-15 18:45:29 -080029import static android.app.AppOpsManager.UID_STATE_MAX_LAST_NON_RESTRICTED;
Hai Zhang2b98fb32018-09-21 15:18:46 -070030import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
31import static android.app.AppOpsManager.UID_STATE_TOP;
Eugene Suslae4ee2c22018-11-05 12:23:30 -080032import static android.app.AppOpsManager.modeToName;
33import static android.app.AppOpsManager.opToName;
Svet Ganovaf189e32019-02-15 18:45:29 -080034import static android.app.AppOpsManager.resolveFirstUnrestrictedUidState;
Hai Zhang2b98fb32018-09-21 15:18:46 -070035
Philip P. Moltmanne683f192017-06-23 14:05:04 -070036import android.Manifest;
Svet Ganovad0a49b2018-10-29 10:07:08 -070037import android.annotation.NonNull;
38import android.annotation.Nullable;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070039import android.app.ActivityManager;
40import android.app.ActivityThread;
41import android.app.AppGlobals;
42import android.app.AppOpsManager;
Svet Ganov8455ba22019-01-02 13:05:56 -080043import android.app.AppOpsManager.HistoricalOps;
Svet Ganov23c88db2019-01-22 20:38:11 -080044import android.app.AppOpsManager.HistoricalOpsRequest;
Svet Ganovaf189e32019-02-15 18:45:29 -080045import android.app.AppOpsManager.Mode;
46import android.app.AppOpsManager.OpEntry;
47import android.app.AppOpsManager.OpFlags;
Dianne Hackbornd5254412018-05-11 18:02:58 -070048import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070049import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080050import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070051import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070052import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080053import android.content.Intent;
54import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070055import android.content.pm.ApplicationInfo;
56import android.content.pm.IPackageManager;
57import android.content.pm.PackageManager;
58import android.content.pm.PackageManagerInternal;
59import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070060import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070061import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070062import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070063import android.os.AsyncTask;
64import android.os.Binder;
65import android.os.Bundle;
66import android.os.Handler;
67import android.os.IBinder;
68import android.os.Process;
Svet Ganov8455ba22019-01-02 13:05:56 -080069import android.os.RemoteCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070070import android.os.RemoteException;
71import android.os.ResultReceiver;
72import android.os.ServiceManager;
73import android.os.ShellCallback;
74import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070075import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070076import android.os.UserHandle;
77import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070078import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070079import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070080import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070081import android.util.ArrayMap;
82import android.util.ArraySet;
83import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070084import android.util.KeyValueListParser;
Svet Ganovaf189e32019-02-15 18:45:29 -080085import android.util.LongSparseArray;
86import android.util.LongSparseLongArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070087import android.util.Slog;
88import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070089import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070090import android.util.SparseIntArray;
91import android.util.TimeUtils;
92import android.util.Xml;
93
Todd Kennedy556efba2018-11-15 07:43:55 -080094import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070095import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080096import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070097import com.android.internal.app.IAppOpsCallback;
Svet Ganovb3d2ae22018-12-17 22:06:15 -080098import com.android.internal.app.IAppOpsNotedCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070099import com.android.internal.app.IAppOpsService;
100import com.android.internal.os.Zygote;
101import com.android.internal.util.ArrayUtils;
102import com.android.internal.util.DumpUtils;
103import com.android.internal.util.FastXmlSerializer;
104import com.android.internal.util.Preconditions;
105import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800106import com.android.internal.util.function.pooled.PooledLambda;
Svet Ganov8455ba22019-01-02 13:05:56 -0800107import com.android.server.LocalServices;
108import com.android.server.LockGuard;
Philip P. Moltmanndde07852019-01-25 16:42:36 -0800109
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700110import libcore.util.EmptyArray;
111
112import org.xmlpull.v1.XmlPullParser;
113import org.xmlpull.v1.XmlPullParserException;
114import org.xmlpull.v1.XmlSerializer;
115
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800116import java.io.File;
117import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800118import java.io.FileInputStream;
119import java.io.FileNotFoundException;
120import java.io.FileOutputStream;
121import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800122import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100123import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700124import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800125import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700126import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700127import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700128import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800129import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800130import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800131import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700132import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800133
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800134public class AppOpsService extends IAppOpsService.Stub {
135 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800136 static final boolean DEBUG = false;
137
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700138 private static final int NO_VERSION = -1;
139 /** Increment by one every time and add the corresponding upgrade logic in
140 * {@link #upgradeLocked(int)} below. The first version was 1 */
141 private static final int CURRENT_VERSION = 1;
142
Dianne Hackborn35654b62013-01-14 17:38:02 -0800143 // Write at most every 30 minutes.
144 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800145
Svet Ganov3a95f832018-03-23 17:44:30 -0700146 // Constant meaning that any UID should be matched when dispatching callbacks
147 private static final int UID_ANY = -2;
148
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700149 // Map from process states to the uid states we track.
150 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
151 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
152 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
153 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800154 UID_STATE_FOREGROUND_SERVICE_LOCATION,
155 // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
Amith Yamasanif235d0b2019-03-20 22:49:43 -0700156 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_TOP
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700157 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
158 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
159 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
160 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
161 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
162 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
163 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
164 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
165 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
166 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
167 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
168 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
169 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
170 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
171 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
172 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
173 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
174 };
175
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800176 Context mContext;
177 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800178 final Handler mHandler;
179
Dianne Hackbornd5254412018-05-11 18:02:58 -0700180 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
181 = new AppOpsManagerInternalImpl();
182
Dianne Hackborn35654b62013-01-14 17:38:02 -0800183 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800184 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800185 final Runnable mWriteRunner = new Runnable() {
186 public void run() {
187 synchronized (AppOpsService.this) {
188 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800189 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800190 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
191 @Override protected Void doInBackground(Void... params) {
192 writeState();
193 return null;
194 }
195 };
196 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
197 }
198 }
199 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800200
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700201 @VisibleForTesting
202 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800203
Svet Ganovdc0f4432019-06-04 14:16:51 -0700204 final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
Svet Ganov8455ba22019-01-02 13:05:56 -0800205
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700206 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700207
Ruben Brunk29931bc2016-03-11 00:24:26 -0800208 /*
209 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800210 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700211 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400212
Dianne Hackbornd5254412018-05-11 18:02:58 -0700213 SparseIntArray mProfileOwners;
214
Todd Kennedy556efba2018-11-15 07:43:55 -0800215 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700216 private CheckOpsDelegate mCheckOpsDelegate;
217
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700218 /**
219 * All times are in milliseconds. These constants are kept synchronized with the system
220 * global Settings. Any access to this class or its fields should be done while
221 * holding the AppOpsService lock.
222 */
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700223 @VisibleForTesting
224 final class Constants extends ContentObserver {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700225 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700226 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
227 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
228 = "fg_service_state_settle_time";
229 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700230
231 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700232 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700233 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700234 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700235 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700236 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700237
Dianne Hackborne93ab412018-05-14 17:52:30 -0700238 /**
239 * How long we want for a drop in uid state from foreground to settle before applying it.
240 * @see Settings.Global#APP_OPS_CONSTANTS
241 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
242 */
243 public long FG_SERVICE_STATE_SETTLE_TIME;
244
245 /**
246 * How long we want for a drop in uid state from background to settle before applying it.
247 * @see Settings.Global#APP_OPS_CONSTANTS
248 * @see #KEY_BG_STATE_SETTLE_TIME
249 */
250 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700251
252 private final KeyValueListParser mParser = new KeyValueListParser(',');
253 private ContentResolver mResolver;
254
255 public Constants(Handler handler) {
256 super(handler);
257 updateConstants();
258 }
259
260 public void startMonitoring(ContentResolver resolver) {
261 mResolver = resolver;
262 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700263 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700264 false, this);
265 updateConstants();
266 }
267
268 @Override
269 public void onChange(boolean selfChange, Uri uri) {
270 updateConstants();
271 }
272
273 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700274 String value = mResolver != null ? Settings.Global.getString(mResolver,
275 Settings.Global.APP_OPS_CONSTANTS) : "";
276
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700277 synchronized (AppOpsService.this) {
278 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700279 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700280 } catch (IllegalArgumentException e) {
281 // Failed to parse the settings string, log this and move on
282 // with defaults.
283 Slog.e(TAG, "Bad app ops settings", e);
284 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700285 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
286 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
287 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
288 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
289 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
290 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700291 }
292 }
293
294 void dump(PrintWriter pw) {
295 pw.println(" Settings:");
296
Dianne Hackborne93ab412018-05-14 17:52:30 -0700297 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
298 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700299 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700300 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
301 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700302 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700303 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
304 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700305 pw.println();
306 }
307 }
308
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700309 @VisibleForTesting
310 final Constants mConstants;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700311
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700312 @VisibleForTesting
313 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700314 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700315
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700316 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700317 public int pendingState = UID_STATE_CACHED;
318 public long pendingStateCommitTime;
319
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700320 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700321 public ArrayMap<String, Ops> pkgOps;
322 public SparseIntArray opModes;
323
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700324 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700325 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700326 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700327
Svet Ganov2af57082015-07-30 08:44:20 -0700328 public UidState(int uid) {
329 this.uid = uid;
330 }
331
332 public void clear() {
333 pkgOps = null;
334 opModes = null;
335 }
336
337 public boolean isDefault() {
338 return (pkgOps == null || pkgOps.isEmpty())
Svet Ganovaf189e32019-02-15 18:45:29 -0800339 && (opModes == null || opModes.size() <= 0)
340 && (state == UID_STATE_CACHED
341 && (pendingState == UID_STATE_CACHED));
Svet Ganov2af57082015-07-30 08:44:20 -0700342 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700343
Svet Ganovaf189e32019-02-15 18:45:29 -0800344 int evalMode(int op, int mode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700345 if (mode == AppOpsManager.MODE_FOREGROUND) {
Wei Wange1f864e2019-03-28 18:12:18 -0700346 return state <= AppOpsManager.resolveFirstUnrestrictedUidState(op)
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700347 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
348 }
349 return mode;
350 }
351
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700352 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
353 SparseBooleanArray which) {
354 boolean curValue = which.get(op, false);
355 ArraySet<ModeCallback> callbacks = watchers.get(op);
356 if (callbacks != null) {
357 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
358 if ((callbacks.valueAt(cbi).mFlags
359 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
360 hasForegroundWatchers = true;
361 curValue = true;
362 }
363 }
364 }
365 which.put(op, curValue);
366 }
367
368 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700369 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700370 hasForegroundWatchers = false;
371 if (opModes != null) {
372 for (int i = opModes.size() - 1; i >= 0; i--) {
373 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
374 if (which == null) {
375 which = new SparseBooleanArray();
376 }
377 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
378 }
379 }
380 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700381 if (pkgOps != null) {
382 for (int i = pkgOps.size() - 1; i >= 0; i--) {
383 Ops ops = pkgOps.valueAt(i);
384 for (int j = ops.size() - 1; j >= 0; j--) {
385 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
386 if (which == null) {
387 which = new SparseBooleanArray();
388 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700389 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700390 }
391 }
392 }
393 }
394 foregroundOps = which;
395 }
Svet Ganov2af57082015-07-30 08:44:20 -0700396 }
397
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700398 final static class Ops extends SparseArray<Op> {
399 final String packageName;
400 final UidState uidState;
401 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800402
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700403 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800404 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700405 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400406 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800407 }
408 }
409
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700410 final static class Op {
Svet Ganovaf189e32019-02-15 18:45:29 -0800411 int op;
412 boolean running;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700413 final UidState uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -0800414 final @NonNull String packageName;
415
416 private @Mode int mode;
417 private @Nullable LongSparseLongArray mAccessTimes;
418 private @Nullable LongSparseLongArray mRejectTimes;
419 private @Nullable LongSparseLongArray mDurations;
420 private @Nullable LongSparseLongArray mProxyUids;
421 private @Nullable LongSparseArray<String> mProxyPackageNames;
422
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700423 int startNesting;
424 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800425
Svet Ganovaf189e32019-02-15 18:45:29 -0800426 Op(UidState uidState, String packageName, int op) {
427 this.op = op;
428 this.uidState = uidState;
429 this.packageName = packageName;
430 this.mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700431 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700432
433 int getMode() {
Svet Ganovaf189e32019-02-15 18:45:29 -0800434 return mode;
435 }
436
437 int evalMode() {
438 return uidState.evalMode(op, mode);
439 }
440
441 /** @hide */
442 public void accessed(long time, int proxyUid, @Nullable String proxyPackageName,
443 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
444 final long key = AppOpsManager.makeKey(uidState, flags);
445 if (mAccessTimes == null) {
446 mAccessTimes = new LongSparseLongArray();
447 }
448 mAccessTimes.put(key, time);
449 updateProxyState(key, proxyUid, proxyPackageName);
450 if (mDurations != null) {
451 mDurations.delete(key);
452 }
453 }
454
455 /** @hide */
456 public void rejected(long time, int proxyUid, @Nullable String proxyPackageName,
457 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
458 final long key = AppOpsManager.makeKey(uidState, flags);
459 if (mRejectTimes == null) {
460 mRejectTimes = new LongSparseLongArray();
461 }
462 mRejectTimes.put(key, time);
463 updateProxyState(key, proxyUid, proxyPackageName);
464 if (mDurations != null) {
465 mDurations.delete(key);
466 }
467 }
468
469 /** @hide */
470 public void started(long time, @AppOpsManager.UidState int uidState, @OpFlags int flags) {
471 updateAccessTimeAndDuration(time, -1 /*duration*/, uidState, flags);
472 running = true;
473 }
474
475 /** @hide */
476 public void finished(long time, long duration, @AppOpsManager.UidState int uidState,
477 @OpFlags int flags) {
478 updateAccessTimeAndDuration(time, duration, uidState, flags);
479 running = false;
480 }
481
482 /** @hide */
483 public void running(long time, long duration, @AppOpsManager.UidState int uidState,
484 @OpFlags int flags) {
485 updateAccessTimeAndDuration(time, duration, uidState, flags);
486 }
487
488 /** @hide */
489 public void continuing(long duration, @AppOpsManager.UidState int uidState,
490 @OpFlags int flags) {
491 final long key = AppOpsManager.makeKey(uidState, flags);
492 if (mDurations == null) {
493 mDurations = new LongSparseLongArray();
494 }
495 mDurations.put(key, duration);
496 }
497
498 private void updateAccessTimeAndDuration(long time, long duration,
499 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
500 final long key = AppOpsManager.makeKey(uidState, flags);
501 if (mAccessTimes == null) {
502 mAccessTimes = new LongSparseLongArray();
503 }
504 mAccessTimes.put(key, time);
505 if (mDurations == null) {
506 mDurations = new LongSparseLongArray();
507 }
508 mDurations.put(key, duration);
509 }
510
511 private void updateProxyState(long key, int proxyUid,
512 @Nullable String proxyPackageName) {
Philip P. Moltmann4052d362019-09-19 14:52:38 -0700513 if (proxyUid == Process.INVALID_UID) {
514 return;
515 }
516
Svet Ganovaf189e32019-02-15 18:45:29 -0800517 if (mProxyUids == null) {
518 mProxyUids = new LongSparseLongArray();
519 }
520 mProxyUids.put(key, proxyUid);
521 if (mProxyPackageNames == null) {
522 mProxyPackageNames = new LongSparseArray<>();
523 }
524 mProxyPackageNames.put(key, proxyPackageName);
525 }
526
527 boolean hasAnyTime() {
528 return (mAccessTimes != null && mAccessTimes.size() > 0)
529 || (mRejectTimes != null && mRejectTimes.size() > 0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700530 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800531 }
532
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800533 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
534 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
535 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
536 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800537 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800538 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800539
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700540 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800541 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700542 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700543 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700544 final int mCallingUid;
545 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800546
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700547 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700548 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800549 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700550 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700551 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700552 mCallingUid = callingUid;
553 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800554 try {
555 mCallback.asBinder().linkToDeath(this, 0);
556 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800557 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800558 }
559 }
560
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700561 public boolean isWatchingUid(int uid) {
562 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
563 }
564
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700565 @Override
566 public String toString() {
567 StringBuilder sb = new StringBuilder(128);
568 sb.append("ModeCallback{");
569 sb.append(Integer.toHexString(System.identityHashCode(this)));
570 sb.append(" watchinguid=");
571 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700572 sb.append(" flags=0x");
573 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700574 sb.append(" from uid=");
575 UserHandle.formatUid(sb, mCallingUid);
576 sb.append(" pid=");
577 sb.append(mCallingPid);
578 sb.append('}');
579 return sb.toString();
580 }
581
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700582 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800583 mCallback.asBinder().unlinkToDeath(this, 0);
584 }
585
586 @Override
587 public void binderDied() {
588 stopWatchingMode(mCallback);
589 }
590 }
591
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700592 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800593 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700594 final int mWatchingUid;
595 final int mCallingUid;
596 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800597
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700598 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700599 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800600 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700601 mWatchingUid = watchingUid;
602 mCallingUid = callingUid;
603 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800604 try {
605 mCallback.asBinder().linkToDeath(this, 0);
606 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800607 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800608 }
609 }
610
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700611 @Override
612 public String toString() {
613 StringBuilder sb = new StringBuilder(128);
614 sb.append("ActiveCallback{");
615 sb.append(Integer.toHexString(System.identityHashCode(this)));
616 sb.append(" watchinguid=");
617 UserHandle.formatUid(sb, mWatchingUid);
618 sb.append(" from uid=");
619 UserHandle.formatUid(sb, mCallingUid);
620 sb.append(" pid=");
621 sb.append(mCallingPid);
622 sb.append('}');
623 return sb.toString();
624 }
625
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700626 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800627 mCallback.asBinder().unlinkToDeath(this, 0);
628 }
629
630 @Override
631 public void binderDied() {
632 stopWatchingActive(mCallback);
633 }
634 }
635
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800636 final class NotedCallback implements DeathRecipient {
637 final IAppOpsNotedCallback mCallback;
638 final int mWatchingUid;
639 final int mCallingUid;
640 final int mCallingPid;
641
642 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
643 int callingPid) {
644 mCallback = callback;
645 mWatchingUid = watchingUid;
646 mCallingUid = callingUid;
647 mCallingPid = callingPid;
648 try {
649 mCallback.asBinder().linkToDeath(this, 0);
650 } catch (RemoteException e) {
651 /*ignored*/
652 }
653 }
654
655 @Override
656 public String toString() {
657 StringBuilder sb = new StringBuilder(128);
658 sb.append("NotedCallback{");
659 sb.append(Integer.toHexString(System.identityHashCode(this)));
660 sb.append(" watchinguid=");
661 UserHandle.formatUid(sb, mWatchingUid);
662 sb.append(" from uid=");
663 UserHandle.formatUid(sb, mCallingUid);
664 sb.append(" pid=");
665 sb.append(mCallingPid);
666 sb.append('}');
667 return sb.toString();
668 }
669
670 void destroy() {
671 mCallback.asBinder().unlinkToDeath(this, 0);
672 }
673
674 @Override
675 public void binderDied() {
676 stopWatchingNoted(mCallback);
677 }
678 }
679
Svet Ganova7a0db62018-02-27 20:08:01 -0800680 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700681
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700682 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800683 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700684 final IBinder mAppToken;
685 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700686
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700687 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700688 mAppToken = appToken;
689 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800690 // Watch only for remote processes dying
691 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700692 try {
693 mAppToken.linkToDeath(this, 0);
694 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800695 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700696 }
697 }
698 }
699
700 @Override
701 public String toString() {
702 return "ClientState{" +
703 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800704 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700705 '}';
706 }
707
708 @Override
709 public void binderDied() {
710 synchronized (AppOpsService.this) {
711 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800712 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700713 }
714 mClients.remove(mAppToken);
715 }
716 }
717 }
718
Jeff Brown6f357d32014-01-15 20:40:55 -0800719 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600720 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800721 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800722 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700723 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800724 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800725 }
David Braunf5d83192013-09-16 13:43:51 -0700726
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800727 public void publish(Context context) {
728 mContext = context;
729 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700730 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800731 }
732
Dianne Hackborn514074f2013-02-11 10:52:46 -0800733 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700734 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800735 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700736
Dianne Hackborn514074f2013-02-11 10:52:46 -0800737 synchronized (this) {
738 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700739 for (int i = mUidStates.size() - 1; i >= 0; i--) {
740 UidState uidState = mUidStates.valueAt(i);
741
742 String[] packageNames = getPackagesForUid(uidState.uid);
743 if (ArrayUtils.isEmpty(packageNames)) {
744 uidState.clear();
745 mUidStates.removeAt(i);
746 changed = true;
747 continue;
748 }
749
750 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
751 if (pkgs == null) {
752 continue;
753 }
754
Dianne Hackborn514074f2013-02-11 10:52:46 -0800755 Iterator<Ops> it = pkgs.values().iterator();
756 while (it.hasNext()) {
757 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700758 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800759 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700760 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
761 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700762 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700763 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800764 }
Svet Ganov2af57082015-07-30 08:44:20 -0700765 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800766 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700767 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800768 it.remove();
769 changed = true;
770 }
771 }
Svet Ganov2af57082015-07-30 08:44:20 -0700772
773 if (uidState.isDefault()) {
774 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800775 }
776 }
777 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800778 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800779 }
780 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700781
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800782 final IntentFilter packageSuspendFilter = new IntentFilter();
783 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
784 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
785 mContext.registerReceiver(new BroadcastReceiver() {
786 @Override
787 public void onReceive(Context context, Intent intent) {
788 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
789 final String[] changedPkgs = intent.getStringArrayExtra(
790 Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackbornb298b352019-04-04 11:01:41 -0700791 ArraySet<ModeCallback> callbacks;
792 synchronized (AppOpsService.this) {
793 callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
794 if (callbacks == null) {
795 return;
796 }
797 callbacks = new ArraySet<>(callbacks);
798 }
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800799 for (int i = 0; i < changedUids.length; i++) {
800 final int changedUid = changedUids[i];
801 final String changedPkg = changedPkgs[i];
Dianne Hackbornb298b352019-04-04 11:01:41 -0700802 // We trust packagemanager to insert matching uid and packageNames in the
803 // extras
804 notifyOpChanged(callbacks, OP_PLAY_AUDIO, changedUid, changedPkg);
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800805 }
806 }
807 }, packageSuspendFilter);
808
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800809 PackageManagerInternal packageManagerInternal = LocalServices.getService(
810 PackageManagerInternal.class);
811 packageManagerInternal.setExternalSourcesPolicy(
812 new PackageManagerInternal.ExternalSourcesPolicy() {
813 @Override
814 public int getPackageTrustedToInstallApps(String packageName, int uid) {
815 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
816 uid, packageName);
817 switch (appOpMode) {
818 case AppOpsManager.MODE_ALLOWED:
819 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
820 case AppOpsManager.MODE_ERRORED:
821 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
822 default:
823 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
824 }
825 }
826 });
827
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700828 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700829 StorageManagerInternal storageManagerInternal = LocalServices.getService(
830 StorageManagerInternal.class);
831 storageManagerInternal.addExternalStoragePolicy(
832 new StorageManagerInternal.ExternalStorageMountPolicy() {
833 @Override
834 public int getMountMode(int uid, String packageName) {
835 if (Process.isIsolated(uid)) {
836 return Zygote.MOUNT_EXTERNAL_NONE;
837 }
838 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
839 packageName) != AppOpsManager.MODE_ALLOWED) {
840 return Zygote.MOUNT_EXTERNAL_NONE;
841 }
842 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
843 packageName) != AppOpsManager.MODE_ALLOWED) {
844 return Zygote.MOUNT_EXTERNAL_READ;
845 }
846 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700847 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700848
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700849 @Override
850 public boolean hasExternalStorage(int uid, String packageName) {
851 final int mountMode = getMountMode(uid, packageName);
852 return mountMode == Zygote.MOUNT_EXTERNAL_READ
853 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
854 }
855 });
856 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800857 }
858
859 public void packageRemoved(int uid, String packageName) {
860 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700861 UidState uidState = mUidStates.get(uid);
862 if (uidState == null) {
863 return;
864 }
865
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800866 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700867
868 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800869 if (uidState.pkgOps != null) {
870 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700871 }
872
873 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800874 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700875 && getPackagesForUid(uid).length <= 0) {
876 mUidStates.remove(uid);
877 }
878
Svet Ganova7a0db62018-02-27 20:08:01 -0800879 // Finish ops other packages started on behalf of the package.
880 final int clientCount = mClients.size();
881 for (int i = 0; i < clientCount; i++) {
882 final ClientState client = mClients.valueAt(i);
883 if (client.mStartedOps == null) {
884 continue;
885 }
886 final int opCount = client.mStartedOps.size();
887 for (int j = opCount - 1; j >= 0; j--) {
888 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800889 if (uid == op.uidState.uid && packageName.equals(op.packageName)) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800890 finishOperationLocked(op, /*finishNested*/ true);
891 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700892 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800893 scheduleOpActiveChangedIfNeededLocked(op.op,
894 uid, packageName, false);
895 }
896 }
897 }
898 }
899
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800900 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700901 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800902
903 final int opCount = ops.size();
904 for (int i = 0; i < opCount; i++) {
905 final Op op = ops.valueAt(i);
Svet Ganovaf189e32019-02-15 18:45:29 -0800906 if (op.running) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800907 scheduleOpActiveChangedIfNeededLocked(
Svet Ganovaf189e32019-02-15 18:45:29 -0800908 op.op, op.uidState.uid, op.packageName, false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800909 }
910 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800911 }
Winson4e3b4352019-05-07 16:29:59 -0700912
913 mHistoricalRegistry.clearHistory(uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800914 }
915 }
916
917 public void uidRemoved(int uid) {
918 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700919 if (mUidStates.indexOfKey(uid) >= 0) {
920 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800921 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800922 }
923 }
924 }
925
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700926 public void updateUidProcState(int uid, int procState) {
927 synchronized (this) {
928 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800929 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700930 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700931 final int oldPendingState = uidState.pendingState;
932 uidState.pendingState = newState;
Wei Wange1f864e2019-03-28 18:12:18 -0700933 if (newState < uidState.state
934 || (newState <= UID_STATE_MAX_LAST_NON_RESTRICTED
935 && uidState.state > UID_STATE_MAX_LAST_NON_RESTRICTED)) {
936 // We are moving to a more important state, or the new state may be in the
937 // foreground and the old state is in the background, then always do it
938 // immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700939 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700940 } else if (uidState.pendingStateCommitTime == 0) {
941 // We are moving to a less important state for the first time,
942 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700943 final long settleTime;
944 if (uidState.state <= UID_STATE_TOP) {
945 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
946 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
947 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
948 } else {
949 settleTime = mConstants.BG_STATE_SETTLE_TIME;
950 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700951 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700952 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700953 if (uidState.startNesting != 0) {
954 // There is some actively running operation... need to find it
955 // and appropriately update its state.
956 final long now = System.currentTimeMillis();
957 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
958 final Ops ops = uidState.pkgOps.valueAt(i);
959 for (int j = ops.size() - 1; j >= 0; j--) {
960 final Op op = ops.valueAt(j);
961 if (op.startNesting > 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800962 final long duration = SystemClock.elapsedRealtime()
963 - op.startRealtime;
964 // We don't support proxy long running ops (start/stop)
965 mHistoricalRegistry.increaseOpAccessDuration(op.op,
966 op.uidState.uid, op.packageName, oldPendingState,
967 AppOpsManager.OP_FLAG_SELF, duration);
968 // Finish the op in the old state
969 op.finished(now, duration, oldPendingState,
970 AppOpsManager.OP_FLAG_SELF);
971 // Start the op in the new state
972 op.startRealtime = now;
973 op.started(now, newState, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700974 }
975 }
976 }
977 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700978 }
979 }
980 }
981
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800982 public void shutdown() {
983 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800984 boolean doWrite = false;
985 synchronized (this) {
986 if (mWriteScheduled) {
987 mWriteScheduled = false;
988 doWrite = true;
989 }
990 }
991 if (doWrite) {
992 writeState();
993 }
994 }
995
Dianne Hackborn72e39832013-01-18 18:36:09 -0800996 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
997 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700998 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800999 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001000 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001001 for (int j=0; j<pkgOps.size(); j++) {
1002 Op curOp = pkgOps.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08001003 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001004 }
1005 } else {
1006 for (int j=0; j<ops.length; j++) {
1007 Op curOp = pkgOps.get(ops[j]);
1008 if (curOp != null) {
1009 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001010 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001011 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001012 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001013 }
1014 }
1015 }
1016 return resOps;
1017 }
1018
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001019 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001020 if (uidOps == null) {
1021 return null;
1022 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001023 ArrayList<AppOpsManager.OpEntry> resOps = null;
1024 if (ops == null) {
1025 resOps = new ArrayList<>();
1026 for (int j=0; j<uidOps.size(); j++) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001027 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001028 }
1029 } else {
1030 for (int j=0; j<ops.length; j++) {
1031 int index = uidOps.indexOfKey(ops[j]);
1032 if (index >= 0) {
1033 if (resOps == null) {
1034 resOps = new ArrayList<>();
1035 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001036 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001037 }
1038 }
1039 }
1040 return resOps;
1041 }
1042
Svet Ganovaf189e32019-02-15 18:45:29 -08001043 private static @NonNull OpEntry getOpEntryForResult(@NonNull Op op, long elapsedNow) {
1044 if (op.running) {
1045 op.continuing(elapsedNow - op.startRealtime,
1046 op.uidState.state, AppOpsManager.OP_FLAG_SELF);
1047 }
1048 final OpEntry entry = new OpEntry(op.op, op.running, op.mode,
1049 op.mAccessTimes != null ? op.mAccessTimes.clone() : null,
1050 op.mRejectTimes != null ? op.mRejectTimes.clone() : null,
1051 op.mDurations != null ? op.mDurations.clone() : null,
1052 op.mProxyUids != null ? op.mProxyUids.clone() : null,
1053 op.mProxyPackageNames != null ? op.mProxyPackageNames.clone() : null);
1054 return entry;
1055 }
1056
Dianne Hackborn35654b62013-01-14 17:38:02 -08001057 @Override
1058 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1059 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1060 Binder.getCallingPid(), Binder.getCallingUid(), null);
1061 ArrayList<AppOpsManager.PackageOps> res = null;
1062 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001063 final int uidStateCount = mUidStates.size();
1064 for (int i = 0; i < uidStateCount; i++) {
1065 UidState uidState = mUidStates.valueAt(i);
1066 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
1067 continue;
1068 }
1069 ArrayMap<String, Ops> packages = uidState.pkgOps;
1070 final int packageCount = packages.size();
1071 for (int j = 0; j < packageCount; j++) {
1072 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001073 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001074 if (resOps != null) {
1075 if (res == null) {
1076 res = new ArrayList<AppOpsManager.PackageOps>();
1077 }
1078 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001079 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001080 res.add(resPackage);
1081 }
1082 }
1083 }
1084 }
1085 return res;
1086 }
1087
1088 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001089 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1090 int[] ops) {
1091 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1092 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001093 String resolvedPackageName = resolvePackageName(uid, packageName);
1094 if (resolvedPackageName == null) {
1095 return Collections.emptyList();
1096 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001097 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001098 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1099 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001100 if (pkgOps == null) {
1101 return null;
1102 }
1103 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1104 if (resOps == null) {
1105 return null;
1106 }
1107 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1108 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001109 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001110 res.add(resPackage);
1111 return res;
1112 }
1113 }
1114
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001115 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001116 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001117 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001118 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001119 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001120 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001121 beginTimeMillis, endTimeMillis)
1122 .setUid(uid)
1123 .setPackageName(packageName)
1124 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001125 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001126 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001127 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001128
1129 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001130 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001131
Svet Ganov23c88db2019-01-22 20:38:11 -08001132 final String[] opNamesArray = (opNames != null)
1133 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganovad0a49b2018-10-29 10:07:08 -07001134
Svet Ganovaf189e32019-02-15 18:45:29 -08001135 // Must not hold the appops lock
1136 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
1137 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001138 }
1139
1140 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001141 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001142 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001143 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001144 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001145 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001146 beginTimeMillis, endTimeMillis)
1147 .setUid(uid)
1148 .setPackageName(packageName)
1149 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001150 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001151 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001152 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001153
Svet Ganov8e5bf962019-03-19 23:59:03 -07001154 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001155 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001156
Svet Ganov23c88db2019-01-22 20:38:11 -08001157 final String[] opNamesArray = (opNames != null)
1158 ? opNames.toArray(new String[opNames.size()]) : null;
1159
Svet Ganov8455ba22019-01-02 13:05:56 -08001160 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001161 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganovaf189e32019-02-15 18:45:29 -08001162 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001163 }
1164
1165 @Override
Svet Ganov8e5bf962019-03-19 23:59:03 -07001166 public void reloadNonHistoricalState() {
1167 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
1168 Binder.getCallingPid(), Binder.getCallingUid(), "reloadNonHistoricalState");
1169 writeState();
1170 readState();
1171 }
1172
1173 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001174 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1175 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1176 Binder.getCallingPid(), Binder.getCallingUid(), null);
1177 synchronized (this) {
1178 UidState uidState = getUidStateLocked(uid, false);
1179 if (uidState == null) {
1180 return null;
1181 }
1182 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1183 if (resOps == null) {
1184 return null;
1185 }
1186 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1187 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1188 null, uidState.uid, resOps);
1189 res.add(resPackage);
1190 return res;
1191 }
1192 }
1193
Dianne Hackborn607b4142013-08-02 18:10:10 -07001194 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001195 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001196 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1197 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001198 if (ops != null) {
1199 ops.remove(op.op);
1200 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001201 UidState uidState = ops.uidState;
1202 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001203 if (pkgOps != null) {
1204 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001205 if (pkgOps.isEmpty()) {
1206 uidState.pkgOps = null;
1207 }
1208 if (uidState.isDefault()) {
1209 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001210 }
1211 }
1212 }
1213 }
1214 }
1215 }
1216
Svet Ganovaf189e32019-02-15 18:45:29 -08001217 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001218 if (callingPid == Process.myPid()) {
1219 return;
1220 }
1221 final int callingUser = UserHandle.getUserId(callingUid);
1222 synchronized (this) {
1223 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1224 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1225 // Profile owners are allowed to change modes but only for apps
1226 // within their user.
1227 return;
1228 }
1229 }
1230 }
1231 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1232 Binder.getCallingPid(), Binder.getCallingUid(), null);
1233 }
1234
Dianne Hackborn72e39832013-01-18 18:36:09 -08001235 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001236 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001237 if (DEBUG) {
1238 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1239 + " by uid " + Binder.getCallingUid());
1240 }
1241
Dianne Hackbornd5254412018-05-11 18:02:58 -07001242 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001243 verifyIncomingOp(code);
1244 code = AppOpsManager.opToSwitch(code);
1245
1246 synchronized (this) {
1247 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1248
1249 UidState uidState = getUidStateLocked(uid, false);
1250 if (uidState == null) {
1251 if (mode == defaultMode) {
1252 return;
1253 }
1254 uidState = new UidState(uid);
1255 uidState.opModes = new SparseIntArray();
1256 uidState.opModes.put(code, mode);
1257 mUidStates.put(uid, uidState);
1258 scheduleWriteLocked();
1259 } else if (uidState.opModes == null) {
1260 if (mode != defaultMode) {
1261 uidState.opModes = new SparseIntArray();
1262 uidState.opModes.put(code, mode);
1263 scheduleWriteLocked();
1264 }
1265 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001266 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001267 return;
1268 }
1269 if (mode == defaultMode) {
1270 uidState.opModes.delete(code);
1271 if (uidState.opModes.size() <= 0) {
1272 uidState.opModes = null;
1273 }
1274 } else {
1275 uidState.opModes.put(code, mode);
1276 }
1277 scheduleWriteLocked();
1278 }
Wei Wang711eb662019-03-21 18:24:17 -07001279 uidState.evalForegroundOps(mOpModeWatchers);
Svet Ganov2af57082015-07-30 08:44:20 -07001280 }
1281
Svetoslav215b44a2015-08-04 19:03:40 -07001282 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001283 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001284
riddle_hsu40b300f2015-11-23 13:22:03 +08001285 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001286 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001287 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001288 final int callbackCount = callbacks.size();
1289 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001290 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001291 ArraySet<String> changedPackages = new ArraySet<>();
1292 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001293 if (callbackSpecs == null) {
1294 callbackSpecs = new ArrayMap<>();
1295 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001296 callbackSpecs.put(callback, changedPackages);
1297 }
1298 }
1299
1300 for (String uidPackageName : uidPackageNames) {
1301 callbacks = mPackageModeWatchers.get(uidPackageName);
1302 if (callbacks != null) {
1303 if (callbackSpecs == null) {
1304 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001305 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001306 final int callbackCount = callbacks.size();
1307 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001308 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001309 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1310 if (changedPackages == null) {
1311 changedPackages = new ArraySet<>();
1312 callbackSpecs.put(callback, changedPackages);
1313 }
1314 changedPackages.add(uidPackageName);
1315 }
Svet Ganov2af57082015-07-30 08:44:20 -07001316 }
1317 }
1318 }
1319
1320 if (callbackSpecs == null) {
Sudheer Shankab1613982019-05-16 16:55:50 -07001321 notifyOpChangedSync(code, uid, null, mode);
Svet Ganov2af57082015-07-30 08:44:20 -07001322 return;
1323 }
1324
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001325 for (int i = 0; i < callbackSpecs.size(); i++) {
1326 final ModeCallback callback = callbackSpecs.keyAt(i);
1327 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1328 if (reportedPackageNames == null) {
1329 mHandler.sendMessage(PooledLambda.obtainMessage(
1330 AppOpsService::notifyOpChanged,
1331 this, callback, code, uid, (String) null));
1332
1333 } else {
1334 final int reportedPackageCount = reportedPackageNames.size();
1335 for (int j = 0; j < reportedPackageCount; j++) {
1336 final String reportedPackageName = reportedPackageNames.valueAt(j);
1337 mHandler.sendMessage(PooledLambda.obtainMessage(
1338 AppOpsService::notifyOpChanged,
1339 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001340 }
1341 }
Svet Ganov2af57082015-07-30 08:44:20 -07001342 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001343
1344 notifyOpChangedSync(code, uid, null, mode);
1345 }
1346
1347 private void notifyOpChangedSync(int code, int uid, @NonNull String packageName, int mode) {
1348 final StorageManagerInternal storageManagerInternal =
1349 LocalServices.getService(StorageManagerInternal.class);
1350 if (storageManagerInternal != null) {
1351 storageManagerInternal.onAppOpsChanged(code, uid, packageName, mode);
1352 }
Svet Ganov2af57082015-07-30 08:44:20 -07001353 }
1354
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001355 /**
1356 * Set all {@link #setMode (package) modes} for this uid to the default value.
1357 *
1358 * @param code The app-op
1359 * @param uid The uid
1360 */
1361 private void setAllPkgModesToDefault(int code, int uid) {
1362 synchronized (this) {
1363 UidState uidState = getUidStateLocked(uid, false);
1364 if (uidState == null) {
1365 return;
1366 }
1367
1368 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1369 if (pkgOps == null) {
1370 return;
1371 }
1372
Svet Ganovaf189e32019-02-15 18:45:29 -08001373 boolean scheduleWrite = false;
1374
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001375 int numPkgs = pkgOps.size();
1376 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1377 Ops ops = pkgOps.valueAt(pkgNum);
1378
1379 Op op = ops.get(code);
1380 if (op == null) {
1381 continue;
1382 }
1383
1384 int defaultMode = AppOpsManager.opToDefaultMode(code);
1385 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001386 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001387 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001388 }
1389 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001390
1391 if (scheduleWrite) {
1392 scheduleWriteLocked();
1393 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001394 }
1395 }
1396
Svet Ganov2af57082015-07-30 08:44:20 -07001397 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001398 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001399 setMode(code, uid, packageName, mode, true, false);
1400 }
1401
1402 /**
1403 * Sets the mode for a certain op and uid.
1404 *
1405 * @param code The op code to set
1406 * @param uid The UID for which to set
1407 * @param packageName The package for which to set
1408 * @param mode The new mode to set
1409 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1410 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1411 * false})
1412 */
1413 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1414 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001415 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001416 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001417 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001418 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001419 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001420 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001421 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001422 if (op != null) {
1423 if (op.mode != mode) {
1424 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001425 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001426 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001427 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001428 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001429 if (cbs != null) {
1430 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001431 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001432 }
1433 repCbs.addAll(cbs);
1434 }
1435 cbs = mPackageModeWatchers.get(packageName);
1436 if (cbs != null) {
1437 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001438 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001439 }
1440 repCbs.addAll(cbs);
1441 }
David Braunf5d83192013-09-16 13:43:51 -07001442 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001443 // If going into the default mode, prune this op
1444 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001445 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001446 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001447 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001448 }
1449 }
1450 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001451 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001452 mHandler.sendMessage(PooledLambda.obtainMessage(
1453 AppOpsService::notifyOpChanged,
1454 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001455 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001456
1457 notifyOpChangedSync(code, uid, packageName, mode);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001458 }
1459
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001460 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1461 int uid, String packageName) {
1462 for (int i = 0; i < callbacks.size(); i++) {
1463 final ModeCallback callback = callbacks.valueAt(i);
1464 notifyOpChanged(callback, code, uid, packageName);
1465 }
1466 }
1467
1468 private void notifyOpChanged(ModeCallback callback, int code,
1469 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001470 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001471 return;
1472 }
1473 // There are components watching for mode changes such as window manager
1474 // and location manager which are in our process. The callbacks in these
1475 // components may require permissions our remote caller does not have.
1476 final long identity = Binder.clearCallingIdentity();
1477 try {
1478 callback.mCallback.opChanged(code, uid, packageName);
1479 } catch (RemoteException e) {
1480 /* ignore */
1481 } finally {
1482 Binder.restoreCallingIdentity(identity);
1483 }
1484 }
1485
1486 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1487 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1488 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001489 if (cbs == null) {
1490 return callbacks;
1491 }
1492 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001493 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001494 }
Svet Ganov2af57082015-07-30 08:44:20 -07001495 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001496 final int N = cbs.size();
1497 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001498 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001499 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001500 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001501 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001502 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001503 } else {
1504 final int reportCount = reports.size();
1505 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001506 ChangeRec report = reports.get(j);
1507 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001508 duplicate = true;
1509 break;
1510 }
1511 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001512 }
Svet Ganov2af57082015-07-30 08:44:20 -07001513 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001514 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001515 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001516 }
1517 return callbacks;
1518 }
1519
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001520 static final class ChangeRec {
1521 final int op;
1522 final int uid;
1523 final String pkg;
1524
1525 ChangeRec(int _op, int _uid, String _pkg) {
1526 op = _op;
1527 uid = _uid;
1528 pkg = _pkg;
1529 }
1530 }
1531
Dianne Hackborn607b4142013-08-02 18:10:10 -07001532 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001533 public void resetAllModes(int reqUserId, String reqPackageName) {
1534 final int callingPid = Binder.getCallingPid();
1535 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001536 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1537 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001538
1539 int reqUid = -1;
1540 if (reqPackageName != null) {
1541 try {
1542 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001543 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001544 } catch (RemoteException e) {
1545 /* ignore - local call */
1546 }
1547 }
1548
Dianne Hackbornd5254412018-05-11 18:02:58 -07001549 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1550
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001551 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001552 synchronized (this) {
1553 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001554 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1555 UidState uidState = mUidStates.valueAt(i);
1556
1557 SparseIntArray opModes = uidState.opModes;
1558 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1559 final int uidOpCount = opModes.size();
1560 for (int j = uidOpCount - 1; j >= 0; j--) {
1561 final int code = opModes.keyAt(j);
1562 if (AppOpsManager.opAllowsReset(code)) {
1563 opModes.removeAt(j);
1564 if (opModes.size() <= 0) {
1565 uidState.opModes = null;
1566 }
1567 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001568 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001569 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001570 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001571 mPackageModeWatchers.get(packageName));
1572 }
1573 }
1574 }
1575 }
1576
1577 if (uidState.pkgOps == null) {
1578 continue;
1579 }
1580
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001581 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001582 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001583 // Skip any ops for a different user
1584 continue;
1585 }
Svet Ganov2af57082015-07-30 08:44:20 -07001586
1587 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001588 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001589 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001590 while (it.hasNext()) {
1591 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001592 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001593 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1594 // Skip any ops for a different package
1595 continue;
1596 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001597 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001598 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001599 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001600 if (AppOpsManager.opAllowsReset(curOp.op)
1601 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001602 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001603 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001604 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001605 final int uid = curOp.uidState.uid;
1606 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001607 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001608 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001609 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001610 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001611 pkgOps.removeAt(j);
1612 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001613 }
1614 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001615 if (pkgOps.size() == 0) {
1616 it.remove();
1617 }
1618 }
Svet Ganov2af57082015-07-30 08:44:20 -07001619 if (uidState.isDefault()) {
1620 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001621 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001622 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001623 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001624 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001625 }
Svet Ganov2af57082015-07-30 08:44:20 -07001626
Dianne Hackborn607b4142013-08-02 18:10:10 -07001627 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001628 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001629 }
1630 }
1631 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001632 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1633 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001634 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001635 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001636 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001637 mHandler.sendMessage(PooledLambda.obtainMessage(
1638 AppOpsService::notifyOpChanged,
1639 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001640 }
1641 }
1642 }
1643 }
1644
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001645 private void evalAllForegroundOpsLocked() {
1646 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1647 final UidState uidState = mUidStates.valueAt(uidi);
1648 if (uidState.foregroundOps != null) {
1649 uidState.evalForegroundOps(mOpModeWatchers);
1650 }
1651 }
1652 }
1653
Dianne Hackbornc2293022013-02-06 23:14:49 -08001654 @Override
1655 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001656 startWatchingModeWithFlags(op, packageName, 0, callback);
1657 }
1658
1659 @Override
1660 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1661 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001662 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001663 final int callingUid = Binder.getCallingUid();
1664 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001665 // TODO: should have a privileged permission to protect this.
1666 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1667 // the USAGE_STATS permission since this can provide information about when an
1668 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001669 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1670 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001671 if (callback == null) {
1672 return;
1673 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001674 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001675 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001676 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001677 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001678 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001679 mModeWatchers.put(callback.asBinder(), cb);
1680 }
1681 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001682 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001683 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001684 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001685 mOpModeWatchers.put(op, cbs);
1686 }
1687 cbs.add(cb);
1688 }
1689 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001690 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001691 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001692 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001693 mPackageModeWatchers.put(packageName, cbs);
1694 }
1695 cbs.add(cb);
1696 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001697 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001698 }
1699 }
1700
1701 @Override
1702 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001703 if (callback == null) {
1704 return;
1705 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001706 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001707 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001708 if (cb != null) {
1709 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001710 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001711 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001712 cbs.remove(cb);
1713 if (cbs.size() <= 0) {
1714 mOpModeWatchers.removeAt(i);
1715 }
1716 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001717 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001718 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001719 cbs.remove(cb);
1720 if (cbs.size() <= 0) {
1721 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001722 }
1723 }
1724 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001725 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001726 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001727 }
1728
1729 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001730 public IBinder getToken(IBinder clientToken) {
1731 synchronized (this) {
1732 ClientState cs = mClients.get(clientToken);
1733 if (cs == null) {
1734 cs = new ClientState(clientToken);
1735 mClients.put(clientToken, cs);
1736 }
1737 return cs;
1738 }
1739 }
1740
Svet Ganovd873ae62018-06-25 16:39:23 -07001741 public CheckOpsDelegate getAppOpsServiceDelegate() {
1742 synchronized (this) {
1743 return mCheckOpsDelegate;
1744 }
1745 }
1746
1747 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1748 synchronized (this) {
1749 mCheckOpsDelegate = delegate;
1750 }
1751 }
1752
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001753 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001754 public int checkOperationRaw(int code, int uid, String packageName) {
1755 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1756 }
1757
1758 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001759 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001760 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1761 }
1762
1763 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001764 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001765 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001766 delegate = mCheckOpsDelegate;
1767 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001768 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001769 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001770 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001771 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001772 AppOpsService.this::checkOperationImpl);
1773 }
1774
Svet Ganov9d528a12018-12-19 17:23:11 -08001775 private int checkOperationImpl(int code, int uid, String packageName,
1776 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001777 verifyIncomingUid(uid);
1778 verifyIncomingOp(code);
1779 String resolvedPackageName = resolvePackageName(uid, packageName);
1780 if (resolvedPackageName == null) {
1781 return AppOpsManager.MODE_IGNORED;
1782 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001783 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001784 }
1785
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001786 /**
1787 * @see #checkOperationUnchecked(int, int, String, boolean, boolean)
1788 */
1789 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1790 boolean raw) {
1791 return checkOperationUnchecked(code, uid, packageName, raw, true);
1792 }
1793
1794 /**
1795 * Get the mode of an app-op.
1796 *
1797 * @param code The code of the op
1798 * @param uid The uid of the package the op belongs to
1799 * @param packageName The package the op belongs to
1800 * @param raw If the raw state of eval-ed state should be checked.
1801 * @param verify If the code should check the package belongs to the uid
1802 *
1803 * @return The mode of the op
1804 */
1805 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1806 boolean raw, boolean verify) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001807 synchronized (this) {
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001808 if (verify) {
1809 checkPackage(uid, packageName);
1810 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001811 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001812 return AppOpsManager.MODE_IGNORED;
1813 }
Svet Ganov2af57082015-07-30 08:44:20 -07001814 code = AppOpsManager.opToSwitch(code);
1815 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001816 if (uidState != null && uidState.opModes != null
1817 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001818 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001819 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001820 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001821 Op op = getOpLocked(code, uid, packageName, false, verify, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001822 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001823 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001824 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001825 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001826 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001827 }
1828
1829 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001830 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001831 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001832 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001833 delegate = mCheckOpsDelegate;
1834 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001835 if (delegate == null) {
1836 return checkAudioOperationImpl(code, usage, uid, packageName);
1837 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001838 return delegate.checkAudioOperation(code, usage, uid, packageName,
1839 AppOpsService.this::checkAudioOperationImpl);
1840 }
1841
1842 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001843 boolean suspended;
1844 try {
1845 suspended = isPackageSuspendedForUser(packageName, uid);
1846 } catch (IllegalArgumentException ex) {
1847 // Package not found.
1848 suspended = false;
1849 }
1850
1851 if (suspended) {
1852 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1853 + " for uid=" + uid);
1854 return AppOpsManager.MODE_IGNORED;
1855 }
1856
Svet Ganovd873ae62018-06-25 16:39:23 -07001857 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001858 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001859 if (mode != AppOpsManager.MODE_ALLOWED) {
1860 return mode;
1861 }
1862 }
1863 return checkOperation(code, uid, packageName);
1864 }
1865
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001866 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Svet Ganov8d123f42019-04-09 17:11:12 -07001867 final long identity = Binder.clearCallingIdentity();
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001868 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001869 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1870 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001871 } catch (RemoteException re) {
1872 throw new SecurityException("Could not talk to package manager service");
Svet Ganov8d123f42019-04-09 17:11:12 -07001873 } finally {
1874 Binder.restoreCallingIdentity(identity);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001875 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001876 }
1877
John Spurlock7b414672014-07-18 13:02:39 -04001878 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1879 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1880 if (usageRestrictions != null) {
1881 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001882 if (r != null && !r.exceptionPackages.contains(packageName)) {
1883 return r.mode;
1884 }
1885 }
1886 return AppOpsManager.MODE_ALLOWED;
1887 }
1888
1889 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001890 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001891 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001892 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001893 verifyIncomingUid(uid);
1894 verifyIncomingOp(code);
1895 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001896 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1897 if (usageRestrictions == null) {
1898 usageRestrictions = new SparseArray<Restriction>();
1899 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001900 }
John Spurlock7b414672014-07-18 13:02:39 -04001901 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001902 if (mode != AppOpsManager.MODE_ALLOWED) {
1903 final Restriction r = new Restriction();
1904 r.mode = mode;
1905 if (exceptionPackages != null) {
1906 final int N = exceptionPackages.length;
1907 r.exceptionPackages = new ArraySet<String>(N);
1908 for (int i = 0; i < N; i++) {
1909 final String pkg = exceptionPackages[i];
1910 if (pkg != null) {
1911 r.exceptionPackages.add(pkg.trim());
1912 }
1913 }
1914 }
John Spurlock7b414672014-07-18 13:02:39 -04001915 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001916 }
1917 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001918
1919 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001920 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001921 }
1922
1923 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001924 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001925 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001926 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001927 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1928 true /* uidMismatchExpected */);
1929 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001930 return AppOpsManager.MODE_ALLOWED;
1931 } else {
1932 return AppOpsManager.MODE_ERRORED;
1933 }
1934 }
1935 }
1936
1937 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001938 public int noteProxyOperation(int code, int proxyUid,
1939 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1940 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001941 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001942
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001943 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1944 if (resolveProxyPackageName == null) {
1945 return AppOpsManager.MODE_IGNORED;
1946 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001947
1948 final boolean isProxyTrusted = mContext.checkPermission(
1949 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1950 == PackageManager.PERMISSION_GRANTED;
1951
1952 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1953 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001954 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001955 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001956 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1957 return proxyMode;
1958 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001959
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001960 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1961 if (resolveProxiedPackageName == null) {
1962 return AppOpsManager.MODE_IGNORED;
1963 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001964 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1965 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001966 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001967 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001968 }
1969
1970 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001971 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001972 final CheckOpsDelegate delegate;
1973 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001974 delegate = mCheckOpsDelegate;
1975 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001976 if (delegate == null) {
1977 return noteOperationImpl(code, uid, packageName);
1978 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001979 return delegate.noteOperation(code, uid, packageName,
1980 AppOpsService.this::noteOperationImpl);
1981 }
1982
1983 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001984 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001985 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001986 String resolvedPackageName = resolvePackageName(uid, packageName);
1987 if (resolvedPackageName == null) {
1988 return AppOpsManager.MODE_IGNORED;
1989 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001990 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
1991 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07001992 }
1993
1994 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001995 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001996 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001997 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001998 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001999 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002000 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2001 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002002 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002003 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002004 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002005 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002006 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002007 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002008 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2009 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04002010 return AppOpsManager.MODE_IGNORED;
2011 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002012 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08002013 if (op.running) {
2014 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2015 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002016 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08002017 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
2018 uidState.state, flags) + " duration=" + entry.getLastDuration(
2019 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002020 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002021
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002022 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002023 // If there is a non-default per UID policy (we set UID op mode only if
2024 // non-default) it takes over, otherwise use the per package policy.
2025 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002026 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07002027 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002028 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002029 + switchCode + " (" + code + ") uid " + uid + " package "
2030 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002031 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2032 uidState.state, flags);
2033 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2034 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002035 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07002036 return uidMode;
2037 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002038 } else {
2039 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002040 final int mode = switchOp.evalMode();
2041 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002042 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002043 + switchCode + " (" + code + ") uid " + uid + " package "
2044 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002045 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2046 uidState.state, flags);
2047 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2048 uidState.state, flags);
2049 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002050 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002051 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002052 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002053 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002054 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002055 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
2056 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08002057 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002058 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002059 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2060 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002061 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002062 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002063 }
2064
2065 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002066 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002067 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002068 final int callingUid = Binder.getCallingUid();
2069 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002070 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2071 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002072 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002073 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002074 if (ops != null) {
2075 Preconditions.checkArrayElementsInRange(ops, 0,
2076 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2077 }
2078 if (callback == null) {
2079 return;
2080 }
2081 synchronized (this) {
2082 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2083 if (callbacks == null) {
2084 callbacks = new SparseArray<>();
2085 mActiveWatchers.put(callback.asBinder(), callbacks);
2086 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002087 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2088 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002089 for (int op : ops) {
2090 callbacks.put(op, activeCallback);
2091 }
2092 }
2093 }
2094
2095 @Override
2096 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2097 if (callback == null) {
2098 return;
2099 }
2100 synchronized (this) {
2101 final SparseArray<ActiveCallback> activeCallbacks =
2102 mActiveWatchers.remove(callback.asBinder());
2103 if (activeCallbacks == null) {
2104 return;
2105 }
2106 final int callbackCount = activeCallbacks.size();
2107 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002108 activeCallbacks.valueAt(i).destroy();
2109 }
2110 }
2111 }
2112
2113 @Override
2114 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2115 int watchedUid = Process.INVALID_UID;
2116 final int callingUid = Binder.getCallingUid();
2117 final int callingPid = Binder.getCallingPid();
2118 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2119 != PackageManager.PERMISSION_GRANTED) {
2120 watchedUid = callingUid;
2121 }
2122 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2123 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2124 "Invalid op code in: " + Arrays.toString(ops));
2125 Preconditions.checkNotNull(callback, "Callback cannot be null");
2126 synchronized (this) {
2127 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2128 if (callbacks == null) {
2129 callbacks = new SparseArray<>();
2130 mNotedWatchers.put(callback.asBinder(), callbacks);
2131 }
2132 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2133 callingUid, callingPid);
2134 for (int op : ops) {
2135 callbacks.put(op, notedCallback);
2136 }
2137 }
2138 }
2139
2140 @Override
2141 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2142 Preconditions.checkNotNull(callback, "Callback cannot be null");
2143 synchronized (this) {
2144 final SparseArray<NotedCallback> notedCallbacks =
2145 mNotedWatchers.remove(callback.asBinder());
2146 if (notedCallbacks == null) {
2147 return;
2148 }
2149 final int callbackCount = notedCallbacks.size();
2150 for (int i = 0; i < callbackCount; i++) {
2151 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002152 }
2153 }
2154 }
2155
2156 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002157 public int startOperation(IBinder token, int code, int uid, String packageName,
2158 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002159 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002160 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002161 String resolvedPackageName = resolvePackageName(uid, packageName);
2162 if (resolvedPackageName == null) {
2163 return AppOpsManager.MODE_IGNORED;
2164 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002165 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002166 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002167 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002168 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002169 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002170 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002171 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002172 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002173 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002174 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002175 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002176 return AppOpsManager.MODE_IGNORED;
2177 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002178 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002179 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002180 // If there is a non-default per UID policy (we set UID op mode only if
2181 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002182 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002183 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002184 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002185 if (uidMode != AppOpsManager.MODE_ALLOWED
2186 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002187 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002188 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002189 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002190 // We don't support proxy long running ops (start/stop)
2191 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2192 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2193 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2194 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002195 return uidMode;
2196 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002197 } else {
2198 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002199 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002200 if (mode != AppOpsManager.MODE_ALLOWED
2201 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2202 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002203 + switchCode + " (" + code + ") uid " + uid + " package "
2204 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002205 // We don't support proxy long running ops (start/stop)
2206 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2207 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2208 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2209 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002210 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002211 }
Svet Ganov2af57082015-07-30 08:44:20 -07002212 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002213 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002214 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002215 if (op.startNesting == 0) {
2216 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002217 // We don't support proxy long running ops (start/stop)
2218 op.started(System.currentTimeMillis(), uidState.state,
2219 AppOpsManager.OP_FLAG_SELF);
2220 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2221 uidState.state, AppOpsManager.OP_FLAG_SELF);
2222
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002223 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002224 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002225 op.startNesting++;
2226 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002227 if (client.mStartedOps != null) {
2228 client.mStartedOps.add(op);
2229 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002230 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002231
2232 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002233 }
2234
2235 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002236 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002237 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002238 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002239 String resolvedPackageName = resolvePackageName(uid, packageName);
2240 if (resolvedPackageName == null) {
2241 return;
2242 }
2243 if (!(token instanceof ClientState)) {
2244 return;
2245 }
2246 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002247 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002248 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002249 if (op == null) {
2250 return;
2251 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002252 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002253 // We finish ops when packages get removed to guarantee no dangling
2254 // started ops. However, some part of the system may asynchronously
2255 // finish ops for an already gone package. Hence, finishing an op
2256 // for a non existing package is fine and we don't log as a wtf.
2257 final long identity = Binder.clearCallingIdentity();
2258 try {
2259 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2260 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2261 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2262 + " for non-existing package=" + resolvedPackageName
2263 + " in uid=" + uid);
2264 return;
2265 }
2266 } finally {
2267 Binder.restoreCallingIdentity(identity);
2268 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002269 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002270 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002271 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002272 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002273 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002274 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002275 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2276 }
2277 }
2278 }
2279
2280 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2281 boolean active) {
2282 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2283 final int callbackListCount = mActiveWatchers.size();
2284 for (int i = 0; i < callbackListCount; i++) {
2285 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2286 ActiveCallback callback = callbacks.get(code);
2287 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002288 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002289 continue;
2290 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002291 if (dispatchedCallbacks == null) {
2292 dispatchedCallbacks = new ArraySet<>();
2293 }
2294 dispatchedCallbacks.add(callback);
2295 }
2296 }
2297 if (dispatchedCallbacks == null) {
2298 return;
2299 }
2300 mHandler.sendMessage(PooledLambda.obtainMessage(
2301 AppOpsService::notifyOpActiveChanged,
2302 this, dispatchedCallbacks, code, uid, packageName, active));
2303 }
2304
2305 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2306 int code, int uid, String packageName, boolean active) {
2307 // There are components watching for mode changes such as window manager
2308 // and location manager which are in our process. The callbacks in these
2309 // components may require permissions our remote caller does not have.
2310 final long identity = Binder.clearCallingIdentity();
2311 try {
2312 final int callbackCount = callbacks.size();
2313 for (int i = 0; i < callbackCount; i++) {
2314 final ActiveCallback callback = callbacks.valueAt(i);
2315 try {
2316 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2317 } catch (RemoteException e) {
2318 /* do nothing */
2319 }
2320 }
2321 } finally {
2322 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002323 }
2324 }
2325
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002326 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2327 int result) {
2328 ArraySet<NotedCallback> dispatchedCallbacks = null;
2329 final int callbackListCount = mNotedWatchers.size();
2330 for (int i = 0; i < callbackListCount; i++) {
2331 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2332 final NotedCallback callback = callbacks.get(code);
2333 if (callback != null) {
2334 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2335 continue;
2336 }
2337 if (dispatchedCallbacks == null) {
2338 dispatchedCallbacks = new ArraySet<>();
2339 }
2340 dispatchedCallbacks.add(callback);
2341 }
2342 }
2343 if (dispatchedCallbacks == null) {
2344 return;
2345 }
2346 mHandler.sendMessage(PooledLambda.obtainMessage(
2347 AppOpsService::notifyOpChecked,
2348 this, dispatchedCallbacks, code, uid, packageName, result));
2349 }
2350
2351 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2352 int code, int uid, String packageName, int result) {
2353 // There are components watching for checks in our process. The callbacks in
2354 // these components may require permissions our remote caller does not have.
2355 final long identity = Binder.clearCallingIdentity();
2356 try {
2357 final int callbackCount = callbacks.size();
2358 for (int i = 0; i < callbackCount; i++) {
2359 final NotedCallback callback = callbacks.valueAt(i);
2360 try {
2361 callback.mCallback.opNoted(code, uid, packageName, result);
2362 } catch (RemoteException e) {
2363 /* do nothing */
2364 }
2365 }
2366 } finally {
2367 Binder.restoreCallingIdentity(identity);
2368 }
2369 }
2370
Svet Ganovb9d71a62015-04-30 10:38:13 -07002371 @Override
2372 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002373 if (permission == null) {
2374 return AppOpsManager.OP_NONE;
2375 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002376 return AppOpsManager.permissionToOpCode(permission);
2377 }
2378
Svet Ganova7a0db62018-02-27 20:08:01 -08002379 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002380 final int opCode = op.op;
2381 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002382 if (op.startNesting <= 1 || finishNested) {
2383 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002384 // We don't support proxy long running ops (start/stop)
2385 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2386 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2387 AppOpsManager.OP_FLAG_SELF);
2388 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2389 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002390 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002391 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2392 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2393 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2394 + op.packageName + " code " + opCode + " time="
2395 + entry.getLastAccessTime(OP_FLAGS_ALL)
2396 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2397 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002398 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002399 if (op.startNesting >= 1) {
2400 op.uidState.startNesting -= op.startNesting;
2401 }
2402 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002403 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002404 op.startNesting--;
2405 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002406 }
2407 }
2408
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002409 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002410 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002411 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002412 }
2413 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002414 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002415 }
2416 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2417 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002418 }
2419
Dianne Hackborn961321f2013-02-05 17:22:41 -08002420 private void verifyIncomingOp(int op) {
2421 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2422 return;
2423 }
2424 throw new IllegalArgumentException("Bad operation #" + op);
2425 }
2426
Philip P. Moltmann724150d2019-03-11 17:01:05 -07002427 private @Nullable UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002428 UidState uidState = mUidStates.get(uid);
2429 if (uidState == null) {
2430 if (!edit) {
2431 return null;
2432 }
2433 uidState = new UidState(uid);
2434 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002435 } else {
2436 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002437 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002438 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002439 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002440 mLastRealtime = SystemClock.elapsedRealtime();
2441 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002442 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002443 }
2444 }
2445 }
Svet Ganov2af57082015-07-30 08:44:20 -07002446 }
2447 return uidState;
2448 }
2449
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002450 private void commitUidPendingStateLocked(UidState uidState) {
Wei Wange1f864e2019-03-28 18:12:18 -07002451 if (uidState.hasForegroundWatchers) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002452 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2453 if (!uidState.foregroundOps.valueAt(fgi)) {
2454 continue;
2455 }
2456 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002457 // For location ops we consider fg state only if the fg service
2458 // is of location type, for all other ops any fg service will do.
Wei Wang711eb662019-03-21 18:24:17 -07002459 final long firstUnrestrictedUidState = resolveFirstUnrestrictedUidState(code);
2460 final boolean resolvedLastFg = uidState.state <= firstUnrestrictedUidState;
2461 final boolean resolvedNowFg = uidState.pendingState <= firstUnrestrictedUidState;
2462 if (resolvedLastFg == resolvedNowFg) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002463 continue;
2464 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002465 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2466 if (callbacks != null) {
2467 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2468 final ModeCallback callback = callbacks.valueAt(cbi);
2469 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2470 || !callback.isWatchingUid(uidState.uid)) {
2471 continue;
2472 }
2473 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002474 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002475 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2476 if (uidState.pkgOps != null) {
2477 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2478 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002479 if (op == null) {
2480 continue;
2481 }
2482 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002483 mHandler.sendMessage(PooledLambda.obtainMessage(
2484 AppOpsService::notifyOpChanged,
2485 this, callback, code, uidState.uid,
2486 uidState.pkgOps.keyAt(pkgi)));
2487 }
2488 }
2489 }
2490 }
2491 }
2492 }
2493 }
Wei Wang711eb662019-03-21 18:24:17 -07002494 uidState.state = uidState.pendingState;
2495 uidState.pendingStateCommitTime = 0;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002496 }
2497
Yohei Yukawaa965d652017-10-12 15:02:26 -07002498 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2499 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002500 UidState uidState = getUidStateLocked(uid, edit);
2501 if (uidState == null) {
2502 return null;
2503 }
2504
2505 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002506 if (!edit) {
2507 return null;
2508 }
Svet Ganov2af57082015-07-30 08:44:20 -07002509 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002510 }
Svet Ganov2af57082015-07-30 08:44:20 -07002511
2512 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002513 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002514 if (!edit) {
2515 return null;
2516 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002517 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002518 // This is the first time we have seen this package name under this uid,
2519 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002520 if (uid != 0) {
2521 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002522 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002523 int pkgUid = -1;
2524 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002525 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002526 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002527 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002528 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002529 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002530 if (appInfo != null) {
2531 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002532 isPrivileged = (appInfo.privateFlags
2533 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002534 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002535 pkgUid = resolveUid(packageName);
2536 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002537 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002538 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002539 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002540 } catch (RemoteException e) {
2541 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002542 }
2543 if (pkgUid != uid) {
2544 // Oops! The package name is not valid for the uid they are calling
2545 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002546 if (!uidMismatchExpected) {
2547 RuntimeException ex = new RuntimeException("here");
2548 ex.fillInStackTrace();
2549 Slog.w(TAG, "Bad call: specified package " + packageName
2550 + " under uid " + uid + " but it is really " + pkgUid, ex);
2551 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002552 return null;
2553 }
2554 } finally {
2555 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002556 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002557 }
Svet Ganov2af57082015-07-30 08:44:20 -07002558 ops = new Ops(packageName, uidState, isPrivileged);
2559 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002560 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002561 return ops;
2562 }
2563
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002564 /**
2565 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2566 *
2567 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2568 *
2569 * @param uid The uid the of the package
2570 * @param packageName The package name for which to get the state for
2571 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2572 * @param isPrivileged Whether the package is privileged or not
2573 *
2574 * @return The {@link Ops state} of all ops for the package
2575 */
2576 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2577 boolean edit, boolean isPrivileged) {
2578 UidState uidState = getUidStateLocked(uid, edit);
2579 if (uidState == null) {
2580 return null;
2581 }
2582
2583 if (uidState.pkgOps == null) {
2584 if (!edit) {
2585 return null;
2586 }
2587 uidState.pkgOps = new ArrayMap<>();
2588 }
2589
2590 Ops ops = uidState.pkgOps.get(packageName);
2591 if (ops == null) {
2592 if (!edit) {
2593 return null;
2594 }
2595 ops = new Ops(packageName, uidState, isPrivileged);
2596 uidState.pkgOps.put(packageName, ops);
2597 }
2598 return ops;
2599 }
2600
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002601 private void scheduleWriteLocked() {
2602 if (!mWriteScheduled) {
2603 mWriteScheduled = true;
2604 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2605 }
2606 }
2607
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002608 private void scheduleFastWriteLocked() {
2609 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002610 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002611 mFastWriteScheduled = true;
2612 mHandler.removeCallbacks(mWriteRunner);
2613 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002614 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002615 }
2616
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002617 /**
2618 * Get the state of an op for a uid.
2619 *
2620 * @param code The code of the op
2621 * @param uid The uid the of the package
2622 * @param packageName The package name for which to get the state for
2623 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2624 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2625 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2626 * == false})
2627 *
2628 * @return The {@link Op state} of the op
2629 */
2630 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2631 boolean verifyUid, boolean isPrivileged) {
2632 Ops ops;
2633
2634 if (verifyUid) {
2635 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2636 } else {
2637 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2638 }
2639
Dianne Hackborn72e39832013-01-18 18:36:09 -08002640 if (ops == null) {
2641 return null;
2642 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002643 return getOpLocked(ops, code, edit);
2644 }
2645
2646 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002647 Op op = ops.get(code);
2648 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002649 if (!edit) {
2650 return null;
2651 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002652 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002653 ops.put(code, op);
2654 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002655 if (edit) {
2656 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002657 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002658 return op;
2659 }
2660
Svet Ganov442ed572016-08-17 17:29:43 -07002661 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002662 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002663 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002664
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002665 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002666 // For each client, check that the given op is not restricted, or that the given
2667 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002668 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002669 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2670 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2671 // If we are the system, bypass user restrictions for certain codes
2672 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002673 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2674 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002675 if ((ops != null) && ops.isPrivileged) {
2676 return false;
2677 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002678 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002679 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002680 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002681 }
Jason Monk62062992014-05-06 09:55:28 -04002682 }
2683 return false;
2684 }
2685
Dianne Hackborn35654b62013-01-14 17:38:02 -08002686 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002687 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002688 synchronized (mFile) {
2689 synchronized (this) {
2690 FileInputStream stream;
2691 try {
2692 stream = mFile.openRead();
2693 } catch (FileNotFoundException e) {
2694 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2695 return;
2696 }
2697 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002698 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002699 try {
2700 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002701 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002702 int type;
2703 while ((type = parser.next()) != XmlPullParser.START_TAG
2704 && type != XmlPullParser.END_DOCUMENT) {
2705 ;
2706 }
2707
2708 if (type != XmlPullParser.START_TAG) {
2709 throw new IllegalStateException("no start tag found");
2710 }
2711
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002712 final String versionString = parser.getAttributeValue(null, "v");
2713 if (versionString != null) {
2714 oldVersion = Integer.parseInt(versionString);
2715 }
2716
Dianne Hackborn35654b62013-01-14 17:38:02 -08002717 int outerDepth = parser.getDepth();
2718 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2719 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2720 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2721 continue;
2722 }
2723
2724 String tagName = parser.getName();
2725 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002726 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002727 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002728 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002729 } else {
2730 Slog.w(TAG, "Unknown element under <app-ops>: "
2731 + parser.getName());
2732 XmlUtils.skipCurrentTag(parser);
2733 }
2734 }
2735 success = true;
2736 } catch (IllegalStateException e) {
2737 Slog.w(TAG, "Failed parsing " + e);
2738 } catch (NullPointerException e) {
2739 Slog.w(TAG, "Failed parsing " + e);
2740 } catch (NumberFormatException e) {
2741 Slog.w(TAG, "Failed parsing " + e);
2742 } catch (XmlPullParserException e) {
2743 Slog.w(TAG, "Failed parsing " + e);
2744 } catch (IOException e) {
2745 Slog.w(TAG, "Failed parsing " + e);
2746 } catch (IndexOutOfBoundsException e) {
2747 Slog.w(TAG, "Failed parsing " + e);
2748 } finally {
2749 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002750 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002751 }
2752 try {
2753 stream.close();
2754 } catch (IOException e) {
2755 }
2756 }
2757 }
2758 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002759 synchronized (this) {
2760 upgradeLocked(oldVersion);
2761 }
2762 }
2763
2764 private void upgradeRunAnyInBackgroundLocked() {
2765 for (int i = 0; i < mUidStates.size(); i++) {
2766 final UidState uidState = mUidStates.valueAt(i);
2767 if (uidState == null) {
2768 continue;
2769 }
2770 if (uidState.opModes != null) {
2771 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2772 if (idx >= 0) {
2773 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002774 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002775 }
2776 }
2777 if (uidState.pkgOps == null) {
2778 continue;
2779 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002780 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002781 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2782 Ops ops = uidState.pkgOps.valueAt(j);
2783 if (ops != null) {
2784 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2785 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002786 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002787 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002788 copy.mode = op.mode;
2789 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002790 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002791 }
2792 }
2793 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002794 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002795 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002796 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002797 }
2798 }
2799
2800 private void upgradeLocked(int oldVersion) {
2801 if (oldVersion >= CURRENT_VERSION) {
2802 return;
2803 }
2804 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2805 switch (oldVersion) {
2806 case NO_VERSION:
2807 upgradeRunAnyInBackgroundLocked();
2808 // fall through
2809 case 1:
2810 // for future upgrades
2811 }
2812 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002813 }
2814
Svet Ganovaf189e32019-02-15 18:45:29 -08002815 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002816 XmlPullParserException, IOException {
2817 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2818 int outerDepth = parser.getDepth();
2819 int type;
2820 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2821 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2822 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2823 continue;
2824 }
2825
2826 String tagName = parser.getName();
2827 if (tagName.equals("op")) {
2828 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2829 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2830 UidState uidState = getUidStateLocked(uid, true);
2831 if (uidState.opModes == null) {
2832 uidState.opModes = new SparseIntArray();
2833 }
2834 uidState.opModes.put(code, mode);
2835 } else {
2836 Slog.w(TAG, "Unknown element under <uid-ops>: "
2837 + parser.getName());
2838 XmlUtils.skipCurrentTag(parser);
2839 }
2840 }
2841 }
2842
Svet Ganovaf189e32019-02-15 18:45:29 -08002843 private void readPackage(XmlPullParser parser)
2844 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002845 String pkgName = parser.getAttributeValue(null, "n");
2846 int outerDepth = parser.getDepth();
2847 int type;
2848 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2849 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2850 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2851 continue;
2852 }
2853
2854 String tagName = parser.getName();
2855 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002856 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002857 } else {
2858 Slog.w(TAG, "Unknown element under <pkg>: "
2859 + parser.getName());
2860 XmlUtils.skipCurrentTag(parser);
2861 }
2862 }
2863 }
2864
Svet Ganovaf189e32019-02-15 18:45:29 -08002865 private void readUid(XmlPullParser parser, String pkgName)
2866 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002867 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002868 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002869 String isPrivilegedString = parser.getAttributeValue(null, "p");
2870 boolean isPrivileged = false;
2871 if (isPrivilegedString == null) {
2872 try {
2873 IPackageManager packageManager = ActivityThread.getPackageManager();
2874 if (packageManager != null) {
2875 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2876 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2877 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002878 isPrivileged = (appInfo.privateFlags
2879 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002880 }
2881 } else {
2882 // Could not load data, don't add to cache so it will be loaded later.
2883 return;
2884 }
2885 } catch (RemoteException e) {
2886 Slog.w(TAG, "Could not contact PackageManager", e);
2887 }
2888 } else {
2889 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2890 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002891 int outerDepth = parser.getDepth();
2892 int type;
2893 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2894 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2895 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2896 continue;
2897 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002898 String tagName = parser.getName();
2899 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002900 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002901 } else {
2902 Slog.w(TAG, "Unknown element under <pkg>: "
2903 + parser.getName());
2904 XmlUtils.skipCurrentTag(parser);
2905 }
2906 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002907 uidState.evalForegroundOps(mOpModeWatchers);
2908 }
2909
2910 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2911 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2912 XmlPullParserException, IOException {
2913 Op op = new Op(uidState, pkgName,
2914 Integer.parseInt(parser.getAttributeValue(null, "n")));
2915
2916 final int mode = XmlUtils.readIntAttribute(parser, "m",
2917 AppOpsManager.opToDefaultMode(op.op));
2918 op.mode = mode;
2919
2920 int outerDepth = parser.getDepth();
2921 int type;
2922 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2923 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2924 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2925 continue;
2926 }
2927 String tagName = parser.getName();
2928 if (tagName.equals("st")) {
2929 final long key = XmlUtils.readLongAttribute(parser, "n");
2930
2931 final int flags = AppOpsManager.extractFlagsFromKey(key);
2932 final int state = AppOpsManager.extractUidStateFromKey(key);
2933
2934 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2935 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2936 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2937 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2938 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2939
2940 if (accessTime > 0) {
2941 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2942 }
2943 if (rejectTime > 0) {
2944 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2945 }
2946 if (accessDuration > 0) {
2947 op.running(accessTime, accessDuration, state, flags);
2948 }
2949 } else {
2950 Slog.w(TAG, "Unknown element under <op>: "
2951 + parser.getName());
2952 XmlUtils.skipCurrentTag(parser);
2953 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002954 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002955
2956 if (uidState.pkgOps == null) {
2957 uidState.pkgOps = new ArrayMap<>();
2958 }
2959 Ops ops = uidState.pkgOps.get(pkgName);
2960 if (ops == null) {
2961 ops = new Ops(pkgName, uidState, isPrivileged);
2962 uidState.pkgOps.put(pkgName, ops);
2963 }
2964 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002965 }
2966
2967 void writeState() {
2968 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002969 FileOutputStream stream;
2970 try {
2971 stream = mFile.startWrite();
2972 } catch (IOException e) {
2973 Slog.w(TAG, "Failed to write state: " + e);
2974 return;
2975 }
2976
Dianne Hackborne17b4452018-01-10 13:15:40 -08002977 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2978
Dianne Hackborn35654b62013-01-14 17:38:02 -08002979 try {
2980 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002981 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002982 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002983 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002984 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002985
Eugene Susla3454f3e2019-08-28 14:28:32 -07002986 SparseArray<SparseIntArray> uidStatesClone;
2987 synchronized (this) {
2988 uidStatesClone = new SparseArray<>(mUidStates.size());
2989
2990 final int uidStateCount = mUidStates.size();
2991 for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
2992 UidState uidState = mUidStates.valueAt(uidStateNum);
2993 int uid = mUidStates.keyAt(uidStateNum);
2994
2995 SparseIntArray opModes = uidState.opModes;
2996 if (opModes != null && opModes.size() > 0) {
2997 uidStatesClone.put(uid, new SparseIntArray(opModes.size()));
2998
2999 final int opCount = opModes.size();
3000 for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
3001 uidStatesClone.get(uid).put(
3002 opModes.keyAt(opCountNum),
3003 opModes.valueAt(opCountNum));
3004 }
3005 }
3006 }
3007 }
3008
3009 final int uidStateCount = uidStatesClone.size();
3010 for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
3011 SparseIntArray opModes = uidStatesClone.valueAt(uidStateNum);
3012 if (opModes != null && opModes.size() > 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07003013 out.startTag(null, "uid");
Eugene Susla3454f3e2019-08-28 14:28:32 -07003014 out.attribute(null, "n",
3015 Integer.toString(uidStatesClone.keyAt(uidStateNum)));
3016 final int opCount = opModes.size();
3017 for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
3018 final int op = opModes.keyAt(opCountNum);
3019 final int mode = opModes.valueAt(opCountNum);
Svet Ganov2af57082015-07-30 08:44:20 -07003020 out.startTag(null, "op");
3021 out.attribute(null, "n", Integer.toString(op));
3022 out.attribute(null, "m", Integer.toString(mode));
3023 out.endTag(null, "op");
3024 }
3025 out.endTag(null, "uid");
3026 }
3027 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003028
3029 if (allOps != null) {
3030 String lastPkg = null;
3031 for (int i=0; i<allOps.size(); i++) {
3032 AppOpsManager.PackageOps pkg = allOps.get(i);
3033 if (!pkg.getPackageName().equals(lastPkg)) {
3034 if (lastPkg != null) {
3035 out.endTag(null, "pkg");
3036 }
3037 lastPkg = pkg.getPackageName();
3038 out.startTag(null, "pkg");
3039 out.attribute(null, "n", lastPkg);
3040 }
3041 out.startTag(null, "uid");
3042 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04003043 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07003044 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
3045 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04003046 // Should always be present as the list of PackageOps is generated
3047 // from Ops.
3048 if (ops != null) {
3049 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
3050 } else {
3051 out.attribute(null, "p", Boolean.toString(false));
3052 }
3053 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003054 List<AppOpsManager.OpEntry> ops = pkg.getOps();
3055 for (int j=0; j<ops.size(); j++) {
3056 AppOpsManager.OpEntry op = ops.get(j);
3057 out.startTag(null, "op");
3058 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07003059 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003060 out.attribute(null, "m", Integer.toString(op.getMode()));
3061 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003062
3063 final LongSparseArray keys = op.collectKeys();
3064 if (keys == null || keys.size() <= 0) {
Svet Ganov8e5bf962019-03-19 23:59:03 -07003065 out.endTag(null, "op");
Svet Ganovaf189e32019-02-15 18:45:29 -08003066 continue;
3067 }
3068
3069 final int keyCount = keys.size();
3070 for (int k = 0; k < keyCount; k++) {
3071 final long key = keys.keyAt(k);
3072
3073 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3074 final int flags = AppOpsManager.extractFlagsFromKey(key);
3075
3076 final long accessTime = op.getLastAccessTime(
3077 uidState, uidState, flags);
3078 final long rejectTime = op.getLastRejectTime(
3079 uidState, uidState, flags);
3080 final long accessDuration = op.getLastDuration(
3081 uidState, uidState, flags);
3082 final String proxyPkg = op.getProxyPackageName(uidState, flags);
3083 final int proxyUid = op.getProxyUid(uidState, flags);
3084
3085 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3086 && proxyPkg == null && proxyUid < 0) {
3087 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003088 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003089
3090 out.startTag(null, "st");
3091 out.attribute(null, "n", Long.toString(key));
3092 if (accessTime > 0) {
3093 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003094 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003095 if (rejectTime > 0) {
3096 out.attribute(null, "r", Long.toString(rejectTime));
3097 }
3098 if (accessDuration > 0) {
3099 out.attribute(null, "d", Long.toString(accessDuration));
3100 }
3101 if (proxyPkg != null) {
3102 out.attribute(null, "pp", proxyPkg);
3103 }
3104 if (proxyUid >= 0) {
3105 out.attribute(null, "pu", Integer.toString(proxyUid));
3106 }
3107 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003108 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003109
Dianne Hackborn35654b62013-01-14 17:38:02 -08003110 out.endTag(null, "op");
3111 }
3112 out.endTag(null, "uid");
3113 }
3114 if (lastPkg != null) {
3115 out.endTag(null, "pkg");
3116 }
3117 }
3118
3119 out.endTag(null, "app-ops");
3120 out.endDocument();
3121 mFile.finishWrite(stream);
3122 } catch (IOException e) {
3123 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3124 mFile.failWrite(stream);
3125 }
3126 }
3127 }
3128
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003129 static class Shell extends ShellCommand {
3130 final IAppOpsService mInterface;
3131 final AppOpsService mInternal;
3132
3133 int userId = UserHandle.USER_SYSTEM;
3134 String packageName;
3135 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003136 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003137 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003138 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003139 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003140 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003141 final static Binder sBinder = new Binder();
3142 IBinder mToken;
Svet Ganovd563e932019-04-14 13:07:41 -07003143 boolean targetsUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003144
3145 Shell(IAppOpsService iface, AppOpsService internal) {
3146 mInterface = iface;
3147 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003148 try {
3149 mToken = mInterface.getToken(sBinder);
3150 } catch (RemoteException e) {
3151 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003152 }
3153
3154 @Override
3155 public int onCommand(String cmd) {
3156 return onShellCommand(this, cmd);
3157 }
3158
3159 @Override
3160 public void onHelp() {
3161 PrintWriter pw = getOutPrintWriter();
3162 dumpCommandHelp(pw);
3163 }
3164
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003165 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003166 try {
3167 return AppOpsManager.strOpToOp(op);
3168 } catch (IllegalArgumentException e) {
3169 }
3170 try {
3171 return Integer.parseInt(op);
3172 } catch (NumberFormatException e) {
3173 }
3174 try {
3175 return AppOpsManager.strDebugOpToOp(op);
3176 } catch (IllegalArgumentException e) {
3177 err.println("Error: " + e.getMessage());
3178 return -1;
3179 }
3180 }
3181
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003182 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003183 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3184 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003185 return i;
3186 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003187 }
3188 try {
3189 return Integer.parseInt(modeStr);
3190 } catch (NumberFormatException e) {
3191 }
3192 err.println("Error: Mode " + modeStr + " is not valid");
3193 return -1;
3194 }
3195
3196 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3197 userId = UserHandle.USER_CURRENT;
3198 opStr = null;
3199 modeStr = null;
3200 for (String argument; (argument = getNextArg()) != null;) {
3201 if ("--user".equals(argument)) {
3202 userId = UserHandle.parseUserArg(getNextArgRequired());
3203 } else {
3204 if (opStr == null) {
3205 opStr = argument;
3206 } else if (modeStr == null) {
3207 modeStr = argument;
3208 break;
3209 }
3210 }
3211 }
3212 if (opStr == null) {
3213 err.println("Error: Operation not specified.");
3214 return -1;
3215 }
3216 op = strOpToOp(opStr, err);
3217 if (op < 0) {
3218 return -1;
3219 }
3220 if (modeStr != null) {
3221 if ((mode=strModeToMode(modeStr, err)) < 0) {
3222 return -1;
3223 }
3224 } else {
3225 mode = defMode;
3226 }
3227 return 0;
3228 }
3229
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003230 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3231 userId = UserHandle.USER_CURRENT;
3232 packageName = null;
3233 opStr = null;
3234 for (String argument; (argument = getNextArg()) != null;) {
3235 if ("--user".equals(argument)) {
3236 userId = UserHandle.parseUserArg(getNextArgRequired());
Svet Ganovd563e932019-04-14 13:07:41 -07003237 } else if ("--uid".equals(argument)) {
3238 targetsUid = true;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003239 } else {
3240 if (packageName == null) {
3241 packageName = argument;
3242 } else if (opStr == null) {
3243 opStr = argument;
3244 break;
3245 }
3246 }
3247 }
3248 if (packageName == null) {
3249 err.println("Error: Package name not specified.");
3250 return -1;
3251 } else if (opStr == null && reqOp) {
3252 err.println("Error: Operation not specified.");
3253 return -1;
3254 }
3255 if (opStr != null) {
3256 op = strOpToOp(opStr, err);
3257 if (op < 0) {
3258 return -1;
3259 }
3260 } else {
3261 op = AppOpsManager.OP_NONE;
3262 }
3263 if (userId == UserHandle.USER_CURRENT) {
3264 userId = ActivityManager.getCurrentUser();
3265 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003266 nonpackageUid = -1;
3267 try {
3268 nonpackageUid = Integer.parseInt(packageName);
3269 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003270 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003271 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3272 && packageName.indexOf('.') < 0) {
3273 int i = 1;
3274 while (i < packageName.length() && packageName.charAt(i) >= '0'
3275 && packageName.charAt(i) <= '9') {
3276 i++;
3277 }
3278 if (i > 1 && i < packageName.length()) {
3279 String userStr = packageName.substring(1, i);
3280 try {
3281 int user = Integer.parseInt(userStr);
3282 char type = packageName.charAt(i);
3283 i++;
3284 int startTypeVal = i;
3285 while (i < packageName.length() && packageName.charAt(i) >= '0'
3286 && packageName.charAt(i) <= '9') {
3287 i++;
3288 }
3289 if (i > startTypeVal) {
3290 String typeValStr = packageName.substring(startTypeVal, i);
3291 try {
3292 int typeVal = Integer.parseInt(typeValStr);
3293 if (type == 'a') {
3294 nonpackageUid = UserHandle.getUid(user,
3295 typeVal + Process.FIRST_APPLICATION_UID);
3296 } else if (type == 's') {
3297 nonpackageUid = UserHandle.getUid(user, typeVal);
3298 }
3299 } catch (NumberFormatException e) {
3300 }
3301 }
3302 } catch (NumberFormatException e) {
3303 }
3304 }
3305 }
3306 if (nonpackageUid != -1) {
3307 packageName = null;
3308 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003309 packageUid = resolveUid(packageName);
3310 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003311 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3312 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3313 }
3314 if (packageUid < 0) {
3315 err.println("Error: No UID for " + packageName + " in user " + userId);
3316 return -1;
3317 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003318 }
3319 return 0;
3320 }
3321 }
3322
3323 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003324 FileDescriptor err, String[] args, ShellCallback callback,
3325 ResultReceiver resultReceiver) {
3326 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003327 }
3328
3329 static void dumpCommandHelp(PrintWriter pw) {
3330 pw.println("AppOps service (appops) commands:");
3331 pw.println(" help");
3332 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003333 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3334 pw.println(" Starts a given operation for a particular application.");
3335 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3336 pw.println(" Stops a given operation for a particular application.");
Svet Ganovb687fad2019-04-30 17:32:44 -07003337 pw.println(" set [--user <USER_ID>] <[--uid] PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003338 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003339 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003340 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003341 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3342 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003343 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3344 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003345 pw.println(" write-settings");
3346 pw.println(" Immediately write pending changes to storage.");
3347 pw.println(" read-settings");
3348 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003349 pw.println(" options:");
Svet Ganovb687fad2019-04-30 17:32:44 -07003350 pw.println(" <PACKAGE> an Android package name or its UID if prefixed by --uid");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003351 pw.println(" <OP> an AppOps operation.");
3352 pw.println(" <MODE> one of allow, ignore, deny, or default");
3353 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3354 pw.println(" specified, the current user is assumed.");
3355 }
3356
3357 static int onShellCommand(Shell shell, String cmd) {
3358 if (cmd == null) {
3359 return shell.handleDefaultCommands(cmd);
3360 }
3361 PrintWriter pw = shell.getOutPrintWriter();
3362 PrintWriter err = shell.getErrPrintWriter();
3363 try {
3364 switch (cmd) {
3365 case "set": {
3366 int res = shell.parseUserPackageOp(true, err);
3367 if (res < 0) {
3368 return res;
3369 }
3370 String modeStr = shell.getNextArg();
3371 if (modeStr == null) {
3372 err.println("Error: Mode not specified.");
3373 return -1;
3374 }
3375
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003376 final int mode = shell.strModeToMode(modeStr, err);
3377 if (mode < 0) {
3378 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003379 }
3380
Svet Ganovd563e932019-04-14 13:07:41 -07003381 if (!shell.targetsUid && shell.packageName != null) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003382 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3383 mode);
Svet Ganovd563e932019-04-14 13:07:41 -07003384 } else if (shell.targetsUid && shell.packageName != null) {
3385 try {
3386 final int uid = shell.mInternal.mContext.getPackageManager()
3387 .getPackageUid(shell.packageName, shell.userId);
3388 shell.mInterface.setUidMode(shell.op, uid, mode);
3389 } catch (PackageManager.NameNotFoundException e) {
3390 return -1;
3391 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003392 } else {
3393 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3394 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003395 return 0;
3396 }
3397 case "get": {
3398 int res = shell.parseUserPackageOp(false, err);
3399 if (res < 0) {
3400 return res;
3401 }
3402
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003403 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003404 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003405 // Uid mode overrides package mode, so make sure it's also reported
3406 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3407 shell.packageUid,
3408 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3409 if (r != null) {
3410 ops.addAll(r);
3411 }
3412 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003413 shell.packageUid, shell.packageName,
3414 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003415 if (r != null) {
3416 ops.addAll(r);
3417 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003418 } else {
3419 ops = shell.mInterface.getUidOps(
3420 shell.nonpackageUid,
3421 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3422 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003423 if (ops == null || ops.size() <= 0) {
3424 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003425 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003426 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003427 AppOpsManager.opToDefaultMode(shell.op)));
3428 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003429 return 0;
3430 }
3431 final long now = System.currentTimeMillis();
3432 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003433 AppOpsManager.PackageOps packageOps = ops.get(i);
3434 if (packageOps.getPackageName() == null) {
3435 pw.print("Uid mode: ");
3436 }
3437 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003438 for (int j=0; j<entries.size(); j++) {
3439 AppOpsManager.OpEntry ent = entries.get(j);
3440 pw.print(AppOpsManager.opToName(ent.getOp()));
3441 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003442 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003443 if (ent.getTime() != 0) {
3444 pw.print("; time=");
3445 TimeUtils.formatDuration(now - ent.getTime(), pw);
3446 pw.print(" ago");
3447 }
3448 if (ent.getRejectTime() != 0) {
3449 pw.print("; rejectTime=");
3450 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3451 pw.print(" ago");
3452 }
3453 if (ent.getDuration() == -1) {
3454 pw.print(" (running)");
3455 } else if (ent.getDuration() != 0) {
3456 pw.print("; duration=");
3457 TimeUtils.formatDuration(ent.getDuration(), pw);
3458 }
3459 pw.println();
3460 }
3461 }
3462 return 0;
3463 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003464 case "query-op": {
3465 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3466 if (res < 0) {
3467 return res;
3468 }
3469 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3470 new int[] {shell.op});
3471 if (ops == null || ops.size() <= 0) {
3472 pw.println("No operations.");
3473 return 0;
3474 }
3475 for (int i=0; i<ops.size(); i++) {
3476 final AppOpsManager.PackageOps pkg = ops.get(i);
3477 boolean hasMatch = false;
3478 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3479 for (int j=0; j<entries.size(); j++) {
3480 AppOpsManager.OpEntry ent = entries.get(j);
3481 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3482 hasMatch = true;
3483 break;
3484 }
3485 }
3486 if (hasMatch) {
3487 pw.println(pkg.getPackageName());
3488 }
3489 }
3490 return 0;
3491 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003492 case "reset": {
3493 String packageName = null;
3494 int userId = UserHandle.USER_CURRENT;
3495 for (String argument; (argument = shell.getNextArg()) != null;) {
3496 if ("--user".equals(argument)) {
3497 String userStr = shell.getNextArgRequired();
3498 userId = UserHandle.parseUserArg(userStr);
3499 } else {
3500 if (packageName == null) {
3501 packageName = argument;
3502 } else {
3503 err.println("Error: Unsupported argument: " + argument);
3504 return -1;
3505 }
3506 }
3507 }
3508
3509 if (userId == UserHandle.USER_CURRENT) {
3510 userId = ActivityManager.getCurrentUser();
3511 }
3512
3513 shell.mInterface.resetAllModes(userId, packageName);
3514 pw.print("Reset all modes for: ");
3515 if (userId == UserHandle.USER_ALL) {
3516 pw.print("all users");
3517 } else {
3518 pw.print("user "); pw.print(userId);
3519 }
3520 pw.print(", ");
3521 if (packageName == null) {
3522 pw.println("all packages");
3523 } else {
3524 pw.print("package "); pw.println(packageName);
3525 }
3526 return 0;
3527 }
3528 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003529 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3530 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003531 long token = Binder.clearCallingIdentity();
3532 try {
3533 synchronized (shell.mInternal) {
3534 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3535 }
3536 shell.mInternal.writeState();
3537 pw.println("Current settings written.");
3538 } finally {
3539 Binder.restoreCallingIdentity(token);
3540 }
3541 return 0;
3542 }
3543 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003544 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3545 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003546 long token = Binder.clearCallingIdentity();
3547 try {
3548 shell.mInternal.readState();
3549 pw.println("Last settings read.");
3550 } finally {
3551 Binder.restoreCallingIdentity(token);
3552 }
3553 return 0;
3554 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003555 case "start": {
3556 int res = shell.parseUserPackageOp(true, err);
3557 if (res < 0) {
3558 return res;
3559 }
3560
3561 if (shell.packageName != null) {
3562 shell.mInterface.startOperation(shell.mToken,
3563 shell.op, shell.packageUid, shell.packageName, true);
3564 } else {
3565 return -1;
3566 }
3567 return 0;
3568 }
3569 case "stop": {
3570 int res = shell.parseUserPackageOp(true, err);
3571 if (res < 0) {
3572 return res;
3573 }
3574
3575 if (shell.packageName != null) {
3576 shell.mInterface.finishOperation(shell.mToken,
3577 shell.op, shell.packageUid, shell.packageName);
3578 } else {
3579 return -1;
3580 }
3581 return 0;
3582 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003583 default:
3584 return shell.handleDefaultCommands(cmd);
3585 }
3586 } catch (RemoteException e) {
3587 pw.println("Remote exception: " + e);
3588 }
3589 return -1;
3590 }
3591
3592 private void dumpHelp(PrintWriter pw) {
3593 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003594 pw.println(" -h");
3595 pw.println(" Print this help text.");
3596 pw.println(" --op [OP]");
3597 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003598 pw.println(" --mode [MODE]");
3599 pw.println(" Limit output to data associated with the given app op mode.");
3600 pw.println(" --package [PACKAGE]");
3601 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003602 pw.println(" --watchers");
3603 pw.println(" Only output the watcher sections.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003604 }
3605
Svet Ganovaf189e32019-02-15 18:45:29 -08003606 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3607 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3608
3609 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3610 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3611
3612 final LongSparseArray keys = entry.collectKeys();
3613 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003614 return;
3615 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003616
3617 final int keyCount = keys.size();
3618 for (int k = 0; k < keyCount; k++) {
3619 final long key = keys.keyAt(k);
3620
3621 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3622 final int flags = AppOpsManager.extractFlagsFromKey(key);
3623
3624 final long accessTime = entry.getLastAccessTime(
3625 uidState, uidState, flags);
3626 final long rejectTime = entry.getLastRejectTime(
3627 uidState, uidState, flags);
3628 final long accessDuration = entry.getLastDuration(
3629 uidState, uidState, flags);
3630 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3631 final int proxyUid = entry.getProxyUid(uidState, flags);
3632
3633 if (accessTime > 0) {
3634 pw.print(prefix);
3635 pw.print("Access: ");
3636 pw.print(AppOpsManager.keyToString(key));
3637 pw.print(" ");
3638 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003639 pw.print(sdf.format(date));
3640 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003641 TimeUtils.formatDuration(accessTime - now, pw);
3642 pw.print(")");
3643 if (accessDuration > 0) {
3644 pw.print(" duration=");
3645 TimeUtils.formatDuration(accessDuration, pw);
3646 }
3647 if (proxyUid >= 0) {
3648 pw.print(" proxy[");
3649 pw.print("uid=");
3650 pw.print(proxyUid);
3651 pw.print(", pkg=");
3652 pw.print(proxyPkg);
3653 pw.print("]");
3654 }
3655 pw.println();
3656 }
3657
3658 if (rejectTime > 0) {
3659 pw.print(prefix);
3660 pw.print("Reject: ");
3661 pw.print(AppOpsManager.keyToString(key));
3662 date.setTime(rejectTime);
3663 pw.print(sdf.format(date));
3664 pw.print(" (");
3665 TimeUtils.formatDuration(rejectTime - now, pw);
3666 pw.print(")");
3667 if (proxyUid >= 0) {
3668 pw.print(" proxy[");
3669 pw.print("uid=");
3670 pw.print(proxyUid);
3671 pw.print(", pkg=");
3672 pw.print(proxyPkg);
3673 pw.print("]");
3674 }
3675 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003676 }
3677 }
3678 }
3679
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003680 @Override
3681 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003682 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003683
Svet Ganov8455ba22019-01-02 13:05:56 -08003684 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003685 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003686 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003687 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003688 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003689 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003690
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003691 if (args != null) {
3692 for (int i=0; i<args.length; i++) {
3693 String arg = args[i];
3694 if ("-h".equals(arg)) {
3695 dumpHelp(pw);
3696 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003697 } else if ("-a".equals(arg)) {
3698 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003699 } else if ("--op".equals(arg)) {
3700 i++;
3701 if (i >= args.length) {
3702 pw.println("No argument for --op option");
3703 return;
3704 }
3705 dumpOp = Shell.strOpToOp(args[i], pw);
3706 if (dumpOp < 0) {
3707 return;
3708 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003709 } else if ("--package".equals(arg)) {
3710 i++;
3711 if (i >= args.length) {
3712 pw.println("No argument for --package option");
3713 return;
3714 }
3715 dumpPackage = args[i];
3716 try {
3717 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3718 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3719 0);
3720 } catch (RemoteException e) {
3721 }
3722 if (dumpUid < 0) {
3723 pw.println("Unknown package: " + dumpPackage);
3724 return;
3725 }
3726 dumpUid = UserHandle.getAppId(dumpUid);
3727 } else if ("--mode".equals(arg)) {
3728 i++;
3729 if (i >= args.length) {
3730 pw.println("No argument for --mode option");
3731 return;
3732 }
3733 dumpMode = Shell.strModeToMode(args[i], pw);
3734 if (dumpMode < 0) {
3735 return;
3736 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003737 } else if ("--watchers".equals(arg)) {
3738 dumpWatchers = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003739 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3740 pw.println("Unknown option: " + arg);
3741 return;
3742 } else {
3743 pw.println("Unknown command: " + arg);
3744 return;
3745 }
3746 }
3747 }
3748
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003749 synchronized (this) {
3750 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003751 if (!dumpHistory && !dumpWatchers) {
3752 mConstants.dump(pw);
3753 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003754 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003755 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003756 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003757 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003758 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3759 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003760 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003761 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003762 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003763 pw.println(" Profile owners:");
3764 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3765 pw.print(" User #");
3766 pw.print(mProfileOwners.keyAt(poi));
3767 pw.print(": ");
3768 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3769 pw.println();
3770 }
3771 pw.println();
3772 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003773 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003774 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003775 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003776 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3777 continue;
3778 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003779 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003780 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003781 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003782 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003783 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003784 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3785 continue;
3786 }
3787 needSep = true;
3788 if (!printedHeader) {
3789 pw.println(" Op mode watchers:");
3790 printedHeader = true;
3791 }
3792 if (!printedOpHeader) {
3793 pw.print(" Op ");
3794 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3795 pw.println(":");
3796 printedOpHeader = true;
3797 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003798 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003799 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003800 }
3801 }
3802 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003803 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003804 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003805 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003806 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3807 continue;
3808 }
3809 needSep = true;
3810 if (!printedHeader) {
3811 pw.println(" Package mode watchers:");
3812 printedHeader = true;
3813 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003814 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3815 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003816 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003817 for (int j=0; j<callbacks.size(); j++) {
3818 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003819 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003820 }
3821 }
3822 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003823 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003824 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003825 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003826 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003827 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003828 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3829 continue;
3830 }
3831 needSep = true;
3832 if (!printedHeader) {
3833 pw.println(" All op mode watchers:");
3834 printedHeader = true;
3835 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003836 pw.print(" ");
3837 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003838 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003839 }
3840 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003841 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003842 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003843 boolean printedHeader = false;
Philip P. Moltmannba136462019-05-21 10:20:38 -07003844 for (int watcherNum = 0; watcherNum < mActiveWatchers.size(); watcherNum++) {
3845 final SparseArray<ActiveCallback> activeWatchers =
3846 mActiveWatchers.valueAt(watcherNum);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003847 if (activeWatchers.size() <= 0) {
3848 continue;
3849 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003850 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003851 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3852 continue;
3853 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003854 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003855 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3856 continue;
3857 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003858 if (!printedHeader) {
3859 pw.println(" All op active watchers:");
3860 printedHeader = true;
3861 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003862 pw.print(" ");
3863 pw.print(Integer.toHexString(System.identityHashCode(
Philip P. Moltmannba136462019-05-21 10:20:38 -07003864 mActiveWatchers.keyAt(watcherNum))));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003865 pw.println(" ->");
3866 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003867 final int opCount = activeWatchers.size();
Philip P. Moltmannba136462019-05-21 10:20:38 -07003868 for (int opNum = 0; opNum < opCount; opNum++) {
3869 if (opNum > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003870 pw.print(' ');
3871 }
Philip P. Moltmannba136462019-05-21 10:20:38 -07003872 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(opNum)));
3873 if (opNum < opCount - 1) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003874 pw.print(',');
3875 }
3876 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003877 pw.println("]");
3878 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003879 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003880 }
3881 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003882 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3883 needSep = true;
3884 boolean printedHeader = false;
3885 for (int i = 0; i < mNotedWatchers.size(); i++) {
3886 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3887 if (notedWatchers.size() <= 0) {
3888 continue;
3889 }
3890 final NotedCallback cb = notedWatchers.valueAt(0);
3891 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3892 continue;
3893 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003894 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003895 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3896 continue;
3897 }
3898 if (!printedHeader) {
3899 pw.println(" All op noted watchers:");
3900 printedHeader = true;
3901 }
3902 pw.print(" ");
3903 pw.print(Integer.toHexString(System.identityHashCode(
3904 mNotedWatchers.keyAt(i))));
3905 pw.println(" ->");
3906 pw.print(" [");
3907 final int opCount = notedWatchers.size();
3908 for (i = 0; i < opCount; i++) {
3909 if (i > 0) {
3910 pw.print(' ');
3911 }
3912 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3913 if (i < opCount - 1) {
3914 pw.print(',');
3915 }
3916 }
3917 pw.println("]");
3918 pw.print(" ");
3919 pw.println(cb);
3920 }
3921 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003922 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003923 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003924 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003925 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003926 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003927 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003928 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003929 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003930 for (int j=0; j<cs.mStartedOps.size(); j++) {
3931 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003932 if (dumpOp >= 0 && op.op != dumpOp) {
3933 continue;
3934 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003935 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3936 continue;
3937 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003938 if (!printedHeader) {
3939 pw.println(" Clients:");
3940 printedHeader = true;
3941 }
3942 if (!printedClient) {
3943 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3944 pw.print(" "); pw.println(cs);
3945 printedClient = true;
3946 }
3947 if (!printedStarted) {
3948 pw.println(" Started ops:");
3949 printedStarted = true;
3950 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003951 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003952 pw.print(" pkg="); pw.print(op.packageName);
3953 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3954 }
3955 }
3956 }
3957 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003958 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003959 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003960 boolean printedHeader = false;
3961 for (int o=0; o<mAudioRestrictions.size(); o++) {
3962 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3963 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3964 for (int i=0; i<restrictions.size(); i++) {
3965 if (!printedHeader){
3966 pw.println(" Audio Restrictions:");
3967 printedHeader = true;
3968 needSep = true;
3969 }
John Spurlock7b414672014-07-18 13:02:39 -04003970 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003971 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003972 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003973 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003974 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003975 if (!r.exceptionPackages.isEmpty()) {
3976 pw.println(" Exceptions:");
3977 for (int j=0; j<r.exceptionPackages.size(); j++) {
3978 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3979 }
3980 }
3981 }
3982 }
3983 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003984 if (needSep) {
3985 pw.println();
3986 }
Svet Ganov2af57082015-07-30 08:44:20 -07003987 for (int i=0; i<mUidStates.size(); i++) {
3988 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003989 final SparseIntArray opModes = uidState.opModes;
3990 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3991
Svet Ganovaf189e32019-02-15 18:45:29 -08003992 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08003993 continue;
3994 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003995 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3996 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3997 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3998 boolean hasPackage = dumpPackage == null;
3999 boolean hasMode = dumpMode < 0;
4000 if (!hasMode && opModes != null) {
4001 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
4002 if (opModes.valueAt(opi) == dumpMode) {
4003 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004004 }
4005 }
4006 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004007 if (pkgOps != null) {
4008 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08004009 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
4010 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004011 Ops ops = pkgOps.valueAt(pkgi);
4012 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
4013 hasOp = true;
4014 }
4015 if (!hasMode) {
4016 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
4017 if (ops.valueAt(opi).mode == dumpMode) {
4018 hasMode = true;
4019 }
4020 }
4021 }
4022 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
4023 hasPackage = true;
4024 }
4025 }
4026 }
4027 if (uidState.foregroundOps != null && !hasOp) {
4028 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
4029 hasOp = true;
4030 }
4031 }
4032 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004033 continue;
4034 }
4035 }
Svet Ganov2af57082015-07-30 08:44:20 -07004036
4037 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004038 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004039 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004040 if (uidState.state != uidState.pendingState) {
4041 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004042 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004043 }
4044 if (uidState.pendingStateCommitTime != 0) {
4045 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07004046 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004047 pw.println();
4048 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004049 if (uidState.startNesting != 0) {
4050 pw.print(" startNesting=");
4051 pw.println(uidState.startNesting);
4052 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004053 if (uidState.foregroundOps != null && (dumpMode < 0
4054 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004055 pw.println(" foregroundOps:");
4056 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004057 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
4058 continue;
4059 }
4060 pw.print(" ");
4061 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
4062 pw.print(": ");
4063 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004064 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004065 pw.print(" hasForegroundWatchers=");
4066 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004067 }
Svet Ganovee438d42017-01-19 18:04:38 -08004068 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07004069
Svet Ganov2af57082015-07-30 08:44:20 -07004070 if (opModes != null) {
4071 final int opModeCount = opModes.size();
4072 for (int j = 0; j < opModeCount; j++) {
4073 final int code = opModes.keyAt(j);
4074 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004075 if (dumpOp >= 0 && dumpOp != code) {
4076 continue;
4077 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004078 if (dumpMode >= 0 && dumpMode != mode) {
4079 continue;
4080 }
Svet Ganov2af57082015-07-30 08:44:20 -07004081 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004082 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07004083 }
4084 }
4085
Svet Ganov2af57082015-07-30 08:44:20 -07004086 if (pkgOps == null) {
4087 continue;
4088 }
4089
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004090 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004091 final Ops ops = pkgOps.valueAt(pkgi);
4092 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
4093 continue;
4094 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004095 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004096 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004097 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004098 final int opCode = op.op;
4099 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004100 continue;
4101 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004102 if (dumpMode >= 0 && dumpMode != op.mode) {
4103 continue;
4104 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004105 if (!printedPackage) {
4106 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4107 printedPackage = true;
4108 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004109 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004110 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004111 final int switchOp = AppOpsManager.opToSwitch(opCode);
4112 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004113 pw.print(" / switch ");
4114 pw.print(AppOpsManager.opToName(switchOp));
4115 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004116 int mode = switchObj != null ? switchObj.mode
4117 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004118 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4119 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004120 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004121 dumpStatesLocked(pw, op, now, sdf, date, " ");
4122 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004123 pw.print(" Running start at: ");
4124 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4125 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004126 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004127 if (op.startNesting != 0) {
4128 pw.print(" startNesting=");
4129 pw.println(op.startNesting);
4130 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004131 }
4132 }
4133 }
Svet Ganovee438d42017-01-19 18:04:38 -08004134 if (needSep) {
4135 pw.println();
4136 }
4137
4138 final int userRestrictionCount = mOpUserRestrictions.size();
4139 for (int i = 0; i < userRestrictionCount; i++) {
4140 IBinder token = mOpUserRestrictions.keyAt(i);
4141 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004142 boolean printedTokenHeader = false;
4143
Svet Ganovaf189e32019-02-15 18:45:29 -08004144 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004145 continue;
4146 }
Svet Ganovee438d42017-01-19 18:04:38 -08004147
4148 final int restrictionCount = restrictionState.perUserRestrictions != null
4149 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004150 if (restrictionCount > 0 && dumpPackage == null) {
4151 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004152 for (int j = 0; j < restrictionCount; j++) {
4153 int userId = restrictionState.perUserRestrictions.keyAt(j);
4154 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4155 if (restrictedOps == null) {
4156 continue;
4157 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004158 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4159 || !restrictedOps[dumpOp])) {
4160 continue;
4161 }
4162 if (!printedTokenHeader) {
4163 pw.println(" User restrictions for token " + token + ":");
4164 printedTokenHeader = true;
4165 }
4166 if (!printedOpsHeader) {
4167 pw.println(" Restricted ops:");
4168 printedOpsHeader = true;
4169 }
Svet Ganovee438d42017-01-19 18:04:38 -08004170 StringBuilder restrictedOpsValue = new StringBuilder();
4171 restrictedOpsValue.append("[");
4172 final int restrictedOpCount = restrictedOps.length;
4173 for (int k = 0; k < restrictedOpCount; k++) {
4174 if (restrictedOps[k]) {
4175 if (restrictedOpsValue.length() > 1) {
4176 restrictedOpsValue.append(", ");
4177 }
4178 restrictedOpsValue.append(AppOpsManager.opToName(k));
4179 }
4180 }
4181 restrictedOpsValue.append("]");
4182 pw.print(" "); pw.print("user: "); pw.print(userId);
4183 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4184 }
4185 }
4186
4187 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4188 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004189 if (excludedPackageCount > 0 && dumpOp < 0) {
4190 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004191 for (int j = 0; j < excludedPackageCount; j++) {
4192 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4193 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004194 if (packageNames == null) {
4195 continue;
4196 }
4197 boolean hasPackage;
4198 if (dumpPackage != null) {
4199 hasPackage = false;
4200 for (String pkg : packageNames) {
4201 if (dumpPackage.equals(pkg)) {
4202 hasPackage = true;
4203 break;
4204 }
4205 }
4206 } else {
4207 hasPackage = true;
4208 }
4209 if (!hasPackage) {
4210 continue;
4211 }
4212 if (!printedTokenHeader) {
4213 pw.println(" User restrictions for token " + token + ":");
4214 printedTokenHeader = true;
4215 }
4216 if (!printedPackagesHeader) {
4217 pw.println(" Excluded packages:");
4218 printedPackagesHeader = true;
4219 }
Svet Ganovee438d42017-01-19 18:04:38 -08004220 pw.print(" "); pw.print("user: "); pw.print(userId);
4221 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4222 }
4223 }
4224 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004225 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004226
4227 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004228 if (dumpHistory && !dumpWatchers) {
4229 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4230 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004231 }
John Spurlock1af30c72014-03-10 08:33:35 -04004232
4233 private static final class Restriction {
4234 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4235 int mode;
4236 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4237 }
Jason Monk62062992014-05-06 09:55:28 -04004238
4239 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004240 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004241 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004242 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004243 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004244 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004245 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004246 if (restriction != null) {
4247 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4248 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004249 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004250 }
4251 }
4252
4253 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004254 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4255 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004256 if (Binder.getCallingPid() != Process.myPid()) {
4257 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4258 Binder.getCallingPid(), Binder.getCallingUid(), null);
4259 }
4260 if (userHandle != UserHandle.getCallingUserId()) {
4261 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4262 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4263 && mContext.checkCallingOrSelfPermission(Manifest.permission
4264 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4265 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4266 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004267 }
4268 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004269 verifyIncomingOp(code);
4270 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004271 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004272 }
4273
4274 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004275 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004276 synchronized (AppOpsService.this) {
4277 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4278
4279 if (restrictionState == null) {
4280 try {
4281 restrictionState = new ClientRestrictionState(token);
4282 } catch (RemoteException e) {
4283 return;
4284 }
4285 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004286 }
Svet Ganov442ed572016-08-17 17:29:43 -07004287
4288 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004289 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004290 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004291 }
4292
4293 if (restrictionState.isDefault()) {
4294 mOpUserRestrictions.remove(token);
4295 restrictionState.destroy();
4296 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004297 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004298 }
4299
Svet Ganov3a95f832018-03-23 17:44:30 -07004300 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004301 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004302 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004303 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004304 if (callbacks == null) {
4305 return;
4306 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004307 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004308 }
4309
Svet Ganov3a95f832018-03-23 17:44:30 -07004310 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004311 }
4312
4313 @Override
4314 public void removeUser(int userHandle) throws RemoteException {
4315 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004316 synchronized (AppOpsService.this) {
4317 final int tokenCount = mOpUserRestrictions.size();
4318 for (int i = tokenCount - 1; i >= 0; i--) {
4319 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4320 opRestrictions.removeUser(userHandle);
4321 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004322 removeUidsForUserLocked(userHandle);
4323 }
4324 }
4325
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004326 @Override
4327 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004328 if (Binder.getCallingUid() != uid) {
4329 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4330 != PackageManager.PERMISSION_GRANTED) {
4331 return false;
4332 }
4333 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004334 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004335 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004336 if (resolvedPackageName == null) {
4337 return false;
4338 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004339 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004340 for (int i = mClients.size() - 1; i >= 0; i--) {
4341 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004342 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4343 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004344 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004345 }
4346 }
4347 }
4348 return false;
4349 }
4350
Svet Ganov8455ba22019-01-02 13:05:56 -08004351 @Override
4352 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4353 long baseSnapshotInterval, int compressionStep) {
4354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4355 "setHistoryParameters");
4356 // Must not hold the appops lock
4357 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4358 }
4359
4360 @Override
4361 public void offsetHistory(long offsetMillis) {
4362 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4363 "offsetHistory");
4364 // Must not hold the appops lock
4365 mHistoricalRegistry.offsetHistory(offsetMillis);
4366 }
4367
4368 @Override
4369 public void addHistoricalOps(HistoricalOps ops) {
4370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4371 "addHistoricalOps");
4372 // Must not hold the appops lock
4373 mHistoricalRegistry.addHistoricalOps(ops);
4374 }
4375
4376 @Override
4377 public void resetHistoryParameters() {
4378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4379 "resetHistoryParameters");
4380 // Must not hold the appops lock
4381 mHistoricalRegistry.resetHistoryParameters();
4382 }
4383
4384 @Override
4385 public void clearHistory() {
4386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4387 "clearHistory");
4388 // Must not hold the appops lock
4389 mHistoricalRegistry.clearHistory();
4390 }
4391
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004392 private void removeUidsForUserLocked(int userHandle) {
4393 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4394 final int uid = mUidStates.keyAt(i);
4395 if (UserHandle.getUserId(uid) == userHandle) {
4396 mUidStates.removeAt(i);
4397 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004398 }
4399 }
4400
Jason Monk62062992014-05-06 09:55:28 -04004401 private void checkSystemUid(String function) {
4402 int uid = Binder.getCallingUid();
4403 if (uid != Process.SYSTEM_UID) {
4404 throw new SecurityException(function + " must by called by the system");
4405 }
4406 }
4407
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004408 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004409 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004410 return "root";
4411 } else if (uid == Process.SHELL_UID) {
4412 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004413 } else if (uid == Process.MEDIA_UID) {
4414 return "media";
4415 } else if (uid == Process.AUDIOSERVER_UID) {
4416 return "audioserver";
4417 } else if (uid == Process.CAMERASERVER_UID) {
4418 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004419 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4420 return "android";
4421 }
4422 return packageName;
4423 }
4424
Svet Ganov82f09bc2018-01-12 22:08:40 -08004425 private static int resolveUid(String packageName) {
4426 if (packageName == null) {
4427 return -1;
4428 }
4429 switch (packageName) {
4430 case "root":
4431 return Process.ROOT_UID;
4432 case "shell":
4433 return Process.SHELL_UID;
4434 case "media":
4435 return Process.MEDIA_UID;
4436 case "audioserver":
4437 return Process.AUDIOSERVER_UID;
4438 case "cameraserver":
4439 return Process.CAMERASERVER_UID;
4440 }
4441 return -1;
4442 }
4443
Svet Ganov2af57082015-07-30 08:44:20 -07004444 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004445 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004446
4447 // Very early during boot the package manager is not yet or not yet fully started. At this
4448 // time there are no packages yet.
4449 if (AppGlobals.getPackageManager() != null) {
4450 try {
4451 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4452 } catch (RemoteException e) {
4453 /* ignore - local call */
4454 }
Svet Ganov2af57082015-07-30 08:44:20 -07004455 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004456 if (packageNames == null) {
4457 return EmptyArray.STRING;
4458 }
4459 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004460 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004461
4462 private final class ClientRestrictionState implements DeathRecipient {
4463 private final IBinder token;
4464 SparseArray<boolean[]> perUserRestrictions;
4465 SparseArray<String[]> perUserExcludedPackages;
4466
4467 public ClientRestrictionState(IBinder token)
4468 throws RemoteException {
4469 token.linkToDeath(this, 0);
4470 this.token = token;
4471 }
4472
4473 public boolean setRestriction(int code, boolean restricted,
4474 String[] excludedPackages, int userId) {
4475 boolean changed = false;
4476
4477 if (perUserRestrictions == null && restricted) {
4478 perUserRestrictions = new SparseArray<>();
4479 }
4480
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004481 int[] users;
4482 if (userId == UserHandle.USER_ALL) {
4483 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004484
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004485 users = new int[liveUsers.size()];
4486 for (int i = 0; i < liveUsers.size(); i++) {
4487 users[i] = liveUsers.get(i).id;
4488 }
4489 } else {
4490 users = new int[]{userId};
4491 }
4492
4493 if (perUserRestrictions != null) {
4494 int numUsers = users.length;
4495
4496 for (int i = 0; i < numUsers; i++) {
4497 int thisUserId = users[i];
4498
4499 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4500 if (userRestrictions == null && restricted) {
4501 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4502 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004503 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004504 if (userRestrictions != null && userRestrictions[code] != restricted) {
4505 userRestrictions[code] = restricted;
4506 if (!restricted && isDefault(userRestrictions)) {
4507 perUserRestrictions.remove(thisUserId);
4508 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004509 }
4510 changed = true;
4511 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004512
4513 if (userRestrictions != null) {
4514 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4515 if (perUserExcludedPackages == null && !noExcludedPackages) {
4516 perUserExcludedPackages = new SparseArray<>();
4517 }
4518 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4519 perUserExcludedPackages.get(thisUserId))) {
4520 if (noExcludedPackages) {
4521 perUserExcludedPackages.remove(thisUserId);
4522 if (perUserExcludedPackages.size() <= 0) {
4523 perUserExcludedPackages = null;
4524 }
4525 } else {
4526 perUserExcludedPackages.put(thisUserId, excludedPackages);
4527 }
4528 changed = true;
4529 }
4530 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004531 }
4532 }
4533
4534 return changed;
4535 }
4536
4537 public boolean hasRestriction(int restriction, String packageName, int userId) {
4538 if (perUserRestrictions == null) {
4539 return false;
4540 }
4541 boolean[] restrictions = perUserRestrictions.get(userId);
4542 if (restrictions == null) {
4543 return false;
4544 }
4545 if (!restrictions[restriction]) {
4546 return false;
4547 }
4548 if (perUserExcludedPackages == null) {
4549 return true;
4550 }
4551 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4552 if (perUserExclusions == null) {
4553 return true;
4554 }
4555 return !ArrayUtils.contains(perUserExclusions, packageName);
4556 }
4557
4558 public void removeUser(int userId) {
4559 if (perUserExcludedPackages != null) {
4560 perUserExcludedPackages.remove(userId);
4561 if (perUserExcludedPackages.size() <= 0) {
4562 perUserExcludedPackages = null;
4563 }
4564 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004565 if (perUserRestrictions != null) {
4566 perUserRestrictions.remove(userId);
4567 if (perUserRestrictions.size() <= 0) {
4568 perUserRestrictions = null;
4569 }
4570 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004571 }
4572
4573 public boolean isDefault() {
4574 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4575 }
4576
4577 @Override
4578 public void binderDied() {
4579 synchronized (AppOpsService.this) {
4580 mOpUserRestrictions.remove(token);
4581 if (perUserRestrictions == null) {
4582 return;
4583 }
4584 final int userCount = perUserRestrictions.size();
4585 for (int i = 0; i < userCount; i++) {
4586 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4587 final int restrictionCount = restrictions.length;
4588 for (int j = 0; j < restrictionCount; j++) {
4589 if (restrictions[j]) {
4590 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004591 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004592 }
4593 }
4594 }
4595 destroy();
4596 }
4597 }
4598
4599 public void destroy() {
4600 token.unlinkToDeath(this, 0);
4601 }
4602
4603 private boolean isDefault(boolean[] array) {
4604 if (ArrayUtils.isEmpty(array)) {
4605 return true;
4606 }
4607 for (boolean value : array) {
4608 if (value) {
4609 return false;
4610 }
4611 }
4612 return true;
4613 }
4614 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004615
4616 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4617 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4618 synchronized (AppOpsService.this) {
4619 mProfileOwners = owners;
4620 }
4621 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004622
4623 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004624 public void setUidMode(int code, int uid, int mode) {
4625 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004626 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004627
4628 @Override
4629 public void setAllPkgModesToDefault(int code, int uid) {
4630 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4631 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07004632
4633 @Override
4634 public @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName) {
4635 return AppOpsService.this.checkOperationUnchecked(code, uid, packageName, true, false);
4636 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004637 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004638}