OSDN Git Service

[automerger] [RESTRICT AUTOMERGE] Pass correct realCallingUid to startActivity()...
[android-x86/frameworks-base.git] / services / core / java / com / android / server / pm / PackageManagerService.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server.pm;
18
19 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61 import static android.content.pm.PackageManager.MATCH_ALL;
62 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74 import static android.content.pm.PackageManager.PERMISSION_DENIED;
75 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77 import static android.content.pm.PackageParser.isApkFile;
78 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79 import static android.system.OsConstants.O_CREAT;
80 import static android.system.OsConstants.O_RDWR;
81
82 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86 import static com.android.internal.util.ArrayUtils.appendInt;
87 import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100 import android.Manifest;
101 import android.annotation.NonNull;
102 import android.annotation.Nullable;
103 import android.app.ActivityManager;
104 import android.app.ActivityManagerNative;
105 import android.app.IActivityManager;
106 import android.app.ResourcesManager;
107 import android.app.admin.IDevicePolicyManager;
108 import android.app.admin.SecurityLog;
109 import android.app.backup.IBackupManager;
110 import android.content.BroadcastReceiver;
111 import android.content.ComponentName;
112 import android.content.ContentResolver;
113 import android.content.Context;
114 import android.content.IIntentReceiver;
115 import android.content.Intent;
116 import android.content.IntentFilter;
117 import android.content.IntentSender;
118 import android.content.IntentSender.SendIntentException;
119 import android.content.ServiceConnection;
120 import android.content.pm.ActivityInfo;
121 import android.content.pm.ApplicationInfo;
122 import android.content.pm.AppsQueryHelper;
123 import android.content.pm.ComponentInfo;
124 import android.content.pm.EphemeralApplicationInfo;
125 import android.content.pm.EphemeralResolveInfo;
126 import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127 import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128 import android.content.pm.FeatureInfo;
129 import android.content.pm.IOnPermissionsChangeListener;
130 import android.content.pm.IPackageDataObserver;
131 import android.content.pm.IPackageDeleteObserver;
132 import android.content.pm.IPackageDeleteObserver2;
133 import android.content.pm.IPackageInstallObserver2;
134 import android.content.pm.IPackageInstaller;
135 import android.content.pm.IPackageManager;
136 import android.content.pm.IPackageMoveObserver;
137 import android.content.pm.IPackageStatsObserver;
138 import android.content.pm.InstrumentationInfo;
139 import android.content.pm.IntentFilterVerificationInfo;
140 import android.content.pm.KeySet;
141 import android.content.pm.PackageCleanItem;
142 import android.content.pm.PackageInfo;
143 import android.content.pm.PackageInfoLite;
144 import android.content.pm.PackageInstaller;
145 import android.content.pm.PackageManager;
146 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147 import android.content.pm.PackageManagerInternal;
148 import android.content.pm.PackageParser;
149 import android.content.pm.PackageParser.ActivityIntentInfo;
150 import android.content.pm.PackageParser.PackageLite;
151 import android.content.pm.PackageParser.PackageParserException;
152 import android.content.pm.PackageStats;
153 import android.content.pm.PackageUserState;
154 import android.content.pm.ParceledListSlice;
155 import android.content.pm.PermissionGroupInfo;
156 import android.content.pm.PermissionInfo;
157 import android.content.pm.ProviderInfo;
158 import android.content.pm.ResolveInfo;
159 import android.content.pm.ServiceInfo;
160 import android.content.pm.Signature;
161 import android.content.pm.UserInfo;
162 import android.content.pm.VerifierDeviceIdentity;
163 import android.content.pm.VerifierInfo;
164 import android.content.res.Resources;
165 import android.graphics.Bitmap;
166 import android.hardware.display.DisplayManager;
167 import android.net.Uri;
168 import android.os.AsyncTask;
169 import android.os.Binder;
170 import android.os.Build;
171 import android.os.Bundle;
172 import android.os.Debug;
173 import android.os.Environment;
174 import android.os.Environment.UserEnvironment;
175 import android.os.FileUtils;
176 import android.os.Handler;
177 import android.os.IBinder;
178 import android.os.Looper;
179 import android.os.Message;
180 import android.os.Parcel;
181 import android.os.ParcelFileDescriptor;
182 import android.os.PatternMatcher;
183 import android.os.Process;
184 import android.os.RemoteCallbackList;
185 import android.os.RemoteException;
186 import android.os.ResultReceiver;
187 import android.os.SELinux;
188 import android.os.ServiceManager;
189 import android.os.SystemClock;
190 import android.os.SystemProperties;
191 import android.os.Trace;
192 import android.os.UserHandle;
193 import android.os.UserManager;
194 import android.os.UserManagerInternal;
195 import android.os.storage.IMountService;
196 import android.os.storage.MountServiceInternal;
197 import android.os.storage.StorageEventListener;
198 import android.os.storage.StorageManager;
199 import android.os.storage.VolumeInfo;
200 import android.os.storage.VolumeRecord;
201 import android.provider.Settings.Global;
202 import android.provider.Settings.Secure;
203 import android.security.KeyStore;
204 import android.security.SystemKeyStore;
205 import android.system.ErrnoException;
206 import android.system.Os;
207 import android.text.TextUtils;
208 import android.text.format.DateUtils;
209 import android.util.ArrayMap;
210 import android.util.ArraySet;
211 import android.util.DisplayMetrics;
212 import android.util.EventLog;
213 import android.util.ExceptionUtils;
214 import android.util.Log;
215 import android.util.LogPrinter;
216 import android.util.MathUtils;
217 import android.util.Pair;
218 import android.util.PrintStreamPrinter;
219 import android.util.Slog;
220 import android.util.SparseArray;
221 import android.util.SparseBooleanArray;
222 import android.util.SparseIntArray;
223 import android.util.Xml;
224 import android.util.jar.StrictJarFile;
225 import android.view.Display;
226
227 import com.android.internal.R;
228 import com.android.internal.annotations.GuardedBy;
229 import com.android.internal.app.IMediaContainerService;
230 import com.android.internal.app.ResolverActivity;
231 import com.android.internal.content.NativeLibraryHelper;
232 import com.android.internal.content.PackageHelper;
233 import com.android.internal.logging.MetricsLogger;
234 import com.android.internal.os.IParcelFileDescriptorFactory;
235 import com.android.internal.os.InstallerConnection.InstallerException;
236 import com.android.internal.os.SomeArgs;
237 import com.android.internal.os.Zygote;
238 import com.android.internal.telephony.CarrierAppUtils;
239 import com.android.internal.util.ArrayUtils;
240 import com.android.internal.util.FastPrintWriter;
241 import com.android.internal.util.FastXmlSerializer;
242 import com.android.internal.util.IndentingPrintWriter;
243 import com.android.internal.util.Preconditions;
244 import com.android.internal.util.XmlUtils;
245 import com.android.server.AttributeCache;
246 import com.android.server.EventLogTags;
247 import com.android.server.FgThread;
248 import com.android.server.IntentResolver;
249 import com.android.server.LocalServices;
250 import com.android.server.ServiceThread;
251 import com.android.server.SystemConfig;
252 import com.android.server.Watchdog;
253 import com.android.server.net.NetworkPolicyManagerInternal;
254 import com.android.server.pm.PermissionsState.PermissionState;
255 import com.android.server.pm.Settings.DatabaseVersion;
256 import com.android.server.pm.Settings.VersionInfo;
257 import com.android.server.storage.DeviceStorageMonitorInternal;
258
259 import dalvik.system.CloseGuard;
260 import dalvik.system.DexFile;
261 import dalvik.system.VMRuntime;
262
263 import libcore.io.IoUtils;
264 import libcore.util.EmptyArray;
265
266 import org.xmlpull.v1.XmlPullParser;
267 import org.xmlpull.v1.XmlPullParserException;
268 import org.xmlpull.v1.XmlSerializer;
269
270 import java.io.BufferedOutputStream;
271 import java.io.BufferedReader;
272 import java.io.ByteArrayInputStream;
273 import java.io.ByteArrayOutputStream;
274 import java.io.File;
275 import java.io.FileDescriptor;
276 import java.io.FileInputStream;
277 import java.io.FileNotFoundException;
278 import java.io.FileOutputStream;
279 import java.io.FileReader;
280 import java.io.FilenameFilter;
281 import java.io.IOException;
282 import java.io.PrintWriter;
283 import java.nio.charset.StandardCharsets;
284 import java.security.DigestInputStream;
285 import java.security.MessageDigest;
286 import java.security.NoSuchAlgorithmException;
287 import java.security.PublicKey;
288 import java.security.cert.Certificate;
289 import java.security.cert.CertificateEncodingException;
290 import java.security.cert.CertificateException;
291 import java.text.SimpleDateFormat;
292 import java.util.ArrayList;
293 import java.util.Arrays;
294 import java.util.Collection;
295 import java.util.Collections;
296 import java.util.Comparator;
297 import java.util.Date;
298 import java.util.HashSet;
299 import java.util.Iterator;
300 import java.util.List;
301 import java.util.Map;
302 import java.util.Objects;
303 import java.util.Set;
304 import java.util.concurrent.CountDownLatch;
305 import java.util.concurrent.TimeUnit;
306 import java.util.concurrent.atomic.AtomicBoolean;
307 import java.util.concurrent.atomic.AtomicInteger;
308
309 /**
310  * Keep track of all those APKs everywhere.
311  * <p>
312  * Internally there are two important locks:
313  * <ul>
314  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315  * and other related state. It is a fine-grained lock that should only be held
316  * momentarily, as it's one of the most contended locks in the system.
317  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318  * operations typically involve heavy lifting of application data on disk. Since
319  * {@code installd} is single-threaded, and it's operations can often be slow,
320  * this lock should never be acquired while already holding {@link #mPackages}.
321  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322  * holding {@link #mInstallLock}.
323  * </ul>
324  * Many internal methods rely on the caller to hold the appropriate locks, and
325  * this contract is expressed through method name suffixes:
326  * <ul>
327  * <li>fooLI(): the caller must hold {@link #mInstallLock}
328  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329  * being modified must be frozen
330  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332  * </ul>
333  * <p>
334  * Because this class is very central to the platform's security; please run all
335  * CTS and unit tests whenever making modifications:
336  *
337  * <pre>
338  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339  * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340  * </pre>
341  */
342 public class PackageManagerService extends IPackageManager.Stub {
343     static final String TAG = "PackageManager";
344     static final boolean DEBUG_SETTINGS = false;
345     static final boolean DEBUG_PREFERRED = false;
346     static final boolean DEBUG_UPGRADE = false;
347     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348     private static final boolean DEBUG_BACKUP = false;
349     private static final boolean DEBUG_INSTALL = false;
350     private static final boolean DEBUG_REMOVE = false;
351     private static final boolean DEBUG_BROADCASTS = false;
352     private static final boolean DEBUG_SHOW_INFO = false;
353     private static final boolean DEBUG_PACKAGE_INFO = false;
354     private static final boolean DEBUG_INTENT_MATCHING = false;
355     private static final boolean DEBUG_PACKAGE_SCANNING = false;
356     private static final boolean DEBUG_VERIFY = false;
357     private static final boolean DEBUG_FILTERS = false;
358
359     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361     // user, but by default initialize to this.
362     static final boolean DEBUG_DEXOPT = false;
363
364     private static final boolean DEBUG_ABI_SELECTION = false;
365     private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
366     private static final boolean DEBUG_TRIAGED_MISSING = false;
367     private static final boolean DEBUG_APP_DATA = false;
368
369     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370
371     private static final boolean DISABLE_EPHEMERAL_APPS = false;
372     private static final boolean HIDE_EPHEMERAL_APIS = true;
373
374     private static final int RADIO_UID = Process.PHONE_UID;
375     private static final int LOG_UID = Process.LOG_UID;
376     private static final int NFC_UID = Process.NFC_UID;
377     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
378     private static final int SHELL_UID = Process.SHELL_UID;
379
380     // Cap the size of permission trees that 3rd party apps can define
381     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
382
383     // Suffix used during package installation when copying/moving
384     // package apks to install directory.
385     private static final String INSTALL_PACKAGE_SUFFIX = "-";
386
387     static final int SCAN_NO_DEX = 1<<1;
388     static final int SCAN_FORCE_DEX = 1<<2;
389     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
390     static final int SCAN_NEW_INSTALL = 1<<4;
391     static final int SCAN_NO_PATHS = 1<<5;
392     static final int SCAN_UPDATE_TIME = 1<<6;
393     static final int SCAN_DEFER_DEX = 1<<7;
394     static final int SCAN_BOOTING = 1<<8;
395     static final int SCAN_TRUSTED_OVERLAY = 1<<9;
396     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
397     static final int SCAN_REPLACING = 1<<11;
398     static final int SCAN_REQUIRE_KNOWN = 1<<12;
399     static final int SCAN_MOVE = 1<<13;
400     static final int SCAN_INITIAL = 1<<14;
401     static final int SCAN_CHECK_ONLY = 1<<15;
402     static final int SCAN_DONT_KILL_APP = 1<<17;
403     static final int SCAN_IGNORE_FROZEN = 1<<18;
404
405     static final int REMOVE_CHATTY = 1<<16;
406
407     private static final int[] EMPTY_INT_ARRAY = new int[0];
408
409     /**
410      * Timeout (in milliseconds) after which the watchdog should declare that
411      * our handler thread is wedged.  The usual default for such things is one
412      * minute but we sometimes do very lengthy I/O operations on this thread,
413      * such as installing multi-gigabyte applications, so ours needs to be longer.
414      */
415     private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
416
417     /**
418      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
419      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
420      * settings entry if available, otherwise we use the hardcoded default.  If it's been
421      * more than this long since the last fstrim, we force one during the boot sequence.
422      *
423      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
424      * one gets run at the next available charging+idle time.  This final mandatory
425      * no-fstrim check kicks in only of the other scheduling criteria is never met.
426      */
427     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
428
429     /**
430      * Whether verification is enabled by default.
431      */
432     private static final boolean DEFAULT_VERIFY_ENABLE = true;
433
434     /**
435      * The default maximum time to wait for the verification agent to return in
436      * milliseconds.
437      */
438     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
439
440     /**
441      * The default response for package verification timeout.
442      *
443      * This can be either PackageManager.VERIFICATION_ALLOW or
444      * PackageManager.VERIFICATION_REJECT.
445      */
446     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
447
448     static final String PLATFORM_PACKAGE_NAME = "android";
449
450     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
451
452     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
453             DEFAULT_CONTAINER_PACKAGE,
454             "com.android.defcontainer.DefaultContainerService");
455
456     private static final String KILL_APP_REASON_GIDS_CHANGED =
457             "permission grant or revoke changed gids";
458
459     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
460             "permissions revoked";
461
462     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
463
464     private static final String PACKAGE_SCHEME = "package";
465
466     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
467     /**
468      * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
469      * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
470      * VENDOR_OVERLAY_DIR.
471      */
472     private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
473
474     private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
475     private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
476
477     /** Permission grant: not grant the permission. */
478     private static final int GRANT_DENIED = 1;
479
480     /** Permission grant: grant the permission as an install permission. */
481     private static final int GRANT_INSTALL = 2;
482
483     /** Permission grant: grant the permission as a runtime one. */
484     private static final int GRANT_RUNTIME = 3;
485
486     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
487     private static final int GRANT_UPGRADE = 4;
488
489     /** Canonical intent used to identify what counts as a "web browser" app */
490     private static final Intent sBrowserIntent;
491     static {
492         sBrowserIntent = new Intent();
493         sBrowserIntent.setAction(Intent.ACTION_VIEW);
494         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
495         sBrowserIntent.setData(Uri.parse("http:"));
496     }
497
498     /**
499      * The set of all protected actions [i.e. those actions for which a high priority
500      * intent filter is disallowed].
501      */
502     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
503     static {
504         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
505         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
506         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
507         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
508     }
509
510     // Compilation reasons.
511     public static final int REASON_FIRST_BOOT = 0;
512     public static final int REASON_BOOT = 1;
513     public static final int REASON_INSTALL = 2;
514     public static final int REASON_BACKGROUND_DEXOPT = 3;
515     public static final int REASON_AB_OTA = 4;
516     public static final int REASON_NON_SYSTEM_LIBRARY = 5;
517     public static final int REASON_SHARED_APK = 6;
518     public static final int REASON_FORCED_DEXOPT = 7;
519     public static final int REASON_CORE_APP = 8;
520
521     public static final int REASON_LAST = REASON_CORE_APP;
522
523     /** Special library name that skips shared libraries check during compilation. */
524     private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
525
526     final ServiceThread mHandlerThread;
527
528     final PackageHandler mHandler;
529
530     private final ProcessLoggingHandler mProcessLoggingHandler;
531
532     /**
533      * Messages for {@link #mHandler} that need to wait for system ready before
534      * being dispatched.
535      */
536     private ArrayList<Message> mPostSystemReadyMessages;
537
538     final int mSdkVersion = Build.VERSION.SDK_INT;
539
540     final Context mContext;
541     final boolean mFactoryTest;
542     final boolean mOnlyCore;
543     final DisplayMetrics mMetrics;
544     final int mDefParseFlags;
545     final String[] mSeparateProcesses;
546     final boolean mIsUpgrade;
547     final boolean mIsPreNUpgrade;
548     final boolean mIsPreNMR1Upgrade;
549
550     @GuardedBy("mPackages")
551     private boolean mDexOptDialogShown;
552
553     /** The location for ASEC container files on internal storage. */
554     final String mAsecInternalPath;
555
556     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
557     // LOCK HELD.  Can be called with mInstallLock held.
558     @GuardedBy("mInstallLock")
559     final Installer mInstaller;
560
561     /** Directory where installed third-party apps stored */
562     final File mAppInstallDir;
563     final File mEphemeralInstallDir;
564
565     /**
566      * Directory to which applications installed internally have their
567      * 32 bit native libraries copied.
568      */
569     private File mAppLib32InstallDir;
570
571     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
572     // apps.
573     final File mDrmAppPrivateInstallDir;
574
575     // ----------------------------------------------------------------
576
577     // Lock for state used when installing and doing other long running
578     // operations.  Methods that must be called with this lock held have
579     // the suffix "LI".
580     final Object mInstallLock = new Object();
581
582     // ----------------------------------------------------------------
583
584     // Keys are String (package name), values are Package.  This also serves
585     // as the lock for the global state.  Methods that must be called with
586     // this lock held have the prefix "LP".
587     @GuardedBy("mPackages")
588     final ArrayMap<String, PackageParser.Package> mPackages =
589             new ArrayMap<String, PackageParser.Package>();
590
591     final ArrayMap<String, Set<String>> mKnownCodebase =
592             new ArrayMap<String, Set<String>>();
593
594     // Tracks available target package names -> overlay package paths.
595     final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
596         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
597
598     /**
599      * Tracks new system packages [received in an OTA] that we expect to
600      * find updated user-installed versions. Keys are package name, values
601      * are package location.
602      */
603     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
604     /**
605      * Tracks high priority intent filters for protected actions. During boot, certain
606      * filter actions are protected and should never be allowed to have a high priority
607      * intent filter for them. However, there is one, and only one exception -- the
608      * setup wizard. It must be able to define a high priority intent filter for these
609      * actions to ensure there are no escapes from the wizard. We need to delay processing
610      * of these during boot as we need to look at all of the system packages in order
611      * to know which component is the setup wizard.
612      */
613     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
614     /**
615      * Whether or not processing protected filters should be deferred.
616      */
617     private boolean mDeferProtectedFilters = true;
618
619     /**
620      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
621      */
622     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
623     /**
624      * Whether or not system app permissions should be promoted from install to runtime.
625      */
626     boolean mPromoteSystemApps;
627
628     @GuardedBy("mPackages")
629     final Settings mSettings;
630
631     /**
632      * Set of package names that are currently "frozen", which means active
633      * surgery is being done on the code/data for that package. The platform
634      * will refuse to launch frozen packages to avoid race conditions.
635      *
636      * @see PackageFreezer
637      */
638     @GuardedBy("mPackages")
639     final ArraySet<String> mFrozenPackages = new ArraySet<>();
640
641     final ProtectedPackages mProtectedPackages;
642
643     boolean mFirstBoot;
644
645     // System configuration read by SystemConfig.
646     final int[] mGlobalGids;
647     final SparseArray<ArraySet<String>> mSystemPermissions;
648     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
649
650     // If mac_permissions.xml was found for seinfo labeling.
651     boolean mFoundPolicyFile;
652
653     private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
654
655     public static final class SharedLibraryEntry {
656         public final String path;
657         public final String apk;
658
659         SharedLibraryEntry(String _path, String _apk) {
660             path = _path;
661             apk = _apk;
662         }
663     }
664
665     // Currently known shared libraries.
666     final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
667             new ArrayMap<String, SharedLibraryEntry>();
668
669     // All available activities, for your resolving pleasure.
670     final ActivityIntentResolver mActivities =
671             new ActivityIntentResolver();
672
673     // All available receivers, for your resolving pleasure.
674     final ActivityIntentResolver mReceivers =
675             new ActivityIntentResolver();
676
677     // All available services, for your resolving pleasure.
678     final ServiceIntentResolver mServices = new ServiceIntentResolver();
679
680     // All available providers, for your resolving pleasure.
681     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
682
683     // Mapping from provider base names (first directory in content URI codePath)
684     // to the provider information.
685     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
686             new ArrayMap<String, PackageParser.Provider>();
687
688     // Mapping from instrumentation class names to info about them.
689     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
690             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
691
692     // Mapping from permission names to info about them.
693     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
694             new ArrayMap<String, PackageParser.PermissionGroup>();
695
696     // Packages whose data we have transfered into another package, thus
697     // should no longer exist.
698     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
699
700     // Broadcast actions that are only available to the system.
701     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
702
703     /** List of packages waiting for verification. */
704     final SparseArray<PackageVerificationState> mPendingVerification
705             = new SparseArray<PackageVerificationState>();
706
707     /** Set of packages associated with each app op permission. */
708     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
709
710     final PackageInstallerService mInstallerService;
711
712     private final PackageDexOptimizer mPackageDexOptimizer;
713
714     private AtomicInteger mNextMoveId = new AtomicInteger();
715     private final MoveCallbacks mMoveCallbacks;
716
717     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
718
719     // Cache of users who need badging.
720     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
721
722     /** Token for keys in mPendingVerification. */
723     private int mPendingVerificationToken = 0;
724
725     volatile boolean mSystemReady;
726     volatile boolean mSafeMode;
727     volatile boolean mHasSystemUidErrors;
728
729     ApplicationInfo mAndroidApplication;
730     final ActivityInfo mResolveActivity = new ActivityInfo();
731     final ResolveInfo mResolveInfo = new ResolveInfo();
732     ComponentName mResolveComponentName;
733     PackageParser.Package mPlatformPackage;
734     ComponentName mCustomResolverComponentName;
735
736     boolean mResolverReplaced = false;
737
738     private final @Nullable ComponentName mIntentFilterVerifierComponent;
739     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
740
741     private int mIntentFilterVerificationToken = 0;
742
743     /** Component that knows whether or not an ephemeral application exists */
744     final ComponentName mEphemeralResolverComponent;
745     /** The service connection to the ephemeral resolver */
746     final EphemeralResolverConnection mEphemeralResolverConnection;
747
748     /** Component used to install ephemeral applications */
749     final ComponentName mEphemeralInstallerComponent;
750     final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
751     final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
752
753     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
754             = new SparseArray<IntentFilterVerificationState>();
755
756     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
757
758     // List of packages names to keep cached, even if they are uninstalled for all users
759     private List<String> mKeepUninstalledPackages;
760
761     private UserManagerInternal mUserManagerInternal;
762
763     private static class IFVerificationParams {
764         PackageParser.Package pkg;
765         boolean replacing;
766         int userId;
767         int verifierUid;
768
769         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
770                 int _userId, int _verifierUid) {
771             pkg = _pkg;
772             replacing = _replacing;
773             userId = _userId;
774             replacing = _replacing;
775             verifierUid = _verifierUid;
776         }
777     }
778
779     private interface IntentFilterVerifier<T extends IntentFilter> {
780         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
781                                                T filter, String packageName);
782         void startVerifications(int userId);
783         void receiveVerificationResponse(int verificationId);
784     }
785
786     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
787         private Context mContext;
788         private ComponentName mIntentFilterVerifierComponent;
789         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
790
791         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
792             mContext = context;
793             mIntentFilterVerifierComponent = verifierComponent;
794         }
795
796         private String getDefaultScheme() {
797             return IntentFilter.SCHEME_HTTPS;
798         }
799
800         @Override
801         public void startVerifications(int userId) {
802             // Launch verifications requests
803             int count = mCurrentIntentFilterVerifications.size();
804             for (int n=0; n<count; n++) {
805                 int verificationId = mCurrentIntentFilterVerifications.get(n);
806                 final IntentFilterVerificationState ivs =
807                         mIntentFilterVerificationStates.get(verificationId);
808
809                 String packageName = ivs.getPackageName();
810
811                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
812                 final int filterCount = filters.size();
813                 ArraySet<String> domainsSet = new ArraySet<>();
814                 for (int m=0; m<filterCount; m++) {
815                     PackageParser.ActivityIntentInfo filter = filters.get(m);
816                     domainsSet.addAll(filter.getHostsList());
817                 }
818                 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
819                 synchronized (mPackages) {
820                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
821                             packageName, domainsList) != null) {
822                         scheduleWriteSettingsLocked();
823                     }
824                 }
825                 sendVerificationRequest(userId, verificationId, ivs);
826             }
827             mCurrentIntentFilterVerifications.clear();
828         }
829
830         private void sendVerificationRequest(int userId, int verificationId,
831                 IntentFilterVerificationState ivs) {
832
833             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
834             verificationIntent.putExtra(
835                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
836                     verificationId);
837             verificationIntent.putExtra(
838                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
839                     getDefaultScheme());
840             verificationIntent.putExtra(
841                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
842                     ivs.getHostsString());
843             verificationIntent.putExtra(
844                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
845                     ivs.getPackageName());
846             verificationIntent.setComponent(mIntentFilterVerifierComponent);
847             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
848
849             UserHandle user = new UserHandle(userId);
850             mContext.sendBroadcastAsUser(verificationIntent, user);
851             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
852                     "Sending IntentFilter verification broadcast");
853         }
854
855         public void receiveVerificationResponse(int verificationId) {
856             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
857
858             final boolean verified = ivs.isVerified();
859
860             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
861             final int count = filters.size();
862             if (DEBUG_DOMAIN_VERIFICATION) {
863                 Slog.i(TAG, "Received verification response " + verificationId
864                         + " for " + count + " filters, verified=" + verified);
865             }
866             for (int n=0; n<count; n++) {
867                 PackageParser.ActivityIntentInfo filter = filters.get(n);
868                 filter.setVerified(verified);
869
870                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
871                         + " verified with result:" + verified + " and hosts:"
872                         + ivs.getHostsString());
873             }
874
875             mIntentFilterVerificationStates.remove(verificationId);
876
877             final String packageName = ivs.getPackageName();
878             IntentFilterVerificationInfo ivi = null;
879
880             synchronized (mPackages) {
881                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
882             }
883             if (ivi == null) {
884                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
885                         + verificationId + " packageName:" + packageName);
886                 return;
887             }
888             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
889                     "Updating IntentFilterVerificationInfo for package " + packageName
890                             +" verificationId:" + verificationId);
891
892             synchronized (mPackages) {
893                 if (verified) {
894                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
895                 } else {
896                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
897                 }
898                 scheduleWriteSettingsLocked();
899
900                 final int userId = ivs.getUserId();
901                 if (userId != UserHandle.USER_ALL) {
902                     final int userStatus =
903                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
904
905                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
906                     boolean needUpdate = false;
907
908                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
909                     // already been set by the User thru the Disambiguation dialog
910                     switch (userStatus) {
911                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
912                             if (verified) {
913                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                             } else {
915                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
916                             }
917                             needUpdate = true;
918                             break;
919
920                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
921                             if (verified) {
922                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
923                                 needUpdate = true;
924                             }
925                             break;
926
927                         default:
928                             // Nothing to do
929                     }
930
931                     if (needUpdate) {
932                         mSettings.updateIntentFilterVerificationStatusLPw(
933                                 packageName, updatedStatus, userId);
934                         scheduleWritePackageRestrictionsLocked(userId);
935                     }
936                 }
937             }
938         }
939
940         @Override
941         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
942                     ActivityIntentInfo filter, String packageName) {
943             if (!hasValidDomains(filter)) {
944                 return false;
945             }
946             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
947             if (ivs == null) {
948                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
949                         packageName);
950             }
951             if (DEBUG_DOMAIN_VERIFICATION) {
952                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
953             }
954             ivs.addFilter(filter);
955             return true;
956         }
957
958         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
959                 int userId, int verificationId, String packageName) {
960             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
961                     verifierUid, userId, packageName);
962             ivs.setPendingState();
963             synchronized (mPackages) {
964                 mIntentFilterVerificationStates.append(verificationId, ivs);
965                 mCurrentIntentFilterVerifications.add(verificationId);
966             }
967             return ivs;
968         }
969     }
970
971     private static boolean hasValidDomains(ActivityIntentInfo filter) {
972         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
973                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
974                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
975     }
976
977     // Set of pending broadcasts for aggregating enable/disable of components.
978     static class PendingPackageBroadcasts {
979         // for each user id, a map of <package name -> components within that package>
980         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
981
982         public PendingPackageBroadcasts() {
983             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
984         }
985
986         public ArrayList<String> get(int userId, String packageName) {
987             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
988             return packages.get(packageName);
989         }
990
991         public void put(int userId, String packageName, ArrayList<String> components) {
992             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
993             packages.put(packageName, components);
994         }
995
996         public void remove(int userId, String packageName) {
997             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
998             if (packages != null) {
999                 packages.remove(packageName);
1000             }
1001         }
1002
1003         public void remove(int userId) {
1004             mUidMap.remove(userId);
1005         }
1006
1007         public int userIdCount() {
1008             return mUidMap.size();
1009         }
1010
1011         public int userIdAt(int n) {
1012             return mUidMap.keyAt(n);
1013         }
1014
1015         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1016             return mUidMap.get(userId);
1017         }
1018
1019         public int size() {
1020             // total number of pending broadcast entries across all userIds
1021             int num = 0;
1022             for (int i = 0; i< mUidMap.size(); i++) {
1023                 num += mUidMap.valueAt(i).size();
1024             }
1025             return num;
1026         }
1027
1028         public void clear() {
1029             mUidMap.clear();
1030         }
1031
1032         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1033             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1034             if (map == null) {
1035                 map = new ArrayMap<String, ArrayList<String>>();
1036                 mUidMap.put(userId, map);
1037             }
1038             return map;
1039         }
1040     }
1041     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1042
1043     // Service Connection to remote media container service to copy
1044     // package uri's from external media onto secure containers
1045     // or internal storage.
1046     private IMediaContainerService mContainerService = null;
1047
1048     static final int SEND_PENDING_BROADCAST = 1;
1049     static final int MCS_BOUND = 3;
1050     static final int END_COPY = 4;
1051     static final int INIT_COPY = 5;
1052     static final int MCS_UNBIND = 6;
1053     static final int START_CLEANING_PACKAGE = 7;
1054     static final int FIND_INSTALL_LOC = 8;
1055     static final int POST_INSTALL = 9;
1056     static final int MCS_RECONNECT = 10;
1057     static final int MCS_GIVE_UP = 11;
1058     static final int UPDATED_MEDIA_STATUS = 12;
1059     static final int WRITE_SETTINGS = 13;
1060     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1061     static final int PACKAGE_VERIFIED = 15;
1062     static final int CHECK_PENDING_VERIFICATION = 16;
1063     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1064     static final int INTENT_FILTER_VERIFIED = 18;
1065     static final int WRITE_PACKAGE_LIST = 19;
1066
1067     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1068
1069     // Delay time in millisecs
1070     static final int BROADCAST_DELAY = 10 * 1000;
1071
1072     static UserManagerService sUserManager;
1073
1074     // Stores a list of users whose package restrictions file needs to be updated
1075     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1076
1077     final private DefaultContainerConnection mDefContainerConn =
1078             new DefaultContainerConnection();
1079     class DefaultContainerConnection implements ServiceConnection {
1080         public void onServiceConnected(ComponentName name, IBinder service) {
1081             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1082             IMediaContainerService imcs =
1083                 IMediaContainerService.Stub.asInterface(service);
1084             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1085         }
1086
1087         public void onServiceDisconnected(ComponentName name) {
1088             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1089         }
1090     }
1091
1092     // Recordkeeping of restore-after-install operations that are currently in flight
1093     // between the Package Manager and the Backup Manager
1094     static class PostInstallData {
1095         public InstallArgs args;
1096         public PackageInstalledInfo res;
1097
1098         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1099             args = _a;
1100             res = _r;
1101         }
1102     }
1103
1104     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1105     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1106
1107     // XML tags for backup/restore of various bits of state
1108     private static final String TAG_PREFERRED_BACKUP = "pa";
1109     private static final String TAG_DEFAULT_APPS = "da";
1110     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1111
1112     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1113     private static final String TAG_ALL_GRANTS = "rt-grants";
1114     private static final String TAG_GRANT = "grant";
1115     private static final String ATTR_PACKAGE_NAME = "pkg";
1116
1117     private static final String TAG_PERMISSION = "perm";
1118     private static final String ATTR_PERMISSION_NAME = "name";
1119     private static final String ATTR_IS_GRANTED = "g";
1120     private static final String ATTR_USER_SET = "set";
1121     private static final String ATTR_USER_FIXED = "fixed";
1122     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1123
1124     // System/policy permission grants are not backed up
1125     private static final int SYSTEM_RUNTIME_GRANT_MASK =
1126             FLAG_PERMISSION_POLICY_FIXED
1127             | FLAG_PERMISSION_SYSTEM_FIXED
1128             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1129
1130     // And we back up these user-adjusted states
1131     private static final int USER_RUNTIME_GRANT_MASK =
1132             FLAG_PERMISSION_USER_SET
1133             | FLAG_PERMISSION_USER_FIXED
1134             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1135
1136     final @Nullable String mRequiredVerifierPackage;
1137     final @NonNull String mRequiredInstallerPackage;
1138     final @NonNull String mRequiredUninstallerPackage;
1139     final @Nullable String mSetupWizardPackage;
1140     final @Nullable String mStorageManagerPackage;
1141     final @NonNull String mServicesSystemSharedLibraryPackageName;
1142     final @NonNull String mSharedSystemSharedLibraryPackageName;
1143
1144     final boolean mPermissionReviewRequired;
1145
1146     private final PackageUsage mPackageUsage = new PackageUsage();
1147     private final CompilerStats mCompilerStats = new CompilerStats();
1148
1149     class PackageHandler extends Handler {
1150         private boolean mBound = false;
1151         final ArrayList<HandlerParams> mPendingInstalls =
1152             new ArrayList<HandlerParams>();
1153
1154         private boolean connectToService() {
1155             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1156                     " DefaultContainerService");
1157             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1158             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1159             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1160                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1161                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162                 mBound = true;
1163                 return true;
1164             }
1165             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166             return false;
1167         }
1168
1169         private void disconnectService() {
1170             mContainerService = null;
1171             mBound = false;
1172             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1173             mContext.unbindService(mDefContainerConn);
1174             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175         }
1176
1177         PackageHandler(Looper looper) {
1178             super(looper);
1179         }
1180
1181         public void handleMessage(Message msg) {
1182             try {
1183                 doHandleMessage(msg);
1184             } finally {
1185                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186             }
1187         }
1188
1189         void doHandleMessage(Message msg) {
1190             switch (msg.what) {
1191                 case INIT_COPY: {
1192                     HandlerParams params = (HandlerParams) msg.obj;
1193                     int idx = mPendingInstalls.size();
1194                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1195                     // If a bind was already initiated we dont really
1196                     // need to do anything. The pending install
1197                     // will be processed later on.
1198                     if (!mBound) {
1199                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                 System.identityHashCode(mHandler));
1201                         // If this is the only one pending we might
1202                         // have to bind to the service again.
1203                         if (!connectToService()) {
1204                             Slog.e(TAG, "Failed to bind to media container service");
1205                             params.serviceError();
1206                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                     System.identityHashCode(mHandler));
1208                             if (params.traceMethod != null) {
1209                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1210                                         params.traceCookie);
1211                             }
1212                             return;
1213                         } else {
1214                             // Once we bind to the service, the first
1215                             // pending request will be processed.
1216                             mPendingInstalls.add(idx, params);
1217                         }
1218                     } else {
1219                         mPendingInstalls.add(idx, params);
1220                         // Already bound to the service. Just make
1221                         // sure we trigger off processing the first request.
1222                         if (idx == 0) {
1223                             mHandler.sendEmptyMessage(MCS_BOUND);
1224                         }
1225                     }
1226                     break;
1227                 }
1228                 case MCS_BOUND: {
1229                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1230                     if (msg.obj != null) {
1231                         mContainerService = (IMediaContainerService) msg.obj;
1232                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233                                 System.identityHashCode(mHandler));
1234                     }
1235                     if (mContainerService == null) {
1236                         if (!mBound) {
1237                             // Something seriously wrong since we are not bound and we are not
1238                             // waiting for connection. Bail out.
1239                             Slog.e(TAG, "Cannot bind to media container service");
1240                             for (HandlerParams params : mPendingInstalls) {
1241                                 // Indicate service bind error
1242                                 params.serviceError();
1243                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244                                         System.identityHashCode(params));
1245                                 if (params.traceMethod != null) {
1246                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1247                                             params.traceMethod, params.traceCookie);
1248                                 }
1249                                 return;
1250                             }
1251                             mPendingInstalls.clear();
1252                         } else {
1253                             Slog.w(TAG, "Waiting to connect to media container service");
1254                         }
1255                     } else if (mPendingInstalls.size() > 0) {
1256                         HandlerParams params = mPendingInstalls.get(0);
1257                         if (params != null) {
1258                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                     System.identityHashCode(params));
1260                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1261                             if (params.startCopy()) {
1262                                 // We are done...  look for more work or to
1263                                 // go idle.
1264                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1265                                         "Checking for more work or unbind...");
1266                                 // Delete pending install
1267                                 if (mPendingInstalls.size() > 0) {
1268                                     mPendingInstalls.remove(0);
1269                                 }
1270                                 if (mPendingInstalls.size() == 0) {
1271                                     if (mBound) {
1272                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                                 "Posting delayed MCS_UNBIND");
1274                                         removeMessages(MCS_UNBIND);
1275                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1276                                         // Unbind after a little delay, to avoid
1277                                         // continual thrashing.
1278                                         sendMessageDelayed(ubmsg, 10000);
1279                                     }
1280                                 } else {
1281                                     // There are more pending requests in queue.
1282                                     // Just post MCS_BOUND message to trigger processing
1283                                     // of next pending install.
1284                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                             "Posting MCS_BOUND for next work");
1286                                     mHandler.sendEmptyMessage(MCS_BOUND);
1287                                 }
1288                             }
1289                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1290                         }
1291                     } else {
1292                         // Should never happen ideally.
1293                         Slog.w(TAG, "Empty queue");
1294                     }
1295                     break;
1296                 }
1297                 case MCS_RECONNECT: {
1298                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1299                     if (mPendingInstalls.size() > 0) {
1300                         if (mBound) {
1301                             disconnectService();
1302                         }
1303                         if (!connectToService()) {
1304                             Slog.e(TAG, "Failed to bind to media container service");
1305                             for (HandlerParams params : mPendingInstalls) {
1306                                 // Indicate service bind error
1307                                 params.serviceError();
1308                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1309                                         System.identityHashCode(params));
1310                             }
1311                             mPendingInstalls.clear();
1312                         }
1313                     }
1314                     break;
1315                 }
1316                 case MCS_UNBIND: {
1317                     // If there is no actual work left, then time to unbind.
1318                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1319
1320                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1321                         if (mBound) {
1322                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1323
1324                             disconnectService();
1325                         }
1326                     } else if (mPendingInstalls.size() > 0) {
1327                         // There are more pending requests in queue.
1328                         // Just post MCS_BOUND message to trigger processing
1329                         // of next pending install.
1330                         mHandler.sendEmptyMessage(MCS_BOUND);
1331                     }
1332
1333                     break;
1334                 }
1335                 case MCS_GIVE_UP: {
1336                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1337                     HandlerParams params = mPendingInstalls.remove(0);
1338                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                             System.identityHashCode(params));
1340                     break;
1341                 }
1342                 case SEND_PENDING_BROADCAST: {
1343                     String packages[];
1344                     ArrayList<String> components[];
1345                     int size = 0;
1346                     int uids[];
1347                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1348                     synchronized (mPackages) {
1349                         if (mPendingBroadcasts == null) {
1350                             return;
1351                         }
1352                         size = mPendingBroadcasts.size();
1353                         if (size <= 0) {
1354                             // Nothing to be done. Just return
1355                             return;
1356                         }
1357                         packages = new String[size];
1358                         components = new ArrayList[size];
1359                         uids = new int[size];
1360                         int i = 0;  // filling out the above arrays
1361
1362                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1363                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1364                             Iterator<Map.Entry<String, ArrayList<String>>> it
1365                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1366                                             .entrySet().iterator();
1367                             while (it.hasNext() && i < size) {
1368                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1369                                 packages[i] = ent.getKey();
1370                                 components[i] = ent.getValue();
1371                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1372                                 uids[i] = (ps != null)
1373                                         ? UserHandle.getUid(packageUserId, ps.appId)
1374                                         : -1;
1375                                 i++;
1376                             }
1377                         }
1378                         size = i;
1379                         mPendingBroadcasts.clear();
1380                     }
1381                     // Send broadcasts
1382                     for (int i = 0; i < size; i++) {
1383                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1384                     }
1385                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1386                     break;
1387                 }
1388                 case START_CLEANING_PACKAGE: {
1389                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1390                     final String packageName = (String)msg.obj;
1391                     final int userId = msg.arg1;
1392                     final boolean andCode = msg.arg2 != 0;
1393                     synchronized (mPackages) {
1394                         if (userId == UserHandle.USER_ALL) {
1395                             int[] users = sUserManager.getUserIds();
1396                             for (int user : users) {
1397                                 mSettings.addPackageToCleanLPw(
1398                                         new PackageCleanItem(user, packageName, andCode));
1399                             }
1400                         } else {
1401                             mSettings.addPackageToCleanLPw(
1402                                     new PackageCleanItem(userId, packageName, andCode));
1403                         }
1404                     }
1405                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406                     startCleaningPackages();
1407                 } break;
1408                 case POST_INSTALL: {
1409                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1410
1411                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1412                     final boolean didRestore = (msg.arg2 != 0);
1413                     mRunningInstalls.delete(msg.arg1);
1414
1415                     if (data != null) {
1416                         InstallArgs args = data.args;
1417                         PackageInstalledInfo parentRes = data.res;
1418
1419                         final boolean grantPermissions = (args.installFlags
1420                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1421                         final boolean killApp = (args.installFlags
1422                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1423                         final String[] grantedPermissions = args.installGrantPermissions;
1424
1425                         // Handle the parent package
1426                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
1427                                 grantedPermissions, didRestore, args.installerPackageName,
1428                                 args.observer);
1429
1430                         // Handle the child packages
1431                         final int childCount = (parentRes.addedChildPackages != null)
1432                                 ? parentRes.addedChildPackages.size() : 0;
1433                         for (int i = 0; i < childCount; i++) {
1434                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1435                             handlePackagePostInstall(childRes, grantPermissions, killApp,
1436                                     grantedPermissions, false, args.installerPackageName,
1437                                     args.observer);
1438                         }
1439
1440                         // Log tracing if needed
1441                         if (args.traceMethod != null) {
1442                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1443                                     args.traceCookie);
1444                         }
1445                     } else {
1446                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                     }
1448
1449                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1450                 } break;
1451                 case UPDATED_MEDIA_STATUS: {
1452                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453                     boolean reportStatus = msg.arg1 == 1;
1454                     boolean doGc = msg.arg2 == 1;
1455                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456                     if (doGc) {
1457                         // Force a gc to clear up stale containers.
1458                         Runtime.getRuntime().gc();
1459                     }
1460                     if (msg.obj != null) {
1461                         @SuppressWarnings("unchecked")
1462                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464                         // Unload containers
1465                         unloadAllContainers(args);
1466                     }
1467                     if (reportStatus) {
1468                         try {
1469                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470                             PackageHelper.getMountService().finishMediaUpdate();
1471                         } catch (RemoteException e) {
1472                             Log.e(TAG, "MountService not running?");
1473                         }
1474                     }
1475                 } break;
1476                 case WRITE_SETTINGS: {
1477                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                     synchronized (mPackages) {
1479                         removeMessages(WRITE_SETTINGS);
1480                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                         mSettings.writeLPr();
1482                         mDirtyUsers.clear();
1483                     }
1484                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                 } break;
1486                 case WRITE_PACKAGE_RESTRICTIONS: {
1487                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                     synchronized (mPackages) {
1489                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                         for (int userId : mDirtyUsers) {
1491                             mSettings.writePackageRestrictionsLPr(userId);
1492                         }
1493                         mDirtyUsers.clear();
1494                     }
1495                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                 } break;
1497                 case WRITE_PACKAGE_LIST: {
1498                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                     synchronized (mPackages) {
1500                         removeMessages(WRITE_PACKAGE_LIST);
1501                         mSettings.writePackageListLPr(msg.arg1);
1502                     }
1503                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                 } break;
1505                 case CHECK_PENDING_VERIFICATION: {
1506                     final int verificationId = msg.arg1;
1507                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                     if ((state != null) && !state.timeoutExtended()) {
1510                         final InstallArgs args = state.getInstallArgs();
1511                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                         Slog.i(TAG, "Verification timed out for " + originUri);
1514                         mPendingVerification.remove(verificationId);
1515
1516                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                             Slog.i(TAG, "Continuing with installation of " + originUri);
1520                             state.setVerifierResponse(Binder.getCallingUid(),
1521                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                             broadcastPackageVerified(verificationId, originUri,
1523                                     PackageManager.VERIFICATION_ALLOW,
1524                                     state.getInstallArgs().getUser());
1525                             try {
1526                                 ret = args.copyApk(mContainerService, true);
1527                             } catch (RemoteException e) {
1528                                 Slog.e(TAG, "Could not contact the ContainerService");
1529                             }
1530                         } else {
1531                             broadcastPackageVerified(verificationId, originUri,
1532                                     PackageManager.VERIFICATION_REJECT,
1533                                     state.getInstallArgs().getUser());
1534                         }
1535
1536                         Trace.asyncTraceEnd(
1537                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538
1539                         processPendingInstall(args, ret);
1540                         mHandler.sendEmptyMessage(MCS_UNBIND);
1541                     }
1542                     break;
1543                 }
1544                 case PACKAGE_VERIFIED: {
1545                     final int verificationId = msg.arg1;
1546
1547                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1548                     if (state == null) {
1549                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1550                         break;
1551                     }
1552
1553                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554
1555                     state.setVerifierResponse(response.callerUid, response.code);
1556
1557                     if (state.isVerificationComplete()) {
1558                         mPendingVerification.remove(verificationId);
1559
1560                         final InstallArgs args = state.getInstallArgs();
1561                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                         int ret;
1564                         if (state.isInstallAllowed()) {
1565                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566                             broadcastPackageVerified(verificationId, originUri,
1567                                     response.code, state.getInstallArgs().getUser());
1568                             try {
1569                                 ret = args.copyApk(mContainerService, true);
1570                             } catch (RemoteException e) {
1571                                 Slog.e(TAG, "Could not contact the ContainerService");
1572                             }
1573                         } else {
1574                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575                         }
1576
1577                         Trace.asyncTraceEnd(
1578                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579
1580                         processPendingInstall(args, ret);
1581                         mHandler.sendEmptyMessage(MCS_UNBIND);
1582                     }
1583
1584                     break;
1585                 }
1586                 case START_INTENT_FILTER_VERIFICATIONS: {
1587                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1588                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589                             params.replacing, params.pkg);
1590                     break;
1591                 }
1592                 case INTENT_FILTER_VERIFIED: {
1593                     final int verificationId = msg.arg1;
1594
1595                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596                             verificationId);
1597                     if (state == null) {
1598                         Slog.w(TAG, "Invalid IntentFilter verification token "
1599                                 + verificationId + " received");
1600                         break;
1601                     }
1602
1603                     final int userId = state.getUserId();
1604
1605                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                             "Processing IntentFilter verification with token:"
1607                             + verificationId + " and userId:" + userId);
1608
1609                     final IntentFilterVerificationResponse response =
1610                             (IntentFilterVerificationResponse) msg.obj;
1611
1612                     state.setVerifierResponse(response.callerUid, response.code);
1613
1614                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                             "IntentFilter verification with token:" + verificationId
1616                             + " and userId:" + userId
1617                             + " is settings verifier response with response code:"
1618                             + response.code);
1619
1620                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622                                 + response.getFailedDomainsString());
1623                     }
1624
1625                     if (state.isVerificationComplete()) {
1626                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627                     } else {
1628                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629                                 "IntentFilter verification with token:" + verificationId
1630                                 + " was not said to be complete");
1631                     }
1632
1633                     break;
1634                 }
1635             }
1636         }
1637     }
1638
1639     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640             boolean killApp, String[] grantedPermissions,
1641             boolean launchedForRestore, String installerPackage,
1642             IPackageInstallObserver2 installObserver) {
1643         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644             // Send the removed broadcasts
1645             if (res.removedInfo != null) {
1646                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1647             }
1648
1649             // Now that we successfully installed the package, grant runtime
1650             // permissions if requested before broadcasting the install.
1651             if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652                     >= Build.VERSION_CODES.M) {
1653                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1654             }
1655
1656             final boolean update = res.removedInfo != null
1657                     && res.removedInfo.removedPackage != null;
1658
1659             // If this is the first time we have child packages for a disabled privileged
1660             // app that had no children, we grant requested runtime permissions to the new
1661             // children if the parent on the system image had them already granted.
1662             if (res.pkg.parentPackage != null) {
1663                 synchronized (mPackages) {
1664                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1665                 }
1666             }
1667
1668             synchronized (mPackages) {
1669                 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1670             }
1671
1672             final String packageName = res.pkg.applicationInfo.packageName;
1673             Bundle extras = new Bundle(1);
1674             extras.putInt(Intent.EXTRA_UID, res.uid);
1675
1676             // Determine the set of users who are adding this package for
1677             // the first time vs. those who are seeing an update.
1678             int[] firstUsers = EMPTY_INT_ARRAY;
1679             int[] updateUsers = EMPTY_INT_ARRAY;
1680             if (res.origUsers == null || res.origUsers.length == 0) {
1681                 firstUsers = res.newUsers;
1682             } else {
1683                 for (int newUser : res.newUsers) {
1684                     boolean isNew = true;
1685                     for (int origUser : res.origUsers) {
1686                         if (origUser == newUser) {
1687                             isNew = false;
1688                             break;
1689                         }
1690                     }
1691                     if (isNew) {
1692                         firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1693                     } else {
1694                         updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1695                     }
1696                 }
1697             }
1698
1699             // Send installed broadcasts if the install/update is not ephemeral
1700             if (!isEphemeral(res.pkg)) {
1701                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1702
1703                 // Send added for users that see the package for the first time
1704                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                         extras, 0 /*flags*/, null /*targetPackage*/,
1706                         null /*finishedReceiver*/, firstUsers);
1707
1708                 // Send added for users that don't see the package for the first time
1709                 if (update) {
1710                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1711                 }
1712                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1713                         extras, 0 /*flags*/, null /*targetPackage*/,
1714                         null /*finishedReceiver*/, updateUsers);
1715
1716                 // Send replaced for users that don't see the package for the first time
1717                 if (update) {
1718                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1719                             packageName, extras, 0 /*flags*/,
1720                             null /*targetPackage*/, null /*finishedReceiver*/,
1721                             updateUsers);
1722                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1723                             null /*package*/, null /*extras*/, 0 /*flags*/,
1724                             packageName /*targetPackage*/,
1725                             null /*finishedReceiver*/, updateUsers);
1726                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1727                     // First-install and we did a restore, so we're responsible for the
1728                     // first-launch broadcast.
1729                     if (DEBUG_BACKUP) {
1730                         Slog.i(TAG, "Post-restore of " + packageName
1731                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1732                     }
1733                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1734                 }
1735
1736                 // Send broadcast package appeared if forward locked/external for all users
1737                 // treat asec-hosted packages like removable media on upgrade
1738                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1739                     if (DEBUG_INSTALL) {
1740                         Slog.i(TAG, "upgrading pkg " + res.pkg
1741                                 + " is ASEC-hosted -> AVAILABLE");
1742                     }
1743                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1744                     ArrayList<String> pkgList = new ArrayList<>(1);
1745                     pkgList.add(packageName);
1746                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1747                 }
1748             }
1749
1750             // Work that needs to happen on first install within each user
1751             if (firstUsers != null && firstUsers.length > 0) {
1752                 synchronized (mPackages) {
1753                     for (int userId : firstUsers) {
1754                         // If this app is a browser and it's newly-installed for some
1755                         // users, clear any default-browser state in those users. The
1756                         // app's nature doesn't depend on the user, so we can just check
1757                         // its browser nature in any user and generalize.
1758                         if (packageIsBrowser(packageName, userId)) {
1759                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1760                         }
1761
1762                         // We may also need to apply pending (restored) runtime
1763                         // permission grants within these users.
1764                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1765                     }
1766                 }
1767             }
1768
1769             // Log current value of "unknown sources" setting
1770             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1771                     getUnknownSourcesSettings());
1772
1773             // Force a gc to clear up things
1774             Runtime.getRuntime().gc();
1775
1776             // Remove the replaced package's older resources safely now
1777             // We delete after a gc for applications  on sdcard.
1778             if (res.removedInfo != null && res.removedInfo.args != null) {
1779                 synchronized (mInstallLock) {
1780                     res.removedInfo.args.doPostDeleteLI(true);
1781                 }
1782             }
1783         }
1784
1785         // If someone is watching installs - notify them
1786         if (installObserver != null) {
1787             try {
1788                 Bundle extras = extrasForInstallResult(res);
1789                 installObserver.onPackageInstalled(res.name, res.returnCode,
1790                         res.returnMsg, extras);
1791             } catch (RemoteException e) {
1792                 Slog.i(TAG, "Observer no longer exists.");
1793             }
1794         }
1795     }
1796
1797     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1798             PackageParser.Package pkg) {
1799         if (pkg.parentPackage == null) {
1800             return;
1801         }
1802         if (pkg.requestedPermissions == null) {
1803             return;
1804         }
1805         final PackageSetting disabledSysParentPs = mSettings
1806                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1807         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1808                 || !disabledSysParentPs.isPrivileged()
1809                 || (disabledSysParentPs.childPackageNames != null
1810                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
1811             return;
1812         }
1813         final int[] allUserIds = sUserManager.getUserIds();
1814         final int permCount = pkg.requestedPermissions.size();
1815         for (int i = 0; i < permCount; i++) {
1816             String permission = pkg.requestedPermissions.get(i);
1817             BasePermission bp = mSettings.mPermissions.get(permission);
1818             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1819                 continue;
1820             }
1821             for (int userId : allUserIds) {
1822                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1823                         permission, userId)) {
1824                     grantRuntimePermission(pkg.packageName, permission, userId);
1825                 }
1826             }
1827         }
1828     }
1829
1830     private StorageEventListener mStorageListener = new StorageEventListener() {
1831         @Override
1832         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1833             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1834                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1835                     final String volumeUuid = vol.getFsUuid();
1836
1837                     // Clean up any users or apps that were removed or recreated
1838                     // while this volume was missing
1839                     reconcileUsers(volumeUuid);
1840                     reconcileApps(volumeUuid);
1841
1842                     // Clean up any install sessions that expired or were
1843                     // cancelled while this volume was missing
1844                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
1845
1846                     loadPrivatePackages(vol);
1847
1848                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849                     unloadPrivatePackages(vol);
1850                 }
1851             }
1852
1853             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1854                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1855                     updateExternalMediaStatus(true, false);
1856                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1857                     updateExternalMediaStatus(false, false);
1858                 }
1859             }
1860         }
1861
1862         @Override
1863         public void onVolumeForgotten(String fsUuid) {
1864             if (TextUtils.isEmpty(fsUuid)) {
1865                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1866                 return;
1867             }
1868
1869             // Remove any apps installed on the forgotten volume
1870             synchronized (mPackages) {
1871                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1872                 for (PackageSetting ps : packages) {
1873                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1874                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1875                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1876                 }
1877
1878                 mSettings.onVolumeForgotten(fsUuid);
1879                 mSettings.writeLPr();
1880             }
1881         }
1882     };
1883
1884     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1885             String[] grantedPermissions) {
1886         for (int userId : userIds) {
1887             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1888         }
1889
1890         // We could have touched GID membership, so flush out packages.list
1891         synchronized (mPackages) {
1892             mSettings.writePackageListLPr();
1893         }
1894     }
1895
1896     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1897             String[] grantedPermissions) {
1898         SettingBase sb = (SettingBase) pkg.mExtras;
1899         if (sb == null) {
1900             return;
1901         }
1902
1903         PermissionsState permissionsState = sb.getPermissionsState();
1904
1905         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1906                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1907
1908         for (String permission : pkg.requestedPermissions) {
1909             final BasePermission bp;
1910             synchronized (mPackages) {
1911                 bp = mSettings.mPermissions.get(permission);
1912             }
1913             if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1914                     && (grantedPermissions == null
1915                            || ArrayUtils.contains(grantedPermissions, permission))) {
1916                 final int flags = permissionsState.getPermissionFlags(permission, userId);
1917                 // Installer cannot change immutable permissions.
1918                 if ((flags & immutableFlags) == 0) {
1919                     grantRuntimePermission(pkg.packageName, permission, userId);
1920                 }
1921             }
1922         }
1923     }
1924
1925     Bundle extrasForInstallResult(PackageInstalledInfo res) {
1926         Bundle extras = null;
1927         switch (res.returnCode) {
1928             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1929                 extras = new Bundle();
1930                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1931                         res.origPermission);
1932                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1933                         res.origPackage);
1934                 break;
1935             }
1936             case PackageManager.INSTALL_SUCCEEDED: {
1937                 extras = new Bundle();
1938                 extras.putBoolean(Intent.EXTRA_REPLACING,
1939                         res.removedInfo != null && res.removedInfo.removedPackage != null);
1940                 break;
1941             }
1942         }
1943         return extras;
1944     }
1945
1946     void scheduleWriteSettingsLocked() {
1947         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1948             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1949         }
1950     }
1951
1952     void scheduleWritePackageListLocked(int userId) {
1953         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1954             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1955             msg.arg1 = userId;
1956             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1957         }
1958     }
1959
1960     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1961         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1962         scheduleWritePackageRestrictionsLocked(userId);
1963     }
1964
1965     void scheduleWritePackageRestrictionsLocked(int userId) {
1966         final int[] userIds = (userId == UserHandle.USER_ALL)
1967                 ? sUserManager.getUserIds() : new int[]{userId};
1968         for (int nextUserId : userIds) {
1969             if (!sUserManager.exists(nextUserId)) return;
1970             mDirtyUsers.add(nextUserId);
1971             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1972                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1973             }
1974         }
1975     }
1976
1977     public static PackageManagerService main(Context context, Installer installer,
1978             boolean factoryTest, boolean onlyCore) {
1979         // Self-check for initial settings.
1980         PackageManagerServiceCompilerMapping.checkProperties();
1981
1982         PackageManagerService m = new PackageManagerService(context, installer,
1983                 factoryTest, onlyCore);
1984         m.enableSystemUserPackages();
1985         ServiceManager.addService("package", m);
1986         return m;
1987     }
1988
1989     private void enableSystemUserPackages() {
1990         if (!UserManager.isSplitSystemUser()) {
1991             return;
1992         }
1993         // For system user, enable apps based on the following conditions:
1994         // - app is whitelisted or belong to one of these groups:
1995         //   -- system app which has no launcher icons
1996         //   -- system app which has INTERACT_ACROSS_USERS permission
1997         //   -- system IME app
1998         // - app is not in the blacklist
1999         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2000         Set<String> enableApps = new ArraySet<>();
2001         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2002                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2003                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2004         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2005         enableApps.addAll(wlApps);
2006         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2007                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2008         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2009         enableApps.removeAll(blApps);
2010         Log.i(TAG, "Applications installed for system user: " + enableApps);
2011         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2012                 UserHandle.SYSTEM);
2013         final int allAppsSize = allAps.size();
2014         synchronized (mPackages) {
2015             for (int i = 0; i < allAppsSize; i++) {
2016                 String pName = allAps.get(i);
2017                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2018                 // Should not happen, but we shouldn't be failing if it does
2019                 if (pkgSetting == null) {
2020                     continue;
2021                 }
2022                 boolean install = enableApps.contains(pName);
2023                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2024                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2025                             + " for system user");
2026                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2027                 }
2028             }
2029         }
2030     }
2031
2032     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2033         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2034                 Context.DISPLAY_SERVICE);
2035         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2036     }
2037
2038     /**
2039      * Requests that files preopted on a secondary system partition be copied to the data partition
2040      * if possible.  Note that the actual copying of the files is accomplished by init for security
2041      * reasons. This simply requests that the copy takes place and awaits confirmation of its
2042      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2043      */
2044     private static void requestCopyPreoptedFiles() {
2045         final int WAIT_TIME_MS = 100;
2046         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2047         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2048             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2049             // We will wait for up to 100 seconds.
2050             final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2051             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2052                 try {
2053                     Thread.sleep(WAIT_TIME_MS);
2054                 } catch (InterruptedException e) {
2055                     // Do nothing
2056                 }
2057                 if (SystemClock.uptimeMillis() > timeEnd) {
2058                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2059                     Slog.wtf(TAG, "cppreopt did not finish!");
2060                     break;
2061                 }
2062             }
2063         }
2064     }
2065
2066     public PackageManagerService(Context context, Installer installer,
2067             boolean factoryTest, boolean onlyCore) {
2068         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2069                 SystemClock.uptimeMillis());
2070
2071         if (mSdkVersion <= 0) {
2072             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2073         }
2074
2075         mContext = context;
2076
2077         mPermissionReviewRequired = context.getResources().getBoolean(
2078                 R.bool.config_permissionReviewRequired);
2079
2080         mFactoryTest = factoryTest;
2081         mOnlyCore = onlyCore;
2082         mMetrics = new DisplayMetrics();
2083         mSettings = new Settings(mPackages);
2084         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2085                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2086         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2087                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2088         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2089                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2090         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2091                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2092         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2093                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2095                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096
2097         String separateProcesses = SystemProperties.get("debug.separate_processes");
2098         if (separateProcesses != null && separateProcesses.length() > 0) {
2099             if ("*".equals(separateProcesses)) {
2100                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2101                 mSeparateProcesses = null;
2102                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2103             } else {
2104                 mDefParseFlags = 0;
2105                 mSeparateProcesses = separateProcesses.split(",");
2106                 Slog.w(TAG, "Running with debug.separate_processes: "
2107                         + separateProcesses);
2108             }
2109         } else {
2110             mDefParseFlags = 0;
2111             mSeparateProcesses = null;
2112         }
2113
2114         mInstaller = installer;
2115         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2116                 "*dexopt*");
2117         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2118
2119         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2120                 FgThread.get().getLooper());
2121
2122         getDefaultDisplayMetrics(context, mMetrics);
2123
2124         SystemConfig systemConfig = SystemConfig.getInstance();
2125         mGlobalGids = systemConfig.getGlobalGids();
2126         mSystemPermissions = systemConfig.getSystemPermissions();
2127         mAvailableFeatures = systemConfig.getAvailableFeatures();
2128
2129         mProtectedPackages = new ProtectedPackages(mContext);
2130
2131         synchronized (mInstallLock) {
2132         // writer
2133         synchronized (mPackages) {
2134             mHandlerThread = new ServiceThread(TAG,
2135                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2136             mHandlerThread.start();
2137             mHandler = new PackageHandler(mHandlerThread.getLooper());
2138             mProcessLoggingHandler = new ProcessLoggingHandler();
2139             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2140
2141             mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2142
2143             File dataDir = Environment.getDataDirectory();
2144             mAppInstallDir = new File(dataDir, "app");
2145             mAppLib32InstallDir = new File(dataDir, "app-lib");
2146             mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2147             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2148             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2149
2150             sUserManager = new UserManagerService(context, this, mPackages);
2151
2152             // Propagate permission configuration in to package manager.
2153             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2154                     = systemConfig.getPermissions();
2155             for (int i=0; i<permConfig.size(); i++) {
2156                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2157                 BasePermission bp = mSettings.mPermissions.get(perm.name);
2158                 if (bp == null) {
2159                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2160                     mSettings.mPermissions.put(perm.name, bp);
2161                 }
2162                 if (perm.gids != null) {
2163                     bp.setGids(perm.gids, perm.perUser);
2164                 }
2165             }
2166
2167             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2168             for (int i=0; i<libConfig.size(); i++) {
2169                 mSharedLibraries.put(libConfig.keyAt(i),
2170                         new SharedLibraryEntry(libConfig.valueAt(i), null));
2171             }
2172
2173             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2174
2175             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2176
2177             // Clean up orphaned packages for which the code path doesn't exist
2178             // and they are an update to a system app - caused by bug/32321269
2179             final int packageSettingCount = mSettings.mPackages.size();
2180             for (int i = packageSettingCount - 1; i >= 0; i--) {
2181                 PackageSetting ps = mSettings.mPackages.valueAt(i);
2182                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2183                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2184                     mSettings.mPackages.removeAt(i);
2185                     mSettings.enableSystemPackageLPw(ps.name);
2186                 }
2187             }
2188
2189             if (mFirstBoot) {
2190                 requestCopyPreoptedFiles();
2191             }
2192
2193             String customResolverActivity = Resources.getSystem().getString(
2194                     R.string.config_customResolverActivity);
2195             if (TextUtils.isEmpty(customResolverActivity)) {
2196                 customResolverActivity = null;
2197             } else {
2198                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2199                         customResolverActivity);
2200             }
2201
2202             long startTime = SystemClock.uptimeMillis();
2203
2204             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2205                     startTime);
2206
2207             // Set flag to monitor and not change apk file paths when
2208             // scanning install directories.
2209             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2210
2211             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2212             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2213
2214             if (bootClassPath == null) {
2215                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2216             }
2217
2218             if (systemServerClassPath == null) {
2219                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2220             }
2221
2222             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2223             final String[] dexCodeInstructionSets =
2224                     getDexCodeInstructionSets(
2225                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
2226
2227             /**
2228              * Ensure all external libraries have had dexopt run on them.
2229              */
2230             if (mSharedLibraries.size() > 0) {
2231                 // NOTE: For now, we're compiling these system "shared libraries"
2232                 // (and framework jars) into all available architectures. It's possible
2233                 // to compile them only when we come across an app that uses them (there's
2234                 // already logic for that in scanPackageLI) but that adds some complexity.
2235                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2236                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2237                         final String lib = libEntry.path;
2238                         if (lib == null) {
2239                             continue;
2240                         }
2241
2242                         try {
2243                             // Shared libraries do not have profiles so we perform a full
2244                             // AOT compilation (if needed).
2245                             int dexoptNeeded = DexFile.getDexOptNeeded(
2246                                     lib, dexCodeInstructionSet,
2247                                     getCompilerFilterForReason(REASON_SHARED_APK),
2248                                     false /* newProfile */);
2249                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2250                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2251                                         dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2252                                         getCompilerFilterForReason(REASON_SHARED_APK),
2253                                         StorageManager.UUID_PRIVATE_INTERNAL,
2254                                         SKIP_SHARED_LIBRARY_CHECK);
2255                             }
2256                         } catch (FileNotFoundException e) {
2257                             Slog.w(TAG, "Library not found: " + lib);
2258                         } catch (IOException | InstallerException e) {
2259                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2260                                     + e.getMessage());
2261                         }
2262                     }
2263                 }
2264             }
2265
2266             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2267
2268             final VersionInfo ver = mSettings.getInternalVersion();
2269             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2270
2271             // when upgrading from pre-M, promote system app permissions from install to runtime
2272             mPromoteSystemApps =
2273                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2274
2275             // When upgrading from pre-N, we need to handle package extraction like first boot,
2276             // as there is no profiling data available.
2277             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2278
2279             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2280
2281             // save off the names of pre-existing system packages prior to scanning; we don't
2282             // want to automatically grant runtime permissions for new system apps
2283             if (mPromoteSystemApps) {
2284                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2285                 while (pkgSettingIter.hasNext()) {
2286                     PackageSetting ps = pkgSettingIter.next();
2287                     if (isSystemApp(ps)) {
2288                         mExistingSystemPackages.add(ps.name);
2289                     }
2290                 }
2291             }
2292
2293             // Collect vendor overlay packages. (Do this before scanning any apps.)
2294             // For security and version matching reason, only consider
2295             // overlay packages if they reside in the right directory.
2296             String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2297             if (!overlayThemeDir.isEmpty()) {
2298                 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2299                         | PackageParser.PARSE_IS_SYSTEM
2300                         | PackageParser.PARSE_IS_SYSTEM_DIR
2301                         | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2302             }
2303             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2304                     | PackageParser.PARSE_IS_SYSTEM
2305                     | PackageParser.PARSE_IS_SYSTEM_DIR
2306                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2307
2308             // Find base frameworks (resource packages without code).
2309             scanDirTracedLI(frameworkDir, mDefParseFlags
2310                     | PackageParser.PARSE_IS_SYSTEM
2311                     | PackageParser.PARSE_IS_SYSTEM_DIR
2312                     | PackageParser.PARSE_IS_PRIVILEGED,
2313                     scanFlags | SCAN_NO_DEX, 0);
2314
2315             // Collected privileged system packages.
2316             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2317             scanDirTracedLI(privilegedAppDir, mDefParseFlags
2318                     | PackageParser.PARSE_IS_SYSTEM
2319                     | PackageParser.PARSE_IS_SYSTEM_DIR
2320                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2321
2322             // Collect ordinary system packages.
2323             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2324             scanDirTracedLI(systemAppDir, mDefParseFlags
2325                     | PackageParser.PARSE_IS_SYSTEM
2326                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2327
2328             // Collect all vendor packages.
2329             File vendorAppDir = new File("/vendor/app");
2330             try {
2331                 vendorAppDir = vendorAppDir.getCanonicalFile();
2332             } catch (IOException e) {
2333                 // failed to look up canonical path, continue with original one
2334             }
2335             scanDirTracedLI(vendorAppDir, mDefParseFlags
2336                     | PackageParser.PARSE_IS_SYSTEM
2337                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2338
2339             // Collect all OEM packages.
2340             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2341             scanDirTracedLI(oemAppDir, mDefParseFlags
2342                     | PackageParser.PARSE_IS_SYSTEM
2343                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2344
2345             // Prune any system packages that no longer exist.
2346             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2347             if (!mOnlyCore) {
2348                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2349                 while (psit.hasNext()) {
2350                     PackageSetting ps = psit.next();
2351
2352                     /*
2353                      * If this is not a system app, it can't be a
2354                      * disable system app.
2355                      */
2356                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2357                         continue;
2358                     }
2359
2360                     /*
2361                      * If the package is scanned, it's not erased.
2362                      */
2363                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2364                     if (scannedPkg != null) {
2365                         /*
2366                          * If the system app is both scanned and in the
2367                          * disabled packages list, then it must have been
2368                          * added via OTA. Remove it from the currently
2369                          * scanned package so the previously user-installed
2370                          * application can be scanned.
2371                          */
2372                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2373                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2374                                     + ps.name + "; removing system app.  Last known codePath="
2375                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2376                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2377                                     + scannedPkg.mVersionCode);
2378                             removePackageLI(scannedPkg, true);
2379                             mExpectingBetter.put(ps.name, ps.codePath);
2380                         }
2381
2382                         continue;
2383                     }
2384
2385                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2386                         psit.remove();
2387                         logCriticalInfo(Log.WARN, "System package " + ps.name
2388                                 + " no longer exists; it's data will be wiped");
2389                         // Actual deletion of code and data will be handled by later
2390                         // reconciliation step
2391                     } else {
2392                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2393                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2394                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2395                         }
2396                     }
2397                 }
2398             }
2399
2400             //look for any incomplete package installations
2401             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2402             for (int i = 0; i < deletePkgsList.size(); i++) {
2403                 // Actual deletion of code and data will be handled by later
2404                 // reconciliation step
2405                 final String packageName = deletePkgsList.get(i).name;
2406                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2407                 synchronized (mPackages) {
2408                     mSettings.removePackageLPw(packageName);
2409                 }
2410             }
2411
2412             //delete tmp files
2413             deleteTempPackageFiles();
2414
2415             // Remove any shared userIDs that have no associated packages
2416             mSettings.pruneSharedUsersLPw();
2417
2418             if (!mOnlyCore) {
2419                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2420                         SystemClock.uptimeMillis());
2421                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2422
2423                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2424                         | PackageParser.PARSE_FORWARD_LOCK,
2425                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2426
2427                 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2428                         | PackageParser.PARSE_IS_EPHEMERAL,
2429                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2430
2431                 /**
2432                  * Remove disable package settings for any updated system
2433                  * apps that were removed via an OTA. If they're not a
2434                  * previously-updated app, remove them completely.
2435                  * Otherwise, just revoke their system-level permissions.
2436                  */
2437                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2438                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2439                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2440
2441                     String msg;
2442                     if (deletedPkg == null) {
2443                         msg = "Updated system package " + deletedAppName
2444                                 + " no longer exists; it's data will be wiped";
2445                         // Actual deletion of code and data will be handled by later
2446                         // reconciliation step
2447                     } else {
2448                         msg = "Updated system app + " + deletedAppName
2449                                 + " no longer present; removing system privileges for "
2450                                 + deletedAppName;
2451
2452                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2453
2454                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2455                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2456                     }
2457                     logCriticalInfo(Log.WARN, msg);
2458                 }
2459
2460                 /**
2461                  * Make sure all system apps that we expected to appear on
2462                  * the userdata partition actually showed up. If they never
2463                  * appeared, crawl back and revive the system version.
2464                  */
2465                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2466                     final String packageName = mExpectingBetter.keyAt(i);
2467                     if (!mPackages.containsKey(packageName)) {
2468                         final File scanFile = mExpectingBetter.valueAt(i);
2469
2470                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2471                                 + " but never showed up; reverting to system");
2472
2473                         int reparseFlags = mDefParseFlags;
2474                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2475                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2476                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2477                                     | PackageParser.PARSE_IS_PRIVILEGED;
2478                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2479                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2480                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2481                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2482                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2483                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2484                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2485                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2486                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2487                         } else {
2488                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2489                             continue;
2490                         }
2491
2492                         mSettings.enableSystemPackageLPw(packageName);
2493
2494                         try {
2495                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2496                         } catch (PackageManagerException e) {
2497                             Slog.e(TAG, "Failed to parse original system package: "
2498                                     + e.getMessage());
2499                         }
2500                     }
2501                 }
2502             }
2503             mExpectingBetter.clear();
2504
2505             // Resolve the storage manager.
2506             mStorageManagerPackage = getStorageManagerPackageName();
2507
2508             // Resolve protected action filters. Only the setup wizard is allowed to
2509             // have a high priority filter for these actions.
2510             mSetupWizardPackage = getSetupWizardPackageName();
2511             if (mProtectedFilters.size() > 0) {
2512                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2513                     Slog.i(TAG, "No setup wizard;"
2514                         + " All protected intents capped to priority 0");
2515                 }
2516                 for (ActivityIntentInfo filter : mProtectedFilters) {
2517                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2518                         if (DEBUG_FILTERS) {
2519                             Slog.i(TAG, "Found setup wizard;"
2520                                 + " allow priority " + filter.getPriority() + ";"
2521                                 + " package: " + filter.activity.info.packageName
2522                                 + " activity: " + filter.activity.className
2523                                 + " priority: " + filter.getPriority());
2524                         }
2525                         // skip setup wizard; allow it to keep the high priority filter
2526                         continue;
2527                     }
2528                     Slog.w(TAG, "Protected action; cap priority to 0;"
2529                             + " package: " + filter.activity.info.packageName
2530                             + " activity: " + filter.activity.className
2531                             + " origPrio: " + filter.getPriority());
2532                     filter.setPriority(0);
2533                 }
2534             }
2535             mDeferProtectedFilters = false;
2536             mProtectedFilters.clear();
2537
2538             // Now that we know all of the shared libraries, update all clients to have
2539             // the correct library paths.
2540             updateAllSharedLibrariesLPw();
2541
2542             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2543                 // NOTE: We ignore potential failures here during a system scan (like
2544                 // the rest of the commands above) because there's precious little we
2545                 // can do about it. A settings error is reported, though.
2546                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2547                         false /* boot complete */);
2548             }
2549
2550             // Now that we know all the packages we are keeping,
2551             // read and update their last usage times.
2552             mPackageUsage.read(mPackages);
2553             mCompilerStats.read();
2554
2555             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2556                     SystemClock.uptimeMillis());
2557             Slog.i(TAG, "Time to scan packages: "
2558                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2559                     + " seconds");
2560
2561             // If the platform SDK has changed since the last time we booted,
2562             // we need to re-grant app permission to catch any new ones that
2563             // appear.  This is really a hack, and means that apps can in some
2564             // cases get permissions that the user didn't initially explicitly
2565             // allow...  it would be nice to have some better way to handle
2566             // this situation.
2567             int updateFlags = UPDATE_PERMISSIONS_ALL;
2568             if (ver.sdkVersion != mSdkVersion) {
2569                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2570                         + mSdkVersion + "; regranting permissions for internal storage");
2571                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2572             }
2573             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2574             ver.sdkVersion = mSdkVersion;
2575
2576             // If this is the first boot or an update from pre-M, and it is a normal
2577             // boot, then we need to initialize the default preferred apps across
2578             // all defined users.
2579             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2580                 for (UserInfo user : sUserManager.getUsers(true)) {
2581                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2582                     applyFactoryDefaultBrowserLPw(user.id);
2583                     primeDomainVerificationsLPw(user.id);
2584                 }
2585             }
2586
2587             // Prepare storage for system user really early during boot,
2588             // since core system apps like SettingsProvider and SystemUI
2589             // can't wait for user to start
2590             final int storageFlags;
2591             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2592                 storageFlags = StorageManager.FLAG_STORAGE_DE;
2593             } else {
2594                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2595             }
2596             reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2597                     storageFlags);
2598
2599             // If this is first boot after an OTA, and a normal boot, then
2600             // we need to clear code cache directories.
2601             // Note that we do *not* clear the application profiles. These remain valid
2602             // across OTAs and are used to drive profile verification (post OTA) and
2603             // profile compilation (without waiting to collect a fresh set of profiles).
2604             if (mIsUpgrade && !onlyCore) {
2605                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2606                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2607                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2608                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2609                         // No apps are running this early, so no need to freeze
2610                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2611                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2612                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2613                     }
2614                 }
2615                 ver.fingerprint = Build.FINGERPRINT;
2616             }
2617
2618             checkDefaultBrowser();
2619
2620             // clear only after permissions and other defaults have been updated
2621             mExistingSystemPackages.clear();
2622             mPromoteSystemApps = false;
2623
2624             // All the changes are done during package scanning.
2625             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2626
2627             // can downgrade to reader
2628             mSettings.writeLPr();
2629
2630             // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2631             // early on (before the package manager declares itself as early) because other
2632             // components in the system server might ask for package contexts for these apps.
2633             //
2634             // Note that "onlyCore" in this context means the system is encrypted or encrypting
2635             // (i.e, that the data partition is unavailable).
2636             if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2637                 long start = System.nanoTime();
2638                 List<PackageParser.Package> coreApps = new ArrayList<>();
2639                 for (PackageParser.Package pkg : mPackages.values()) {
2640                     if (pkg.coreApp) {
2641                         coreApps.add(pkg);
2642                     }
2643                 }
2644
2645                 int[] stats = performDexOptUpgrade(coreApps, false,
2646                         getCompilerFilterForReason(REASON_CORE_APP));
2647
2648                 final int elapsedTimeSeconds =
2649                         (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2650                 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2651
2652                 if (DEBUG_DEXOPT) {
2653                     Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2654                             stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2655                 }
2656
2657
2658                 // TODO: Should we log these stats to tron too ?
2659                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2660                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2661                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2662                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2663             }
2664
2665             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2666                     SystemClock.uptimeMillis());
2667
2668             if (!mOnlyCore) {
2669                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2670                 mRequiredInstallerPackage = getRequiredInstallerLPr();
2671                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2672                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2673                 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2674                         mIntentFilterVerifierComponent);
2675                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2676                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2677                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2678                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2679             } else {
2680                 mRequiredVerifierPackage = null;
2681                 mRequiredInstallerPackage = null;
2682                 mRequiredUninstallerPackage = null;
2683                 mIntentFilterVerifierComponent = null;
2684                 mIntentFilterVerifier = null;
2685                 mServicesSystemSharedLibraryPackageName = null;
2686                 mSharedSystemSharedLibraryPackageName = null;
2687             }
2688
2689             mInstallerService = new PackageInstallerService(context, this);
2690
2691             final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2692             final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2693             // both the installer and resolver must be present to enable ephemeral
2694             if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2695                 if (DEBUG_EPHEMERAL) {
2696                     Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2697                             + " installer:" + ephemeralInstallerComponent);
2698                 }
2699                 mEphemeralResolverComponent = ephemeralResolverComponent;
2700                 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2701                 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2702                 mEphemeralResolverConnection =
2703                         new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2704             } else {
2705                 if (DEBUG_EPHEMERAL) {
2706                     final String missingComponent =
2707                             (ephemeralResolverComponent == null)
2708                             ? (ephemeralInstallerComponent == null)
2709                                     ? "resolver and installer"
2710                                     : "resolver"
2711                             : "installer";
2712                     Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2713                 }
2714                 mEphemeralResolverComponent = null;
2715                 mEphemeralInstallerComponent = null;
2716                 mEphemeralResolverConnection = null;
2717             }
2718
2719             mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2720         } // synchronized (mPackages)
2721         } // synchronized (mInstallLock)
2722
2723         // Now after opening every single application zip, make sure they
2724         // are all flushed.  Not really needed, but keeps things nice and
2725         // tidy.
2726         Runtime.getRuntime().gc();
2727
2728         // The initial scanning above does many calls into installd while
2729         // holding the mPackages lock, but we're mostly interested in yelling
2730         // once we have a booted system.
2731         mInstaller.setWarnIfHeld(mPackages);
2732
2733         // Expose private service for system components to use.
2734         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2735     }
2736
2737     @Override
2738     public boolean isFirstBoot() {
2739         return mFirstBoot;
2740     }
2741
2742     @Override
2743     public boolean isOnlyCoreApps() {
2744         return mOnlyCore;
2745     }
2746
2747     @Override
2748     public boolean isUpgrade() {
2749         return mIsUpgrade;
2750     }
2751
2752     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2753         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2754
2755         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757                 UserHandle.USER_SYSTEM);
2758         if (matches.size() == 1) {
2759             return matches.get(0).getComponentInfo().packageName;
2760         } else if (matches.size() == 0) {
2761             Log.e(TAG, "There should probably be a verifier, but, none were found");
2762             return null;
2763         }
2764         throw new RuntimeException("There must be exactly one verifier; found " + matches);
2765     }
2766
2767     private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2768         synchronized (mPackages) {
2769             SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2770             if (libraryEntry == null) {
2771                 throw new IllegalStateException("Missing required shared library:" + libraryName);
2772             }
2773             return libraryEntry.apk;
2774         }
2775     }
2776
2777     private @NonNull String getRequiredInstallerLPr() {
2778         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2779         intent.addCategory(Intent.CATEGORY_DEFAULT);
2780         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2781
2782         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2783                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2784                 UserHandle.USER_SYSTEM);
2785         if (matches.size() == 1) {
2786             ResolveInfo resolveInfo = matches.get(0);
2787             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2788                 throw new RuntimeException("The installer must be a privileged app");
2789             }
2790             return matches.get(0).getComponentInfo().packageName;
2791         } else {
2792             throw new RuntimeException("There must be exactly one installer; found " + matches);
2793         }
2794     }
2795
2796     private @NonNull String getRequiredUninstallerLPr() {
2797         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2798         intent.addCategory(Intent.CATEGORY_DEFAULT);
2799         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2800
2801         final ResolveInfo resolveInfo = resolveIntent(intent, null,
2802                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2803                 UserHandle.USER_SYSTEM);
2804         if (resolveInfo == null ||
2805                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2806             throw new RuntimeException("There must be exactly one uninstaller; found "
2807                     + resolveInfo);
2808         }
2809         return resolveInfo.getComponentInfo().packageName;
2810     }
2811
2812     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2813         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2814
2815         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2816                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817                 UserHandle.USER_SYSTEM);
2818         ResolveInfo best = null;
2819         final int N = matches.size();
2820         for (int i = 0; i < N; i++) {
2821             final ResolveInfo cur = matches.get(i);
2822             final String packageName = cur.getComponentInfo().packageName;
2823             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2824                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2825                 continue;
2826             }
2827
2828             if (best == null || cur.priority > best.priority) {
2829                 best = cur;
2830             }
2831         }
2832
2833         if (best != null) {
2834             return best.getComponentInfo().getComponentName();
2835         } else {
2836             throw new RuntimeException("There must be at least one intent filter verifier");
2837         }
2838     }
2839
2840     private @Nullable ComponentName getEphemeralResolverLPr() {
2841         final String[] packageArray =
2842                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2843         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2844             if (DEBUG_EPHEMERAL) {
2845                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2846             }
2847             return null;
2848         }
2849
2850         final int resolveFlags =
2851                 MATCH_DIRECT_BOOT_AWARE
2852                 | MATCH_DIRECT_BOOT_UNAWARE
2853                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2854         final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2855         final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2856                 resolveFlags, UserHandle.USER_SYSTEM);
2857
2858         final int N = resolvers.size();
2859         if (N == 0) {
2860             if (DEBUG_EPHEMERAL) {
2861                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2862             }
2863             return null;
2864         }
2865
2866         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2867         for (int i = 0; i < N; i++) {
2868             final ResolveInfo info = resolvers.get(i);
2869
2870             if (info.serviceInfo == null) {
2871                 continue;
2872             }
2873
2874             final String packageName = info.serviceInfo.packageName;
2875             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2876                 if (DEBUG_EPHEMERAL) {
2877                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2878                             + " pkg: " + packageName + ", info:" + info);
2879                 }
2880                 continue;
2881             }
2882
2883             if (DEBUG_EPHEMERAL) {
2884                 Slog.v(TAG, "Ephemeral resolver found;"
2885                         + " pkg: " + packageName + ", info:" + info);
2886             }
2887             return new ComponentName(packageName, info.serviceInfo.name);
2888         }
2889         if (DEBUG_EPHEMERAL) {
2890             Slog.v(TAG, "Ephemeral resolver NOT found");
2891         }
2892         return null;
2893     }
2894
2895     private @Nullable ComponentName getEphemeralInstallerLPr() {
2896         final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2897         intent.addCategory(Intent.CATEGORY_DEFAULT);
2898         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2899
2900         final int resolveFlags =
2901                 MATCH_DIRECT_BOOT_AWARE
2902                 | MATCH_DIRECT_BOOT_UNAWARE
2903                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2904         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2905                 resolveFlags, UserHandle.USER_SYSTEM);
2906         if (matches.size() == 0) {
2907             return null;
2908         } else if (matches.size() == 1) {
2909             return matches.get(0).getComponentInfo().getComponentName();
2910         } else {
2911             throw new RuntimeException(
2912                     "There must be at most one ephemeral installer; found " + matches);
2913         }
2914     }
2915
2916     private void primeDomainVerificationsLPw(int userId) {
2917         if (DEBUG_DOMAIN_VERIFICATION) {
2918             Slog.d(TAG, "Priming domain verifications in user " + userId);
2919         }
2920
2921         SystemConfig systemConfig = SystemConfig.getInstance();
2922         ArraySet<String> packages = systemConfig.getLinkedApps();
2923         ArraySet<String> domains = new ArraySet<String>();
2924
2925         for (String packageName : packages) {
2926             PackageParser.Package pkg = mPackages.get(packageName);
2927             if (pkg != null) {
2928                 if (!pkg.isSystemApp()) {
2929                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2930                     continue;
2931                 }
2932
2933                 domains.clear();
2934                 for (PackageParser.Activity a : pkg.activities) {
2935                     for (ActivityIntentInfo filter : a.intents) {
2936                         if (hasValidDomains(filter)) {
2937                             domains.addAll(filter.getHostsList());
2938                         }
2939                     }
2940                 }
2941
2942                 if (domains.size() > 0) {
2943                     if (DEBUG_DOMAIN_VERIFICATION) {
2944                         Slog.v(TAG, "      + " + packageName);
2945                     }
2946                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2947                     // state w.r.t. the formal app-linkage "no verification attempted" state;
2948                     // and then 'always' in the per-user state actually used for intent resolution.
2949                     final IntentFilterVerificationInfo ivi;
2950                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2951                             new ArrayList<String>(domains));
2952                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2953                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2954                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2955                 } else {
2956                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2957                             + "' does not handle web links");
2958                 }
2959             } else {
2960                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2961             }
2962         }
2963
2964         scheduleWritePackageRestrictionsLocked(userId);
2965         scheduleWriteSettingsLocked();
2966     }
2967
2968     private void applyFactoryDefaultBrowserLPw(int userId) {
2969         // The default browser app's package name is stored in a string resource,
2970         // with a product-specific overlay used for vendor customization.
2971         String browserPkg = mContext.getResources().getString(
2972                 com.android.internal.R.string.default_browser);
2973         if (!TextUtils.isEmpty(browserPkg)) {
2974             // non-empty string => required to be a known package
2975             PackageSetting ps = mSettings.mPackages.get(browserPkg);
2976             if (ps == null) {
2977                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2978                 browserPkg = null;
2979             } else {
2980                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2981             }
2982         }
2983
2984         // Nothing valid explicitly set? Make the factory-installed browser the explicit
2985         // default.  If there's more than one, just leave everything alone.
2986         if (browserPkg == null) {
2987             calculateDefaultBrowserLPw(userId);
2988         }
2989     }
2990
2991     private void calculateDefaultBrowserLPw(int userId) {
2992         List<String> allBrowsers = resolveAllBrowserApps(userId);
2993         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2994         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2995     }
2996
2997     private List<String> resolveAllBrowserApps(int userId) {
2998         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2999         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3000                 PackageManager.MATCH_ALL, userId);
3001
3002         final int count = list.size();
3003         List<String> result = new ArrayList<String>(count);
3004         for (int i=0; i<count; i++) {
3005             ResolveInfo info = list.get(i);
3006             if (info.activityInfo == null
3007                     || !info.handleAllWebDataURI
3008                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3009                     || result.contains(info.activityInfo.packageName)) {
3010                 continue;
3011             }
3012             result.add(info.activityInfo.packageName);
3013         }
3014
3015         return result;
3016     }
3017
3018     private boolean packageIsBrowser(String packageName, int userId) {
3019         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3020                 PackageManager.MATCH_ALL, userId);
3021         final int N = list.size();
3022         for (int i = 0; i < N; i++) {
3023             ResolveInfo info = list.get(i);
3024             if (packageName.equals(info.activityInfo.packageName)) {
3025                 return true;
3026             }
3027         }
3028         return false;
3029     }
3030
3031     private void checkDefaultBrowser() {
3032         final int myUserId = UserHandle.myUserId();
3033         final String packageName = getDefaultBrowserPackageName(myUserId);
3034         if (packageName != null) {
3035             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3036             if (info == null) {
3037                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3038                 synchronized (mPackages) {
3039                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3040                 }
3041             }
3042         }
3043     }
3044
3045     @Override
3046     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3047             throws RemoteException {
3048         try {
3049             return super.onTransact(code, data, reply, flags);
3050         } catch (RuntimeException e) {
3051             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3052                 Slog.wtf(TAG, "Package Manager Crash", e);
3053             }
3054             throw e;
3055         }
3056     }
3057
3058     static int[] appendInts(int[] cur, int[] add) {
3059         if (add == null) return cur;
3060         if (cur == null) return add;
3061         final int N = add.length;
3062         for (int i=0; i<N; i++) {
3063             cur = appendInt(cur, add[i]);
3064         }
3065         return cur;
3066     }
3067
3068     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3069         if (!sUserManager.exists(userId)) return null;
3070         if (ps == null) {
3071             return null;
3072         }
3073         final PackageParser.Package p = ps.pkg;
3074         if (p == null) {
3075             return null;
3076         }
3077
3078         final PermissionsState permissionsState = ps.getPermissionsState();
3079
3080         // Compute GIDs only if requested
3081         final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3082                 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3083         // Compute granted permissions only if package has requested permissions
3084         final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3085                 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3086         final PackageUserState state = ps.readUserState(userId);
3087
3088         return PackageParser.generatePackageInfo(p, gids, flags,
3089                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3090     }
3091
3092     @Override
3093     public void checkPackageStartable(String packageName, int userId) {
3094         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3095
3096         synchronized (mPackages) {
3097             final PackageSetting ps = mSettings.mPackages.get(packageName);
3098             if (ps == null) {
3099                 throw new SecurityException("Package " + packageName + " was not found!");
3100             }
3101
3102             if (!ps.getInstalled(userId)) {
3103                 throw new SecurityException(
3104                         "Package " + packageName + " was not installed for user " + userId + "!");
3105             }
3106
3107             if (mSafeMode && !ps.isSystem()) {
3108                 throw new SecurityException("Package " + packageName + " not a system app!");
3109             }
3110
3111             if (mFrozenPackages.contains(packageName)) {
3112                 throw new SecurityException("Package " + packageName + " is currently frozen!");
3113             }
3114
3115             if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3116                     || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3117                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3118             }
3119         }
3120     }
3121
3122     @Override
3123     public boolean isPackageAvailable(String packageName, int userId) {
3124         if (!sUserManager.exists(userId)) return false;
3125         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3126                 false /* requireFullPermission */, false /* checkShell */, "is package available");
3127         synchronized (mPackages) {
3128             PackageParser.Package p = mPackages.get(packageName);
3129             if (p != null) {
3130                 final PackageSetting ps = (PackageSetting) p.mExtras;
3131                 if (ps != null) {
3132                     final PackageUserState state = ps.readUserState(userId);
3133                     if (state != null) {
3134                         return PackageParser.isAvailable(state);
3135                     }
3136                 }
3137             }
3138         }
3139         return false;
3140     }
3141
3142     @Override
3143     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3144         if (!sUserManager.exists(userId)) return null;
3145         flags = updateFlagsForPackage(flags, userId, packageName);
3146         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147                 false /* requireFullPermission */, false /* checkShell */, "get package info");
3148
3149         // reader
3150         synchronized (mPackages) {
3151             // Normalize package name to hanlde renamed packages
3152             packageName = normalizePackageNameLPr(packageName);
3153
3154             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3155             PackageParser.Package p = null;
3156             if (matchFactoryOnly) {
3157                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3158                 if (ps != null) {
3159                     return generatePackageInfo(ps, flags, userId);
3160                 }
3161             }
3162             if (p == null) {
3163                 p = mPackages.get(packageName);
3164                 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3165                     return null;
3166                 }
3167             }
3168             if (DEBUG_PACKAGE_INFO)
3169                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3170             if (p != null) {
3171                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3172             }
3173             if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3174                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3175                 return generatePackageInfo(ps, flags, userId);
3176             }
3177         }
3178         return null;
3179     }
3180
3181     @Override
3182     public String[] currentToCanonicalPackageNames(String[] names) {
3183         String[] out = new String[names.length];
3184         // reader
3185         synchronized (mPackages) {
3186             for (int i=names.length-1; i>=0; i--) {
3187                 PackageSetting ps = mSettings.mPackages.get(names[i]);
3188                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3189             }
3190         }
3191         return out;
3192     }
3193
3194     @Override
3195     public String[] canonicalToCurrentPackageNames(String[] names) {
3196         String[] out = new String[names.length];
3197         // reader
3198         synchronized (mPackages) {
3199             for (int i=names.length-1; i>=0; i--) {
3200                 String cur = mSettings.mRenamedPackages.get(names[i]);
3201                 out[i] = cur != null ? cur : names[i];
3202             }
3203         }
3204         return out;
3205     }
3206
3207     @Override
3208     public int getPackageUid(String packageName, int flags, int userId) {
3209         if (!sUserManager.exists(userId)) return -1;
3210         flags = updateFlagsForPackage(flags, userId, packageName);
3211         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3212                 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3213
3214         // reader
3215         synchronized (mPackages) {
3216             final PackageParser.Package p = mPackages.get(packageName);
3217             if (p != null && p.isMatch(flags)) {
3218                 return UserHandle.getUid(userId, p.applicationInfo.uid);
3219             }
3220             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3221                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3222                 if (ps != null && ps.isMatch(flags)) {
3223                     return UserHandle.getUid(userId, ps.appId);
3224                 }
3225             }
3226         }
3227
3228         return -1;
3229     }
3230
3231     @Override
3232     public int[] getPackageGids(String packageName, int flags, int userId) {
3233         if (!sUserManager.exists(userId)) return null;
3234         flags = updateFlagsForPackage(flags, userId, packageName);
3235         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3236                 false /* requireFullPermission */, false /* checkShell */,
3237                 "getPackageGids");
3238
3239         // reader
3240         synchronized (mPackages) {
3241             final PackageParser.Package p = mPackages.get(packageName);
3242             if (p != null && p.isMatch(flags)) {
3243                 PackageSetting ps = (PackageSetting) p.mExtras;
3244                 return ps.getPermissionsState().computeGids(userId);
3245             }
3246             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3247                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3248                 if (ps != null && ps.isMatch(flags)) {
3249                     return ps.getPermissionsState().computeGids(userId);
3250                 }
3251             }
3252         }
3253
3254         return null;
3255     }
3256
3257     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3258         if (bp.perm != null) {
3259             return PackageParser.generatePermissionInfo(bp.perm, flags);
3260         }
3261         PermissionInfo pi = new PermissionInfo();
3262         pi.name = bp.name;
3263         pi.packageName = bp.sourcePackage;
3264         pi.nonLocalizedLabel = bp.name;
3265         pi.protectionLevel = bp.protectionLevel;
3266         return pi;
3267     }
3268
3269     @Override
3270     public PermissionInfo getPermissionInfo(String name, int flags) {
3271         // reader
3272         synchronized (mPackages) {
3273             final BasePermission p = mSettings.mPermissions.get(name);
3274             if (p != null) {
3275                 return generatePermissionInfo(p, flags);
3276             }
3277             return null;
3278         }
3279     }
3280
3281     @Override
3282     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3283             int flags) {
3284         // reader
3285         synchronized (mPackages) {
3286             if (group != null && !mPermissionGroups.containsKey(group)) {
3287                 // This is thrown as NameNotFoundException
3288                 return null;
3289             }
3290
3291             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3292             for (BasePermission p : mSettings.mPermissions.values()) {
3293                 if (group == null) {
3294                     if (p.perm == null || p.perm.info.group == null) {
3295                         out.add(generatePermissionInfo(p, flags));
3296                     }
3297                 } else {
3298                     if (p.perm != null && group.equals(p.perm.info.group)) {
3299                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3300                     }
3301                 }
3302             }
3303             return new ParceledListSlice<>(out);
3304         }
3305     }
3306
3307     @Override
3308     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3309         // reader
3310         synchronized (mPackages) {
3311             return PackageParser.generatePermissionGroupInfo(
3312                     mPermissionGroups.get(name), flags);
3313         }
3314     }
3315
3316     @Override
3317     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3318         // reader
3319         synchronized (mPackages) {
3320             final int N = mPermissionGroups.size();
3321             ArrayList<PermissionGroupInfo> out
3322                     = new ArrayList<PermissionGroupInfo>(N);
3323             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3324                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3325             }
3326             return new ParceledListSlice<>(out);
3327         }
3328     }
3329
3330     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3331             int userId) {
3332         if (!sUserManager.exists(userId)) return null;
3333         PackageSetting ps = mSettings.mPackages.get(packageName);
3334         if (ps != null) {
3335             if (ps.pkg == null) {
3336                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3337                 if (pInfo != null) {
3338                     return pInfo.applicationInfo;
3339                 }
3340                 return null;
3341             }
3342             return PackageParser.generateApplicationInfo(ps.pkg, flags,
3343                     ps.readUserState(userId), userId);
3344         }
3345         return null;
3346     }
3347
3348     @Override
3349     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3350         if (!sUserManager.exists(userId)) return null;
3351         flags = updateFlagsForApplication(flags, userId, packageName);
3352         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3353                 false /* requireFullPermission */, false /* checkShell */, "get application info");
3354
3355         // writer
3356         synchronized (mPackages) {
3357             // Normalize package name to hanlde renamed packages
3358             packageName = normalizePackageNameLPr(packageName);
3359
3360             PackageParser.Package p = mPackages.get(packageName);
3361             if (DEBUG_PACKAGE_INFO) Log.v(
3362                     TAG, "getApplicationInfo " + packageName
3363                     + ": " + p);
3364             if (p != null) {
3365                 PackageSetting ps = mSettings.mPackages.get(packageName);
3366                 if (ps == null) return null;
3367                 // Note: isEnabledLP() does not apply here - always return info
3368                 return PackageParser.generateApplicationInfo(
3369                         p, flags, ps.readUserState(userId), userId);
3370             }
3371             if ("android".equals(packageName)||"system".equals(packageName)) {
3372                 return mAndroidApplication;
3373             }
3374             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3375                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3376             }
3377         }
3378         return null;
3379     }
3380
3381     private String normalizePackageNameLPr(String packageName) {
3382         String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3383         return normalizedPackageName != null ? normalizedPackageName : packageName;
3384     }
3385
3386     @Override
3387     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3388             final IPackageDataObserver observer) {
3389         mContext.enforceCallingOrSelfPermission(
3390                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3391         // Queue up an async operation since clearing cache may take a little while.
3392         mHandler.post(new Runnable() {
3393             public void run() {
3394                 mHandler.removeCallbacks(this);
3395                 boolean success = true;
3396                 synchronized (mInstallLock) {
3397                     try {
3398                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3399                     } catch (InstallerException e) {
3400                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3401                         success = false;
3402                     }
3403                 }
3404                 if (observer != null) {
3405                     try {
3406                         observer.onRemoveCompleted(null, success);
3407                     } catch (RemoteException e) {
3408                         Slog.w(TAG, "RemoveException when invoking call back");
3409                     }
3410                 }
3411             }
3412         });
3413     }
3414
3415     @Override
3416     public void freeStorage(final String volumeUuid, final long freeStorageSize,
3417             final IntentSender pi) {
3418         mContext.enforceCallingOrSelfPermission(
3419                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3420         // Queue up an async operation since clearing cache may take a little while.
3421         mHandler.post(new Runnable() {
3422             public void run() {
3423                 mHandler.removeCallbacks(this);
3424                 boolean success = true;
3425                 synchronized (mInstallLock) {
3426                     try {
3427                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3428                     } catch (InstallerException e) {
3429                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3430                         success = false;
3431                     }
3432                 }
3433                 if(pi != null) {
3434                     try {
3435                         // Callback via pending intent
3436                         int code = success ? 1 : 0;
3437                         pi.sendIntent(null, code, null,
3438                                 null, null);
3439                     } catch (SendIntentException e1) {
3440                         Slog.i(TAG, "Failed to send pending intent");
3441                     }
3442                 }
3443             }
3444         });
3445     }
3446
3447     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3448         synchronized (mInstallLock) {
3449             try {
3450                 mInstaller.freeCache(volumeUuid, freeStorageSize);
3451             } catch (InstallerException e) {
3452                 throw new IOException("Failed to free enough space", e);
3453             }
3454         }
3455     }
3456
3457     /**
3458      * Update given flags based on encryption status of current user.
3459      */
3460     private int updateFlags(int flags, int userId) {
3461         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3462                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3463             // Caller expressed an explicit opinion about what encryption
3464             // aware/unaware components they want to see, so fall through and
3465             // give them what they want
3466         } else {
3467             // Caller expressed no opinion, so match based on user state
3468             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3469                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3470             } else {
3471                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3472             }
3473         }
3474         return flags;
3475     }
3476
3477     private UserManagerInternal getUserManagerInternal() {
3478         if (mUserManagerInternal == null) {
3479             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3480         }
3481         return mUserManagerInternal;
3482     }
3483
3484     /**
3485      * Update given flags when being used to request {@link PackageInfo}.
3486      */
3487     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3488         boolean triaged = true;
3489         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3490                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3491             // Caller is asking for component details, so they'd better be
3492             // asking for specific encryption matching behavior, or be triaged
3493             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3494                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
3495                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3496                 triaged = false;
3497             }
3498         }
3499         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3500                 | PackageManager.MATCH_SYSTEM_ONLY
3501                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3502             triaged = false;
3503         }
3504         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3505             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3506                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3507         }
3508         return updateFlags(flags, userId);
3509     }
3510
3511     /**
3512      * Update given flags when being used to request {@link ApplicationInfo}.
3513      */
3514     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3515         return updateFlagsForPackage(flags, userId, cookie);
3516     }
3517
3518     /**
3519      * Update given flags when being used to request {@link ComponentInfo}.
3520      */
3521     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3522         if (cookie instanceof Intent) {
3523             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3524                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3525             }
3526         }
3527
3528         boolean triaged = true;
3529         // Caller is asking for component details, so they'd better be
3530         // asking for specific encryption matching behavior, or be triaged
3531         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3532                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3533                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3534             triaged = false;
3535         }
3536         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3537             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3538                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3539         }
3540
3541         return updateFlags(flags, userId);
3542     }
3543
3544     /**
3545      * Update given flags when being used to request {@link ResolveInfo}.
3546      */
3547     int updateFlagsForResolve(int flags, int userId, Object cookie) {
3548         // Safe mode means we shouldn't match any third-party components
3549         if (mSafeMode) {
3550             flags |= PackageManager.MATCH_SYSTEM_ONLY;
3551         }
3552
3553         return updateFlagsForComponent(flags, userId, cookie);
3554     }
3555
3556     @Override
3557     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3558         if (!sUserManager.exists(userId)) return null;
3559         flags = updateFlagsForComponent(flags, userId, component);
3560         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3561                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3562         synchronized (mPackages) {
3563             PackageParser.Activity a = mActivities.mActivities.get(component);
3564
3565             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3566             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3567                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3568                 if (ps == null) return null;
3569                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3570                         userId);
3571             }
3572             if (mResolveComponentName.equals(component)) {
3573                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3574                         new PackageUserState(), userId);
3575             }
3576         }
3577         return null;
3578     }
3579
3580     @Override
3581     public boolean activitySupportsIntent(ComponentName component, Intent intent,
3582             String resolvedType) {
3583         synchronized (mPackages) {
3584             if (component.equals(mResolveComponentName)) {
3585                 // The resolver supports EVERYTHING!
3586                 return true;
3587             }
3588             PackageParser.Activity a = mActivities.mActivities.get(component);
3589             if (a == null) {
3590                 return false;
3591             }
3592             for (int i=0; i<a.intents.size(); i++) {
3593                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3594                         intent.getData(), intent.getCategories(), TAG) >= 0) {
3595                     return true;
3596                 }
3597             }
3598             return false;
3599         }
3600     }
3601
3602     @Override
3603     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3604         if (!sUserManager.exists(userId)) return null;
3605         flags = updateFlagsForComponent(flags, userId, component);
3606         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3607                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3608         synchronized (mPackages) {
3609             PackageParser.Activity a = mReceivers.mActivities.get(component);
3610             if (DEBUG_PACKAGE_INFO) Log.v(
3611                 TAG, "getReceiverInfo " + component + ": " + a);
3612             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3613                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3614                 if (ps == null) return null;
3615                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3616                         userId);
3617             }
3618         }
3619         return null;
3620     }
3621
3622     @Override
3623     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3624         if (!sUserManager.exists(userId)) return null;
3625         flags = updateFlagsForComponent(flags, userId, component);
3626         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3627                 false /* requireFullPermission */, false /* checkShell */, "get service info");
3628         synchronized (mPackages) {
3629             PackageParser.Service s = mServices.mServices.get(component);
3630             if (DEBUG_PACKAGE_INFO) Log.v(
3631                 TAG, "getServiceInfo " + component + ": " + s);
3632             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3633                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3634                 if (ps == null) return null;
3635                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3636                         userId);
3637             }
3638         }
3639         return null;
3640     }
3641
3642     @Override
3643     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3644         if (!sUserManager.exists(userId)) return null;
3645         flags = updateFlagsForComponent(flags, userId, component);
3646         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3647                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3648         synchronized (mPackages) {
3649             PackageParser.Provider p = mProviders.mProviders.get(component);
3650             if (DEBUG_PACKAGE_INFO) Log.v(
3651                 TAG, "getProviderInfo " + component + ": " + p);
3652             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3653                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3654                 if (ps == null) return null;
3655                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3656                         userId);
3657             }
3658         }
3659         return null;
3660     }
3661
3662     @Override
3663     public String[] getSystemSharedLibraryNames() {
3664         Set<String> libSet;
3665         synchronized (mPackages) {
3666             libSet = mSharedLibraries.keySet();
3667             int size = libSet.size();
3668             if (size > 0) {
3669                 String[] libs = new String[size];
3670                 libSet.toArray(libs);
3671                 return libs;
3672             }
3673         }
3674         return null;
3675     }
3676
3677     @Override
3678     public @NonNull String getServicesSystemSharedLibraryPackageName() {
3679         synchronized (mPackages) {
3680             return mServicesSystemSharedLibraryPackageName;
3681         }
3682     }
3683
3684     @Override
3685     public @NonNull String getSharedSystemSharedLibraryPackageName() {
3686         synchronized (mPackages) {
3687             return mSharedSystemSharedLibraryPackageName;
3688         }
3689     }
3690
3691     @Override
3692     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3693         synchronized (mPackages) {
3694             final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3695
3696             final FeatureInfo fi = new FeatureInfo();
3697             fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3698                     FeatureInfo.GL_ES_VERSION_UNDEFINED);
3699             res.add(fi);
3700
3701             return new ParceledListSlice<>(res);
3702         }
3703     }
3704
3705     @Override
3706     public boolean hasSystemFeature(String name, int version) {
3707         synchronized (mPackages) {
3708             final FeatureInfo feat = mAvailableFeatures.get(name);
3709             if (feat == null) {
3710                 return false;
3711             } else {
3712                 return feat.version >= version;
3713             }
3714         }
3715     }
3716
3717     @Override
3718     public int checkPermission(String permName, String pkgName, int userId) {
3719         if (!sUserManager.exists(userId)) {
3720             return PackageManager.PERMISSION_DENIED;
3721         }
3722
3723         synchronized (mPackages) {
3724             final PackageParser.Package p = mPackages.get(pkgName);
3725             if (p != null && p.mExtras != null) {
3726                 final PackageSetting ps = (PackageSetting) p.mExtras;
3727                 final PermissionsState permissionsState = ps.getPermissionsState();
3728                 if (permissionsState.hasPermission(permName, userId)) {
3729                     return PackageManager.PERMISSION_GRANTED;
3730                 }
3731                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3732                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3733                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3734                     return PackageManager.PERMISSION_GRANTED;
3735                 }
3736             }
3737         }
3738
3739         return PackageManager.PERMISSION_DENIED;
3740     }
3741
3742     @Override
3743     public int checkUidPermission(String permName, int uid) {
3744         final int userId = UserHandle.getUserId(uid);
3745
3746         if (!sUserManager.exists(userId)) {
3747             return PackageManager.PERMISSION_DENIED;
3748         }
3749
3750         synchronized (mPackages) {
3751             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3752             if (obj != null) {
3753                 final SettingBase ps = (SettingBase) obj;
3754                 final PermissionsState permissionsState = ps.getPermissionsState();
3755                 if (permissionsState.hasPermission(permName, userId)) {
3756                     return PackageManager.PERMISSION_GRANTED;
3757                 }
3758                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3759                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3760                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3761                     return PackageManager.PERMISSION_GRANTED;
3762                 }
3763             } else {
3764                 ArraySet<String> perms = mSystemPermissions.get(uid);
3765                 if (perms != null) {
3766                     if (perms.contains(permName)) {
3767                         return PackageManager.PERMISSION_GRANTED;
3768                     }
3769                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3770                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3771                         return PackageManager.PERMISSION_GRANTED;
3772                     }
3773                 }
3774             }
3775         }
3776
3777         return PackageManager.PERMISSION_DENIED;
3778     }
3779
3780     @Override
3781     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3782         if (UserHandle.getCallingUserId() != userId) {
3783             mContext.enforceCallingPermission(
3784                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3785                     "isPermissionRevokedByPolicy for user " + userId);
3786         }
3787
3788         if (checkPermission(permission, packageName, userId)
3789                 == PackageManager.PERMISSION_GRANTED) {
3790             return false;
3791         }
3792
3793         final long identity = Binder.clearCallingIdentity();
3794         try {
3795             final int flags = getPermissionFlags(permission, packageName, userId);
3796             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3797         } finally {
3798             Binder.restoreCallingIdentity(identity);
3799         }
3800     }
3801
3802     @Override
3803     public String getPermissionControllerPackageName() {
3804         synchronized (mPackages) {
3805             return mRequiredInstallerPackage;
3806         }
3807     }
3808
3809     /**
3810      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3811      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3812      * @param checkShell whether to prevent shell from access if there's a debugging restriction
3813      * @param message the message to log on security exception
3814      */
3815     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3816             boolean checkShell, String message) {
3817         enforceCrossUserPermission(
3818               callingUid,
3819               userId,
3820               requireFullPermission,
3821               checkShell,
3822               false,
3823               message);
3824     }
3825
3826     private void enforceCrossUserPermission(int callingUid, int userId,
3827             boolean requireFullPermission, boolean checkShell,
3828             boolean requirePermissionWhenSameUser, String message) {
3829         if (userId < 0) {
3830             throw new IllegalArgumentException("Invalid userId " + userId);
3831         }
3832         if (checkShell) {
3833             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3834         }
3835         if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
3836         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3837             if (requireFullPermission) {
3838                 mContext.enforceCallingOrSelfPermission(
3839                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3840             } else {
3841                 try {
3842                     mContext.enforceCallingOrSelfPermission(
3843                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3844                 } catch (SecurityException se) {
3845                     mContext.enforceCallingOrSelfPermission(
3846                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3847                 }
3848             }
3849         }
3850     }
3851
3852     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3853         if (callingUid == Process.SHELL_UID) {
3854             if (userHandle >= 0
3855                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3856                 throw new SecurityException("Shell does not have permission to access user "
3857                         + userHandle);
3858             } else if (userHandle < 0) {
3859                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3860                         + Debug.getCallers(3));
3861             }
3862         }
3863     }
3864
3865     private BasePermission findPermissionTreeLP(String permName) {
3866         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3867             if (permName.startsWith(bp.name) &&
3868                     permName.length() > bp.name.length() &&
3869                     permName.charAt(bp.name.length()) == '.') {
3870                 return bp;
3871             }
3872         }
3873         return null;
3874     }
3875
3876     private BasePermission checkPermissionTreeLP(String permName) {
3877         if (permName != null) {
3878             BasePermission bp = findPermissionTreeLP(permName);
3879             if (bp != null) {
3880                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3881                     return bp;
3882                 }
3883                 throw new SecurityException("Calling uid "
3884                         + Binder.getCallingUid()
3885                         + " is not allowed to add to permission tree "
3886                         + bp.name + " owned by uid " + bp.uid);
3887             }
3888         }
3889         throw new SecurityException("No permission tree found for " + permName);
3890     }
3891
3892     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3893         if (s1 == null) {
3894             return s2 == null;
3895         }
3896         if (s2 == null) {
3897             return false;
3898         }
3899         if (s1.getClass() != s2.getClass()) {
3900             return false;
3901         }
3902         return s1.equals(s2);
3903     }
3904
3905     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3906         if (pi1.icon != pi2.icon) return false;
3907         if (pi1.logo != pi2.logo) return false;
3908         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3909         if (!compareStrings(pi1.name, pi2.name)) return false;
3910         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3911         // We'll take care of setting this one.
3912         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3913         // These are not currently stored in settings.
3914         //if (!compareStrings(pi1.group, pi2.group)) return false;
3915         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3916         //if (pi1.labelRes != pi2.labelRes) return false;
3917         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3918         return true;
3919     }
3920
3921     int permissionInfoFootprint(PermissionInfo info) {
3922         int size = info.name.length();
3923         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3924         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3925         return size;
3926     }
3927
3928     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3929         int size = 0;
3930         for (BasePermission perm : mSettings.mPermissions.values()) {
3931             if (perm.uid == tree.uid) {
3932                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3933             }
3934         }
3935         return size;
3936     }
3937
3938     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3939         // We calculate the max size of permissions defined by this uid and throw
3940         // if that plus the size of 'info' would exceed our stated maximum.
3941         if (tree.uid != Process.SYSTEM_UID) {
3942             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3943             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3944                 throw new SecurityException("Permission tree size cap exceeded");
3945             }
3946         }
3947     }
3948
3949     boolean addPermissionLocked(PermissionInfo info, boolean async) {
3950         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3951             throw new SecurityException("Label must be specified in permission");
3952         }
3953         BasePermission tree = checkPermissionTreeLP(info.name);
3954         BasePermission bp = mSettings.mPermissions.get(info.name);
3955         boolean added = bp == null;
3956         boolean changed = true;
3957         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3958         if (added) {
3959             enforcePermissionCapLocked(info, tree);
3960             bp = new BasePermission(info.name, tree.sourcePackage,
3961                     BasePermission.TYPE_DYNAMIC);
3962         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3963             throw new SecurityException(
3964                     "Not allowed to modify non-dynamic permission "
3965                     + info.name);
3966         } else {
3967             if ((bp.perm == null) || (tree.perm == null)) {
3968                 Slog.w(TAG, "Base or tree permission is null: " + bp.perm + ", " + tree.perm);
3969                 return false;
3970             }
3971             if (bp.protectionLevel == fixedLevel
3972                     && bp.perm.owner.equals(tree.perm.owner)
3973                     && bp.uid == tree.uid
3974                     && comparePermissionInfos(bp.perm.info, info)) {
3975                 changed = false;
3976             }
3977         }
3978         bp.protectionLevel = fixedLevel;
3979         info = new PermissionInfo(info);
3980         info.protectionLevel = fixedLevel;
3981         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3982         bp.perm.info.packageName = tree.perm.info.packageName;
3983         bp.uid = tree.uid;
3984         if (added) {
3985             mSettings.mPermissions.put(info.name, bp);
3986         }
3987         if (changed) {
3988             if (!async) {
3989                 mSettings.writeLPr();
3990             } else {
3991                 scheduleWriteSettingsLocked();
3992             }
3993         }
3994         return added;
3995     }
3996
3997     @Override
3998     public boolean addPermission(PermissionInfo info) {
3999         synchronized (mPackages) {
4000             return addPermissionLocked(info, false);
4001         }
4002     }
4003
4004     @Override
4005     public boolean addPermissionAsync(PermissionInfo info) {
4006         synchronized (mPackages) {
4007             return addPermissionLocked(info, true);
4008         }
4009     }
4010
4011     @Override
4012     public void removePermission(String name) {
4013         synchronized (mPackages) {
4014             checkPermissionTreeLP(name);
4015             BasePermission bp = mSettings.mPermissions.get(name);
4016             if (bp != null) {
4017                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4018                     throw new SecurityException(
4019                             "Not allowed to modify non-dynamic permission "
4020                             + name);
4021                 }
4022                 mSettings.mPermissions.remove(name);
4023                 mSettings.writeLPr();
4024             }
4025         }
4026     }
4027
4028     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4029             BasePermission bp) {
4030         int index = pkg.requestedPermissions.indexOf(bp.name);
4031         if (index == -1) {
4032             throw new SecurityException("Package " + pkg.packageName
4033                     + " has not requested permission " + bp.name);
4034         }
4035         if (!bp.isRuntime() && !bp.isDevelopment()) {
4036             throw new SecurityException("Permission " + bp.name
4037                     + " is not a changeable permission type");
4038         }
4039     }
4040
4041     @Override
4042     public void grantRuntimePermission(String packageName, String name, final int userId) {
4043         if (!sUserManager.exists(userId)) {
4044             Log.e(TAG, "No such user:" + userId);
4045             return;
4046         }
4047
4048         mContext.enforceCallingOrSelfPermission(
4049                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4050                 "grantRuntimePermission");
4051
4052         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4053                 true /* requireFullPermission */, true /* checkShell */,
4054                 "grantRuntimePermission");
4055
4056         final int uid;
4057         final SettingBase sb;
4058
4059         synchronized (mPackages) {
4060             final PackageParser.Package pkg = mPackages.get(packageName);
4061             if (pkg == null) {
4062                 throw new IllegalArgumentException("Unknown package: " + packageName);
4063             }
4064
4065             final BasePermission bp = mSettings.mPermissions.get(name);
4066             if (bp == null) {
4067                 throw new IllegalArgumentException("Unknown permission: " + name);
4068             }
4069
4070             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4071
4072             // If a permission review is required for legacy apps we represent
4073             // their permissions as always granted runtime ones since we need
4074             // to keep the review required permission flag per user while an
4075             // install permission's state is shared across all users.
4076             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4077                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4078                     && bp.isRuntime()) {
4079                 return;
4080             }
4081
4082             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4083             sb = (SettingBase) pkg.mExtras;
4084             if (sb == null) {
4085                 throw new IllegalArgumentException("Unknown package: " + packageName);
4086             }
4087
4088             final PermissionsState permissionsState = sb.getPermissionsState();
4089
4090             final int flags = permissionsState.getPermissionFlags(name, userId);
4091             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4092                 throw new SecurityException("Cannot grant system fixed permission "
4093                         + name + " for package " + packageName);
4094             }
4095
4096             if (bp.isDevelopment()) {
4097                 // Development permissions must be handled specially, since they are not
4098                 // normal runtime permissions.  For now they apply to all users.
4099                 if (permissionsState.grantInstallPermission(bp) !=
4100                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4101                     scheduleWriteSettingsLocked();
4102                 }
4103                 return;
4104             }
4105
4106             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4107                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4108                 return;
4109             }
4110
4111             final int result = permissionsState.grantRuntimePermission(bp, userId);
4112             switch (result) {
4113                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4114                     return;
4115                 }
4116
4117                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4118                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4119                     mHandler.post(new Runnable() {
4120                         @Override
4121                         public void run() {
4122                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4123                         }
4124                     });
4125                 }
4126                 break;
4127             }
4128
4129             mOnPermissionChangeListeners.onPermissionsChanged(uid);
4130
4131             // Not critical if that is lost - app has to request again.
4132             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4133         }
4134
4135         // Only need to do this if user is initialized. Otherwise it's a new user
4136         // and there are no processes running as the user yet and there's no need
4137         // to make an expensive call to remount processes for the changed permissions.
4138         if (READ_EXTERNAL_STORAGE.equals(name)
4139                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4140             final long token = Binder.clearCallingIdentity();
4141             try {
4142                 if (sUserManager.isInitialized(userId)) {
4143                     MountServiceInternal mountServiceInternal = LocalServices.getService(
4144                             MountServiceInternal.class);
4145                     mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4146                 }
4147             } finally {
4148                 Binder.restoreCallingIdentity(token);
4149             }
4150         }
4151     }
4152
4153     @Override
4154     public void revokeRuntimePermission(String packageName, String name, int userId) {
4155         if (!sUserManager.exists(userId)) {
4156             Log.e(TAG, "No such user:" + userId);
4157             return;
4158         }
4159
4160         mContext.enforceCallingOrSelfPermission(
4161                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4162                 "revokeRuntimePermission");
4163
4164         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165                 true /* requireFullPermission */, true /* checkShell */,
4166                 "revokeRuntimePermission");
4167
4168         final int appId;
4169
4170         synchronized (mPackages) {
4171             final PackageParser.Package pkg = mPackages.get(packageName);
4172             if (pkg == null) {
4173                 throw new IllegalArgumentException("Unknown package: " + packageName);
4174             }
4175
4176             final BasePermission bp = mSettings.mPermissions.get(name);
4177             if (bp == null) {
4178                 throw new IllegalArgumentException("Unknown permission: " + name);
4179             }
4180
4181             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4182
4183             // If a permission review is required for legacy apps we represent
4184             // their permissions as always granted runtime ones since we need
4185             // to keep the review required permission flag per user while an
4186             // install permission's state is shared across all users.
4187             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4188                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4189                     && bp.isRuntime()) {
4190                 return;
4191             }
4192
4193             SettingBase sb = (SettingBase) pkg.mExtras;
4194             if (sb == null) {
4195                 throw new IllegalArgumentException("Unknown package: " + packageName);
4196             }
4197
4198             final PermissionsState permissionsState = sb.getPermissionsState();
4199
4200             final int flags = permissionsState.getPermissionFlags(name, userId);
4201             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4202                 throw new SecurityException("Cannot revoke system fixed permission "
4203                         + name + " for package " + packageName);
4204             }
4205
4206             if (bp.isDevelopment()) {
4207                 // Development permissions must be handled specially, since they are not
4208                 // normal runtime permissions.  For now they apply to all users.
4209                 if (permissionsState.revokeInstallPermission(bp) !=
4210                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211                     scheduleWriteSettingsLocked();
4212                 }
4213                 return;
4214             }
4215
4216             if (permissionsState.revokeRuntimePermission(bp, userId) ==
4217                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
4218                 return;
4219             }
4220
4221             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4222
4223             // Critical, after this call app should never have the permission.
4224             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4225
4226             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4227         }
4228
4229         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4230     }
4231
4232     /**
4233      * We might auto-grant permissions if any permission of the group is already granted. Hence if
4234      * the group of a granted permission changes we need to revoke it to avoid having permissions of
4235      * the new group auto-granted.
4236      *
4237      * @param newPackage The new package that was installed
4238      * @param oldPackage The old package that was updated
4239      * @param allPackageNames All package names
4240      */
4241     private void revokeRuntimePermissionsIfGroupChanged(
4242             PackageParser.Package newPackage,
4243             PackageParser.Package oldPackage,
4244             ArrayList<String> allPackageNames) {
4245         final int numOldPackagePermissions = oldPackage.permissions.size();
4246         final ArrayMap<String, String> oldPermissionNameToGroupName
4247                 = new ArrayMap<>(numOldPackagePermissions);
4248
4249         for (int i = 0; i < numOldPackagePermissions; i++) {
4250             final PackageParser.Permission permission = oldPackage.permissions.get(i);
4251
4252             if (permission.group != null) {
4253                 oldPermissionNameToGroupName.put(permission.info.name,
4254                         permission.group.info.name);
4255             }
4256         }
4257
4258         final int numNewPackagePermissions = newPackage.permissions.size();
4259         for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
4260                 newPermissionNum++) {
4261             final PackageParser.Permission newPermission =
4262                     newPackage.permissions.get(newPermissionNum);
4263             final int newProtection = newPermission.info.protectionLevel;
4264
4265             if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
4266                 final String permissionName = newPermission.info.name;
4267                 final String newPermissionGroupName =
4268                         newPermission.group == null ? null : newPermission.group.info.name;
4269                 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
4270                         permissionName);
4271
4272                 if (newPermissionGroupName != null
4273                         && !newPermissionGroupName.equals(oldPermissionGroupName)) {
4274                     final List<UserInfo> users = mContext.getSystemService(UserManager.class)
4275                             .getUsers();
4276
4277                     final int numUsers = users.size();
4278                     for (int userNum = 0; userNum < numUsers; userNum++) {
4279                         final int userId = users.get(userNum).id;
4280                         final int numPackages = allPackageNames.size();
4281                         for (int packageNum = 0; packageNum < numPackages; packageNum++) {
4282                             final String packageName = allPackageNames.get(packageNum);
4283
4284                             if (checkPermission(permissionName, packageName, userId)
4285                                     == PackageManager.PERMISSION_GRANTED) {
4286                                 EventLog.writeEvent(0x534e4554, "72710897",
4287                                         newPackage.applicationInfo.uid,
4288                                         "Revoking permission", permissionName, "from package",
4289                                         packageName, "as the group changed from",
4290                                         oldPermissionGroupName, "to", newPermissionGroupName);
4291
4292                                 try {
4293                                     revokeRuntimePermission(packageName, permissionName, userId);
4294                                 } catch (IllegalArgumentException e) {
4295                                     Slog.e(TAG, "Could not revoke " + permissionName + " from "
4296                                             + packageName, e);
4297                                 }
4298                             }
4299                         }
4300                     }
4301                 }
4302             }
4303         }
4304     }
4305
4306
4307     @Override
4308     public void resetRuntimePermissions() {
4309         mContext.enforceCallingOrSelfPermission(
4310                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4311                 "revokeRuntimePermission");
4312
4313         int callingUid = Binder.getCallingUid();
4314         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4315             mContext.enforceCallingOrSelfPermission(
4316                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4317                     "resetRuntimePermissions");
4318         }
4319
4320         synchronized (mPackages) {
4321             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4322             for (int userId : UserManagerService.getInstance().getUserIds()) {
4323                 final int packageCount = mPackages.size();
4324                 for (int i = 0; i < packageCount; i++) {
4325                     PackageParser.Package pkg = mPackages.valueAt(i);
4326                     if (!(pkg.mExtras instanceof PackageSetting)) {
4327                         continue;
4328                     }
4329                     PackageSetting ps = (PackageSetting) pkg.mExtras;
4330                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4331                 }
4332             }
4333         }
4334     }
4335
4336     @Override
4337     public int getPermissionFlags(String name, String packageName, int userId) {
4338         if (!sUserManager.exists(userId)) {
4339             return 0;
4340         }
4341
4342         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4343
4344         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4345                 true /* requireFullPermission */, false /* checkShell */,
4346                 "getPermissionFlags");
4347
4348         synchronized (mPackages) {
4349             final PackageParser.Package pkg = mPackages.get(packageName);
4350             if (pkg == null) {
4351                 return 0;
4352             }
4353
4354             final BasePermission bp = mSettings.mPermissions.get(name);
4355             if (bp == null) {
4356                 return 0;
4357             }
4358
4359             SettingBase sb = (SettingBase) pkg.mExtras;
4360             if (sb == null) {
4361                 return 0;
4362             }
4363
4364             PermissionsState permissionsState = sb.getPermissionsState();
4365             return permissionsState.getPermissionFlags(name, userId);
4366         }
4367     }
4368
4369     @Override
4370     public void updatePermissionFlags(String name, String packageName, int flagMask,
4371             int flagValues, int userId) {
4372         if (!sUserManager.exists(userId)) {
4373             return;
4374         }
4375
4376         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4377
4378         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4379                 true /* requireFullPermission */, true /* checkShell */,
4380                 "updatePermissionFlags");
4381
4382         // Only the system can change these flags and nothing else.
4383         if (getCallingUid() != Process.SYSTEM_UID) {
4384             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4385             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4386             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4387             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4388             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4389         }
4390
4391         synchronized (mPackages) {
4392             final PackageParser.Package pkg = mPackages.get(packageName);
4393             if (pkg == null) {
4394                 throw new IllegalArgumentException("Unknown package: " + packageName);
4395             }
4396
4397             final BasePermission bp = mSettings.mPermissions.get(name);
4398             if (bp == null) {
4399                 throw new IllegalArgumentException("Unknown permission: " + name);
4400             }
4401
4402             SettingBase sb = (SettingBase) pkg.mExtras;
4403             if (sb == null) {
4404                 throw new IllegalArgumentException("Unknown package: " + packageName);
4405             }
4406
4407             PermissionsState permissionsState = sb.getPermissionsState();
4408
4409             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4410
4411             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4412                 // Install and runtime permissions are stored in different places,
4413                 // so figure out what permission changed and persist the change.
4414                 if (permissionsState.getInstallPermissionState(name) != null) {
4415                     scheduleWriteSettingsLocked();
4416                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4417                         || hadState) {
4418                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4419                 }
4420             }
4421         }
4422     }
4423
4424     /**
4425      * Update the permission flags for all packages and runtime permissions of a user in order
4426      * to allow device or profile owner to remove POLICY_FIXED.
4427      */
4428     @Override
4429     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4430         if (!sUserManager.exists(userId)) {
4431             return;
4432         }
4433
4434         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4435
4436         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4437                 true /* requireFullPermission */, true /* checkShell */,
4438                 "updatePermissionFlagsForAllApps");
4439
4440         // Only the system can change system fixed flags.
4441         if (getCallingUid() != Process.SYSTEM_UID) {
4442             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4443             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4444         }
4445
4446         synchronized (mPackages) {
4447             boolean changed = false;
4448             final int packageCount = mPackages.size();
4449             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4450                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4451                 SettingBase sb = (SettingBase) pkg.mExtras;
4452                 if (sb == null) {
4453                     continue;
4454                 }
4455                 PermissionsState permissionsState = sb.getPermissionsState();
4456                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4457                         userId, flagMask, flagValues);
4458             }
4459             if (changed) {
4460                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4461             }
4462         }
4463     }
4464
4465     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4466         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4467                 != PackageManager.PERMISSION_GRANTED
4468             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4469                 != PackageManager.PERMISSION_GRANTED) {
4470             throw new SecurityException(message + " requires "
4471                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4472                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4473         }
4474     }
4475
4476     @Override
4477     public boolean shouldShowRequestPermissionRationale(String permissionName,
4478             String packageName, int userId) {
4479         if (UserHandle.getCallingUserId() != userId) {
4480             mContext.enforceCallingPermission(
4481                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4482                     "canShowRequestPermissionRationale for user " + userId);
4483         }
4484
4485         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4486         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4487             return false;
4488         }
4489
4490         if (checkPermission(permissionName, packageName, userId)
4491                 == PackageManager.PERMISSION_GRANTED) {
4492             return false;
4493         }
4494
4495         final int flags;
4496
4497         final long identity = Binder.clearCallingIdentity();
4498         try {
4499             flags = getPermissionFlags(permissionName,
4500                     packageName, userId);
4501         } finally {
4502             Binder.restoreCallingIdentity(identity);
4503         }
4504
4505         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4506                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4507                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4508
4509         if ((flags & fixedFlags) != 0) {
4510             return false;
4511         }
4512
4513         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4514     }
4515
4516     @Override
4517     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4518         mContext.enforceCallingOrSelfPermission(
4519                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4520                 "addOnPermissionsChangeListener");
4521
4522         synchronized (mPackages) {
4523             mOnPermissionChangeListeners.addListenerLocked(listener);
4524         }
4525     }
4526
4527     @Override
4528     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4529         synchronized (mPackages) {
4530             mOnPermissionChangeListeners.removeListenerLocked(listener);
4531         }
4532     }
4533
4534     @Override
4535     public boolean isProtectedBroadcast(String actionName) {
4536         synchronized (mPackages) {
4537             if (mProtectedBroadcasts.contains(actionName)) {
4538                 return true;
4539             } else if (actionName != null) {
4540                 // TODO: remove these terrible hacks
4541                 if (actionName.startsWith("android.net.netmon.lingerExpired")
4542                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4543                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4544                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4545                     return true;
4546                 }
4547             }
4548         }
4549         return false;
4550     }
4551
4552     @Override
4553     public int checkSignatures(String pkg1, String pkg2) {
4554         synchronized (mPackages) {
4555             final PackageParser.Package p1 = mPackages.get(pkg1);
4556             final PackageParser.Package p2 = mPackages.get(pkg2);
4557             if (p1 == null || p1.mExtras == null
4558                     || p2 == null || p2.mExtras == null) {
4559                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4560             }
4561             return compareSignatures(p1.mSignatures, p2.mSignatures);
4562         }
4563     }
4564
4565     @Override
4566     public int checkUidSignatures(int uid1, int uid2) {
4567         // Map to base uids.
4568         uid1 = UserHandle.getAppId(uid1);
4569         uid2 = UserHandle.getAppId(uid2);
4570         // reader
4571         synchronized (mPackages) {
4572             Signature[] s1;
4573             Signature[] s2;
4574             Object obj = mSettings.getUserIdLPr(uid1);
4575             if (obj != null) {
4576                 if (obj instanceof SharedUserSetting) {
4577                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4578                 } else if (obj instanceof PackageSetting) {
4579                     s1 = ((PackageSetting)obj).signatures.mSignatures;
4580                 } else {
4581                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4582                 }
4583             } else {
4584                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4585             }
4586             obj = mSettings.getUserIdLPr(uid2);
4587             if (obj != null) {
4588                 if (obj instanceof SharedUserSetting) {
4589                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4590                 } else if (obj instanceof PackageSetting) {
4591                     s2 = ((PackageSetting)obj).signatures.mSignatures;
4592                 } else {
4593                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4594                 }
4595             } else {
4596                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4597             }
4598             return compareSignatures(s1, s2);
4599         }
4600     }
4601
4602     /**
4603      * This method should typically only be used when granting or revoking
4604      * permissions, since the app may immediately restart after this call.
4605      * <p>
4606      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4607      * guard your work against the app being relaunched.
4608      */
4609     private void killUid(int appId, int userId, String reason) {
4610         final long identity = Binder.clearCallingIdentity();
4611         try {
4612             IActivityManager am = ActivityManagerNative.getDefault();
4613             if (am != null) {
4614                 try {
4615                     am.killUid(appId, userId, reason);
4616                 } catch (RemoteException e) {
4617                     /* ignore - same process */
4618                 }
4619             }
4620         } finally {
4621             Binder.restoreCallingIdentity(identity);
4622         }
4623     }
4624
4625     /**
4626      * Compares two sets of signatures. Returns:
4627      * <br />
4628      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4629      * <br />
4630      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4631      * <br />
4632      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4633      * <br />
4634      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4635      * <br />
4636      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4637      */
4638     static int compareSignatures(Signature[] s1, Signature[] s2) {
4639         if (s1 == null) {
4640             return s2 == null
4641                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
4642                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4643         }
4644
4645         if (s2 == null) {
4646             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4647         }
4648
4649         if (s1.length != s2.length) {
4650             return PackageManager.SIGNATURE_NO_MATCH;
4651         }
4652
4653         // Since both signature sets are of size 1, we can compare without HashSets.
4654         if (s1.length == 1) {
4655             return s1[0].equals(s2[0]) ?
4656                     PackageManager.SIGNATURE_MATCH :
4657                     PackageManager.SIGNATURE_NO_MATCH;
4658         }
4659
4660         ArraySet<Signature> set1 = new ArraySet<Signature>();
4661         for (Signature sig : s1) {
4662             set1.add(sig);
4663         }
4664         ArraySet<Signature> set2 = new ArraySet<Signature>();
4665         for (Signature sig : s2) {
4666             set2.add(sig);
4667         }
4668         // Make sure s2 contains all signatures in s1.
4669         if (set1.equals(set2)) {
4670             return PackageManager.SIGNATURE_MATCH;
4671         }
4672         return PackageManager.SIGNATURE_NO_MATCH;
4673     }
4674
4675     /**
4676      * If the database version for this type of package (internal storage or
4677      * external storage) is less than the version where package signatures
4678      * were updated, return true.
4679      */
4680     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4681         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4682         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4683     }
4684
4685     /**
4686      * Used for backward compatibility to make sure any packages with
4687      * certificate chains get upgraded to the new style. {@code existingSigs}
4688      * will be in the old format (since they were stored on disk from before the
4689      * system upgrade) and {@code scannedSigs} will be in the newer format.
4690      */
4691     private int compareSignaturesCompat(PackageSignatures existingSigs,
4692             PackageParser.Package scannedPkg) {
4693         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4694             return PackageManager.SIGNATURE_NO_MATCH;
4695         }
4696
4697         ArraySet<Signature> existingSet = new ArraySet<Signature>();
4698         for (Signature sig : existingSigs.mSignatures) {
4699             existingSet.add(sig);
4700         }
4701         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4702         for (Signature sig : scannedPkg.mSignatures) {
4703             try {
4704                 Signature[] chainSignatures = sig.getChainSignatures();
4705                 for (Signature chainSig : chainSignatures) {
4706                     scannedCompatSet.add(chainSig);
4707                 }
4708             } catch (CertificateEncodingException e) {
4709                 scannedCompatSet.add(sig);
4710             }
4711         }
4712         /*
4713          * Make sure the expanded scanned set contains all signatures in the
4714          * existing one.
4715          */
4716         if (scannedCompatSet.equals(existingSet)) {
4717             // Migrate the old signatures to the new scheme.
4718             existingSigs.assignSignatures(scannedPkg.mSignatures);
4719             // The new KeySets will be re-added later in the scanning process.
4720             synchronized (mPackages) {
4721                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4722             }
4723             return PackageManager.SIGNATURE_MATCH;
4724         }
4725         return PackageManager.SIGNATURE_NO_MATCH;
4726     }
4727
4728     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4729         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4730         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4731     }
4732
4733     private int compareSignaturesRecover(PackageSignatures existingSigs,
4734             PackageParser.Package scannedPkg) {
4735         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4736             return PackageManager.SIGNATURE_NO_MATCH;
4737         }
4738
4739         String msg = null;
4740         try {
4741             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4742                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4743                         + scannedPkg.packageName);
4744                 return PackageManager.SIGNATURE_MATCH;
4745             }
4746         } catch (CertificateException e) {
4747             msg = e.getMessage();
4748         }
4749
4750         logCriticalInfo(Log.INFO,
4751                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4752         return PackageManager.SIGNATURE_NO_MATCH;
4753     }
4754
4755     @Override
4756     public List<String> getAllPackages() {
4757         synchronized (mPackages) {
4758             return new ArrayList<String>(mPackages.keySet());
4759         }
4760     }
4761
4762     @Override
4763     public String[] getPackagesForUid(int uid) {
4764         uid = UserHandle.getAppId(uid);
4765         // reader
4766         synchronized (mPackages) {
4767             Object obj = mSettings.getUserIdLPr(uid);
4768             if (obj instanceof SharedUserSetting) {
4769                 final SharedUserSetting sus = (SharedUserSetting) obj;
4770                 final int N = sus.packages.size();
4771                 final String[] res = new String[N];
4772                 for (int i = 0; i < N; i++) {
4773                     res[i] = sus.packages.valueAt(i).name;
4774                 }
4775                 return res;
4776             } else if (obj instanceof PackageSetting) {
4777                 final PackageSetting ps = (PackageSetting) obj;
4778                 return new String[] { ps.name };
4779             }
4780         }
4781         return null;
4782     }
4783
4784     @Override
4785     public String getNameForUid(int uid) {
4786         // reader
4787         synchronized (mPackages) {
4788             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4789             if (obj instanceof SharedUserSetting) {
4790                 final SharedUserSetting sus = (SharedUserSetting) obj;
4791                 return sus.name + ":" + sus.userId;
4792             } else if (obj instanceof PackageSetting) {
4793                 final PackageSetting ps = (PackageSetting) obj;
4794                 return ps.name;
4795             }
4796         }
4797         return null;
4798     }
4799
4800     @Override
4801     public int getUidForSharedUser(String sharedUserName) {
4802         if(sharedUserName == null) {
4803             return -1;
4804         }
4805         // reader
4806         synchronized (mPackages) {
4807             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4808             if (suid == null) {
4809                 return -1;
4810             }
4811             return suid.userId;
4812         }
4813     }
4814
4815     @Override
4816     public int getFlagsForUid(int uid) {
4817         synchronized (mPackages) {
4818             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4819             if (obj instanceof SharedUserSetting) {
4820                 final SharedUserSetting sus = (SharedUserSetting) obj;
4821                 return sus.pkgFlags;
4822             } else if (obj instanceof PackageSetting) {
4823                 final PackageSetting ps = (PackageSetting) obj;
4824                 return ps.pkgFlags;
4825             }
4826         }
4827         return 0;
4828     }
4829
4830     @Override
4831     public int getPrivateFlagsForUid(int uid) {
4832         synchronized (mPackages) {
4833             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4834             if (obj instanceof SharedUserSetting) {
4835                 final SharedUserSetting sus = (SharedUserSetting) obj;
4836                 return sus.pkgPrivateFlags;
4837             } else if (obj instanceof PackageSetting) {
4838                 final PackageSetting ps = (PackageSetting) obj;
4839                 return ps.pkgPrivateFlags;
4840             }
4841         }
4842         return 0;
4843     }
4844
4845     @Override
4846     public boolean isUidPrivileged(int uid) {
4847         uid = UserHandle.getAppId(uid);
4848         // reader
4849         synchronized (mPackages) {
4850             Object obj = mSettings.getUserIdLPr(uid);
4851             if (obj instanceof SharedUserSetting) {
4852                 final SharedUserSetting sus = (SharedUserSetting) obj;
4853                 final Iterator<PackageSetting> it = sus.packages.iterator();
4854                 while (it.hasNext()) {
4855                     if (it.next().isPrivileged()) {
4856                         return true;
4857                     }
4858                 }
4859             } else if (obj instanceof PackageSetting) {
4860                 final PackageSetting ps = (PackageSetting) obj;
4861                 return ps.isPrivileged();
4862             }
4863         }
4864         return false;
4865     }
4866
4867     @Override
4868     public String[] getAppOpPermissionPackages(String permissionName) {
4869         synchronized (mPackages) {
4870             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4871             if (pkgs == null) {
4872                 return null;
4873             }
4874             return pkgs.toArray(new String[pkgs.size()]);
4875         }
4876     }
4877
4878     @Override
4879     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4880             int flags, int userId) {
4881         try {
4882             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4883
4884             if (!sUserManager.exists(userId)) return null;
4885             flags = updateFlagsForResolve(flags, userId, intent);
4886             enforceCrossUserPermission(Binder.getCallingUid(), userId,
4887                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4888
4889             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4890             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4891                     flags, userId);
4892             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4893
4894             final ResolveInfo bestChoice =
4895                     chooseBestActivity(intent, resolvedType, flags, query, userId);
4896             return bestChoice;
4897         } finally {
4898             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4899         }
4900     }
4901
4902     @Override
4903     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4904             IntentFilter filter, int match, ComponentName activity) {
4905         final int userId = UserHandle.getCallingUserId();
4906         if (DEBUG_PREFERRED) {
4907             Log.v(TAG, "setLastChosenActivity intent=" + intent
4908                 + " resolvedType=" + resolvedType
4909                 + " flags=" + flags
4910                 + " filter=" + filter
4911                 + " match=" + match
4912                 + " activity=" + activity);
4913             filter.dump(new PrintStreamPrinter(System.out), "    ");
4914         }
4915         intent.setComponent(null);
4916         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4917                 userId);
4918         // Find any earlier preferred or last chosen entries and nuke them
4919         findPreferredActivity(intent, resolvedType,
4920                 flags, query, 0, false, true, false, userId);
4921         // Add the new activity as the last chosen for this filter
4922         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4923                 "Setting last chosen");
4924     }
4925
4926     @Override
4927     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4928         final int userId = UserHandle.getCallingUserId();
4929         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4930         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4931                 userId);
4932         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4933                 false, false, false, userId);
4934     }
4935
4936     private boolean isEphemeralDisabled() {
4937         // ephemeral apps have been disabled across the board
4938         if (DISABLE_EPHEMERAL_APPS) {
4939             return true;
4940         }
4941         // system isn't up yet; can't read settings, so, assume no ephemeral apps
4942         if (!mSystemReady) {
4943             return true;
4944         }
4945         // we can't get a content resolver until the system is ready; these checks must happen last
4946         final ContentResolver resolver = mContext.getContentResolver();
4947         if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4948             return true;
4949         }
4950         return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4951     }
4952
4953     private boolean isEphemeralAllowed(
4954             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4955             boolean skipPackageCheck) {
4956         // Short circuit and return early if possible.
4957         if (isEphemeralDisabled()) {
4958             return false;
4959         }
4960         final int callingUser = UserHandle.getCallingUserId();
4961         if (callingUser != UserHandle.USER_SYSTEM) {
4962             return false;
4963         }
4964         if (mEphemeralResolverConnection == null) {
4965             return false;
4966         }
4967         if (intent.getComponent() != null) {
4968             return false;
4969         }
4970         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4971             return false;
4972         }
4973         if (!skipPackageCheck && intent.getPackage() != null) {
4974             return false;
4975         }
4976         final boolean isWebUri = hasWebURI(intent);
4977         if (!isWebUri || intent.getData().getHost() == null) {
4978             return false;
4979         }
4980         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4981         synchronized (mPackages) {
4982             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4983             for (int n = 0; n < count; n++) {
4984                 ResolveInfo info = resolvedActivities.get(n);
4985                 String packageName = info.activityInfo.packageName;
4986                 PackageSetting ps = mSettings.mPackages.get(packageName);
4987                 if (ps != null) {
4988                     // Try to get the status from User settings first
4989                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4990                     int status = (int) (packedStatus >> 32);
4991                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4992                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4993                         if (DEBUG_EPHEMERAL) {
4994                             Slog.v(TAG, "DENY ephemeral apps;"
4995                                 + " pkg: " + packageName + ", status: " + status);
4996                         }
4997                         return false;
4998                     }
4999                 }
5000             }
5001         }
5002         // We've exhausted all ways to deny ephemeral application; let the system look for them.
5003         return true;
5004     }
5005
5006     private static EphemeralResolveInfo getEphemeralResolveInfo(
5007             Context context, EphemeralResolverConnection resolverConnection, Intent intent,
5008             String resolvedType, int userId, String packageName) {
5009         final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
5010                 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5011         final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
5012                 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5013         final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5014                 ephemeralPrefixCount);
5015         final int[] shaPrefix = digest.getDigestPrefix();
5016         final byte[][] digestBytes = digest.getDigestBytes();
5017         final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5018                 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
5019         if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5020             // No hash prefix match; there are no ephemeral apps for this domain.
5021             return null;
5022         }
5023
5024         // Go in reverse order so we match the narrowest scope first.
5025         for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5026             for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5027                 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5028                     continue;
5029                 }
5030                 final List<IntentFilter> filters = ephemeralApplication.getFilters();
5031                 // No filters; this should never happen.
5032                 if (filters.isEmpty()) {
5033                     continue;
5034                 }
5035                 if (packageName != null
5036                         && !packageName.equals(ephemeralApplication.getPackageName())) {
5037                     continue;
5038                 }
5039                 // We have a domain match; resolve the filters to see if anything matches.
5040                 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5041                 for (int j = filters.size() - 1; j >= 0; --j) {
5042                     final EphemeralResolveIntentInfo intentInfo =
5043                             new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5044                     ephemeralResolver.addFilter(intentInfo);
5045                 }
5046                 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5047                         intent, resolvedType, false /*defaultOnly*/, userId);
5048                 if (!matchedResolveInfoList.isEmpty()) {
5049                     return matchedResolveInfoList.get(0);
5050                 }
5051             }
5052         }
5053         // Hash or filter mis-match; no ephemeral apps for this domain.
5054         return null;
5055     }
5056
5057     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5058             int flags, List<ResolveInfo> query, int userId) {
5059         if (query != null) {
5060             final int N = query.size();
5061             if (N == 1) {
5062                 return query.get(0);
5063             } else if (N > 1) {
5064                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5065                 // If there is more than one activity with the same priority,
5066                 // then let the user decide between them.
5067                 ResolveInfo r0 = query.get(0);
5068                 ResolveInfo r1 = query.get(1);
5069                 if (DEBUG_INTENT_MATCHING || debug) {
5070                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5071                             + r1.activityInfo.name + "=" + r1.priority);
5072                 }
5073                 // If the first activity has a higher priority, or a different
5074                 // default, then it is always desirable to pick it.
5075                 if (r0.priority != r1.priority
5076                         || r0.preferredOrder != r1.preferredOrder
5077                         || r0.isDefault != r1.isDefault) {
5078                     return query.get(0);
5079                 }
5080                 // If we have saved a preference for a preferred activity for
5081                 // this Intent, use that.
5082                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5083                         flags, query, r0.priority, true, false, debug, userId);
5084                 if (ri != null) {
5085                     return ri;
5086                 }
5087                 ri = new ResolveInfo(mResolveInfo);
5088                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5089                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5090                 // If all of the options come from the same package, show the application's
5091                 // label and icon instead of the generic resolver's.
5092                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5093                 // and then throw away the ResolveInfo itself, meaning that the caller loses
5094                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5095                 // a fallback for this case; we only set the target package's resources on
5096                 // the ResolveInfo, not the ActivityInfo.
5097                 final String intentPackage = intent.getPackage();
5098                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5099                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5100                     ri.resolvePackageName = intentPackage;
5101                     if (userNeedsBadging(userId)) {
5102                         ri.noResourceId = true;
5103                     } else {
5104                         ri.icon = appi.icon;
5105                     }
5106                     ri.iconResourceId = appi.icon;
5107                     ri.labelRes = appi.labelRes;
5108                 }
5109                 ri.activityInfo.applicationInfo = new ApplicationInfo(
5110                         ri.activityInfo.applicationInfo);
5111                 if (userId != 0) {
5112                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5113                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5114                 }
5115                 // Make sure that the resolver is displayable in car mode
5116                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5117                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5118                 return ri;
5119             }
5120         }
5121         return null;
5122     }
5123
5124     /**
5125      * Return true if the given list is not empty and all of its contents have
5126      * an activityInfo with the given package name.
5127      */
5128     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5129         if (ArrayUtils.isEmpty(list)) {
5130             return false;
5131         }
5132         for (int i = 0, N = list.size(); i < N; i++) {
5133             final ResolveInfo ri = list.get(i);
5134             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5135             if (ai == null || !packageName.equals(ai.packageName)) {
5136                 return false;
5137             }
5138         }
5139         return true;
5140     }
5141
5142     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5143             int flags, List<ResolveInfo> query, boolean debug, int userId) {
5144         final int N = query.size();
5145         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5146                 .get(userId);
5147         // Get the list of persistent preferred activities that handle the intent
5148         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5149         List<PersistentPreferredActivity> pprefs = ppir != null
5150                 ? ppir.queryIntent(intent, resolvedType,
5151                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5152                 : null;
5153         if (pprefs != null && pprefs.size() > 0) {
5154             final int M = pprefs.size();
5155             for (int i=0; i<M; i++) {
5156                 final PersistentPreferredActivity ppa = pprefs.get(i);
5157                 if (DEBUG_PREFERRED || debug) {
5158                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5159                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5160                             + "\n  component=" + ppa.mComponent);
5161                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5162                 }
5163                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5164                         flags | MATCH_DISABLED_COMPONENTS, userId);
5165                 if (DEBUG_PREFERRED || debug) {
5166                     Slog.v(TAG, "Found persistent preferred activity:");
5167                     if (ai != null) {
5168                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5169                     } else {
5170                         Slog.v(TAG, "  null");
5171                     }
5172                 }
5173                 if (ai == null) {
5174                     // This previously registered persistent preferred activity
5175                     // component is no longer known. Ignore it and do NOT remove it.
5176                     continue;
5177                 }
5178                 for (int j=0; j<N; j++) {
5179                     final ResolveInfo ri = query.get(j);
5180                     if (!ri.activityInfo.applicationInfo.packageName
5181                             .equals(ai.applicationInfo.packageName)) {
5182                         continue;
5183                     }
5184                     if (!ri.activityInfo.name.equals(ai.name)) {
5185                         continue;
5186                     }
5187                     //  Found a persistent preference that can handle the intent.
5188                     if (DEBUG_PREFERRED || debug) {
5189                         Slog.v(TAG, "Returning persistent preferred activity: " +
5190                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5191                     }
5192                     return ri;
5193                 }
5194             }
5195         }
5196         return null;
5197     }
5198
5199     // TODO: handle preferred activities missing while user has amnesia
5200     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5201             List<ResolveInfo> query, int priority, boolean always,
5202             boolean removeMatches, boolean debug, int userId) {
5203         if (!sUserManager.exists(userId)) return null;
5204         flags = updateFlagsForResolve(flags, userId, intent);
5205         // writer
5206         synchronized (mPackages) {
5207             if (intent.getSelector() != null) {
5208                 intent = intent.getSelector();
5209             }
5210             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5211
5212             // Try to find a matching persistent preferred activity.
5213             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5214                     debug, userId);
5215
5216             // If a persistent preferred activity matched, use it.
5217             if (pri != null) {
5218                 return pri;
5219             }
5220
5221             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5222             // Get the list of preferred activities that handle the intent
5223             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5224             List<PreferredActivity> prefs = pir != null
5225                     ? pir.queryIntent(intent, resolvedType,
5226                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5227                     : null;
5228             if (prefs != null && prefs.size() > 0) {
5229                 boolean changed = false;
5230                 try {
5231                     // First figure out how good the original match set is.
5232                     // We will only allow preferred activities that came
5233                     // from the same match quality.
5234                     int match = 0;
5235
5236                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5237
5238                     final int N = query.size();
5239                     for (int j=0; j<N; j++) {
5240                         final ResolveInfo ri = query.get(j);
5241                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5242                                 + ": 0x" + Integer.toHexString(match));
5243                         if (ri.match > match) {
5244                             match = ri.match;
5245                         }
5246                     }
5247
5248                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5249                             + Integer.toHexString(match));
5250
5251                     match &= IntentFilter.MATCH_CATEGORY_MASK;
5252                     final int M = prefs.size();
5253                     for (int i=0; i<M; i++) {
5254                         final PreferredActivity pa = prefs.get(i);
5255                         if (DEBUG_PREFERRED || debug) {
5256                             Slog.v(TAG, "Checking PreferredActivity ds="
5257                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5258                                     + "\n  component=" + pa.mPref.mComponent);
5259                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5260                         }
5261                         if (pa.mPref.mMatch != match) {
5262                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5263                                     + Integer.toHexString(pa.mPref.mMatch));
5264                             continue;
5265                         }
5266                         // If it's not an "always" type preferred activity and that's what we're
5267                         // looking for, skip it.
5268                         if (always && !pa.mPref.mAlways) {
5269                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5270                             continue;
5271                         }
5272                         final ActivityInfo ai = getActivityInfo(
5273                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5274                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5275                                 userId);
5276                         if (DEBUG_PREFERRED || debug) {
5277                             Slog.v(TAG, "Found preferred activity:");
5278                             if (ai != null) {
5279                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5280                             } else {
5281                                 Slog.v(TAG, "  null");
5282                             }
5283                         }
5284                         if (ai == null) {
5285                             // This previously registered preferred activity
5286                             // component is no longer known.  Most likely an update
5287                             // to the app was installed and in the new version this
5288                             // component no longer exists.  Clean it up by removing
5289                             // it from the preferred activities list, and skip it.
5290                             Slog.w(TAG, "Removing dangling preferred activity: "
5291                                     + pa.mPref.mComponent);
5292                             pir.removeFilter(pa);
5293                             changed = true;
5294                             continue;
5295                         }
5296                         for (int j=0; j<N; j++) {
5297                             final ResolveInfo ri = query.get(j);
5298                             if (!ri.activityInfo.applicationInfo.packageName
5299                                     .equals(ai.applicationInfo.packageName)) {
5300                                 continue;
5301                             }
5302                             if (!ri.activityInfo.name.equals(ai.name)) {
5303                                 continue;
5304                             }
5305
5306                             if (removeMatches) {
5307                                 pir.removeFilter(pa);
5308                                 changed = true;
5309                                 if (DEBUG_PREFERRED) {
5310                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5311                                 }
5312                                 break;
5313                             }
5314
5315                             // Okay we found a previously set preferred or last chosen app.
5316                             // If the result set is different from when this
5317                             // was created, we need to clear it and re-ask the
5318                             // user their preference, if we're looking for an "always" type entry.
5319                             if (always && !pa.mPref.sameSet(query)) {
5320                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5321                                         + intent + " type " + resolvedType);
5322                                 if (DEBUG_PREFERRED) {
5323                                     Slog.v(TAG, "Removing preferred activity since set changed "
5324                                             + pa.mPref.mComponent);
5325                                 }
5326                                 pir.removeFilter(pa);
5327                                 // Re-add the filter as a "last chosen" entry (!always)
5328                                 PreferredActivity lastChosen = new PreferredActivity(
5329                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5330                                 pir.addFilter(lastChosen);
5331                                 changed = true;
5332                                 return null;
5333                             }
5334
5335                             // Yay! Either the set matched or we're looking for the last chosen
5336                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5337                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5338                             return ri;
5339                         }
5340                     }
5341                 } finally {
5342                     if (changed) {
5343                         if (DEBUG_PREFERRED) {
5344                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5345                         }
5346                         scheduleWritePackageRestrictionsLocked(userId);
5347                     }
5348                 }
5349             }
5350         }
5351         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5352         return null;
5353     }
5354
5355     /*
5356      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5357      */
5358     @Override
5359     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5360             int targetUserId) {
5361         mContext.enforceCallingOrSelfPermission(
5362                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5363         List<CrossProfileIntentFilter> matches =
5364                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5365         if (matches != null) {
5366             int size = matches.size();
5367             for (int i = 0; i < size; i++) {
5368                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5369             }
5370         }
5371         if (hasWebURI(intent)) {
5372             // cross-profile app linking works only towards the parent.
5373             final UserInfo parent = getProfileParent(sourceUserId);
5374             synchronized(mPackages) {
5375                 int flags = updateFlagsForResolve(0, parent.id, intent);
5376                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5377                         intent, resolvedType, flags, sourceUserId, parent.id);
5378                 return xpDomainInfo != null;
5379             }
5380         }
5381         return false;
5382     }
5383
5384     private UserInfo getProfileParent(int userId) {
5385         final long identity = Binder.clearCallingIdentity();
5386         try {
5387             return sUserManager.getProfileParent(userId);
5388         } finally {
5389             Binder.restoreCallingIdentity(identity);
5390         }
5391     }
5392
5393     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5394             String resolvedType, int userId) {
5395         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5396         if (resolver != null) {
5397             return resolver.queryIntent(intent, resolvedType, false, userId);
5398         }
5399         return null;
5400     }
5401
5402     @Override
5403     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5404             String resolvedType, int flags, int userId) {
5405         try {
5406             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5407
5408             return new ParceledListSlice<>(
5409                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5410         } finally {
5411             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5412         }
5413     }
5414
5415     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5416             String resolvedType, int flags, int userId) {
5417         if (!sUserManager.exists(userId)) return Collections.emptyList();
5418         flags = updateFlagsForResolve(flags, userId, intent);
5419         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5420                 false /* requireFullPermission */, false /* checkShell */,
5421                 "query intent activities");
5422         ComponentName comp = intent.getComponent();
5423         if (comp == null) {
5424             if (intent.getSelector() != null) {
5425                 intent = intent.getSelector();
5426                 comp = intent.getComponent();
5427             }
5428         }
5429
5430         if (comp != null) {
5431             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5432             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5433             if (ai != null) {
5434                 final ResolveInfo ri = new ResolveInfo();
5435                 ri.activityInfo = ai;
5436                 list.add(ri);
5437             }
5438             return list;
5439         }
5440
5441         // reader
5442         boolean sortResult = false;
5443         boolean addEphemeral = false;
5444         boolean matchEphemeralPackage = false;
5445         List<ResolveInfo> result;
5446         final String pkgName = intent.getPackage();
5447         synchronized (mPackages) {
5448             if (pkgName == null) {
5449                 List<CrossProfileIntentFilter> matchingFilters =
5450                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5451                 // Check for results that need to skip the current profile.
5452                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5453                         resolvedType, flags, userId);
5454                 if (xpResolveInfo != null) {
5455                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5456                     xpResult.add(xpResolveInfo);
5457                     return filterIfNotSystemUser(xpResult, userId);
5458                 }
5459
5460                 // Check for results in the current profile.
5461                 result = filterIfNotSystemUser(mActivities.queryIntent(
5462                         intent, resolvedType, flags, userId), userId);
5463                 addEphemeral =
5464                         isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5465
5466                 // Check for cross profile results.
5467                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5468                 xpResolveInfo = queryCrossProfileIntents(
5469                         matchingFilters, intent, resolvedType, flags, userId,
5470                         hasNonNegativePriorityResult);
5471                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5472                     boolean isVisibleToUser = filterIfNotSystemUser(
5473                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
5474                     if (isVisibleToUser) {
5475                         result.add(xpResolveInfo);
5476                         sortResult = true;
5477                     }
5478                 }
5479                 if (hasWebURI(intent)) {
5480                     CrossProfileDomainInfo xpDomainInfo = null;
5481                     final UserInfo parent = getProfileParent(userId);
5482                     if (parent != null) {
5483                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5484                                 flags, userId, parent.id);
5485                     }
5486                     if (xpDomainInfo != null) {
5487                         if (xpResolveInfo != null) {
5488                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
5489                             // in the result.
5490                             result.remove(xpResolveInfo);
5491                         }
5492                         if (result.size() == 0 && !addEphemeral) {
5493                             // No result in current profile, but found candidate in parent user.
5494                             // And we are not going to add emphemeral app, so we can return the
5495                             // result straight away.
5496                             result.add(xpDomainInfo.resolveInfo);
5497                             return result;
5498                         }
5499                     } else if (result.size() <= 1 && !addEphemeral) {
5500                         // No result in parent user and <= 1 result in current profile, and we
5501                         // are not going to add emphemeral app, so we can return the result without
5502                         // further processing.
5503                         return result;
5504                     }
5505                     // We have more than one candidate (combining results from current and parent
5506                     // profile), so we need filtering and sorting.
5507                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
5508                             intent, flags, result, xpDomainInfo, userId);
5509                     sortResult = true;
5510                 }
5511             } else {
5512                 final PackageParser.Package pkg = mPackages.get(pkgName);
5513                 if (pkg != null) {
5514                     result = filterIfNotSystemUser(
5515                             mActivities.queryIntentForPackage(
5516                                     intent, resolvedType, flags, pkg.activities, userId),
5517                             userId);
5518                 } else {
5519                     // the caller wants to resolve for a particular package; however, there
5520                     // were no installed results, so, try to find an ephemeral result
5521                     addEphemeral = isEphemeralAllowed(
5522                             intent, null /*result*/, userId, true /*skipPackageCheck*/);
5523                     matchEphemeralPackage = true;
5524                     result = new ArrayList<ResolveInfo>();
5525                 }
5526             }
5527         }
5528         if (addEphemeral) {
5529             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5530             final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5531                     mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5532                     matchEphemeralPackage ? pkgName : null);
5533             if (ai != null) {
5534                 if (DEBUG_EPHEMERAL) {
5535                     Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5536                 }
5537                 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5538                 ephemeralInstaller.ephemeralResolveInfo = ai;
5539                 // make sure this resolver is the default
5540                 ephemeralInstaller.isDefault = true;
5541                 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5542                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5543                 // add a non-generic filter
5544                 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5545                 ephemeralInstaller.filter.addDataPath(
5546                         intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5547                 result.add(ephemeralInstaller);
5548             }
5549             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5550         }
5551         if (sortResult) {
5552             Collections.sort(result, mResolvePrioritySorter);
5553         }
5554         return result;
5555     }
5556
5557     private static class CrossProfileDomainInfo {
5558         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5559         ResolveInfo resolveInfo;
5560         /* Best domain verification status of the activities found in the other profile */
5561         int bestDomainVerificationStatus;
5562     }
5563
5564     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5565             String resolvedType, int flags, int sourceUserId, int parentUserId) {
5566         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5567                 sourceUserId)) {
5568             return null;
5569         }
5570         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5571                 resolvedType, flags, parentUserId);
5572
5573         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5574             return null;
5575         }
5576         CrossProfileDomainInfo result = null;
5577         int size = resultTargetUser.size();
5578         for (int i = 0; i < size; i++) {
5579             ResolveInfo riTargetUser = resultTargetUser.get(i);
5580             // Intent filter verification is only for filters that specify a host. So don't return
5581             // those that handle all web uris.
5582             if (riTargetUser.handleAllWebDataURI) {
5583                 continue;
5584             }
5585             String packageName = riTargetUser.activityInfo.packageName;
5586             PackageSetting ps = mSettings.mPackages.get(packageName);
5587             if (ps == null) {
5588                 continue;
5589             }
5590             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5591             int status = (int)(verificationState >> 32);
5592             if (result == null) {
5593                 result = new CrossProfileDomainInfo();
5594                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5595                         sourceUserId, parentUserId);
5596                 result.bestDomainVerificationStatus = status;
5597             } else {
5598                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5599                         result.bestDomainVerificationStatus);
5600             }
5601         }
5602         // Don't consider matches with status NEVER across profiles.
5603         if (result != null && result.bestDomainVerificationStatus
5604                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5605             return null;
5606         }
5607         return result;
5608     }
5609
5610     /**
5611      * Verification statuses are ordered from the worse to the best, except for
5612      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5613      */
5614     private int bestDomainVerificationStatus(int status1, int status2) {
5615         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5616             return status2;
5617         }
5618         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5619             return status1;
5620         }
5621         return (int) MathUtils.max(status1, status2);
5622     }
5623
5624     private boolean isUserEnabled(int userId) {
5625         long callingId = Binder.clearCallingIdentity();
5626         try {
5627             UserInfo userInfo = sUserManager.getUserInfo(userId);
5628             return userInfo != null && userInfo.isEnabled();
5629         } finally {
5630             Binder.restoreCallingIdentity(callingId);
5631         }
5632     }
5633
5634     /**
5635      * Filter out activities with systemUserOnly flag set, when current user is not System.
5636      *
5637      * @return filtered list
5638      */
5639     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5640         if (userId == UserHandle.USER_SYSTEM) {
5641             return resolveInfos;
5642         }
5643         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5644             ResolveInfo info = resolveInfos.get(i);
5645             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5646                 resolveInfos.remove(i);
5647             }
5648         }
5649         return resolveInfos;
5650     }
5651
5652     /**
5653      * @param resolveInfos list of resolve infos in descending priority order
5654      * @return if the list contains a resolve info with non-negative priority
5655      */
5656     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5657         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5658     }
5659
5660     private static boolean hasWebURI(Intent intent) {
5661         if (intent.getData() == null) {
5662             return false;
5663         }
5664         final String scheme = intent.getScheme();
5665         if (TextUtils.isEmpty(scheme)) {
5666             return false;
5667         }
5668         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5669     }
5670
5671     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5672             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5673             int userId) {
5674         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5675
5676         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5677             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5678                     candidates.size());
5679         }
5680
5681         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5682         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5683         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5684         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5685         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5686         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5687
5688         synchronized (mPackages) {
5689             final int count = candidates.size();
5690             // First, try to use linked apps. Partition the candidates into four lists:
5691             // one for the final results, one for the "do not use ever", one for "undefined status"
5692             // and finally one for "browser app type".
5693             for (int n=0; n<count; n++) {
5694                 ResolveInfo info = candidates.get(n);
5695                 String packageName = info.activityInfo.packageName;
5696                 PackageSetting ps = mSettings.mPackages.get(packageName);
5697                 if (ps != null) {
5698                     // Add to the special match all list (Browser use case)
5699                     if (info.handleAllWebDataURI) {
5700                         matchAllList.add(info);
5701                         continue;
5702                     }
5703                     // Try to get the status from User settings first
5704                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5705                     int status = (int)(packedStatus >> 32);
5706                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5707                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5708                         if (DEBUG_DOMAIN_VERIFICATION) {
5709                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5710                                     + " : linkgen=" + linkGeneration);
5711                         }
5712                         // Use link-enabled generation as preferredOrder, i.e.
5713                         // prefer newly-enabled over earlier-enabled.
5714                         info.preferredOrder = linkGeneration;
5715                         alwaysList.add(info);
5716                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5717                         if (DEBUG_DOMAIN_VERIFICATION) {
5718                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5719                         }
5720                         neverList.add(info);
5721                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5722                         if (DEBUG_DOMAIN_VERIFICATION) {
5723                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5724                         }
5725                         alwaysAskList.add(info);
5726                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5727                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5728                         if (DEBUG_DOMAIN_VERIFICATION) {
5729                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5730                         }
5731                         undefinedList.add(info);
5732                     }
5733                 }
5734             }
5735
5736             // We'll want to include browser possibilities in a few cases
5737             boolean includeBrowser = false;
5738
5739             // First try to add the "always" resolution(s) for the current user, if any
5740             if (alwaysList.size() > 0) {
5741                 result.addAll(alwaysList);
5742             } else {
5743                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5744                 result.addAll(undefinedList);
5745                 // Maybe add one for the other profile.
5746                 if (xpDomainInfo != null && (
5747                         xpDomainInfo.bestDomainVerificationStatus
5748                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5749                     result.add(xpDomainInfo.resolveInfo);
5750                 }
5751                 includeBrowser = true;
5752             }
5753
5754             // The presence of any 'always ask' alternatives means we'll also offer browsers.
5755             // If there were 'always' entries their preferred order has been set, so we also
5756             // back that off to make the alternatives equivalent
5757             if (alwaysAskList.size() > 0) {
5758                 for (ResolveInfo i : result) {
5759                     i.preferredOrder = 0;
5760                 }
5761                 result.addAll(alwaysAskList);
5762                 includeBrowser = true;
5763             }
5764
5765             if (includeBrowser) {
5766                 // Also add browsers (all of them or only the default one)
5767                 if (DEBUG_DOMAIN_VERIFICATION) {
5768                     Slog.v(TAG, "   ...including browsers in candidate set");
5769                 }
5770                 if ((matchFlags & MATCH_ALL) != 0) {
5771                     result.addAll(matchAllList);
5772                 } else {
5773                     // Browser/generic handling case.  If there's a default browser, go straight
5774                     // to that (but only if there is no other higher-priority match).
5775                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5776                     int maxMatchPrio = 0;
5777                     ResolveInfo defaultBrowserMatch = null;
5778                     final int numCandidates = matchAllList.size();
5779                     for (int n = 0; n < numCandidates; n++) {
5780                         ResolveInfo info = matchAllList.get(n);
5781                         // track the highest overall match priority...
5782                         if (info.priority > maxMatchPrio) {
5783                             maxMatchPrio = info.priority;
5784                         }
5785                         // ...and the highest-priority default browser match
5786                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5787                             if (defaultBrowserMatch == null
5788                                     || (defaultBrowserMatch.priority < info.priority)) {
5789                                 if (debug) {
5790                                     Slog.v(TAG, "Considering default browser match " + info);
5791                                 }
5792                                 defaultBrowserMatch = info;
5793                             }
5794                         }
5795                     }
5796                     if (defaultBrowserMatch != null
5797                             && defaultBrowserMatch.priority >= maxMatchPrio
5798                             && !TextUtils.isEmpty(defaultBrowserPackageName))
5799                     {
5800                         if (debug) {
5801                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5802                         }
5803                         result.add(defaultBrowserMatch);
5804                     } else {
5805                         result.addAll(matchAllList);
5806                     }
5807                 }
5808
5809                 // If there is nothing selected, add all candidates and remove the ones that the user
5810                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5811                 if (result.size() == 0) {
5812                     result.addAll(candidates);
5813                     result.removeAll(neverList);
5814                 }
5815             }
5816         }
5817         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5818             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5819                     result.size());
5820             for (ResolveInfo info : result) {
5821                 Slog.v(TAG, "  + " + info.activityInfo);
5822             }
5823         }
5824         return result;
5825     }
5826
5827     // Returns a packed value as a long:
5828     //
5829     // high 'int'-sized word: link status: undefined/ask/never/always.
5830     // low 'int'-sized word: relative priority among 'always' results.
5831     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5832         long result = ps.getDomainVerificationStatusForUser(userId);
5833         // if none available, get the master status
5834         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5835             if (ps.getIntentFilterVerificationInfo() != null) {
5836                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5837             }
5838         }
5839         return result;
5840     }
5841
5842     private ResolveInfo querySkipCurrentProfileIntents(
5843             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5844             int flags, int sourceUserId) {
5845         if (matchingFilters != null) {
5846             int size = matchingFilters.size();
5847             for (int i = 0; i < size; i ++) {
5848                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5849                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5850                     // Checking if there are activities in the target user that can handle the
5851                     // intent.
5852                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5853                             resolvedType, flags, sourceUserId);
5854                     if (resolveInfo != null) {
5855                         return resolveInfo;
5856                     }
5857                 }
5858             }
5859         }
5860         return null;
5861     }
5862
5863     // Return matching ResolveInfo in target user if any.
5864     private ResolveInfo queryCrossProfileIntents(
5865             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5866             int flags, int sourceUserId, boolean matchInCurrentProfile) {
5867         if (matchingFilters != null) {
5868             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5869             // match the same intent. For performance reasons, it is better not to
5870             // run queryIntent twice for the same userId
5871             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5872             int size = matchingFilters.size();
5873             for (int i = 0; i < size; i++) {
5874                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5875                 int targetUserId = filter.getTargetUserId();
5876                 boolean skipCurrentProfile =
5877                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5878                 boolean skipCurrentProfileIfNoMatchFound =
5879                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5880                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5881                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5882                     // Checking if there are activities in the target user that can handle the
5883                     // intent.
5884                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5885                             resolvedType, flags, sourceUserId);
5886                     if (resolveInfo != null) return resolveInfo;
5887                     alreadyTriedUserIds.put(targetUserId, true);
5888                 }
5889             }
5890         }
5891         return null;
5892     }
5893
5894     /**
5895      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5896      * will forward the intent to the filter's target user.
5897      * Otherwise, returns null.
5898      */
5899     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5900             String resolvedType, int flags, int sourceUserId) {
5901         int targetUserId = filter.getTargetUserId();
5902         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5903                 resolvedType, flags, targetUserId);
5904         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5905             // If all the matches in the target profile are suspended, return null.
5906             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5907                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5908                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5909                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5910                             targetUserId);
5911                 }
5912             }
5913         }
5914         return null;
5915     }
5916
5917     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5918             int sourceUserId, int targetUserId) {
5919         ResolveInfo forwardingResolveInfo = new ResolveInfo();
5920         long ident = Binder.clearCallingIdentity();
5921         boolean targetIsProfile;
5922         try {
5923             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5924         } finally {
5925             Binder.restoreCallingIdentity(ident);
5926         }
5927         String className;
5928         if (targetIsProfile) {
5929             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5930         } else {
5931             className = FORWARD_INTENT_TO_PARENT;
5932         }
5933         ComponentName forwardingActivityComponentName = new ComponentName(
5934                 mAndroidApplication.packageName, className);
5935         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5936                 sourceUserId);
5937         if (!targetIsProfile) {
5938             forwardingActivityInfo.showUserIcon = targetUserId;
5939             forwardingResolveInfo.noResourceId = true;
5940         }
5941         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5942         forwardingResolveInfo.priority = 0;
5943         forwardingResolveInfo.preferredOrder = 0;
5944         forwardingResolveInfo.match = 0;
5945         forwardingResolveInfo.isDefault = true;
5946         forwardingResolveInfo.filter = filter;
5947         forwardingResolveInfo.targetUserId = targetUserId;
5948         return forwardingResolveInfo;
5949     }
5950
5951     @Override
5952     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5953             Intent[] specifics, String[] specificTypes, Intent intent,
5954             String resolvedType, int flags, int userId) {
5955         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5956                 specificTypes, intent, resolvedType, flags, userId));
5957     }
5958
5959     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5960             Intent[] specifics, String[] specificTypes, Intent intent,
5961             String resolvedType, int flags, int userId) {
5962         if (!sUserManager.exists(userId)) return Collections.emptyList();
5963         flags = updateFlagsForResolve(flags, userId, intent);
5964         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5965                 false /* requireFullPermission */, false /* checkShell */,
5966                 "query intent activity options");
5967         final String resultsAction = intent.getAction();
5968
5969         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5970                 | PackageManager.GET_RESOLVED_FILTER, userId);
5971
5972         if (DEBUG_INTENT_MATCHING) {
5973             Log.v(TAG, "Query " + intent + ": " + results);
5974         }
5975
5976         int specificsPos = 0;
5977         int N;
5978
5979         // todo: note that the algorithm used here is O(N^2).  This
5980         // isn't a problem in our current environment, but if we start running
5981         // into situations where we have more than 5 or 10 matches then this
5982         // should probably be changed to something smarter...
5983
5984         // First we go through and resolve each of the specific items
5985         // that were supplied, taking care of removing any corresponding
5986         // duplicate items in the generic resolve list.
5987         if (specifics != null) {
5988             for (int i=0; i<specifics.length; i++) {
5989                 final Intent sintent = specifics[i];
5990                 if (sintent == null) {
5991                     continue;
5992                 }
5993
5994                 if (DEBUG_INTENT_MATCHING) {
5995                     Log.v(TAG, "Specific #" + i + ": " + sintent);
5996                 }
5997
5998                 String action = sintent.getAction();
5999                 if (resultsAction != null && resultsAction.equals(action)) {
6000                     // If this action was explicitly requested, then don't
6001                     // remove things that have it.
6002                     action = null;
6003                 }
6004
6005                 ResolveInfo ri = null;
6006                 ActivityInfo ai = null;
6007
6008                 ComponentName comp = sintent.getComponent();
6009                 if (comp == null) {
6010                     ri = resolveIntent(
6011                         sintent,
6012                         specificTypes != null ? specificTypes[i] : null,
6013                             flags, userId);
6014                     if (ri == null) {
6015                         continue;
6016                     }
6017                     if (ri == mResolveInfo) {
6018                         // ACK!  Must do something better with this.
6019                     }
6020                     ai = ri.activityInfo;
6021                     comp = new ComponentName(ai.applicationInfo.packageName,
6022                             ai.name);
6023                 } else {
6024                     ai = getActivityInfo(comp, flags, userId);
6025                     if (ai == null) {
6026                         continue;
6027                     }
6028                 }
6029
6030                 // Look for any generic query activities that are duplicates
6031                 // of this specific one, and remove them from the results.
6032                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6033                 N = results.size();
6034                 int j;
6035                 for (j=specificsPos; j<N; j++) {
6036                     ResolveInfo sri = results.get(j);
6037                     if ((sri.activityInfo.name.equals(comp.getClassName())
6038                             && sri.activityInfo.applicationInfo.packageName.equals(
6039                                     comp.getPackageName()))
6040                         || (action != null && sri.filter.matchAction(action))) {
6041                         results.remove(j);
6042                         if (DEBUG_INTENT_MATCHING) Log.v(
6043                             TAG, "Removing duplicate item from " + j
6044                             + " due to specific " + specificsPos);
6045                         if (ri == null) {
6046                             ri = sri;
6047                         }
6048                         j--;
6049                         N--;
6050                     }
6051                 }
6052
6053                 // Add this specific item to its proper place.
6054                 if (ri == null) {
6055                     ri = new ResolveInfo();
6056                     ri.activityInfo = ai;
6057                 }
6058                 results.add(specificsPos, ri);
6059                 ri.specificIndex = i;
6060                 specificsPos++;
6061             }
6062         }
6063
6064         // Now we go through the remaining generic results and remove any
6065         // duplicate actions that are found here.
6066         N = results.size();
6067         for (int i=specificsPos; i<N-1; i++) {
6068             final ResolveInfo rii = results.get(i);
6069             if (rii.filter == null) {
6070                 continue;
6071             }
6072
6073             // Iterate over all of the actions of this result's intent
6074             // filter...  typically this should be just one.
6075             final Iterator<String> it = rii.filter.actionsIterator();
6076             if (it == null) {
6077                 continue;
6078             }
6079             while (it.hasNext()) {
6080                 final String action = it.next();
6081                 if (resultsAction != null && resultsAction.equals(action)) {
6082                     // If this action was explicitly requested, then don't
6083                     // remove things that have it.
6084                     continue;
6085                 }
6086                 for (int j=i+1; j<N; j++) {
6087                     final ResolveInfo rij = results.get(j);
6088                     if (rij.filter != null && rij.filter.hasAction(action)) {
6089                         results.remove(j);
6090                         if (DEBUG_INTENT_MATCHING) Log.v(
6091                             TAG, "Removing duplicate item from " + j
6092                             + " due to action " + action + " at " + i);
6093                         j--;
6094                         N--;
6095                     }
6096                 }
6097             }
6098
6099             // If the caller didn't request filter information, drop it now
6100             // so we don't have to marshall/unmarshall it.
6101             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6102                 rii.filter = null;
6103             }
6104         }
6105
6106         // Filter out the caller activity if so requested.
6107         if (caller != null) {
6108             N = results.size();
6109             for (int i=0; i<N; i++) {
6110                 ActivityInfo ainfo = results.get(i).activityInfo;
6111                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6112                         && caller.getClassName().equals(ainfo.name)) {
6113                     results.remove(i);
6114                     break;
6115                 }
6116             }
6117         }
6118
6119         // If the caller didn't request filter information,
6120         // drop them now so we don't have to
6121         // marshall/unmarshall it.
6122         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6123             N = results.size();
6124             for (int i=0; i<N; i++) {
6125                 results.get(i).filter = null;
6126             }
6127         }
6128
6129         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6130         return results;
6131     }
6132
6133     @Override
6134     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6135             String resolvedType, int flags, int userId) {
6136         return new ParceledListSlice<>(
6137                 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6138     }
6139
6140     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6141             String resolvedType, int flags, int userId) {
6142         if (!sUserManager.exists(userId)) return Collections.emptyList();
6143         flags = updateFlagsForResolve(flags, userId, intent);
6144         ComponentName comp = intent.getComponent();
6145         if (comp == null) {
6146             if (intent.getSelector() != null) {
6147                 intent = intent.getSelector();
6148                 comp = intent.getComponent();
6149             }
6150         }
6151         if (comp != null) {
6152             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6153             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6154             if (ai != null) {
6155                 ResolveInfo ri = new ResolveInfo();
6156                 ri.activityInfo = ai;
6157                 list.add(ri);
6158             }
6159             return list;
6160         }
6161
6162         // reader
6163         synchronized (mPackages) {
6164             String pkgName = intent.getPackage();
6165             if (pkgName == null) {
6166                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6167             }
6168             final PackageParser.Package pkg = mPackages.get(pkgName);
6169             if (pkg != null) {
6170                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6171                         userId);
6172             }
6173             return Collections.emptyList();
6174         }
6175     }
6176
6177     @Override
6178     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6179         if (!sUserManager.exists(userId)) return null;
6180         flags = updateFlagsForResolve(flags, userId, intent);
6181         List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6182         if (query != null) {
6183             if (query.size() >= 1) {
6184                 // If there is more than one service with the same priority,
6185                 // just arbitrarily pick the first one.
6186                 return query.get(0);
6187             }
6188         }
6189         return null;
6190     }
6191
6192     @Override
6193     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6194             String resolvedType, int flags, int userId) {
6195         return new ParceledListSlice<>(
6196                 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6197     }
6198
6199     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6200             String resolvedType, int flags, int userId) {
6201         if (!sUserManager.exists(userId)) return Collections.emptyList();
6202         flags = updateFlagsForResolve(flags, userId, intent);
6203         ComponentName comp = intent.getComponent();
6204         if (comp == null) {
6205             if (intent.getSelector() != null) {
6206                 intent = intent.getSelector();
6207                 comp = intent.getComponent();
6208             }
6209         }
6210         if (comp != null) {
6211             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6212             final ServiceInfo si = getServiceInfo(comp, flags, userId);
6213             if (si != null) {
6214                 final ResolveInfo ri = new ResolveInfo();
6215                 ri.serviceInfo = si;
6216                 list.add(ri);
6217             }
6218             return list;
6219         }
6220
6221         // reader
6222         synchronized (mPackages) {
6223             String pkgName = intent.getPackage();
6224             if (pkgName == null) {
6225                 return mServices.queryIntent(intent, resolvedType, flags, userId);
6226             }
6227             final PackageParser.Package pkg = mPackages.get(pkgName);
6228             if (pkg != null) {
6229                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6230                         userId);
6231             }
6232             return Collections.emptyList();
6233         }
6234     }
6235
6236     @Override
6237     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6238             String resolvedType, int flags, int userId) {
6239         return new ParceledListSlice<>(
6240                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6241     }
6242
6243     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6244             Intent intent, String resolvedType, int flags, int userId) {
6245         if (!sUserManager.exists(userId)) return Collections.emptyList();
6246         flags = updateFlagsForResolve(flags, userId, intent);
6247         ComponentName comp = intent.getComponent();
6248         if (comp == null) {
6249             if (intent.getSelector() != null) {
6250                 intent = intent.getSelector();
6251                 comp = intent.getComponent();
6252             }
6253         }
6254         if (comp != null) {
6255             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6256             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6257             if (pi != null) {
6258                 final ResolveInfo ri = new ResolveInfo();
6259                 ri.providerInfo = pi;
6260                 list.add(ri);
6261             }
6262             return list;
6263         }
6264
6265         // reader
6266         synchronized (mPackages) {
6267             String pkgName = intent.getPackage();
6268             if (pkgName == null) {
6269                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6270             }
6271             final PackageParser.Package pkg = mPackages.get(pkgName);
6272             if (pkg != null) {
6273                 return mProviders.queryIntentForPackage(
6274                         intent, resolvedType, flags, pkg.providers, userId);
6275             }
6276             return Collections.emptyList();
6277         }
6278     }
6279
6280     @Override
6281     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6282         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6283         flags = updateFlagsForPackage(flags, userId, null);
6284         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6285         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6286                 false /* requireFullPermission */, false /* checkShell */,
6287                 "get installed packages");
6288
6289         // writer
6290         synchronized (mPackages) {
6291             ArrayList<PackageInfo> list;
6292             if (listUninstalled) {
6293                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6294                 for (PackageSetting ps : mSettings.mPackages.values()) {
6295                     final PackageInfo pi;
6296                     if (ps.pkg != null) {
6297                         pi = generatePackageInfo(ps, flags, userId);
6298                     } else {
6299                         pi = generatePackageInfo(ps, flags, userId);
6300                     }
6301                     if (pi != null) {
6302                         list.add(pi);
6303                     }
6304                 }
6305             } else {
6306                 list = new ArrayList<PackageInfo>(mPackages.size());
6307                 for (PackageParser.Package p : mPackages.values()) {
6308                     final PackageInfo pi =
6309                             generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6310                     if (pi != null) {
6311                         list.add(pi);
6312                     }
6313                 }
6314             }
6315
6316             return new ParceledListSlice<PackageInfo>(list);
6317         }
6318     }
6319
6320     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6321             String[] permissions, boolean[] tmp, int flags, int userId) {
6322         int numMatch = 0;
6323         final PermissionsState permissionsState = ps.getPermissionsState();
6324         for (int i=0; i<permissions.length; i++) {
6325             final String permission = permissions[i];
6326             if (permissionsState.hasPermission(permission, userId)) {
6327                 tmp[i] = true;
6328                 numMatch++;
6329             } else {
6330                 tmp[i] = false;
6331             }
6332         }
6333         if (numMatch == 0) {
6334             return;
6335         }
6336         final PackageInfo pi;
6337         if (ps.pkg != null) {
6338             pi = generatePackageInfo(ps, flags, userId);
6339         } else {
6340             pi = generatePackageInfo(ps, flags, userId);
6341         }
6342         // The above might return null in cases of uninstalled apps or install-state
6343         // skew across users/profiles.
6344         if (pi != null) {
6345             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6346                 if (numMatch == permissions.length) {
6347                     pi.requestedPermissions = permissions;
6348                 } else {
6349                     pi.requestedPermissions = new String[numMatch];
6350                     numMatch = 0;
6351                     for (int i=0; i<permissions.length; i++) {
6352                         if (tmp[i]) {
6353                             pi.requestedPermissions[numMatch] = permissions[i];
6354                             numMatch++;
6355                         }
6356                     }
6357                 }
6358             }
6359             list.add(pi);
6360         }
6361     }
6362
6363     @Override
6364     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6365             String[] permissions, int flags, int userId) {
6366         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6367         flags = updateFlagsForPackage(flags, userId, permissions);
6368         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6369
6370         // writer
6371         synchronized (mPackages) {
6372             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6373             boolean[] tmpBools = new boolean[permissions.length];
6374             if (listUninstalled) {
6375                 for (PackageSetting ps : mSettings.mPackages.values()) {
6376                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6377                 }
6378             } else {
6379                 for (PackageParser.Package pkg : mPackages.values()) {
6380                     PackageSetting ps = (PackageSetting)pkg.mExtras;
6381                     if (ps != null) {
6382                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6383                                 userId);
6384                     }
6385                 }
6386             }
6387
6388             return new ParceledListSlice<PackageInfo>(list);
6389         }
6390     }
6391
6392     @Override
6393     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6394         final int callingUid = Binder.getCallingUid();
6395         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6396         flags = updateFlagsForApplication(flags, userId, null);
6397         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6398
6399         enforceCrossUserPermission(
6400             callingUid,
6401             userId,
6402             false /* requireFullPermission */,
6403             false /* checkShell */,
6404             "get installed application info");
6405
6406         // writer
6407         synchronized (mPackages) {
6408             ArrayList<ApplicationInfo> list;
6409             if (listUninstalled) {
6410                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6411                 for (PackageSetting ps : mSettings.mPackages.values()) {
6412                     ApplicationInfo ai;
6413                     if (ps.pkg != null) {
6414                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6415                                 ps.readUserState(userId), userId);
6416                     } else {
6417                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6418                     }
6419                     if (ai != null) {
6420                         list.add(ai);
6421                     }
6422                 }
6423             } else {
6424                 list = new ArrayList<ApplicationInfo>(mPackages.size());
6425                 for (PackageParser.Package p : mPackages.values()) {
6426                     if (p.mExtras != null) {
6427                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6428                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6429                         if (ai != null) {
6430                             list.add(ai);
6431                         }
6432                     }
6433                 }
6434             }
6435
6436             return new ParceledListSlice<ApplicationInfo>(list);
6437         }
6438     }
6439
6440     @Override
6441     public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6442         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6443             return null;
6444         }
6445
6446         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6447                 "getEphemeralApplications");
6448         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6449                 true /* requireFullPermission */, false /* checkShell */,
6450                 "getEphemeralApplications");
6451         synchronized (mPackages) {
6452             List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6453                     .getEphemeralApplicationsLPw(userId);
6454             if (ephemeralApps != null) {
6455                 return new ParceledListSlice<>(ephemeralApps);
6456             }
6457         }
6458         return null;
6459     }
6460
6461     @Override
6462     public boolean isEphemeralApplication(String packageName, int userId) {
6463         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6464                 true /* requireFullPermission */, false /* checkShell */,
6465                 "isEphemeral");
6466         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6467             return false;
6468         }
6469
6470         if (!isCallerSameApp(packageName)) {
6471             return false;
6472         }
6473         synchronized (mPackages) {
6474             PackageParser.Package pkg = mPackages.get(packageName);
6475             if (pkg != null) {
6476                 return pkg.applicationInfo.isEphemeralApp();
6477             }
6478         }
6479         return false;
6480     }
6481
6482     @Override
6483     public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6484         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6485             return null;
6486         }
6487
6488         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6489                 true /* requireFullPermission */, false /* checkShell */,
6490                 "getCookie");
6491         if (!isCallerSameApp(packageName)) {
6492             return null;
6493         }
6494         synchronized (mPackages) {
6495             return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6496                     packageName, userId);
6497         }
6498     }
6499
6500     @Override
6501     public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6502         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6503             return true;
6504         }
6505
6506         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6507                 true /* requireFullPermission */, true /* checkShell */,
6508                 "setCookie");
6509         if (!isCallerSameApp(packageName)) {
6510             return false;
6511         }
6512         synchronized (mPackages) {
6513             return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6514                     packageName, cookie, userId);
6515         }
6516     }
6517
6518     @Override
6519     public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6520         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6521             return null;
6522         }
6523
6524         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6525                 "getEphemeralApplicationIcon");
6526         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6527                 true /* requireFullPermission */, false /* checkShell */,
6528                 "getEphemeralApplicationIcon");
6529         synchronized (mPackages) {
6530             return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6531                     packageName, userId);
6532         }
6533     }
6534
6535     private boolean isCallerSameApp(String packageName) {
6536         PackageParser.Package pkg = mPackages.get(packageName);
6537         return pkg != null
6538                 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6539     }
6540
6541     @Override
6542     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6543         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6544     }
6545
6546     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6547         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6548
6549         // reader
6550         synchronized (mPackages) {
6551             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6552             final int userId = UserHandle.getCallingUserId();
6553             while (i.hasNext()) {
6554                 final PackageParser.Package p = i.next();
6555                 if (p.applicationInfo == null) continue;
6556
6557                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6558                         && !p.applicationInfo.isDirectBootAware();
6559                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6560                         && p.applicationInfo.isDirectBootAware();
6561
6562                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6563                         && (!mSafeMode || isSystemApp(p))
6564                         && (matchesUnaware || matchesAware)) {
6565                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
6566                     if (ps != null) {
6567                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6568                                 ps.readUserState(userId), userId);
6569                         if (ai != null) {
6570                             finalList.add(ai);
6571                         }
6572                     }
6573                 }
6574             }
6575         }
6576
6577         return finalList;
6578     }
6579
6580     @Override
6581     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6582         if (!sUserManager.exists(userId)) return null;
6583         flags = updateFlagsForComponent(flags, userId, name);
6584         // reader
6585         synchronized (mPackages) {
6586             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6587             PackageSetting ps = provider != null
6588                     ? mSettings.mPackages.get(provider.owner.packageName)
6589                     : null;
6590             return ps != null
6591                     && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6592                     ? PackageParser.generateProviderInfo(provider, flags,
6593                             ps.readUserState(userId), userId)
6594                     : null;
6595         }
6596     }
6597
6598     /**
6599      * @deprecated
6600      */
6601     @Deprecated
6602     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6603         // reader
6604         synchronized (mPackages) {
6605             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6606                     .entrySet().iterator();
6607             final int userId = UserHandle.getCallingUserId();
6608             while (i.hasNext()) {
6609                 Map.Entry<String, PackageParser.Provider> entry = i.next();
6610                 PackageParser.Provider p = entry.getValue();
6611                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6612
6613                 if (ps != null && p.syncable
6614                         && (!mSafeMode || (p.info.applicationInfo.flags
6615                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6616                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6617                             ps.readUserState(userId), userId);
6618                     if (info != null) {
6619                         outNames.add(entry.getKey());
6620                         outInfo.add(info);
6621                     }
6622                 }
6623             }
6624         }
6625     }
6626
6627     @Override
6628     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6629             int uid, int flags) {
6630         final int userId = processName != null ? UserHandle.getUserId(uid)
6631                 : UserHandle.getCallingUserId();
6632         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6633         flags = updateFlagsForComponent(flags, userId, processName);
6634
6635         ArrayList<ProviderInfo> finalList = null;
6636         // reader
6637         synchronized (mPackages) {
6638             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6639             while (i.hasNext()) {
6640                 final PackageParser.Provider p = i.next();
6641                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6642                 if (ps != null && p.info.authority != null
6643                         && (processName == null
6644                                 || (p.info.processName.equals(processName)
6645                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6646                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6647                     if (finalList == null) {
6648                         finalList = new ArrayList<ProviderInfo>(3);
6649                     }
6650                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6651                             ps.readUserState(userId), userId);
6652                     if (info != null) {
6653                         finalList.add(info);
6654                     }
6655                 }
6656             }
6657         }
6658
6659         if (finalList != null) {
6660             Collections.sort(finalList, mProviderInitOrderSorter);
6661             return new ParceledListSlice<ProviderInfo>(finalList);
6662         }
6663
6664         return ParceledListSlice.emptyList();
6665     }
6666
6667     @Override
6668     public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6669         // reader
6670         synchronized (mPackages) {
6671             final PackageParser.Instrumentation i = mInstrumentation.get(name);
6672             return PackageParser.generateInstrumentationInfo(i, flags);
6673         }
6674     }
6675
6676     @Override
6677     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6678             String targetPackage, int flags) {
6679         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6680     }
6681
6682     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6683             int flags) {
6684         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6685
6686         // reader
6687         synchronized (mPackages) {
6688             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6689             while (i.hasNext()) {
6690                 final PackageParser.Instrumentation p = i.next();
6691                 if (targetPackage == null
6692                         || targetPackage.equals(p.info.targetPackage)) {
6693                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6694                             flags);
6695                     if (ii != null) {
6696                         finalList.add(ii);
6697                     }
6698                 }
6699             }
6700         }
6701
6702         return finalList;
6703     }
6704
6705     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6706         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6707         if (overlays == null) {
6708             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6709             return;
6710         }
6711         for (PackageParser.Package opkg : overlays.values()) {
6712             // Not much to do if idmap fails: we already logged the error
6713             // and we certainly don't want to abort installation of pkg simply
6714             // because an overlay didn't fit properly. For these reasons,
6715             // ignore the return value of createIdmapForPackagePairLI.
6716             createIdmapForPackagePairLI(pkg, opkg);
6717         }
6718     }
6719
6720     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6721             PackageParser.Package opkg) {
6722         if (!opkg.mTrustedOverlay) {
6723             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6724                     opkg.baseCodePath + ": overlay not trusted");
6725             return false;
6726         }
6727         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6728         if (overlaySet == null) {
6729             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6730                     opkg.baseCodePath + " but target package has no known overlays");
6731             return false;
6732         }
6733         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6734         // TODO: generate idmap for split APKs
6735         try {
6736             mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6737         } catch (InstallerException e) {
6738             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6739                     + opkg.baseCodePath);
6740             return false;
6741         }
6742         PackageParser.Package[] overlayArray =
6743             overlaySet.values().toArray(new PackageParser.Package[0]);
6744         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6745             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6746                 return p1.mOverlayPriority - p2.mOverlayPriority;
6747             }
6748         };
6749         Arrays.sort(overlayArray, cmp);
6750
6751         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6752         int i = 0;
6753         for (PackageParser.Package p : overlayArray) {
6754             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6755         }
6756         return true;
6757     }
6758
6759     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6760         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6761         try {
6762             scanDirLI(dir, parseFlags, scanFlags, currentTime);
6763         } finally {
6764             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6765         }
6766     }
6767
6768     private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6769         final File[] files = dir.listFiles();
6770         if (ArrayUtils.isEmpty(files)) {
6771             Log.d(TAG, "No files in app dir " + dir);
6772             return;
6773         }
6774
6775         if (DEBUG_PACKAGE_SCANNING) {
6776             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6777                     + " flags=0x" + Integer.toHexString(parseFlags));
6778         }
6779
6780         for (File file : files) {
6781             final boolean isPackage = (isApkFile(file) || file.isDirectory())
6782                     && !PackageInstallerService.isStageName(file.getName());
6783             if (!isPackage) {
6784                 // Ignore entries which are not packages
6785                 continue;
6786             }
6787             try {
6788                 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6789                         scanFlags, currentTime, null);
6790             } catch (PackageManagerException e) {
6791                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6792
6793                 // Delete invalid userdata apps
6794                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6795                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6796                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6797                     removeCodePathLI(file);
6798                 }
6799             }
6800         }
6801     }
6802
6803     private static File getSettingsProblemFile() {
6804         File dataDir = Environment.getDataDirectory();
6805         File systemDir = new File(dataDir, "system");
6806         File fname = new File(systemDir, "uiderrors.txt");
6807         return fname;
6808     }
6809
6810     static void reportSettingsProblem(int priority, String msg) {
6811         logCriticalInfo(priority, msg);
6812     }
6813
6814     static void logCriticalInfo(int priority, String msg) {
6815         Slog.println(priority, TAG, msg);
6816         EventLogTags.writePmCriticalInfo(msg);
6817         try {
6818             File fname = getSettingsProblemFile();
6819             FileOutputStream out = new FileOutputStream(fname, true);
6820             PrintWriter pw = new FastPrintWriter(out);
6821             SimpleDateFormat formatter = new SimpleDateFormat();
6822             String dateString = formatter.format(new Date(System.currentTimeMillis()));
6823             pw.println(dateString + ": " + msg);
6824             pw.close();
6825             FileUtils.setPermissions(
6826                     fname.toString(),
6827                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6828                     -1, -1);
6829         } catch (java.io.IOException e) {
6830         }
6831     }
6832
6833     private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6834         if (srcFile.isDirectory()) {
6835             final File baseFile = new File(pkg.baseCodePath);
6836             long maxModifiedTime = baseFile.lastModified();
6837             if (pkg.splitCodePaths != null) {
6838                 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6839                     final File splitFile = new File(pkg.splitCodePaths[i]);
6840                     maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6841                 }
6842             }
6843             return maxModifiedTime;
6844         }
6845         return srcFile.lastModified();
6846     }
6847
6848     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6849             final int policyFlags) throws PackageManagerException {
6850         // When upgrading from pre-N MR1, verify the package time stamp using the package
6851         // directory and not the APK file.
6852         final long lastModifiedTime = mIsPreNMR1Upgrade
6853                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6854         if (ps != null
6855                 && ps.codePath.equals(srcFile)
6856                 && ps.timeStamp == lastModifiedTime
6857                 && !isCompatSignatureUpdateNeeded(pkg)
6858                 && !isRecoverSignatureUpdateNeeded(pkg)) {
6859             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6860             KeySetManagerService ksms = mSettings.mKeySetManagerService;
6861             ArraySet<PublicKey> signingKs;
6862             synchronized (mPackages) {
6863                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6864             }
6865             if (ps.signatures.mSignatures != null
6866                     && ps.signatures.mSignatures.length != 0
6867                     && signingKs != null) {
6868                 // Optimization: reuse the existing cached certificates
6869                 // if the package appears to be unchanged.
6870                 pkg.mSignatures = ps.signatures.mSignatures;
6871                 pkg.mSigningKeys = signingKs;
6872                 return;
6873             }
6874
6875             Slog.w(TAG, "PackageSetting for " + ps.name
6876                     + " is missing signatures.  Collecting certs again to recover them.");
6877         } else {
6878             Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6879         }
6880
6881         try {
6882             PackageParser.collectCertificates(pkg, policyFlags);
6883         } catch (PackageParserException e) {
6884             throw PackageManagerException.from(e);
6885         }
6886     }
6887
6888     /**
6889      *  Traces a package scan.
6890      *  @see #scanPackageLI(File, int, int, long, UserHandle)
6891      */
6892     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6893             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6894         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6895         try {
6896             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6897         } finally {
6898             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6899         }
6900     }
6901
6902     /**
6903      *  Scans a package and returns the newly parsed package.
6904      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6905      */
6906     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6907             long currentTime, UserHandle user) throws PackageManagerException {
6908         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6909         PackageParser pp = new PackageParser();
6910         pp.setSeparateProcesses(mSeparateProcesses);
6911         pp.setOnlyCoreApps(mOnlyCore);
6912         pp.setDisplayMetrics(mMetrics);
6913
6914         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6915             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6916         }
6917
6918         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6919         final PackageParser.Package pkg;
6920         try {
6921             pkg = pp.parsePackage(scanFile, parseFlags);
6922         } catch (PackageParserException e) {
6923             throw PackageManagerException.from(e);
6924         } finally {
6925             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6926         }
6927
6928         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6929     }
6930
6931     /**
6932      *  Scans a package and returns the newly parsed package.
6933      *  @throws PackageManagerException on a parse error.
6934      */
6935     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6936             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6937             throws PackageManagerException {
6938         // If the package has children and this is the first dive in the function
6939         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6940         // packages (parent and children) would be successfully scanned before the
6941         // actual scan since scanning mutates internal state and we want to atomically
6942         // install the package and its children.
6943         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6944             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6945                 scanFlags |= SCAN_CHECK_ONLY;
6946             }
6947         } else {
6948             scanFlags &= ~SCAN_CHECK_ONLY;
6949         }
6950
6951         // Scan the parent
6952         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6953                 scanFlags, currentTime, user);
6954
6955         // Scan the children
6956         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6957         for (int i = 0; i < childCount; i++) {
6958             PackageParser.Package childPackage = pkg.childPackages.get(i);
6959             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6960                     currentTime, user);
6961         }
6962
6963
6964         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6965             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6966         }
6967
6968         return scannedPkg;
6969     }
6970
6971     /**
6972      *  Scans a package and returns the newly parsed package.
6973      *  @throws PackageManagerException on a parse error.
6974      */
6975     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6976             int policyFlags, int scanFlags, long currentTime, UserHandle user)
6977             throws PackageManagerException {
6978         PackageSetting ps = null;
6979         PackageSetting updatedPkg;
6980         // reader
6981         synchronized (mPackages) {
6982             // Look to see if we already know about this package.
6983             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6984             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6985                 // This package has been renamed to its original name.  Let's
6986                 // use that.
6987                 ps = mSettings.peekPackageLPr(oldName);
6988             }
6989             // If there was no original package, see one for the real package name.
6990             if (ps == null) {
6991                 ps = mSettings.peekPackageLPr(pkg.packageName);
6992             }
6993             // Check to see if this package could be hiding/updating a system
6994             // package.  Must look for it either under the original or real
6995             // package name depending on our state.
6996             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6997             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6998
6999             // If this is a package we don't know about on the system partition, we
7000             // may need to remove disabled child packages on the system partition
7001             // or may need to not add child packages if the parent apk is updated
7002             // on the data partition and no longer defines this child package.
7003             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7004                 // If this is a parent package for an updated system app and this system
7005                 // app got an OTA update which no longer defines some of the child packages
7006                 // we have to prune them from the disabled system packages.
7007                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7008                 if (disabledPs != null) {
7009                     final int scannedChildCount = (pkg.childPackages != null)
7010                             ? pkg.childPackages.size() : 0;
7011                     final int disabledChildCount = disabledPs.childPackageNames != null
7012                             ? disabledPs.childPackageNames.size() : 0;
7013                     for (int i = 0; i < disabledChildCount; i++) {
7014                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7015                         boolean disabledPackageAvailable = false;
7016                         for (int j = 0; j < scannedChildCount; j++) {
7017                             PackageParser.Package childPkg = pkg.childPackages.get(j);
7018                             if (childPkg.packageName.equals(disabledChildPackageName)) {
7019                                 disabledPackageAvailable = true;
7020                                 break;
7021                             }
7022                          }
7023                          if (!disabledPackageAvailable) {
7024                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7025                          }
7026                     }
7027                 }
7028             }
7029         }
7030
7031         boolean updatedPkgBetter = false;
7032         // First check if this is a system package that may involve an update
7033         if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7034             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7035             // it needs to drop FLAG_PRIVILEGED.
7036             if (locationIsPrivileged(scanFile)) {
7037                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7038             } else {
7039                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7040             }
7041
7042             if (ps != null && !ps.codePath.equals(scanFile)) {
7043                 // The path has changed from what was last scanned...  check the
7044                 // version of the new path against what we have stored to determine
7045                 // what to do.
7046                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7047                 if (pkg.mVersionCode <= ps.versionCode) {
7048                     // The system package has been updated and the code path does not match
7049                     // Ignore entry. Skip it.
7050                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7051                             + " ignored: updated version " + ps.versionCode
7052                             + " better than this " + pkg.mVersionCode);
7053                     if (!updatedPkg.codePath.equals(scanFile)) {
7054                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7055                                 + ps.name + " changing from " + updatedPkg.codePathString
7056                                 + " to " + scanFile);
7057                         updatedPkg.codePath = scanFile;
7058                         updatedPkg.codePathString = scanFile.toString();
7059                         updatedPkg.resourcePath = scanFile;
7060                         updatedPkg.resourcePathString = scanFile.toString();
7061                     }
7062                     updatedPkg.pkg = pkg;
7063                     updatedPkg.versionCode = pkg.mVersionCode;
7064
7065                     // Update the disabled system child packages to point to the package too.
7066                     final int childCount = updatedPkg.childPackageNames != null
7067                             ? updatedPkg.childPackageNames.size() : 0;
7068                     for (int i = 0; i < childCount; i++) {
7069                         String childPackageName = updatedPkg.childPackageNames.get(i);
7070                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7071                                 childPackageName);
7072                         if (updatedChildPkg != null) {
7073                             updatedChildPkg.pkg = pkg;
7074                             updatedChildPkg.versionCode = pkg.mVersionCode;
7075                         }
7076                     }
7077
7078                     throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7079                             + scanFile + " ignored: updated version " + ps.versionCode
7080                             + " better than this " + pkg.mVersionCode);
7081                 } else {
7082                     // The current app on the system partition is better than
7083                     // what we have updated to on the data partition; switch
7084                     // back to the system partition version.
7085                     // At this point, its safely assumed that package installation for
7086                     // apps in system partition will go through. If not there won't be a working
7087                     // version of the app
7088                     // writer
7089                     synchronized (mPackages) {
7090                         // Just remove the loaded entries from package lists.
7091                         mPackages.remove(ps.name);
7092                     }
7093
7094                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7095                             + " reverting from " + ps.codePathString
7096                             + ": new version " + pkg.mVersionCode
7097                             + " better than installed " + ps.versionCode);
7098
7099                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7100                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7101                     synchronized (mInstallLock) {
7102                         args.cleanUpResourcesLI();
7103                     }
7104                     synchronized (mPackages) {
7105                         mSettings.enableSystemPackageLPw(ps.name);
7106                     }
7107                     updatedPkgBetter = true;
7108                 }
7109             }
7110         }
7111
7112         if (updatedPkg != null) {
7113             // An updated system app will not have the PARSE_IS_SYSTEM flag set
7114             // initially
7115             policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7116
7117             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7118             // flag set initially
7119             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7120                 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7121             }
7122         }
7123
7124         // Verify certificates against what was last scanned
7125         collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7126
7127         /*
7128          * A new system app appeared, but we already had a non-system one of the
7129          * same name installed earlier.
7130          */
7131         boolean shouldHideSystemApp = false;
7132         if (updatedPkg == null && ps != null
7133                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7134             /*
7135              * Check to make sure the signatures match first. If they don't,
7136              * wipe the installed application and its data.
7137              */
7138             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7139                     != PackageManager.SIGNATURE_MATCH) {
7140                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7141                         + " signatures don't match existing userdata copy; removing");
7142                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7143                         "scanPackageInternalLI")) {
7144                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7145                 }
7146                 ps = null;
7147             } else {
7148                 /*
7149                  * If the newly-added system app is an older version than the
7150                  * already installed version, hide it. It will be scanned later
7151                  * and re-added like an update.
7152                  */
7153                 if (pkg.mVersionCode <= ps.versionCode) {
7154                     shouldHideSystemApp = true;
7155                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7156                             + " but new version " + pkg.mVersionCode + " better than installed "
7157                             + ps.versionCode + "; hiding system");
7158                 } else {
7159                     /*
7160                      * The newly found system app is a newer version that the
7161                      * one previously installed. Simply remove the
7162                      * already-installed application and replace it with our own
7163                      * while keeping the application data.
7164                      */
7165                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7166                             + " reverting from " + ps.codePathString + ": new version "
7167                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
7168                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7169                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7170                     synchronized (mInstallLock) {
7171                         args.cleanUpResourcesLI();
7172                     }
7173                 }
7174             }
7175         }
7176
7177         // The apk is forward locked (not public) if its code and resources
7178         // are kept in different files. (except for app in either system or
7179         // vendor path).
7180         // TODO grab this value from PackageSettings
7181         if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7182             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7183                 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7184             }
7185         }
7186
7187         // TODO: extend to support forward-locked splits
7188         String resourcePath = null;
7189         String baseResourcePath = null;
7190         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7191             if (ps != null && ps.resourcePathString != null) {
7192                 resourcePath = ps.resourcePathString;
7193                 baseResourcePath = ps.resourcePathString;
7194             } else {
7195                 // Should not happen at all. Just log an error.
7196                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7197             }
7198         } else {
7199             resourcePath = pkg.codePath;
7200             baseResourcePath = pkg.baseCodePath;
7201         }
7202
7203         // Set application objects path explicitly.
7204         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7205         pkg.setApplicationInfoCodePath(pkg.codePath);
7206         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7207         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7208         pkg.setApplicationInfoResourcePath(resourcePath);
7209         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7210         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7211
7212         // Note that we invoke the following method only if we are about to unpack an application
7213         PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7214                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7215
7216         /*
7217          * If the system app should be overridden by a previously installed
7218          * data, hide the system app now and let the /data/app scan pick it up
7219          * again.
7220          */
7221         if (shouldHideSystemApp) {
7222             synchronized (mPackages) {
7223                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7224             }
7225         }
7226
7227         return scannedPkg;
7228     }
7229
7230     private static String fixProcessName(String defProcessName,
7231             String processName, int uid) {
7232         if (processName == null) {
7233             return defProcessName;
7234         }
7235         return processName;
7236     }
7237
7238     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7239             throws PackageManagerException {
7240         if (pkgSetting.signatures.mSignatures != null) {
7241             // Already existing package. Make sure signatures match
7242             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7243                     == PackageManager.SIGNATURE_MATCH;
7244             if (!match) {
7245                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7246                         == PackageManager.SIGNATURE_MATCH;
7247             }
7248             if (!match) {
7249                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7250                         == PackageManager.SIGNATURE_MATCH;
7251             }
7252             if (!match) {
7253                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7254                         + pkg.packageName + " signatures do not match the "
7255                         + "previously installed version; ignoring!");
7256             }
7257         }
7258
7259         // Check for shared user signatures
7260         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7261             // Already existing package. Make sure signatures match
7262             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7263                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7264             if (!match) {
7265                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7266                         == PackageManager.SIGNATURE_MATCH;
7267             }
7268             if (!match) {
7269                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7270                         == PackageManager.SIGNATURE_MATCH;
7271             }
7272             if (!match) {
7273                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7274                         "Package " + pkg.packageName
7275                         + " has no signatures that match those in shared user "
7276                         + pkgSetting.sharedUser.name + "; ignoring!");
7277             }
7278         }
7279     }
7280
7281     /**
7282      * Enforces that only the system UID or root's UID can call a method exposed
7283      * via Binder.
7284      *
7285      * @param message used as message if SecurityException is thrown
7286      * @throws SecurityException if the caller is not system or root
7287      */
7288     private static final void enforceSystemOrRoot(String message) {
7289         final int uid = Binder.getCallingUid();
7290         if (uid != Process.SYSTEM_UID && uid != 0) {
7291             throw new SecurityException(message);
7292         }
7293     }
7294
7295     @Override
7296     public void performFstrimIfNeeded() {
7297         enforceSystemOrRoot("Only the system can request fstrim");
7298
7299         // Before everything else, see whether we need to fstrim.
7300         try {
7301             IMountService ms = PackageHelper.getMountService();
7302             if (ms != null) {
7303                 boolean doTrim = false;
7304                 final long interval = android.provider.Settings.Global.getLong(
7305                         mContext.getContentResolver(),
7306                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7307                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7308                 if (interval > 0) {
7309                     final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7310                     if (timeSinceLast > interval) {
7311                         doTrim = true;
7312                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7313                                 + "; running immediately");
7314                     }
7315                 }
7316                 if (doTrim) {
7317                     final boolean dexOptDialogShown;
7318                     synchronized (mPackages) {
7319                         dexOptDialogShown = mDexOptDialogShown;
7320                     }
7321                     if (!isFirstBoot() && dexOptDialogShown) {
7322                         try {
7323                             ActivityManagerNative.getDefault().showBootMessage(
7324                                     mContext.getResources().getString(
7325                                             R.string.android_upgrading_fstrim), true);
7326                         } catch (RemoteException e) {
7327                         }
7328                     }
7329                     ms.runMaintenance();
7330                 }
7331             } else {
7332                 Slog.e(TAG, "Mount service unavailable!");
7333             }
7334         } catch (RemoteException e) {
7335             // Can't happen; MountService is local
7336         }
7337     }
7338
7339     @Override
7340     public void updatePackagesIfNeeded() {
7341         enforceSystemOrRoot("Only the system can request package update");
7342
7343         // We need to re-extract after an OTA.
7344         boolean causeUpgrade = isUpgrade();
7345
7346         // First boot or factory reset.
7347         // Note: we also handle devices that are upgrading to N right now as if it is their
7348         //       first boot, as they do not have profile data.
7349         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7350
7351         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7352         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7353
7354         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7355             return;
7356         }
7357
7358         List<PackageParser.Package> pkgs;
7359         synchronized (mPackages) {
7360             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7361         }
7362
7363         final long startTime = System.nanoTime();
7364         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7365                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7366
7367         final int elapsedTimeSeconds =
7368                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7369
7370         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7371         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7372         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7373         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7374         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7375     }
7376
7377     /**
7378      * Performs dexopt on the set of packages in {@code packages} and returns an int array
7379      * containing statistics about the invocation. The array consists of three elements,
7380      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7381      * and {@code numberOfPackagesFailed}.
7382      */
7383     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7384             String compilerFilter) {
7385
7386         int numberOfPackagesVisited = 0;
7387         int numberOfPackagesOptimized = 0;
7388         int numberOfPackagesSkipped = 0;
7389         int numberOfPackagesFailed = 0;
7390         final int numberOfPackagesToDexopt = pkgs.size();
7391
7392         for (PackageParser.Package pkg : pkgs) {
7393             numberOfPackagesVisited++;
7394
7395             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7396                 if (DEBUG_DEXOPT) {
7397                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7398                 }
7399                 numberOfPackagesSkipped++;
7400                 continue;
7401             }
7402
7403             if (DEBUG_DEXOPT) {
7404                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7405                         numberOfPackagesToDexopt + ": " + pkg.packageName);
7406             }
7407
7408             if (showDialog) {
7409                 try {
7410                     ActivityManagerNative.getDefault().showBootMessage(
7411                             mContext.getResources().getString(R.string.android_upgrading_apk,
7412                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7413                 } catch (RemoteException e) {
7414                 }
7415                 synchronized (mPackages) {
7416                     mDexOptDialogShown = true;
7417                 }
7418             }
7419
7420             // If the OTA updates a system app which was previously preopted to a non-preopted state
7421             // the app might end up being verified at runtime. That's because by default the apps
7422             // are verify-profile but for preopted apps there's no profile.
7423             // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7424             // that before the OTA the app was preopted) the app gets compiled with a non-profile
7425             // filter (by default interpret-only).
7426             // Note that at this stage unused apps are already filtered.
7427             if (isSystemApp(pkg) &&
7428                     DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7429                     !Environment.getReferenceProfile(pkg.packageName).exists()) {
7430                 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7431             }
7432
7433             // checkProfiles is false to avoid merging profiles during boot which
7434             // might interfere with background compilation (b/28612421).
7435             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7436             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7437             // trade-off worth doing to save boot time work.
7438             int dexOptStatus = performDexOptTraced(pkg.packageName,
7439                     false /* checkProfiles */,
7440                     compilerFilter,
7441                     false /* force */);
7442             switch (dexOptStatus) {
7443                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7444                     numberOfPackagesOptimized++;
7445                     break;
7446                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7447                     numberOfPackagesSkipped++;
7448                     break;
7449                 case PackageDexOptimizer.DEX_OPT_FAILED:
7450                     numberOfPackagesFailed++;
7451                     break;
7452                 default:
7453                     Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7454                     break;
7455             }
7456         }
7457
7458         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7459                 numberOfPackagesFailed };
7460     }
7461
7462     @Override
7463     public void notifyPackageUse(String packageName, int reason) {
7464         synchronized (mPackages) {
7465             PackageParser.Package p = mPackages.get(packageName);
7466             if (p == null) {
7467                 return;
7468             }
7469             p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7470         }
7471     }
7472
7473     // TODO: this is not used nor needed. Delete it.
7474     @Override
7475     public boolean performDexOptIfNeeded(String packageName) {
7476         int dexOptStatus = performDexOptTraced(packageName,
7477                 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7478         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7479     }
7480
7481     @Override
7482     public boolean performDexOpt(String packageName,
7483             boolean checkProfiles, int compileReason, boolean force) {
7484         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7485                 getCompilerFilterForReason(compileReason), force);
7486         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7487     }
7488
7489     @Override
7490     public boolean performDexOptMode(String packageName,
7491             boolean checkProfiles, String targetCompilerFilter, boolean force) {
7492         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7493                 targetCompilerFilter, force);
7494         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7495     }
7496
7497     private int performDexOptTraced(String packageName,
7498                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7499         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7500         try {
7501             return performDexOptInternal(packageName, checkProfiles,
7502                     targetCompilerFilter, force);
7503         } finally {
7504             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7505         }
7506     }
7507
7508     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7509     // if the package can now be considered up to date for the given filter.
7510     private int performDexOptInternal(String packageName,
7511                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7512         PackageParser.Package p;
7513         synchronized (mPackages) {
7514             p = mPackages.get(packageName);
7515             if (p == null) {
7516                 // Package could not be found. Report failure.
7517                 return PackageDexOptimizer.DEX_OPT_FAILED;
7518             }
7519             mPackageUsage.maybeWriteAsync(mPackages);
7520             mCompilerStats.maybeWriteAsync();
7521         }
7522         long callingId = Binder.clearCallingIdentity();
7523         try {
7524             synchronized (mInstallLock) {
7525                 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7526                         targetCompilerFilter, force);
7527             }
7528         } finally {
7529             Binder.restoreCallingIdentity(callingId);
7530         }
7531     }
7532
7533     public ArraySet<String> getOptimizablePackages() {
7534         ArraySet<String> pkgs = new ArraySet<String>();
7535         synchronized (mPackages) {
7536             for (PackageParser.Package p : mPackages.values()) {
7537                 if (PackageDexOptimizer.canOptimizePackage(p)) {
7538                     pkgs.add(p.packageName);
7539                 }
7540             }
7541         }
7542         return pkgs;
7543     }
7544
7545     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7546             boolean checkProfiles, String targetCompilerFilter,
7547             boolean force) {
7548         // Select the dex optimizer based on the force parameter.
7549         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7550         //       allocate an object here.
7551         PackageDexOptimizer pdo = force
7552                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7553                 : mPackageDexOptimizer;
7554
7555         // Optimize all dependencies first. Note: we ignore the return value and march on
7556         // on errors.
7557         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7558         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7559         if (!deps.isEmpty()) {
7560             for (PackageParser.Package depPackage : deps) {
7561                 // TODO: Analyze and investigate if we (should) profile libraries.
7562                 // Currently this will do a full compilation of the library by default.
7563                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7564                         false /* checkProfiles */,
7565                         getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7566                         getOrCreateCompilerPackageStats(depPackage));
7567             }
7568         }
7569         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7570                 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7571     }
7572
7573     Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7574         if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7575             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7576             Set<String> collectedNames = new HashSet<>();
7577             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7578
7579             retValue.remove(p);
7580
7581             return retValue;
7582         } else {
7583             return Collections.emptyList();
7584         }
7585     }
7586
7587     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7588             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7589         if (!collectedNames.contains(p.packageName)) {
7590             collectedNames.add(p.packageName);
7591             collected.add(p);
7592
7593             if (p.usesLibraries != null) {
7594                 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7595             }
7596             if (p.usesOptionalLibraries != null) {
7597                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7598                         collectedNames);
7599             }
7600         }
7601     }
7602
7603     private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7604             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7605         for (String libName : libs) {
7606             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7607             if (libPkg != null) {
7608                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7609             }
7610         }
7611     }
7612
7613     private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7614         synchronized (mPackages) {
7615             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7616             if (lib != null && lib.apk != null) {
7617                 return mPackages.get(lib.apk);
7618             }
7619         }
7620         return null;
7621     }
7622
7623     public void shutdown() {
7624         mPackageUsage.writeNow(mPackages);
7625         mCompilerStats.writeNow();
7626     }
7627
7628     @Override
7629     public void dumpProfiles(String packageName) {
7630         PackageParser.Package pkg;
7631         synchronized (mPackages) {
7632             pkg = mPackages.get(packageName);
7633             if (pkg == null) {
7634                 throw new IllegalArgumentException("Unknown package: " + packageName);
7635             }
7636         }
7637         /* Only the shell, root, or the app user should be able to dump profiles. */
7638         int callingUid = Binder.getCallingUid();
7639         if (callingUid != Process.SHELL_UID &&
7640             callingUid != Process.ROOT_UID &&
7641             callingUid != pkg.applicationInfo.uid) {
7642             throw new SecurityException("dumpProfiles");
7643         }
7644
7645         synchronized (mInstallLock) {
7646             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7647             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7648             try {
7649                 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7650                 String gid = Integer.toString(sharedGid);
7651                 String codePaths = TextUtils.join(";", allCodePaths);
7652                 mInstaller.dumpProfiles(gid, packageName, codePaths);
7653             } catch (InstallerException e) {
7654                 Slog.w(TAG, "Failed to dump profiles", e);
7655             }
7656             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7657         }
7658     }
7659
7660     @Override
7661     public void forceDexOpt(String packageName) {
7662         enforceSystemOrRoot("forceDexOpt");
7663
7664         PackageParser.Package pkg;
7665         synchronized (mPackages) {
7666             pkg = mPackages.get(packageName);
7667             if (pkg == null) {
7668                 throw new IllegalArgumentException("Unknown package: " + packageName);
7669             }
7670         }
7671
7672         synchronized (mInstallLock) {
7673             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7674
7675             // Whoever is calling forceDexOpt wants a fully compiled package.
7676             // Don't use profiles since that may cause compilation to be skipped.
7677             final int res = performDexOptInternalWithDependenciesLI(pkg,
7678                     false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7679                     true /* force */);
7680
7681             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7682             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7683                 throw new IllegalStateException("Failed to dexopt: " + res);
7684             }
7685         }
7686     }
7687
7688     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7689         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7690             Slog.w(TAG, "Unable to update from " + oldPkg.name
7691                     + " to " + newPkg.packageName
7692                     + ": old package not in system partition");
7693             return false;
7694         } else if (mPackages.get(oldPkg.name) != null) {
7695             Slog.w(TAG, "Unable to update from " + oldPkg.name
7696                     + " to " + newPkg.packageName
7697                     + ": old package still exists");
7698             return false;
7699         }
7700         return true;
7701     }
7702
7703     void removeCodePathLI(File codePath) {
7704         if (codePath.isDirectory()) {
7705             try {
7706                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7707             } catch (InstallerException e) {
7708                 Slog.w(TAG, "Failed to remove code path", e);
7709             }
7710         } else {
7711             codePath.delete();
7712         }
7713     }
7714
7715     private int[] resolveUserIds(int userId) {
7716         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7717     }
7718
7719     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7720         if (pkg == null) {
7721             Slog.wtf(TAG, "Package was null!", new Throwable());
7722             return;
7723         }
7724         clearAppDataLeafLIF(pkg, userId, flags);
7725         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7726         for (int i = 0; i < childCount; i++) {
7727             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7728         }
7729     }
7730
7731     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7732         final PackageSetting ps;
7733         synchronized (mPackages) {
7734             ps = mSettings.mPackages.get(pkg.packageName);
7735         }
7736         for (int realUserId : resolveUserIds(userId)) {
7737             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7738             try {
7739                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7740                         ceDataInode);
7741             } catch (InstallerException e) {
7742                 Slog.w(TAG, String.valueOf(e));
7743             }
7744         }
7745     }
7746
7747     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7748         if (pkg == null) {
7749             Slog.wtf(TAG, "Package was null!", new Throwable());
7750             return;
7751         }
7752         destroyAppDataLeafLIF(pkg, userId, flags);
7753         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7754         for (int i = 0; i < childCount; i++) {
7755             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7756         }
7757     }
7758
7759     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7760         final PackageSetting ps;
7761         synchronized (mPackages) {
7762             ps = mSettings.mPackages.get(pkg.packageName);
7763         }
7764         for (int realUserId : resolveUserIds(userId)) {
7765             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7766             try {
7767                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7768                         ceDataInode);
7769             } catch (InstallerException e) {
7770                 Slog.w(TAG, String.valueOf(e));
7771             }
7772         }
7773     }
7774
7775     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7776         if (pkg == null) {
7777             Slog.wtf(TAG, "Package was null!", new Throwable());
7778             return;
7779         }
7780         destroyAppProfilesLeafLIF(pkg);
7781         destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7782         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7783         for (int i = 0; i < childCount; i++) {
7784             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7785             destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7786                     true /* removeBaseMarker */);
7787         }
7788     }
7789
7790     private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7791             boolean removeBaseMarker) {
7792         if (pkg.isForwardLocked()) {
7793             return;
7794         }
7795
7796         for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7797             try {
7798                 path = PackageManagerServiceUtils.realpath(new File(path));
7799             } catch (IOException e) {
7800                 // TODO: Should we return early here ?
7801                 Slog.w(TAG, "Failed to get canonical path", e);
7802                 continue;
7803             }
7804
7805             final String useMarker = path.replace('/', '@');
7806             for (int realUserId : resolveUserIds(userId)) {
7807                 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7808                 if (removeBaseMarker) {
7809                     File foreignUseMark = new File(profileDir, useMarker);
7810                     if (foreignUseMark.exists()) {
7811                         if (!foreignUseMark.delete()) {
7812                             Slog.w(TAG, "Unable to delete foreign user mark for package: "
7813                                     + pkg.packageName);
7814                         }
7815                     }
7816                 }
7817
7818                 File[] markers = profileDir.listFiles();
7819                 if (markers != null) {
7820                     final String searchString = "@" + pkg.packageName + "@";
7821                     // We also delete all markers that contain the package name we're
7822                     // uninstalling. These are associated with secondary dex-files belonging
7823                     // to the package. Reconstructing the path of these dex files is messy
7824                     // in general.
7825                     for (File marker : markers) {
7826                         if (marker.getName().indexOf(searchString) > 0) {
7827                             if (!marker.delete()) {
7828                                 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7829                                     + pkg.packageName);
7830                             }
7831                         }
7832                     }
7833                 }
7834             }
7835         }
7836     }
7837
7838     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7839         try {
7840             mInstaller.destroyAppProfiles(pkg.packageName);
7841         } catch (InstallerException e) {
7842             Slog.w(TAG, String.valueOf(e));
7843         }
7844     }
7845
7846     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7847         if (pkg == null) {
7848             Slog.wtf(TAG, "Package was null!", new Throwable());
7849             return;
7850         }
7851         clearAppProfilesLeafLIF(pkg);
7852         // We don't remove the base foreign use marker when clearing profiles because
7853         // we will rename it when the app is updated. Unlike the actual profile contents,
7854         // the foreign use marker is good across installs.
7855         destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7856         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7857         for (int i = 0; i < childCount; i++) {
7858             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7859         }
7860     }
7861
7862     private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7863         try {
7864             mInstaller.clearAppProfiles(pkg.packageName);
7865         } catch (InstallerException e) {
7866             Slog.w(TAG, String.valueOf(e));
7867         }
7868     }
7869
7870     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7871             long lastUpdateTime) {
7872         // Set parent install/update time
7873         PackageSetting ps = (PackageSetting) pkg.mExtras;
7874         if (ps != null) {
7875             ps.firstInstallTime = firstInstallTime;
7876             ps.lastUpdateTime = lastUpdateTime;
7877         }
7878         // Set children install/update time
7879         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7880         for (int i = 0; i < childCount; i++) {
7881             PackageParser.Package childPkg = pkg.childPackages.get(i);
7882             ps = (PackageSetting) childPkg.mExtras;
7883             if (ps != null) {
7884                 ps.firstInstallTime = firstInstallTime;
7885                 ps.lastUpdateTime = lastUpdateTime;
7886             }
7887         }
7888     }
7889
7890     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7891             PackageParser.Package changingLib) {
7892         if (file.path != null) {
7893             usesLibraryFiles.add(file.path);
7894             return;
7895         }
7896         PackageParser.Package p = mPackages.get(file.apk);
7897         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7898             // If we are doing this while in the middle of updating a library apk,
7899             // then we need to make sure to use that new apk for determining the
7900             // dependencies here.  (We haven't yet finished committing the new apk
7901             // to the package manager state.)
7902             if (p == null || p.packageName.equals(changingLib.packageName)) {
7903                 p = changingLib;
7904             }
7905         }
7906         if (p != null) {
7907             usesLibraryFiles.addAll(p.getAllCodePaths());
7908         }
7909     }
7910
7911     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7912             PackageParser.Package changingLib) throws PackageManagerException {
7913         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7914             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7915             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7916             for (int i=0; i<N; i++) {
7917                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7918                 if (file == null) {
7919                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7920                             "Package " + pkg.packageName + " requires unavailable shared library "
7921                             + pkg.usesLibraries.get(i) + "; failing!");
7922                 }
7923                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7924             }
7925             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7926             for (int i=0; i<N; i++) {
7927                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7928                 if (file == null) {
7929                     Slog.w(TAG, "Package " + pkg.packageName
7930                             + " desires unavailable shared library "
7931                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7932                 } else {
7933                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7934                 }
7935             }
7936             N = usesLibraryFiles.size();
7937             if (N > 0) {
7938                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7939             } else {
7940                 pkg.usesLibraryFiles = null;
7941             }
7942         }
7943     }
7944
7945     private static boolean hasString(List<String> list, List<String> which) {
7946         if (list == null) {
7947             return false;
7948         }
7949         for (int i=list.size()-1; i>=0; i--) {
7950             for (int j=which.size()-1; j>=0; j--) {
7951                 if (which.get(j).equals(list.get(i))) {
7952                     return true;
7953                 }
7954             }
7955         }
7956         return false;
7957     }
7958
7959     private void updateAllSharedLibrariesLPw() {
7960         for (PackageParser.Package pkg : mPackages.values()) {
7961             try {
7962                 updateSharedLibrariesLPw(pkg, null);
7963             } catch (PackageManagerException e) {
7964                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7965             }
7966         }
7967     }
7968
7969     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7970             PackageParser.Package changingPkg) {
7971         ArrayList<PackageParser.Package> res = null;
7972         for (PackageParser.Package pkg : mPackages.values()) {
7973             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7974                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7975                 if (res == null) {
7976                     res = new ArrayList<PackageParser.Package>();
7977                 }
7978                 res.add(pkg);
7979                 try {
7980                     updateSharedLibrariesLPw(pkg, changingPkg);
7981                 } catch (PackageManagerException e) {
7982                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7983                 }
7984             }
7985         }
7986         return res;
7987     }
7988
7989     /**
7990      * Derive the value of the {@code cpuAbiOverride} based on the provided
7991      * value and an optional stored value from the package settings.
7992      */
7993     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7994         String cpuAbiOverride = null;
7995
7996         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7997             cpuAbiOverride = null;
7998         } else if (abiOverride != null) {
7999             cpuAbiOverride = abiOverride;
8000         } else if (settings != null) {
8001             cpuAbiOverride = settings.cpuAbiOverrideString;
8002         }
8003
8004         return cpuAbiOverride;
8005     }
8006
8007     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8008             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8009                     throws PackageManagerException {
8010         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8011         // If the package has children and this is the first dive in the function
8012         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8013         // whether all packages (parent and children) would be successfully scanned
8014         // before the actual scan since scanning mutates internal state and we want
8015         // to atomically install the package and its children.
8016         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8017             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8018                 scanFlags |= SCAN_CHECK_ONLY;
8019             }
8020         } else {
8021             scanFlags &= ~SCAN_CHECK_ONLY;
8022         }
8023
8024         final PackageParser.Package scannedPkg;
8025         try {
8026             // Scan the parent
8027             scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8028             // Scan the children
8029             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8030             for (int i = 0; i < childCount; i++) {
8031                 PackageParser.Package childPkg = pkg.childPackages.get(i);
8032                 scanPackageLI(childPkg, policyFlags,
8033                         scanFlags, currentTime, user);
8034             }
8035         } finally {
8036             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8037         }
8038
8039         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8040             return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8041         }
8042
8043         return scannedPkg;
8044     }
8045
8046     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8047             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8048         boolean success = false;
8049         try {
8050             final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8051                     currentTime, user);
8052             success = true;
8053             return res;
8054         } finally {
8055             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8056                 // DELETE_DATA_ON_FAILURES is only used by frozen paths
8057                 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8058                         StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8059                 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8060             }
8061         }
8062     }
8063
8064     /**
8065      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8066      */
8067     private static boolean apkHasCode(String fileName) {
8068         StrictJarFile jarFile = null;
8069         try {
8070             jarFile = new StrictJarFile(fileName,
8071                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8072             return jarFile.findEntry("classes.dex") != null;
8073         } catch (IOException ignore) {
8074         } finally {
8075             try {
8076                 if (jarFile != null) {
8077                     jarFile.close();
8078                 }
8079             } catch (IOException ignore) {}
8080         }
8081         return false;
8082     }
8083
8084     /**
8085      * Enforces code policy for the package. This ensures that if an APK has
8086      * declared hasCode="true" in its manifest that the APK actually contains
8087      * code.
8088      *
8089      * @throws PackageManagerException If bytecode could not be found when it should exist
8090      */
8091     private static void enforceCodePolicy(PackageParser.Package pkg)
8092             throws PackageManagerException {
8093         final boolean shouldHaveCode =
8094                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8095         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8096             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8097                     "Package " + pkg.baseCodePath + " code is missing");
8098         }
8099
8100         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8101             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8102                 final boolean splitShouldHaveCode =
8103                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8104                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8105                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8106                             "Package " + pkg.splitCodePaths[i] + " code is missing");
8107                 }
8108             }
8109         }
8110     }
8111
8112     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8113             final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8114             throws PackageManagerException {
8115         final File scanFile = new File(pkg.codePath);
8116         if (pkg.applicationInfo.getCodePath() == null ||
8117                 pkg.applicationInfo.getResourcePath() == null) {
8118             // Bail out. The resource and code paths haven't been set.
8119             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8120                     "Code and resource paths haven't been set correctly");
8121         }
8122
8123         // Apply policy
8124         if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8125             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8126             if (pkg.applicationInfo.isDirectBootAware()) {
8127                 // we're direct boot aware; set for all components
8128                 for (PackageParser.Service s : pkg.services) {
8129                     s.info.encryptionAware = s.info.directBootAware = true;
8130                 }
8131                 for (PackageParser.Provider p : pkg.providers) {
8132                     p.info.encryptionAware = p.info.directBootAware = true;
8133                 }
8134                 for (PackageParser.Activity a : pkg.activities) {
8135                     a.info.encryptionAware = a.info.directBootAware = true;
8136                 }
8137                 for (PackageParser.Activity r : pkg.receivers) {
8138                     r.info.encryptionAware = r.info.directBootAware = true;
8139                 }
8140             }
8141         } else {
8142             // Only allow system apps to be flagged as core apps.
8143             pkg.coreApp = false;
8144             // clear flags not applicable to regular apps
8145             pkg.applicationInfo.privateFlags &=
8146                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8147             pkg.applicationInfo.privateFlags &=
8148                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8149         }
8150         pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8151
8152         if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8153             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8154         }
8155
8156         if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8157             enforceCodePolicy(pkg);
8158         }
8159
8160         if (mCustomResolverComponentName != null &&
8161                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8162             setUpCustomResolverActivity(pkg);
8163         }
8164
8165         if (pkg.packageName.equals("android")) {
8166             synchronized (mPackages) {
8167                 if (mAndroidApplication != null) {
8168                     Slog.w(TAG, "*************************************************");
8169                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
8170                     Slog.w(TAG, " file=" + scanFile);
8171                     Slog.w(TAG, "*************************************************");
8172                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8173                             "Core android package being redefined.  Skipping.");
8174                 }
8175
8176                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8177                     // Set up information for our fall-back user intent resolution activity.
8178                     mPlatformPackage = pkg;
8179                     pkg.mVersionCode = mSdkVersion;
8180                     mAndroidApplication = pkg.applicationInfo;
8181
8182                     if (!mResolverReplaced) {
8183                         mResolveActivity.applicationInfo = mAndroidApplication;
8184                         mResolveActivity.name = ResolverActivity.class.getName();
8185                         mResolveActivity.packageName = mAndroidApplication.packageName;
8186                         mResolveActivity.processName = "system:ui";
8187                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8188                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8189                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8190                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8191                         mResolveActivity.exported = true;
8192                         mResolveActivity.enabled = true;
8193                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8194                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8195                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8196                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8197                                 | ActivityInfo.CONFIG_ORIENTATION
8198                                 | ActivityInfo.CONFIG_KEYBOARD
8199                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8200                         mResolveInfo.activityInfo = mResolveActivity;
8201                         mResolveInfo.priority = 0;
8202                         mResolveInfo.preferredOrder = 0;
8203                         mResolveInfo.match = 0;
8204                         mResolveComponentName = new ComponentName(
8205                                 mAndroidApplication.packageName, mResolveActivity.name);
8206                     }
8207                 }
8208             }
8209         }
8210
8211         if (DEBUG_PACKAGE_SCANNING) {
8212             if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8213                 Log.d(TAG, "Scanning package " + pkg.packageName);
8214         }
8215
8216         final PackageParser.Package oldPkg;
8217
8218         synchronized (mPackages) {
8219             if (mPackages.containsKey(pkg.packageName)
8220                     || mSharedLibraries.containsKey(pkg.packageName)) {
8221                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8222                         "Application package " + pkg.packageName
8223                                 + " already installed.  Skipping duplicate.");
8224             }
8225
8226             final PackageSetting oldPkgSetting = mSettings.peekPackageLPr(pkg.packageName);
8227             if (oldPkgSetting == null) {
8228                oldPkg = null;
8229             } else {
8230                oldPkg = oldPkgSetting.pkg;
8231             }
8232
8233             // If we're only installing presumed-existing packages, require that the
8234             // scanned APK is both already known and at the path previously established
8235             // for it.  Previously unknown packages we pick up normally, but if we have an
8236             // a priori expectation about this package's install presence, enforce it.
8237             // With a singular exception for new system packages. When an OTA contains
8238             // a new system package, we allow the codepath to change from a system location
8239             // to the user-installed location. If we don't allow this change, any newer,
8240             // user-installed version of the application will be ignored.
8241             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8242                 if (mExpectingBetter.containsKey(pkg.packageName)) {
8243                     logCriticalInfo(Log.WARN,
8244                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8245                 } else {
8246                     PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8247                     if (known != null) {
8248                         if (DEBUG_PACKAGE_SCANNING) {
8249                             Log.d(TAG, "Examining " + pkg.codePath
8250                                     + " and requiring known paths " + known.codePathString
8251                                     + " & " + known.resourcePathString);
8252                         }
8253                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8254                                 || !pkg.applicationInfo.getResourcePath().equals(
8255                                 known.resourcePathString)) {
8256                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8257                                     "Application package " + pkg.packageName
8258                                             + " found at " + pkg.applicationInfo.getCodePath()
8259                                             + " but expected at " + known.codePathString
8260                                             + "; ignoring.");
8261                         }
8262                     }
8263                 }
8264             }
8265         }
8266
8267         // Initialize package source and resource directories
8268         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8269         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8270
8271         SharedUserSetting suid = null;
8272         PackageSetting pkgSetting = null;
8273
8274         if (!isSystemApp(pkg)) {
8275             // Only system apps can use these features.
8276             pkg.mOriginalPackages = null;
8277             pkg.mRealPackage = null;
8278             pkg.mAdoptPermissions = null;
8279         }
8280
8281         // Getting the package setting may have a side-effect, so if we
8282         // are only checking if scan would succeed, stash a copy of the
8283         // old setting to restore at the end.
8284         PackageSetting nonMutatedPs = null;
8285
8286         // writer
8287         synchronized (mPackages) {
8288             if (pkg.mSharedUserId != null) {
8289                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8290                 if (suid == null) {
8291                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8292                             "Creating application package " + pkg.packageName
8293                             + " for shared user failed");
8294                 }
8295                 if (DEBUG_PACKAGE_SCANNING) {
8296                     if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8297                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8298                                 + "): packages=" + suid.packages);
8299                 }
8300             }
8301
8302             // Check if we are renaming from an original package name.
8303             PackageSetting origPackage = null;
8304             String realName = null;
8305             if (pkg.mOriginalPackages != null) {
8306                 // This package may need to be renamed to a previously
8307                 // installed name.  Let's check on that...
8308                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8309                 if (pkg.mOriginalPackages.contains(renamed)) {
8310                     // This package had originally been installed as the
8311                     // original name, and we have already taken care of
8312                     // transitioning to the new one.  Just update the new
8313                     // one to continue using the old name.
8314                     realName = pkg.mRealPackage;
8315                     if (!pkg.packageName.equals(renamed)) {
8316                         // Callers into this function may have already taken
8317                         // care of renaming the package; only do it here if
8318                         // it is not already done.
8319                         pkg.setPackageName(renamed);
8320                     }
8321
8322                 } else {
8323                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8324                         if ((origPackage = mSettings.peekPackageLPr(
8325                                 pkg.mOriginalPackages.get(i))) != null) {
8326                             // We do have the package already installed under its
8327                             // original name...  should we use it?
8328                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8329                                 // New package is not compatible with original.
8330                                 origPackage = null;
8331                                 continue;
8332                             } else if (origPackage.sharedUser != null) {
8333                                 // Make sure uid is compatible between packages.
8334                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8335                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8336                                             + " to " + pkg.packageName + ": old uid "
8337                                             + origPackage.sharedUser.name
8338                                             + " differs from " + pkg.mSharedUserId);
8339                                     origPackage = null;
8340                                     continue;
8341                                 }
8342                                 // TODO: Add case when shared user id is added [b/28144775]
8343                             } else {
8344                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8345                                         + pkg.packageName + " to old name " + origPackage.name);
8346                             }
8347                             break;
8348                         }
8349                     }
8350                 }
8351             }
8352
8353             if (mTransferedPackages.contains(pkg.packageName)) {
8354                 Slog.w(TAG, "Package " + pkg.packageName
8355                         + " was transferred to another, but its .apk remains");
8356             }
8357
8358             // See comments in nonMutatedPs declaration
8359             if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8360                 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8361                 if (foundPs != null) {
8362                     nonMutatedPs = new PackageSetting(foundPs);
8363                 }
8364             }
8365
8366             // Just create the setting, don't add it yet. For already existing packages
8367             // the PkgSetting exists already and doesn't have to be created.
8368             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8369                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8370                     pkg.applicationInfo.primaryCpuAbi,
8371                     pkg.applicationInfo.secondaryCpuAbi,
8372                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8373                     user, false);
8374             if (pkgSetting == null) {
8375                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8376                         "Creating application package " + pkg.packageName + " failed");
8377             }
8378
8379             if (pkgSetting.origPackage != null) {
8380                 // If we are first transitioning from an original package,
8381                 // fix up the new package's name now.  We need to do this after
8382                 // looking up the package under its new name, so getPackageLP
8383                 // can take care of fiddling things correctly.
8384                 pkg.setPackageName(origPackage.name);
8385
8386                 // File a report about this.
8387                 String msg = "New package " + pkgSetting.realName
8388                         + " renamed to replace old package " + pkgSetting.name;
8389                 reportSettingsProblem(Log.WARN, msg);
8390
8391                 // Make a note of it.
8392                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8393                     mTransferedPackages.add(origPackage.name);
8394                 }
8395
8396                 // No longer need to retain this.
8397                 pkgSetting.origPackage = null;
8398             }
8399
8400             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8401                 // Make a note of it.
8402                 mTransferedPackages.add(pkg.packageName);
8403             }
8404
8405             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8406                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8407             }
8408
8409             if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8410                 // Check all shared libraries and map to their actual file path.
8411                 // We only do this here for apps not on a system dir, because those
8412                 // are the only ones that can fail an install due to this.  We
8413                 // will take care of the system apps by updating all of their
8414                 // library paths after the scan is done.
8415                 updateSharedLibrariesLPw(pkg, null);
8416             }
8417
8418             if (mFoundPolicyFile) {
8419                 SELinuxMMAC.assignSeinfoValue(pkg);
8420             }
8421
8422             pkg.applicationInfo.uid = pkgSetting.appId;
8423             pkg.mExtras = pkgSetting;
8424             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8425                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8426                     // We just determined the app is signed correctly, so bring
8427                     // over the latest parsed certs.
8428                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8429                 } else {
8430                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8431                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8432                                 "Package " + pkg.packageName + " upgrade keys do not match the "
8433                                 + "previously installed version");
8434                     } else {
8435                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
8436                         String msg = "System package " + pkg.packageName
8437                             + " signature changed; retaining data.";
8438                         reportSettingsProblem(Log.WARN, msg);
8439                     }
8440                 }
8441             } else {
8442                 try {
8443                     verifySignaturesLP(pkgSetting, pkg);
8444                     // We just determined the app is signed correctly, so bring
8445                     // over the latest parsed certs.
8446                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8447                 } catch (PackageManagerException e) {
8448                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8449                         throw e;
8450                     }
8451                     // The signature has changed, but this package is in the system
8452                     // image...  let's recover!
8453                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8454                     // However...  if this package is part of a shared user, but it
8455                     // doesn't match the signature of the shared user, let's fail.
8456                     // What this means is that you can't change the signatures
8457                     // associated with an overall shared user, which doesn't seem all
8458                     // that unreasonable.
8459                     if (pkgSetting.sharedUser != null) {
8460                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8461                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8462                             throw new PackageManagerException(
8463                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8464                                             "Signature mismatch for shared user: "
8465                                             + pkgSetting.sharedUser);
8466                         }
8467                     }
8468                     // File a report about this.
8469                     String msg = "System package " + pkg.packageName
8470                         + " signature changed; retaining data.";
8471                     reportSettingsProblem(Log.WARN, msg);
8472                 }
8473             }
8474             // Verify that this new package doesn't have any content providers
8475             // that conflict with existing packages.  Only do this if the
8476             // package isn't already installed, since we don't want to break
8477             // things that are installed.
8478             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8479                 final int N = pkg.providers.size();
8480                 int i;
8481                 for (i=0; i<N; i++) {
8482                     PackageParser.Provider p = pkg.providers.get(i);
8483                     if (p.info.authority != null) {
8484                         String names[] = p.info.authority.split(";");
8485                         for (int j = 0; j < names.length; j++) {
8486                             if (mProvidersByAuthority.containsKey(names[j])) {
8487                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8488                                 final String otherPackageName =
8489                                         ((other != null && other.getComponentName() != null) ?
8490                                                 other.getComponentName().getPackageName() : "?");
8491                                 throw new PackageManagerException(
8492                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
8493                                                 "Can't install because provider name " + names[j]
8494                                                 + " (in package " + pkg.applicationInfo.packageName
8495                                                 + ") is already used by " + otherPackageName);
8496                             }
8497                         }
8498                     }
8499                 }
8500             }
8501
8502             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8503                 // This package wants to adopt ownership of permissions from
8504                 // another package.
8505                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8506                     final String origName = pkg.mAdoptPermissions.get(i);
8507                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
8508                     if (orig != null) {
8509                         if (verifyPackageUpdateLPr(orig, pkg)) {
8510                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
8511                                     + pkg.packageName);
8512                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
8513                         }
8514                     }
8515                 }
8516             }
8517         }
8518
8519         final String pkgName = pkg.packageName;
8520
8521         final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8522         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8523         pkg.applicationInfo.processName = fixProcessName(
8524                 pkg.applicationInfo.packageName,
8525                 pkg.applicationInfo.processName,
8526                 pkg.applicationInfo.uid);
8527
8528         if (pkg != mPlatformPackage) {
8529             // Get all of our default paths setup
8530             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8531         }
8532
8533         final String path = scanFile.getPath();
8534         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8535
8536         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8537             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8538
8539             // Some system apps still use directory structure for native libraries
8540             // in which case we might end up not detecting abi solely based on apk
8541             // structure. Try to detect abi based on directory structure.
8542             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8543                     pkg.applicationInfo.primaryCpuAbi == null) {
8544                 setBundledAppAbisAndRoots(pkg, pkgSetting);
8545                 setNativeLibraryPaths(pkg);
8546             }
8547
8548         } else {
8549             if ((scanFlags & SCAN_MOVE) != 0) {
8550                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8551                 // but we already have this packages package info in the PackageSetting. We just
8552                 // use that and derive the native library path based on the new codepath.
8553                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8554                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8555             }
8556
8557             // Set native library paths again. For moves, the path will be updated based on the
8558             // ABIs we've determined above. For non-moves, the path will be updated based on the
8559             // ABIs we determined during compilation, but the path will depend on the final
8560             // package path (after the rename away from the stage path).
8561             setNativeLibraryPaths(pkg);
8562         }
8563
8564         // This is a special case for the "system" package, where the ABI is
8565         // dictated by the zygote configuration (and init.rc). We should keep track
8566         // of this ABI so that we can deal with "normal" applications that run under
8567         // the same UID correctly.
8568         if (mPlatformPackage == pkg) {
8569             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8570                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8571         }
8572
8573         // If there's a mismatch between the abi-override in the package setting
8574         // and the abiOverride specified for the install. Warn about this because we
8575         // would've already compiled the app without taking the package setting into
8576         // account.
8577         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8578             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8579                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8580                         " for package " + pkg.packageName);
8581             }
8582         }
8583
8584         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8585         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8586         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8587
8588         // Copy the derived override back to the parsed package, so that we can
8589         // update the package settings accordingly.
8590         pkg.cpuAbiOverride = cpuAbiOverride;
8591
8592         if (DEBUG_ABI_SELECTION) {
8593             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8594                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8595                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8596         }
8597
8598         // Push the derived path down into PackageSettings so we know what to
8599         // clean up at uninstall time.
8600         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8601
8602         if (DEBUG_ABI_SELECTION) {
8603             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8604                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
8605                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8606         }
8607
8608         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8609             // We don't do this here during boot because we can do it all
8610             // at once after scanning all existing packages.
8611             //
8612             // We also do this *before* we perform dexopt on this package, so that
8613             // we can avoid redundant dexopts, and also to make sure we've got the
8614             // code and package path correct.
8615             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8616                     pkg, true /* boot complete */);
8617         }
8618
8619         if (mFactoryTest && pkg.requestedPermissions.contains(
8620                 android.Manifest.permission.FACTORY_TEST)) {
8621             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8622         }
8623
8624         if (isSystemApp(pkg)) {
8625             pkgSetting.isOrphaned = true;
8626         }
8627
8628         ArrayList<PackageParser.Package> clientLibPkgs = null;
8629
8630         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8631             if (nonMutatedPs != null) {
8632                 synchronized (mPackages) {
8633                     mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8634                 }
8635             }
8636             return pkg;
8637         }
8638
8639         // Only privileged apps and updated privileged apps can add child packages.
8640         if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8641             if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8642                 throw new PackageManagerException("Only privileged apps and updated "
8643                         + "privileged apps can add child packages. Ignoring package "
8644                         + pkg.packageName);
8645             }
8646             final int childCount = pkg.childPackages.size();
8647             for (int i = 0; i < childCount; i++) {
8648                 PackageParser.Package childPkg = pkg.childPackages.get(i);
8649                 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8650                         childPkg.packageName)) {
8651                     throw new PackageManagerException("Cannot override a child package of "
8652                             + "another disabled system app. Ignoring package " + pkg.packageName);
8653                 }
8654             }
8655         }
8656
8657         // writer
8658         synchronized (mPackages) {
8659             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8660                 // Only system apps can add new shared libraries.
8661                 if (pkg.libraryNames != null) {
8662                     for (int i=0; i<pkg.libraryNames.size(); i++) {
8663                         String name = pkg.libraryNames.get(i);
8664                         boolean allowed = false;
8665                         if (pkg.isUpdatedSystemApp()) {
8666                             // New library entries can only be added through the
8667                             // system image.  This is important to get rid of a lot
8668                             // of nasty edge cases: for example if we allowed a non-
8669                             // system update of the app to add a library, then uninstalling
8670                             // the update would make the library go away, and assumptions
8671                             // we made such as through app install filtering would now
8672                             // have allowed apps on the device which aren't compatible
8673                             // with it.  Better to just have the restriction here, be
8674                             // conservative, and create many fewer cases that can negatively
8675                             // impact the user experience.
8676                             final PackageSetting sysPs = mSettings
8677                                     .getDisabledSystemPkgLPr(pkg.packageName);
8678                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8679                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8680                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8681                                         allowed = true;
8682                                         break;
8683                                     }
8684                                 }
8685                             }
8686                         } else {
8687                             allowed = true;
8688                         }
8689                         if (allowed) {
8690                             if (!mSharedLibraries.containsKey(name)) {
8691                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8692                             } else if (!name.equals(pkg.packageName)) {
8693                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
8694                                         + name + " already exists; skipping");
8695                             }
8696                         } else {
8697                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8698                                     + name + " that is not declared on system image; skipping");
8699                         }
8700                     }
8701                     if ((scanFlags & SCAN_BOOTING) == 0) {
8702                         // If we are not booting, we need to update any applications
8703                         // that are clients of our shared library.  If we are booting,
8704                         // this will all be done once the scan is complete.
8705                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8706                     }
8707                 }
8708             }
8709         }
8710
8711         if ((scanFlags & SCAN_BOOTING) != 0) {
8712             // No apps can run during boot scan, so they don't need to be frozen
8713         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8714             // Caller asked to not kill app, so it's probably not frozen
8715         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8716             // Caller asked us to ignore frozen check for some reason; they
8717             // probably didn't know the package name
8718         } else {
8719             // We're doing major surgery on this package, so it better be frozen
8720             // right now to keep it from launching
8721             checkPackageFrozen(pkgName);
8722         }
8723
8724         // Also need to kill any apps that are dependent on the library.
8725         if (clientLibPkgs != null) {
8726             for (int i=0; i<clientLibPkgs.size(); i++) {
8727                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8728                 killApplication(clientPkg.applicationInfo.packageName,
8729                         clientPkg.applicationInfo.uid, "update lib");
8730             }
8731         }
8732
8733         // Make sure we're not adding any bogus keyset info
8734         KeySetManagerService ksms = mSettings.mKeySetManagerService;
8735         ksms.assertScannedPackageValid(pkg);
8736
8737         // writer
8738         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8739
8740         boolean createIdmapFailed = false;
8741         synchronized (mPackages) {
8742             // We don't expect installation to fail beyond this point
8743
8744             if (pkgSetting.pkg != null) {
8745                 // Note that |user| might be null during the initial boot scan. If a codePath
8746                 // for an app has changed during a boot scan, it's due to an app update that's
8747                 // part of the system partition and marker changes must be applied to all users.
8748                 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8749                     (user != null) ? user : UserHandle.ALL);
8750             }
8751
8752             // Add the new setting to mSettings
8753             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8754             // Add the new setting to mPackages
8755             mPackages.put(pkg.applicationInfo.packageName, pkg);
8756             // Make sure we don't accidentally delete its data.
8757             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8758             while (iter.hasNext()) {
8759                 PackageCleanItem item = iter.next();
8760                 if (pkgName.equals(item.packageName)) {
8761                     iter.remove();
8762                 }
8763             }
8764
8765             // Take care of first install / last update times.
8766             if (currentTime != 0) {
8767                 if (pkgSetting.firstInstallTime == 0) {
8768                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8769                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8770                     pkgSetting.lastUpdateTime = currentTime;
8771                 }
8772             } else if (pkgSetting.firstInstallTime == 0) {
8773                 // We need *something*.  Take time time stamp of the file.
8774                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8775             } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8776                 if (scanFileTime != pkgSetting.timeStamp) {
8777                     // A package on the system image has changed; consider this
8778                     // to be an update.
8779                     pkgSetting.lastUpdateTime = scanFileTime;
8780                 }
8781             }
8782
8783             // Add the package's KeySets to the global KeySetManagerService
8784             ksms.addScannedPackageLPw(pkg);
8785
8786             int N = pkg.providers.size();
8787             StringBuilder r = null;
8788             int i;
8789             for (i=0; i<N; i++) {
8790                 PackageParser.Provider p = pkg.providers.get(i);
8791                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8792                         p.info.processName, pkg.applicationInfo.uid);
8793                 mProviders.addProvider(p);
8794                 p.syncable = p.info.isSyncable;
8795                 if (p.info.authority != null) {
8796                     String names[] = p.info.authority.split(";");
8797                     p.info.authority = null;
8798                     for (int j = 0; j < names.length; j++) {
8799                         if (j == 1 && p.syncable) {
8800                             // We only want the first authority for a provider to possibly be
8801                             // syncable, so if we already added this provider using a different
8802                             // authority clear the syncable flag. We copy the provider before
8803                             // changing it because the mProviders object contains a reference
8804                             // to a provider that we don't want to change.
8805                             // Only do this for the second authority since the resulting provider
8806                             // object can be the same for all future authorities for this provider.
8807                             p = new PackageParser.Provider(p);
8808                             p.syncable = false;
8809                         }
8810                         if (!mProvidersByAuthority.containsKey(names[j])) {
8811                             mProvidersByAuthority.put(names[j], p);
8812                             if (p.info.authority == null) {
8813                                 p.info.authority = names[j];
8814                             } else {
8815                                 p.info.authority = p.info.authority + ";" + names[j];
8816                             }
8817                             if (DEBUG_PACKAGE_SCANNING) {
8818                                 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8819                                     Log.d(TAG, "Registered content provider: " + names[j]
8820                                             + ", className = " + p.info.name + ", isSyncable = "
8821                                             + p.info.isSyncable);
8822                             }
8823                         } else {
8824                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8825                             Slog.w(TAG, "Skipping provider name " + names[j] +
8826                                     " (in package " + pkg.applicationInfo.packageName +
8827                                     "): name already used by "
8828                                     + ((other != null && other.getComponentName() != null)
8829                                             ? other.getComponentName().getPackageName() : "?"));
8830                         }
8831                     }
8832                 }
8833                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8834                     if (r == null) {
8835                         r = new StringBuilder(256);
8836                     } else {
8837                         r.append(' ');
8838                     }
8839                     r.append(p.info.name);
8840                 }
8841             }
8842             if (r != null) {
8843                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8844             }
8845
8846             N = pkg.services.size();
8847             r = null;
8848             for (i=0; i<N; i++) {
8849                 PackageParser.Service s = pkg.services.get(i);
8850                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8851                         s.info.processName, pkg.applicationInfo.uid);
8852                 mServices.addService(s);
8853                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8854                     if (r == null) {
8855                         r = new StringBuilder(256);
8856                     } else {
8857                         r.append(' ');
8858                     }
8859                     r.append(s.info.name);
8860                 }
8861             }
8862             if (r != null) {
8863                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8864             }
8865
8866             N = pkg.receivers.size();
8867             r = null;
8868             for (i=0; i<N; i++) {
8869                 PackageParser.Activity a = pkg.receivers.get(i);
8870                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8871                         a.info.processName, pkg.applicationInfo.uid);
8872                 mReceivers.addActivity(a, "receiver");
8873                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8874                     if (r == null) {
8875                         r = new StringBuilder(256);
8876                     } else {
8877                         r.append(' ');
8878                     }
8879                     r.append(a.info.name);
8880                 }
8881             }
8882             if (r != null) {
8883                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8884             }
8885
8886             N = pkg.activities.size();
8887             r = null;
8888             for (i=0; i<N; i++) {
8889                 PackageParser.Activity a = pkg.activities.get(i);
8890                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8891                         a.info.processName, pkg.applicationInfo.uid);
8892                 mActivities.addActivity(a, "activity");
8893                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8894                     if (r == null) {
8895                         r = new StringBuilder(256);
8896                     } else {
8897                         r.append(' ');
8898                     }
8899                     r.append(a.info.name);
8900                 }
8901             }
8902             if (r != null) {
8903                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8904             }
8905
8906             N = pkg.permissionGroups.size();
8907             r = null;
8908             for (i=0; i<N; i++) {
8909                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8910                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8911                 final String curPackageName = cur == null ? null : cur.info.packageName;
8912                 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8913                 if (cur == null || isPackageUpdate) {
8914                     mPermissionGroups.put(pg.info.name, pg);
8915                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8916                         if (r == null) {
8917                             r = new StringBuilder(256);
8918                         } else {
8919                             r.append(' ');
8920                         }
8921                         if (isPackageUpdate) {
8922                             r.append("UPD:");
8923                         }
8924                         r.append(pg.info.name);
8925                     }
8926                 } else {
8927                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8928                             + pg.info.packageName + " ignored: original from "
8929                             + cur.info.packageName);
8930                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8931                         if (r == null) {
8932                             r = new StringBuilder(256);
8933                         } else {
8934                             r.append(' ');
8935                         }
8936                         r.append("DUP:");
8937                         r.append(pg.info.name);
8938                     }
8939                 }
8940             }
8941             if (r != null) {
8942                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8943             }
8944
8945             N = pkg.permissions.size();
8946             r = null;
8947             for (i=0; i<N; i++) {
8948                 PackageParser.Permission p = pkg.permissions.get(i);
8949
8950                 // Assume by default that we did not install this permission into the system.
8951                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8952
8953                 // Now that permission groups have a special meaning, we ignore permission
8954                 // groups for legacy apps to prevent unexpected behavior. In particular,
8955                 // permissions for one app being granted to someone just becase they happen
8956                 // to be in a group defined by another app (before this had no implications).
8957                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8958                     p.group = mPermissionGroups.get(p.info.group);
8959                     // Warn for a permission in an unknown group.
8960                     if (p.info.group != null && p.group == null) {
8961                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8962                                 + p.info.packageName + " in an unknown group " + p.info.group);
8963                     }
8964                 }
8965
8966                 ArrayMap<String, BasePermission> permissionMap =
8967                         p.tree ? mSettings.mPermissionTrees
8968                                 : mSettings.mPermissions;
8969                 BasePermission bp = permissionMap.get(p.info.name);
8970
8971                 // Allow system apps to redefine non-system permissions
8972                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8973                     final boolean currentOwnerIsSystem = (bp.perm != null
8974                             && isSystemApp(bp.perm.owner));
8975                     if (isSystemApp(p.owner)) {
8976                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8977                             // It's a built-in permission and no owner, take ownership now
8978                             bp.packageSetting = pkgSetting;
8979                             bp.perm = p;
8980                             bp.uid = pkg.applicationInfo.uid;
8981                             bp.sourcePackage = p.info.packageName;
8982                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8983                         } else if (!currentOwnerIsSystem) {
8984                             String msg = "New decl " + p.owner + " of permission  "
8985                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
8986                             reportSettingsProblem(Log.WARN, msg);
8987                             bp = null;
8988                         }
8989                     }
8990                 }
8991
8992                 if (bp == null) {
8993                     bp = new BasePermission(p.info.name, p.info.packageName,
8994                             BasePermission.TYPE_NORMAL);
8995                     permissionMap.put(p.info.name, bp);
8996                 }
8997
8998                 if (bp.perm == null) {
8999                     if (bp.sourcePackage == null
9000                             || bp.sourcePackage.equals(p.info.packageName)) {
9001                         BasePermission tree = findPermissionTreeLP(p.info.name);
9002                         if (tree == null
9003                                 || tree.sourcePackage.equals(p.info.packageName)) {
9004                             bp.packageSetting = pkgSetting;
9005                             bp.perm = p;
9006                             bp.uid = pkg.applicationInfo.uid;
9007                             bp.sourcePackage = p.info.packageName;
9008                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9009                             if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9010                                 if (r == null) {
9011                                     r = new StringBuilder(256);
9012                                 } else {
9013                                     r.append(' ');
9014                                 }
9015                                 r.append(p.info.name);
9016                             }
9017                         } else {
9018                             Slog.w(TAG, "Permission " + p.info.name + " from package "
9019                                     + p.info.packageName + " ignored: base tree "
9020                                     + tree.name + " is from package "
9021                                     + tree.sourcePackage);
9022                         }
9023                     } else {
9024                         Slog.w(TAG, "Permission " + p.info.name + " from package "
9025                                 + p.info.packageName + " ignored: original from "
9026                                 + bp.sourcePackage);
9027                     }
9028                 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9029                     if (r == null) {
9030                         r = new StringBuilder(256);
9031                     } else {
9032                         r.append(' ');
9033                     }
9034                     r.append("DUP:");
9035                     r.append(p.info.name);
9036                 }
9037                 if (bp.perm == p) {
9038                     bp.protectionLevel = p.info.protectionLevel;
9039                 }
9040             }
9041
9042             if (r != null) {
9043                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9044             }
9045
9046             N = pkg.instrumentation.size();
9047             r = null;
9048             for (i=0; i<N; i++) {
9049                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9050                 a.info.packageName = pkg.applicationInfo.packageName;
9051                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
9052                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9053                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9054                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9055                 a.info.dataDir = pkg.applicationInfo.dataDir;
9056                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9057                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9058
9059                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9060                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9061                 mInstrumentation.put(a.getComponentName(), a);
9062                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9063                     if (r == null) {
9064                         r = new StringBuilder(256);
9065                     } else {
9066                         r.append(' ');
9067                     }
9068                     r.append(a.info.name);
9069                 }
9070             }
9071             if (r != null) {
9072                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9073             }
9074
9075             if (pkg.protectedBroadcasts != null) {
9076                 N = pkg.protectedBroadcasts.size();
9077                 for (i=0; i<N; i++) {
9078                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9079                 }
9080             }
9081
9082             pkgSetting.setTimeStamp(scanFileTime);
9083
9084             // Create idmap files for pairs of (packages, overlay packages).
9085             // Note: "android", ie framework-res.apk, is handled by native layers.
9086             if (pkg.mOverlayTarget != null) {
9087                 // This is an overlay package.
9088                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9089                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9090                         mOverlays.put(pkg.mOverlayTarget,
9091                                 new ArrayMap<String, PackageParser.Package>());
9092                     }
9093                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9094                     map.put(pkg.packageName, pkg);
9095                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9096                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9097                         createIdmapFailed = true;
9098                     }
9099                 }
9100             } else if (mOverlays.containsKey(pkg.packageName) &&
9101                     !pkg.packageName.equals("android")) {
9102                 // This is a regular package, with one or more known overlay packages.
9103                 createIdmapsForPackageLI(pkg);
9104             }
9105
9106             if (oldPkg != null) {
9107                 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
9108                 // revokation from this method might need to kill apps which need the
9109                 // mPackages lock on a different thread. This would dead lock.
9110                 //
9111                 // Hence create a copy of all package names and pass it into
9112                 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
9113                 // revoked. If a new package is added before the async code runs the permission
9114                 // won't be granted yet, hence new packages are no problem.
9115                 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
9116
9117                 AsyncTask.execute(new Runnable() {
9118                     public void run() {
9119                         revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, allPackageNames);
9120                     }
9121                 });
9122             }
9123         }
9124
9125         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9126
9127         if (createIdmapFailed) {
9128             throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9129                     "scanPackageLI failed to createIdmap");
9130         }
9131         return pkg;
9132     }
9133
9134     private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9135             PackageParser.Package update, UserHandle user) {
9136         if (existing.applicationInfo == null || update.applicationInfo == null) {
9137             // This isn't due to an app installation.
9138             return;
9139         }
9140
9141         final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9142         final File newCodePath = new File(update.applicationInfo.getCodePath());
9143
9144         // The codePath hasn't changed, so there's nothing for us to do.
9145         if (Objects.equals(oldCodePath, newCodePath)) {
9146             return;
9147         }
9148
9149         File canonicalNewCodePath;
9150         try {
9151             canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9152         } catch (IOException e) {
9153             Slog.w(TAG, "Failed to get canonical path.", e);
9154             return;
9155         }
9156
9157         // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9158         // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9159         // that the last component of the path (i.e, the name) doesn't need canonicalization
9160         // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9161         // but may change in the future. Hopefully this function won't exist at that point.
9162         final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9163                 oldCodePath.getName());
9164
9165         // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9166         // with "@".
9167         String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9168         if (!oldMarkerPrefix.endsWith("@")) {
9169             oldMarkerPrefix += "@";
9170         }
9171         String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9172         if (!newMarkerPrefix.endsWith("@")) {
9173             newMarkerPrefix += "@";
9174         }
9175
9176         List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9177         List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9178         for (String updatedPath : updatedPaths) {
9179             String updatedPathName = new File(updatedPath).getName();
9180             markerSuffixes.add(updatedPathName.replace('/', '@'));
9181         }
9182
9183         for (int userId : resolveUserIds(user.getIdentifier())) {
9184             File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9185
9186             for (String markerSuffix : markerSuffixes) {
9187                 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9188                 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9189                 if (oldForeignUseMark.exists()) {
9190                     try {
9191                         Os.rename(oldForeignUseMark.getAbsolutePath(),
9192                                 newForeignUseMark.getAbsolutePath());
9193                     } catch (ErrnoException e) {
9194                         Slog.w(TAG, "Failed to rename foreign use marker", e);
9195                         oldForeignUseMark.delete();
9196                     }
9197                 }
9198             }
9199         }
9200     }
9201
9202     /**
9203      * Derive the ABI of a non-system package located at {@code scanFile}. This information
9204      * is derived purely on the basis of the contents of {@code scanFile} and
9205      * {@code cpuAbiOverride}.
9206      *
9207      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9208      */
9209     private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9210                                  String cpuAbiOverride, boolean extractLibs)
9211             throws PackageManagerException {
9212         // TODO: We can probably be smarter about this stuff. For installed apps,
9213         // we can calculate this information at install time once and for all. For
9214         // system apps, we can probably assume that this information doesn't change
9215         // after the first boot scan. As things stand, we do lots of unnecessary work.
9216
9217         // Give ourselves some initial paths; we'll come back for another
9218         // pass once we've determined ABI below.
9219         setNativeLibraryPaths(pkg);
9220
9221         // We would never need to extract libs for forward-locked and external packages,
9222         // since the container service will do it for us. We shouldn't attempt to
9223         // extract libs from system app when it was not updated.
9224         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9225                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9226             extractLibs = false;
9227         }
9228
9229         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9230         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9231
9232         NativeLibraryHelper.Handle handle = null;
9233         try {
9234             handle = NativeLibraryHelper.Handle.create(pkg);
9235             // TODO(multiArch): This can be null for apps that didn't go through the
9236             // usual installation process. We can calculate it again, like we
9237             // do during install time.
9238             //
9239             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9240             // unnecessary.
9241             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9242
9243             // Null out the abis so that they can be recalculated.
9244             pkg.applicationInfo.primaryCpuAbi = null;
9245             pkg.applicationInfo.secondaryCpuAbi = null;
9246             if (isMultiArch(pkg.applicationInfo)) {
9247                 // Warn if we've set an abiOverride for multi-lib packages..
9248                 // By definition, we need to copy both 32 and 64 bit libraries for
9249                 // such packages.
9250                 if (pkg.cpuAbiOverride != null
9251                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9252                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9253                 }
9254
9255                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9256                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9257                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9258                     if (extractLibs) {
9259                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9260                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9261                                 useIsaSpecificSubdirs);
9262                     } else {
9263                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9264                     }
9265                 }
9266
9267                 maybeThrowExceptionForMultiArchCopy(
9268                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9269
9270                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9271                     if (extractLibs) {
9272                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9273                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9274                                 useIsaSpecificSubdirs);
9275                     } else {
9276                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9277                     }
9278                 }
9279
9280                 maybeThrowExceptionForMultiArchCopy(
9281                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9282
9283                 if (abi64 >= 0) {
9284                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9285                 }
9286
9287                 if (abi32 >= 0) {
9288                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9289                     if (abi64 >= 0) {
9290                         if (pkg.use32bitAbi) {
9291                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9292                             pkg.applicationInfo.primaryCpuAbi = abi;
9293                         } else {
9294                             pkg.applicationInfo.secondaryCpuAbi = abi;
9295                         }
9296                     } else {
9297                         pkg.applicationInfo.primaryCpuAbi = abi;
9298                     }
9299                 }
9300
9301             } else {
9302                 String[] abiList = (cpuAbiOverride != null) ?
9303                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9304
9305                 // Enable gross and lame hacks for apps that are built with old
9306                 // SDK tools. We must scan their APKs for renderscript bitcode and
9307                 // not launch them if it's present. Don't bother checking on devices
9308                 // that don't have 64 bit support.
9309                 boolean needsRenderScriptOverride = false;
9310                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9311                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9312                     abiList = Build.SUPPORTED_32_BIT_ABIS;
9313                     needsRenderScriptOverride = true;
9314                 }
9315
9316                 final int copyRet;
9317                 if (extractLibs) {
9318                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9319                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9320                 } else {
9321                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9322                 }
9323
9324                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9325                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9326                             "Error unpackaging native libs for app, errorCode=" + copyRet);
9327                 }
9328
9329                 if (copyRet >= 0) {
9330                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9331                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9332                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9333                 } else if (needsRenderScriptOverride) {
9334                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
9335                 }
9336             }
9337         } catch (IOException ioe) {
9338             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9339         } finally {
9340             IoUtils.closeQuietly(handle);
9341         }
9342
9343         // Now that we've calculated the ABIs and determined if it's an internal app,
9344         // we will go ahead and populate the nativeLibraryPath.
9345         setNativeLibraryPaths(pkg);
9346     }
9347
9348     /**
9349      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9350      * i.e, so that all packages can be run inside a single process if required.
9351      *
9352      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9353      * this function will either try and make the ABI for all packages in {@code packagesForUser}
9354      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9355      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9356      * updating a package that belongs to a shared user.
9357      *
9358      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9359      * adds unnecessary complexity.
9360      */
9361     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9362             PackageParser.Package scannedPackage, boolean bootComplete) {
9363         String requiredInstructionSet = null;
9364         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9365             requiredInstructionSet = VMRuntime.getInstructionSet(
9366                      scannedPackage.applicationInfo.primaryCpuAbi);
9367         }
9368
9369         PackageSetting requirer = null;
9370         for (PackageSetting ps : packagesForUser) {
9371             // If packagesForUser contains scannedPackage, we skip it. This will happen
9372             // when scannedPackage is an update of an existing package. Without this check,
9373             // we will never be able to change the ABI of any package belonging to a shared
9374             // user, even if it's compatible with other packages.
9375             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9376                 if (ps.primaryCpuAbiString == null) {
9377                     continue;
9378                 }
9379
9380                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9381                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9382                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
9383                     // this but there's not much we can do.
9384                     String errorMessage = "Instruction set mismatch, "
9385                             + ((requirer == null) ? "[caller]" : requirer)
9386                             + " requires " + requiredInstructionSet + " whereas " + ps
9387                             + " requires " + instructionSet;
9388                     Slog.w(TAG, errorMessage);
9389                 }
9390
9391                 if (requiredInstructionSet == null) {
9392                     requiredInstructionSet = instructionSet;
9393                     requirer = ps;
9394                 }
9395             }
9396         }
9397
9398         if (requiredInstructionSet != null) {
9399             String adjustedAbi;
9400             if (requirer != null) {
9401                 // requirer != null implies that either scannedPackage was null or that scannedPackage
9402                 // did not require an ABI, in which case we have to adjust scannedPackage to match
9403                 // the ABI of the set (which is the same as requirer's ABI)
9404                 adjustedAbi = requirer.primaryCpuAbiString;
9405                 if (scannedPackage != null) {
9406                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9407                 }
9408             } else {
9409                 // requirer == null implies that we're updating all ABIs in the set to
9410                 // match scannedPackage.
9411                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9412             }
9413
9414             for (PackageSetting ps : packagesForUser) {
9415                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9416                     if (ps.primaryCpuAbiString != null) {
9417                         continue;
9418                     }
9419
9420                     ps.primaryCpuAbiString = adjustedAbi;
9421                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9422                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9423                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9424                         Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9425                                 + " (requirer="
9426                                 + (requirer == null ? "null" : requirer.pkg.packageName)
9427                                 + ", scannedPackage="
9428                                 + (scannedPackage != null ? scannedPackage.packageName : "null")
9429                                 + ")");
9430                         try {
9431                             mInstaller.rmdex(ps.codePathString,
9432                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
9433                         } catch (InstallerException ignored) {
9434                         }
9435                     }
9436                 }
9437             }
9438         }
9439     }
9440
9441     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9442         synchronized (mPackages) {
9443             mResolverReplaced = true;
9444             // Set up information for custom user intent resolution activity.
9445             mResolveActivity.applicationInfo = pkg.applicationInfo;
9446             mResolveActivity.name = mCustomResolverComponentName.getClassName();
9447             mResolveActivity.packageName = pkg.applicationInfo.packageName;
9448             mResolveActivity.processName = pkg.applicationInfo.packageName;
9449             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9450             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9451                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9452             mResolveActivity.theme = 0;
9453             mResolveActivity.exported = true;
9454             mResolveActivity.enabled = true;
9455             mResolveInfo.activityInfo = mResolveActivity;
9456             mResolveInfo.priority = 0;
9457             mResolveInfo.preferredOrder = 0;
9458             mResolveInfo.match = 0;
9459             mResolveComponentName = mCustomResolverComponentName;
9460             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9461                     mResolveComponentName);
9462         }
9463     }
9464
9465     private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9466         final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9467
9468         // Set up information for ephemeral installer activity
9469         mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9470         mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9471         mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9472         mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9473         mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9474         mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9475                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9476         mEphemeralInstallerActivity.theme = 0;
9477         mEphemeralInstallerActivity.exported = true;
9478         mEphemeralInstallerActivity.enabled = true;
9479         mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9480         mEphemeralInstallerInfo.priority = 0;
9481         mEphemeralInstallerInfo.preferredOrder = 1;
9482         mEphemeralInstallerInfo.isDefault = true;
9483         mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9484                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9485
9486         if (DEBUG_EPHEMERAL) {
9487             Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9488         }
9489     }
9490
9491     private static String calculateBundledApkRoot(final String codePathString) {
9492         final File codePath = new File(codePathString);
9493         final File codeRoot;
9494         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9495             codeRoot = Environment.getRootDirectory();
9496         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9497             codeRoot = Environment.getOemDirectory();
9498         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9499             codeRoot = Environment.getVendorDirectory();
9500         } else {
9501             // Unrecognized code path; take its top real segment as the apk root:
9502             // e.g. /something/app/blah.apk => /something
9503             try {
9504                 File f = codePath.getCanonicalFile();
9505                 File parent = f.getParentFile();    // non-null because codePath is a file
9506                 File tmp;
9507                 while ((tmp = parent.getParentFile()) != null) {
9508                     f = parent;
9509                     parent = tmp;
9510                 }
9511                 codeRoot = f;
9512                 Slog.w(TAG, "Unrecognized code path "
9513                         + codePath + " - using " + codeRoot);
9514             } catch (IOException e) {
9515                 // Can't canonicalize the code path -- shenanigans?
9516                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9517                 return Environment.getRootDirectory().getPath();
9518             }
9519         }
9520         return codeRoot.getPath();
9521     }
9522
9523     /**
9524      * Derive and set the location of native libraries for the given package,
9525      * which varies depending on where and how the package was installed.
9526      */
9527     private void setNativeLibraryPaths(PackageParser.Package pkg) {
9528         final ApplicationInfo info = pkg.applicationInfo;
9529         final String codePath = pkg.codePath;
9530         final File codeFile = new File(codePath);
9531         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9532         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9533
9534         info.nativeLibraryRootDir = null;
9535         info.nativeLibraryRootRequiresIsa = false;
9536         info.nativeLibraryDir = null;
9537         info.secondaryNativeLibraryDir = null;
9538
9539         if (isApkFile(codeFile)) {
9540             // Monolithic install
9541             if (bundledApp) {
9542                 // If "/system/lib64/apkname" exists, assume that is the per-package
9543                 // native library directory to use; otherwise use "/system/lib/apkname".
9544                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9545                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9546                         getPrimaryInstructionSet(info));
9547
9548                 // This is a bundled system app so choose the path based on the ABI.
9549                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9550                 // is just the default path.
9551                 final String apkName = deriveCodePathName(codePath);
9552                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9553                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9554                         apkName).getAbsolutePath();
9555
9556                 if (info.secondaryCpuAbi != null) {
9557                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9558                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9559                             secondaryLibDir, apkName).getAbsolutePath();
9560                 }
9561             } else if (asecApp) {
9562                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9563                         .getAbsolutePath();
9564             } else {
9565                 final String apkName = deriveCodePathName(codePath);
9566                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9567                         .getAbsolutePath();
9568             }
9569
9570             info.nativeLibraryRootRequiresIsa = false;
9571             info.nativeLibraryDir = info.nativeLibraryRootDir;
9572         } else {
9573             // Cluster install
9574             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9575             info.nativeLibraryRootRequiresIsa = true;
9576
9577             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9578                     getPrimaryInstructionSet(info)).getAbsolutePath();
9579
9580             if (info.secondaryCpuAbi != null) {
9581                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9582                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9583             }
9584         }
9585     }
9586
9587     /**
9588      * Calculate the abis and roots for a bundled app. These can uniquely
9589      * be determined from the contents of the system partition, i.e whether
9590      * it contains 64 or 32 bit shared libraries etc. We do not validate any
9591      * of this information, and instead assume that the system was built
9592      * sensibly.
9593      */
9594     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9595                                            PackageSetting pkgSetting) {
9596         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9597
9598         // If "/system/lib64/apkname" exists, assume that is the per-package
9599         // native library directory to use; otherwise use "/system/lib/apkname".
9600         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9601         setBundledAppAbi(pkg, apkRoot, apkName);
9602         // pkgSetting might be null during rescan following uninstall of updates
9603         // to a bundled app, so accommodate that possibility.  The settings in
9604         // that case will be established later from the parsed package.
9605         //
9606         // If the settings aren't null, sync them up with what we've just derived.
9607         // note that apkRoot isn't stored in the package settings.
9608         if (pkgSetting != null) {
9609             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9610             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9611         }
9612     }
9613
9614     /**
9615      * Deduces the ABI of a bundled app and sets the relevant fields on the
9616      * parsed pkg object.
9617      *
9618      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9619      *        under which system libraries are installed.
9620      * @param apkName the name of the installed package.
9621      */
9622     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9623         final File codeFile = new File(pkg.codePath);
9624
9625         final boolean has64BitLibs;
9626         final boolean has32BitLibs;
9627         if (isApkFile(codeFile)) {
9628             // Monolithic install
9629             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9630             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9631         } else {
9632             // Cluster install
9633             final File rootDir = new File(codeFile, LIB_DIR_NAME);
9634             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9635                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9636                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9637                 has64BitLibs = (new File(rootDir, isa)).exists();
9638             } else {
9639                 has64BitLibs = false;
9640             }
9641             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9642                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9643                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9644                 has32BitLibs = (new File(rootDir, isa)).exists();
9645             } else {
9646                 has32BitLibs = false;
9647             }
9648         }
9649
9650         if (has64BitLibs && !has32BitLibs) {
9651             // The package has 64 bit libs, but not 32 bit libs. Its primary
9652             // ABI should be 64 bit. We can safely assume here that the bundled
9653             // native libraries correspond to the most preferred ABI in the list.
9654
9655             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9656             pkg.applicationInfo.secondaryCpuAbi = null;
9657         } else if (has32BitLibs && !has64BitLibs) {
9658             // The package has 32 bit libs but not 64 bit libs. Its primary
9659             // ABI should be 32 bit.
9660
9661             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9662             pkg.applicationInfo.secondaryCpuAbi = null;
9663         } else if (has32BitLibs && has64BitLibs) {
9664             // The application has both 64 and 32 bit bundled libraries. We check
9665             // here that the app declares multiArch support, and warn if it doesn't.
9666             //
9667             // We will be lenient here and record both ABIs. The primary will be the
9668             // ABI that's higher on the list, i.e, a device that's configured to prefer
9669             // 64 bit apps will see a 64 bit primary ABI,
9670
9671             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9672                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9673             }
9674
9675             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9676                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9677                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9678             } else {
9679                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9680                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9681             }
9682         } else {
9683             pkg.applicationInfo.primaryCpuAbi = null;
9684             pkg.applicationInfo.secondaryCpuAbi = null;
9685         }
9686     }
9687
9688     private void killApplication(String pkgName, int appId, String reason) {
9689         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9690     }
9691
9692     private void killApplication(String pkgName, int appId, int userId, String reason) {
9693         // Request the ActivityManager to kill the process(only for existing packages)
9694         // so that we do not end up in a confused state while the user is still using the older
9695         // version of the application while the new one gets installed.
9696         final long token = Binder.clearCallingIdentity();
9697         try {
9698             IActivityManager am = ActivityManagerNative.getDefault();
9699             if (am != null) {
9700                 try {
9701                     am.killApplication(pkgName, appId, userId, reason);
9702                 } catch (RemoteException e) {
9703                 }
9704             }
9705         } finally {
9706             Binder.restoreCallingIdentity(token);
9707         }
9708     }
9709
9710     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9711         // Remove the parent package setting
9712         PackageSetting ps = (PackageSetting) pkg.mExtras;
9713         if (ps != null) {
9714             removePackageLI(ps, chatty);
9715         }
9716         // Remove the child package setting
9717         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9718         for (int i = 0; i < childCount; i++) {
9719             PackageParser.Package childPkg = pkg.childPackages.get(i);
9720             ps = (PackageSetting) childPkg.mExtras;
9721             if (ps != null) {
9722                 removePackageLI(ps, chatty);
9723             }
9724         }
9725     }
9726
9727     void removePackageLI(PackageSetting ps, boolean chatty) {
9728         if (DEBUG_INSTALL) {
9729             if (chatty)
9730                 Log.d(TAG, "Removing package " + ps.name);
9731         }
9732
9733         // writer
9734         synchronized (mPackages) {
9735             mPackages.remove(ps.name);
9736             final PackageParser.Package pkg = ps.pkg;
9737             if (pkg != null) {
9738                 cleanPackageDataStructuresLILPw(pkg, chatty);
9739             }
9740         }
9741     }
9742
9743     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9744         if (DEBUG_INSTALL) {
9745             if (chatty)
9746                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9747         }
9748
9749         // writer
9750         synchronized (mPackages) {
9751             // Remove the parent package
9752             mPackages.remove(pkg.applicationInfo.packageName);
9753             cleanPackageDataStructuresLILPw(pkg, chatty);
9754
9755             // Remove the child packages
9756             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9757             for (int i = 0; i < childCount; i++) {
9758                 PackageParser.Package childPkg = pkg.childPackages.get(i);
9759                 mPackages.remove(childPkg.applicationInfo.packageName);
9760                 cleanPackageDataStructuresLILPw(childPkg, chatty);
9761             }
9762         }
9763     }
9764
9765     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9766         int N = pkg.providers.size();
9767         StringBuilder r = null;
9768         int i;
9769         for (i=0; i<N; i++) {
9770             PackageParser.Provider p = pkg.providers.get(i);
9771             mProviders.removeProvider(p);
9772             if (p.info.authority == null) {
9773
9774                 /* There was another ContentProvider with this authority when
9775                  * this app was installed so this authority is null,
9776                  * Ignore it as we don't have to unregister the provider.
9777                  */
9778                 continue;
9779             }
9780             String names[] = p.info.authority.split(";");
9781             for (int j = 0; j < names.length; j++) {
9782                 if (mProvidersByAuthority.get(names[j]) == p) {
9783                     mProvidersByAuthority.remove(names[j]);
9784                     if (DEBUG_REMOVE) {
9785                         if (chatty)
9786                             Log.d(TAG, "Unregistered content provider: " + names[j]
9787                                     + ", className = " + p.info.name + ", isSyncable = "
9788                                     + p.info.isSyncable);
9789                     }
9790                 }
9791             }
9792             if (DEBUG_REMOVE && chatty) {
9793                 if (r == null) {
9794                     r = new StringBuilder(256);
9795                 } else {
9796                     r.append(' ');
9797                 }
9798                 r.append(p.info.name);
9799             }
9800         }
9801         if (r != null) {
9802             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9803         }
9804
9805         N = pkg.services.size();
9806         r = null;
9807         for (i=0; i<N; i++) {
9808             PackageParser.Service s = pkg.services.get(i);
9809             mServices.removeService(s);
9810             if (chatty) {
9811                 if (r == null) {
9812                     r = new StringBuilder(256);
9813                 } else {
9814                     r.append(' ');
9815                 }
9816                 r.append(s.info.name);
9817             }
9818         }
9819         if (r != null) {
9820             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9821         }
9822
9823         N = pkg.receivers.size();
9824         r = null;
9825         for (i=0; i<N; i++) {
9826             PackageParser.Activity a = pkg.receivers.get(i);
9827             mReceivers.removeActivity(a, "receiver");
9828             if (DEBUG_REMOVE && chatty) {
9829                 if (r == null) {
9830                     r = new StringBuilder(256);
9831                 } else {
9832                     r.append(' ');
9833                 }
9834                 r.append(a.info.name);
9835             }
9836         }
9837         if (r != null) {
9838             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9839         }
9840
9841         N = pkg.activities.size();
9842         r = null;
9843         for (i=0; i<N; i++) {
9844             PackageParser.Activity a = pkg.activities.get(i);
9845             mActivities.removeActivity(a, "activity");
9846             if (DEBUG_REMOVE && chatty) {
9847                 if (r == null) {
9848                     r = new StringBuilder(256);
9849                 } else {
9850                     r.append(' ');
9851                 }
9852                 r.append(a.info.name);
9853             }
9854         }
9855         if (r != null) {
9856             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9857         }
9858
9859         N = pkg.permissions.size();
9860         r = null;
9861         for (i=0; i<N; i++) {
9862             PackageParser.Permission p = pkg.permissions.get(i);
9863             BasePermission bp = mSettings.mPermissions.get(p.info.name);
9864             if (bp == null) {
9865                 bp = mSettings.mPermissionTrees.get(p.info.name);
9866             }
9867             if (bp != null && bp.perm == p) {
9868                 bp.perm = null;
9869                 if (DEBUG_REMOVE && chatty) {
9870                     if (r == null) {
9871                         r = new StringBuilder(256);
9872                     } else {
9873                         r.append(' ');
9874                     }
9875                     r.append(p.info.name);
9876                 }
9877             }
9878             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9879                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9880                 if (appOpPkgs != null) {
9881                     appOpPkgs.remove(pkg.packageName);
9882                 }
9883             }
9884         }
9885         if (r != null) {
9886             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9887         }
9888
9889         N = pkg.requestedPermissions.size();
9890         r = null;
9891         for (i=0; i<N; i++) {
9892             String perm = pkg.requestedPermissions.get(i);
9893             BasePermission bp = mSettings.mPermissions.get(perm);
9894             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9895                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9896                 if (appOpPkgs != null) {
9897                     appOpPkgs.remove(pkg.packageName);
9898                     if (appOpPkgs.isEmpty()) {
9899                         mAppOpPermissionPackages.remove(perm);
9900                     }
9901                 }
9902             }
9903         }
9904         if (r != null) {
9905             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9906         }
9907
9908         N = pkg.instrumentation.size();
9909         r = null;
9910         for (i=0; i<N; i++) {
9911             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9912             mInstrumentation.remove(a.getComponentName());
9913             if (DEBUG_REMOVE && chatty) {
9914                 if (r == null) {
9915                     r = new StringBuilder(256);
9916                 } else {
9917                     r.append(' ');
9918                 }
9919                 r.append(a.info.name);
9920             }
9921         }
9922         if (r != null) {
9923             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9924         }
9925
9926         r = null;
9927         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9928             // Only system apps can hold shared libraries.
9929             if (pkg.libraryNames != null) {
9930                 for (i=0; i<pkg.libraryNames.size(); i++) {
9931                     String name = pkg.libraryNames.get(i);
9932                     SharedLibraryEntry cur = mSharedLibraries.get(name);
9933                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9934                         mSharedLibraries.remove(name);
9935                         if (DEBUG_REMOVE && chatty) {
9936                             if (r == null) {
9937                                 r = new StringBuilder(256);
9938                             } else {
9939                                 r.append(' ');
9940                             }
9941                             r.append(name);
9942                         }
9943                     }
9944                 }
9945             }
9946         }
9947         if (r != null) {
9948             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9949         }
9950     }
9951
9952     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9953         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9954             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9955                 return true;
9956             }
9957         }
9958         return false;
9959     }
9960
9961     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9962     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9963     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9964
9965     private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9966         // Update the parent permissions
9967         updatePermissionsLPw(pkg.packageName, pkg, flags);
9968         // Update the child permissions
9969         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9970         for (int i = 0; i < childCount; i++) {
9971             PackageParser.Package childPkg = pkg.childPackages.get(i);
9972             updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9973         }
9974     }
9975
9976     private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9977             int flags) {
9978         final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9979         updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9980     }
9981
9982     private void updatePermissionsLPw(String changingPkg,
9983             PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9984         // Make sure there are no dangling permission trees.
9985         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9986         while (it.hasNext()) {
9987             final BasePermission bp = it.next();
9988             if (bp.packageSetting == null) {
9989                 // We may not yet have parsed the package, so just see if
9990                 // we still know about its settings.
9991                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9992             }
9993             if (bp.packageSetting == null) {
9994                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9995                         + " from package " + bp.sourcePackage);
9996                 it.remove();
9997             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9998                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9999                     Slog.i(TAG, "Removing old permission tree: " + bp.name
10000                             + " from package " + bp.sourcePackage);
10001                     flags |= UPDATE_PERMISSIONS_ALL;
10002                     it.remove();
10003                 }
10004             }
10005         }
10006
10007         // Make sure all dynamic permissions have been assigned to a package,
10008         // and make sure there are no dangling permissions.
10009         it = mSettings.mPermissions.values().iterator();
10010         while (it.hasNext()) {
10011             final BasePermission bp = it.next();
10012             if (bp.type == BasePermission.TYPE_DYNAMIC) {
10013                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10014                         + bp.name + " pkg=" + bp.sourcePackage
10015                         + " info=" + bp.pendingInfo);
10016                 if (bp.packageSetting == null && bp.pendingInfo != null) {
10017                     final BasePermission tree = findPermissionTreeLP(bp.name);
10018                     if (tree != null && tree.perm != null) {
10019                         bp.packageSetting = tree.packageSetting;
10020                         bp.perm = new PackageParser.Permission(tree.perm.owner,
10021                                 new PermissionInfo(bp.pendingInfo));
10022                         bp.perm.info.packageName = tree.perm.info.packageName;
10023                         bp.perm.info.name = bp.name;
10024                         bp.uid = tree.uid;
10025                     }
10026                 }
10027             }
10028             if (bp.packageSetting == null) {
10029                 // We may not yet have parsed the package, so just see if
10030                 // we still know about its settings.
10031                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10032             }
10033             if (bp.packageSetting == null) {
10034                 Slog.w(TAG, "Removing dangling permission: " + bp.name
10035                         + " from package " + bp.sourcePackage);
10036                 it.remove();
10037             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10038                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10039                     Slog.i(TAG, "Removing old permission: " + bp.name
10040                             + " from package " + bp.sourcePackage);
10041                     flags |= UPDATE_PERMISSIONS_ALL;
10042                     it.remove();
10043                 }
10044             }
10045         }
10046
10047         // Now update the permissions for all packages, in particular
10048         // replace the granted permissions of the system packages.
10049         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10050             for (PackageParser.Package pkg : mPackages.values()) {
10051                 if (pkg != pkgInfo) {
10052                     // Only replace for packages on requested volume
10053                     final String volumeUuid = getVolumeUuidForPackage(pkg);
10054                     final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10055                             && Objects.equals(replaceVolumeUuid, volumeUuid);
10056                     grantPermissionsLPw(pkg, replace, changingPkg);
10057                 }
10058             }
10059         }
10060
10061         if (pkgInfo != null) {
10062             // Only replace for packages on requested volume
10063             final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10064             final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10065                     && Objects.equals(replaceVolumeUuid, volumeUuid);
10066             grantPermissionsLPw(pkgInfo, replace, changingPkg);
10067         }
10068     }
10069
10070     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10071             String packageOfInterest) {
10072         // IMPORTANT: There are two types of permissions: install and runtime.
10073         // Install time permissions are granted when the app is installed to
10074         // all device users and users added in the future. Runtime permissions
10075         // are granted at runtime explicitly to specific users. Normal and signature
10076         // protected permissions are install time permissions. Dangerous permissions
10077         // are install permissions if the app's target SDK is Lollipop MR1 or older,
10078         // otherwise they are runtime permissions. This function does not manage
10079         // runtime permissions except for the case an app targeting Lollipop MR1
10080         // being upgraded to target a newer SDK, in which case dangerous permissions
10081         // are transformed from install time to runtime ones.
10082
10083         final PackageSetting ps = (PackageSetting) pkg.mExtras;
10084         if (ps == null) {
10085             return;
10086         }
10087
10088         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10089
10090         PermissionsState permissionsState = ps.getPermissionsState();
10091         PermissionsState origPermissions = permissionsState;
10092
10093         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10094
10095         boolean runtimePermissionsRevoked = false;
10096         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10097
10098         boolean changedInstallPermission = false;
10099
10100         if (replace) {
10101             ps.installPermissionsFixed = false;
10102             if (!ps.isSharedUser()) {
10103                 origPermissions = new PermissionsState(permissionsState);
10104                 permissionsState.reset();
10105             } else {
10106                 // We need to know only about runtime permission changes since the
10107                 // calling code always writes the install permissions state but
10108                 // the runtime ones are written only if changed. The only cases of
10109                 // changed runtime permissions here are promotion of an install to
10110                 // runtime and revocation of a runtime from a shared user.
10111                 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10112                         ps.sharedUser, UserManagerService.getInstance().getUserIds());
10113                 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10114                     runtimePermissionsRevoked = true;
10115                 }
10116             }
10117         }
10118
10119         permissionsState.setGlobalGids(mGlobalGids);
10120
10121         final int N = pkg.requestedPermissions.size();
10122         for (int i=0; i<N; i++) {
10123             final String name = pkg.requestedPermissions.get(i);
10124             final BasePermission bp = mSettings.mPermissions.get(name);
10125
10126             if (DEBUG_INSTALL) {
10127                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10128             }
10129
10130             if (bp == null || bp.packageSetting == null) {
10131                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10132                     Slog.w(TAG, "Unknown permission " + name
10133                             + " in package " + pkg.packageName);
10134                 }
10135                 continue;
10136             }
10137
10138             final String perm = bp.name;
10139             boolean allowedSig = false;
10140             int grant = GRANT_DENIED;
10141
10142             // Keep track of app op permissions.
10143             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10144                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10145                 if (pkgs == null) {
10146                     pkgs = new ArraySet<>();
10147                     mAppOpPermissionPackages.put(bp.name, pkgs);
10148                 }
10149                 pkgs.add(pkg.packageName);
10150             }
10151
10152             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10153             final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10154                     >= Build.VERSION_CODES.M;
10155             switch (level) {
10156                 case PermissionInfo.PROTECTION_NORMAL: {
10157                     // For all apps normal permissions are install time ones.
10158                     grant = GRANT_INSTALL;
10159                 } break;
10160
10161                 case PermissionInfo.PROTECTION_DANGEROUS: {
10162                     // If a permission review is required for legacy apps we represent
10163                     // their permissions as always granted runtime ones since we need
10164                     // to keep the review required permission flag per user while an
10165                     // install permission's state is shared across all users.
10166                     if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10167                             && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10168                         // For legacy apps dangerous permissions are install time ones.
10169                         grant = GRANT_INSTALL;
10170                     } else if (origPermissions.hasInstallPermission(bp.name)) {
10171                         // For legacy apps that became modern, install becomes runtime.
10172                         grant = GRANT_UPGRADE;
10173                     } else if (mPromoteSystemApps
10174                             && isSystemApp(ps)
10175                             && mExistingSystemPackages.contains(ps.name)) {
10176                         // For legacy system apps, install becomes runtime.
10177                         // We cannot check hasInstallPermission() for system apps since those
10178                         // permissions were granted implicitly and not persisted pre-M.
10179                         grant = GRANT_UPGRADE;
10180                     } else {
10181                         // For modern apps keep runtime permissions unchanged.
10182                         grant = GRANT_RUNTIME;
10183                     }
10184                 } break;
10185
10186                 case PermissionInfo.PROTECTION_SIGNATURE: {
10187                     // For all apps signature permissions are install time ones.
10188                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10189                     if (allowedSig) {
10190                         grant = GRANT_INSTALL;
10191                     }
10192                 } break;
10193             }
10194
10195             if (DEBUG_INSTALL) {
10196                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10197             }
10198
10199             if (grant != GRANT_DENIED) {
10200                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10201                     // If this is an existing, non-system package, then
10202                     // we can't add any new permissions to it.
10203                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10204                         // Except...  if this is a permission that was added
10205                         // to the platform (note: need to only do this when
10206                         // updating the platform).
10207                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10208                             grant = GRANT_DENIED;
10209                         }
10210                     }
10211                 }
10212
10213                 switch (grant) {
10214                     case GRANT_INSTALL: {
10215                         // Revoke this as runtime permission to handle the case of
10216                         // a runtime permission being downgraded to an install one.
10217                         // Also in permission review mode we keep dangerous permissions
10218                         // for legacy apps
10219                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10220                             if (origPermissions.getRuntimePermissionState(
10221                                     bp.name, userId) != null) {
10222                                 // Revoke the runtime permission and clear the flags.
10223                                 origPermissions.revokeRuntimePermission(bp, userId);
10224                                 origPermissions.updatePermissionFlags(bp, userId,
10225                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
10226                                 // If we revoked a permission permission, we have to write.
10227                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10228                                         changedRuntimePermissionUserIds, userId);
10229                             }
10230                         }
10231                         // Grant an install permission.
10232                         if (permissionsState.grantInstallPermission(bp) !=
10233                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10234                             changedInstallPermission = true;
10235                         }
10236                     } break;
10237
10238                     case GRANT_RUNTIME: {
10239                         // Grant previously granted runtime permissions.
10240                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10241                             PermissionState permissionState = origPermissions
10242                                     .getRuntimePermissionState(bp.name, userId);
10243                             int flags = permissionState != null
10244                                     ? permissionState.getFlags() : 0;
10245                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10246                                 // Don't propagate the permission in a permission review mode if
10247                                 // the former was revoked, i.e. marked to not propagate on upgrade.
10248                                 // Note that in a permission review mode install permissions are
10249                                 // represented as constantly granted runtime ones since we need to
10250                                 // keep a per user state associated with the permission. Also the
10251                                 // revoke on upgrade flag is no longer applicable and is reset.
10252                                 final boolean revokeOnUpgrade = (flags & PackageManager
10253                                         .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10254                                 if (revokeOnUpgrade) {
10255                                     flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10256                                     // Since we changed the flags, we have to write.
10257                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10258                                             changedRuntimePermissionUserIds, userId);
10259                                 }
10260                                 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10261                                     if (permissionsState.grantRuntimePermission(bp, userId) ==
10262                                             PermissionsState.PERMISSION_OPERATION_FAILURE) {
10263                                         // If we cannot put the permission as it was,
10264                                         // we have to write.
10265                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10266                                                 changedRuntimePermissionUserIds, userId);
10267                                     }
10268                                 }
10269
10270                                 // If the app supports runtime permissions no need for a review.
10271                                 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10272                                         && appSupportsRuntimePermissions
10273                                         && (flags & PackageManager
10274                                                 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10275                                     flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10276                                     // Since we changed the flags, we have to write.
10277                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10278                                             changedRuntimePermissionUserIds, userId);
10279                                 }
10280                             } else if ((mPermissionReviewRequired
10281                                         || Build.PERMISSIONS_REVIEW_REQUIRED)
10282                                     && !appSupportsRuntimePermissions) {
10283                                 // For legacy apps that need a permission review, every new
10284                                 // runtime permission is granted but it is pending a review.
10285                                 // We also need to review only platform defined runtime
10286                                 // permissions as these are the only ones the platform knows
10287                                 // how to disable the API to simulate revocation as legacy
10288                                 // apps don't expect to run with revoked permissions.
10289                                 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10290                                     if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10291                                         flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10292                                         // We changed the flags, hence have to write.
10293                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10294                                                 changedRuntimePermissionUserIds, userId);
10295                                     }
10296                                 }
10297                                 if (permissionsState.grantRuntimePermission(bp, userId)
10298                                         != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10299                                     // We changed the permission, hence have to write.
10300                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10301                                             changedRuntimePermissionUserIds, userId);
10302                                 }
10303                             }
10304                             // Propagate the permission flags.
10305                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10306                         }
10307                     } break;
10308
10309                     case GRANT_UPGRADE: {
10310                         // Grant runtime permissions for a previously held install permission.
10311                         PermissionState permissionState = origPermissions
10312                                 .getInstallPermissionState(bp.name);
10313                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
10314
10315                         if (origPermissions.revokeInstallPermission(bp)
10316                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10317                             // We will be transferring the permission flags, so clear them.
10318                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10319                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
10320                             changedInstallPermission = true;
10321                         }
10322
10323                         // If the permission is not to be promoted to runtime we ignore it and
10324                         // also its other flags as they are not applicable to install permissions.
10325                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10326                             for (int userId : currentUserIds) {
10327                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
10328                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10329                                     // Transfer the permission flags.
10330                                     permissionsState.updatePermissionFlags(bp, userId,
10331                                             flags, flags);
10332                                     // If we granted the permission, we have to write.
10333                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10334                                             changedRuntimePermissionUserIds, userId);
10335                                 }
10336                             }
10337                         }
10338                     } break;
10339
10340                     default: {
10341                         if (packageOfInterest == null
10342                                 || packageOfInterest.equals(pkg.packageName)) {
10343                             Slog.w(TAG, "Not granting permission " + perm
10344                                     + " to package " + pkg.packageName
10345                                     + " because it was previously installed without");
10346                         }
10347                     } break;
10348                 }
10349             } else {
10350                 if (permissionsState.revokeInstallPermission(bp) !=
10351                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10352                     // Also drop the permission flags.
10353                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10354                             PackageManager.MASK_PERMISSION_FLAGS, 0);
10355                     changedInstallPermission = true;
10356                     Slog.i(TAG, "Un-granting permission " + perm
10357                             + " from package " + pkg.packageName
10358                             + " (protectionLevel=" + bp.protectionLevel
10359                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10360                             + ")");
10361                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10362                     // Don't print warning for app op permissions, since it is fine for them
10363                     // not to be granted, there is a UI for the user to decide.
10364                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10365                         Slog.w(TAG, "Not granting permission " + perm
10366                                 + " to package " + pkg.packageName
10367                                 + " (protectionLevel=" + bp.protectionLevel
10368                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10369                                 + ")");
10370                     }
10371                 }
10372             }
10373         }
10374
10375         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10376                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10377             // This is the first that we have heard about this package, so the
10378             // permissions we have now selected are fixed until explicitly
10379             // changed.
10380             ps.installPermissionsFixed = true;
10381         }
10382
10383         // Persist the runtime permissions state for users with changes. If permissions
10384         // were revoked because no app in the shared user declares them we have to
10385         // write synchronously to avoid losing runtime permissions state.
10386         for (int userId : changedRuntimePermissionUserIds) {
10387             mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10388         }
10389
10390         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10391     }
10392
10393     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10394         boolean allowed = false;
10395         final int NP = PackageParser.NEW_PERMISSIONS.length;
10396         for (int ip=0; ip<NP; ip++) {
10397             final PackageParser.NewPermissionInfo npi
10398                     = PackageParser.NEW_PERMISSIONS[ip];
10399             if (npi.name.equals(perm)
10400                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10401                 allowed = true;
10402                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10403                         + pkg.packageName);
10404                 break;
10405             }
10406         }
10407         return allowed;
10408     }
10409
10410     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10411             BasePermission bp, PermissionsState origPermissions) {
10412         boolean allowed;
10413         allowed = (compareSignatures(
10414                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10415                         == PackageManager.SIGNATURE_MATCH)
10416                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10417                         == PackageManager.SIGNATURE_MATCH);
10418         if (!allowed && (bp.protectionLevel
10419                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10420             if (isSystemApp(pkg)) {
10421                 // For updated system applications, a system permission
10422                 // is granted only if it had been defined by the original application.
10423                 if (pkg.isUpdatedSystemApp()) {
10424                     final PackageSetting sysPs = mSettings
10425                             .getDisabledSystemPkgLPr(pkg.packageName);
10426                     if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10427                         // If the original was granted this permission, we take
10428                         // that grant decision as read and propagate it to the
10429                         // update.
10430                         if (sysPs.isPrivileged()) {
10431                             allowed = true;
10432                         }
10433                     } else {
10434                         // The system apk may have been updated with an older
10435                         // version of the one on the data partition, but which
10436                         // granted a new system permission that it didn't have
10437                         // before.  In this case we do want to allow the app to
10438                         // now get the new permission if the ancestral apk is
10439                         // privileged to get it.
10440                         if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10441                             for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10442                                 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10443                                     allowed = true;
10444                                     break;
10445                                 }
10446                             }
10447                         }
10448                         // Also if a privileged parent package on the system image or any of
10449                         // its children requested a privileged permission, the updated child
10450                         // packages can also get the permission.
10451                         if (pkg.parentPackage != null) {
10452                             final PackageSetting disabledSysParentPs = mSettings
10453                                     .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10454                             if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10455                                     && disabledSysParentPs.isPrivileged()) {
10456                                 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10457                                     allowed = true;
10458                                 } else if (disabledSysParentPs.pkg.childPackages != null) {
10459                                     final int count = disabledSysParentPs.pkg.childPackages.size();
10460                                     for (int i = 0; i < count; i++) {
10461                                         PackageParser.Package disabledSysChildPkg =
10462                                                 disabledSysParentPs.pkg.childPackages.get(i);
10463                                         if (isPackageRequestingPermission(disabledSysChildPkg,
10464                                                 perm)) {
10465                                             allowed = true;
10466                                             break;
10467                                         }
10468                                     }
10469                                 }
10470                             }
10471                         }
10472                     }
10473                 } else {
10474                     allowed = isPrivilegedApp(pkg);
10475                 }
10476             }
10477         }
10478         if (!allowed) {
10479             if (!allowed && (bp.protectionLevel
10480                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10481                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10482                 // If this was a previously normal/dangerous permission that got moved
10483                 // to a system permission as part of the runtime permission redesign, then
10484                 // we still want to blindly grant it to old apps.
10485                 allowed = true;
10486             }
10487             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10488                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
10489                 // If this permission is to be granted to the system installer and
10490                 // this app is an installer, then it gets the permission.
10491                 allowed = true;
10492             }
10493             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10494                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
10495                 // If this permission is to be granted to the system verifier and
10496                 // this app is a verifier, then it gets the permission.
10497                 allowed = true;
10498             }
10499             if (!allowed && (bp.protectionLevel
10500                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10501                     && isSystemApp(pkg)) {
10502                 // Any pre-installed system app is allowed to get this permission.
10503                 allowed = true;
10504             }
10505             if (!allowed && (bp.protectionLevel
10506                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10507                 // For development permissions, a development permission
10508                 // is granted only if it was already granted.
10509                 allowed = origPermissions.hasInstallPermission(perm);
10510             }
10511             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10512                     && pkg.packageName.equals(mSetupWizardPackage)) {
10513                 // If this permission is to be granted to the system setup wizard and
10514                 // this app is a setup wizard, then it gets the permission.
10515                 allowed = true;
10516             }
10517         }
10518         return allowed;
10519     }
10520
10521     private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10522         final int permCount = pkg.requestedPermissions.size();
10523         for (int j = 0; j < permCount; j++) {
10524             String requestedPermission = pkg.requestedPermissions.get(j);
10525             if (permission.equals(requestedPermission)) {
10526                 return true;
10527             }
10528         }
10529         return false;
10530     }
10531
10532     final class ActivityIntentResolver
10533             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10534         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10535                 boolean defaultOnly, int userId) {
10536             if (!sUserManager.exists(userId)) return null;
10537             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10538             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10539         }
10540
10541         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10542                 int userId) {
10543             if (!sUserManager.exists(userId)) return null;
10544             mFlags = flags;
10545             return super.queryIntent(intent, resolvedType,
10546                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10547         }
10548
10549         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10550                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10551             if (!sUserManager.exists(userId)) return null;
10552             if (packageActivities == null) {
10553                 return null;
10554             }
10555             mFlags = flags;
10556             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10557             final int N = packageActivities.size();
10558             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10559                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10560
10561             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10562             for (int i = 0; i < N; ++i) {
10563                 intentFilters = packageActivities.get(i).intents;
10564                 if (intentFilters != null && intentFilters.size() > 0) {
10565                     PackageParser.ActivityIntentInfo[] array =
10566                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
10567                     intentFilters.toArray(array);
10568                     listCut.add(array);
10569                 }
10570             }
10571             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10572         }
10573
10574         /**
10575          * Finds a privileged activity that matches the specified activity names.
10576          */
10577         private PackageParser.Activity findMatchingActivity(
10578                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10579             for (PackageParser.Activity sysActivity : activityList) {
10580                 if (sysActivity.info.name.equals(activityInfo.name)) {
10581                     return sysActivity;
10582                 }
10583                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10584                     return sysActivity;
10585                 }
10586                 if (sysActivity.info.targetActivity != null) {
10587                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10588                         return sysActivity;
10589                     }
10590                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10591                         return sysActivity;
10592                     }
10593                 }
10594             }
10595             return null;
10596         }
10597
10598         public class IterGenerator<E> {
10599             public Iterator<E> generate(ActivityIntentInfo info) {
10600                 return null;
10601             }
10602         }
10603
10604         public class ActionIterGenerator extends IterGenerator<String> {
10605             @Override
10606             public Iterator<String> generate(ActivityIntentInfo info) {
10607                 return info.actionsIterator();
10608             }
10609         }
10610
10611         public class CategoriesIterGenerator extends IterGenerator<String> {
10612             @Override
10613             public Iterator<String> generate(ActivityIntentInfo info) {
10614                 return info.categoriesIterator();
10615             }
10616         }
10617
10618         public class SchemesIterGenerator extends IterGenerator<String> {
10619             @Override
10620             public Iterator<String> generate(ActivityIntentInfo info) {
10621                 return info.schemesIterator();
10622             }
10623         }
10624
10625         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10626             @Override
10627             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10628                 return info.authoritiesIterator();
10629             }
10630         }
10631
10632         /**
10633          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10634          * MODIFIED. Do not pass in a list that should not be changed.
10635          */
10636         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10637                 IterGenerator<T> generator, Iterator<T> searchIterator) {
10638             // loop through the set of actions; every one must be found in the intent filter
10639             while (searchIterator.hasNext()) {
10640                 // we must have at least one filter in the list to consider a match
10641                 if (intentList.size() == 0) {
10642                     break;
10643                 }
10644
10645                 final T searchAction = searchIterator.next();
10646
10647                 // loop through the set of intent filters
10648                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10649                 while (intentIter.hasNext()) {
10650                     final ActivityIntentInfo intentInfo = intentIter.next();
10651                     boolean selectionFound = false;
10652
10653                     // loop through the intent filter's selection criteria; at least one
10654                     // of them must match the searched criteria
10655                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10656                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10657                         final T intentSelection = intentSelectionIter.next();
10658                         if (intentSelection != null && intentSelection.equals(searchAction)) {
10659                             selectionFound = true;
10660                             break;
10661                         }
10662                     }
10663
10664                     // the selection criteria wasn't found in this filter's set; this filter
10665                     // is not a potential match
10666                     if (!selectionFound) {
10667                         intentIter.remove();
10668                     }
10669                 }
10670             }
10671         }
10672
10673         private boolean isProtectedAction(ActivityIntentInfo filter) {
10674             final Iterator<String> actionsIter = filter.actionsIterator();
10675             while (actionsIter != null && actionsIter.hasNext()) {
10676                 final String filterAction = actionsIter.next();
10677                 if (PROTECTED_ACTIONS.contains(filterAction)) {
10678                     return true;
10679                 }
10680             }
10681             return false;
10682         }
10683
10684         /**
10685          * Adjusts the priority of the given intent filter according to policy.
10686          * <p>
10687          * <ul>
10688          * <li>The priority for non privileged applications is capped to '0'</li>
10689          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10690          * <li>The priority for unbundled updates to privileged applications is capped to the
10691          *      priority defined on the system partition</li>
10692          * </ul>
10693          * <p>
10694          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10695          * allowed to obtain any priority on any action.
10696          */
10697         private void adjustPriority(
10698                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10699             // nothing to do; priority is fine as-is
10700             if (intent.getPriority() <= 0) {
10701                 return;
10702             }
10703
10704             final ActivityInfo activityInfo = intent.activity.info;
10705             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10706
10707             final boolean privilegedApp =
10708                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10709             if (!privilegedApp) {
10710                 // non-privileged applications can never define a priority >0
10711                 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10712                         + " package: " + applicationInfo.packageName
10713                         + " activity: " + intent.activity.className
10714                         + " origPrio: " + intent.getPriority());
10715                 intent.setPriority(0);
10716                 return;
10717             }
10718
10719             if (systemActivities == null) {
10720                 // the system package is not disabled; we're parsing the system partition
10721                 if (isProtectedAction(intent)) {
10722                     if (mDeferProtectedFilters) {
10723                         // We can't deal with these just yet. No component should ever obtain a
10724                         // >0 priority for a protected actions, with ONE exception -- the setup
10725                         // wizard. The setup wizard, however, cannot be known until we're able to
10726                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10727                         // until all intent filters have been processed. Chicken, meet egg.
10728                         // Let the filter temporarily have a high priority and rectify the
10729                         // priorities after all system packages have been scanned.
10730                         mProtectedFilters.add(intent);
10731                         if (DEBUG_FILTERS) {
10732                             Slog.i(TAG, "Protected action; save for later;"
10733                                     + " package: " + applicationInfo.packageName
10734                                     + " activity: " + intent.activity.className
10735                                     + " origPrio: " + intent.getPriority());
10736                         }
10737                         return;
10738                     } else {
10739                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10740                             Slog.i(TAG, "No setup wizard;"
10741                                 + " All protected intents capped to priority 0");
10742                         }
10743                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10744                             if (DEBUG_FILTERS) {
10745                                 Slog.i(TAG, "Found setup wizard;"
10746                                     + " allow priority " + intent.getPriority() + ";"
10747                                     + " package: " + intent.activity.info.packageName
10748                                     + " activity: " + intent.activity.className
10749                                     + " priority: " + intent.getPriority());
10750                             }
10751                             // setup wizard gets whatever it wants
10752                             return;
10753                         }
10754                         Slog.w(TAG, "Protected action; cap priority to 0;"
10755                                 + " package: " + intent.activity.info.packageName
10756                                 + " activity: " + intent.activity.className
10757                                 + " origPrio: " + intent.getPriority());
10758                         intent.setPriority(0);
10759                         return;
10760                     }
10761                 }
10762                 // privileged apps on the system image get whatever priority they request
10763                 return;
10764             }
10765
10766             // privileged app unbundled update ... try to find the same activity
10767             final PackageParser.Activity foundActivity =
10768                     findMatchingActivity(systemActivities, activityInfo);
10769             if (foundActivity == null) {
10770                 // this is a new activity; it cannot obtain >0 priority
10771                 if (DEBUG_FILTERS) {
10772                     Slog.i(TAG, "New activity; cap priority to 0;"
10773                             + " package: " + applicationInfo.packageName
10774                             + " activity: " + intent.activity.className
10775                             + " origPrio: " + intent.getPriority());
10776                 }
10777                 intent.setPriority(0);
10778                 return;
10779             }
10780
10781             // found activity, now check for filter equivalence
10782
10783             // a shallow copy is enough; we modify the list, not its contents
10784             final List<ActivityIntentInfo> intentListCopy =
10785                     new ArrayList<>(foundActivity.intents);
10786             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10787
10788             // find matching action subsets
10789             final Iterator<String> actionsIterator = intent.actionsIterator();
10790             if (actionsIterator != null) {
10791                 getIntentListSubset(
10792                         intentListCopy, new ActionIterGenerator(), actionsIterator);
10793                 if (intentListCopy.size() == 0) {
10794                     // no more intents to match; we're not equivalent
10795                     if (DEBUG_FILTERS) {
10796                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
10797                                 + " package: " + applicationInfo.packageName
10798                                 + " activity: " + intent.activity.className
10799                                 + " origPrio: " + intent.getPriority());
10800                     }
10801                     intent.setPriority(0);
10802                     return;
10803                 }
10804             }
10805
10806             // find matching category subsets
10807             final Iterator<String> categoriesIterator = intent.categoriesIterator();
10808             if (categoriesIterator != null) {
10809                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10810                         categoriesIterator);
10811                 if (intentListCopy.size() == 0) {
10812                     // no more intents to match; we're not equivalent
10813                     if (DEBUG_FILTERS) {
10814                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
10815                                 + " package: " + applicationInfo.packageName
10816                                 + " activity: " + intent.activity.className
10817                                 + " origPrio: " + intent.getPriority());
10818                     }
10819                     intent.setPriority(0);
10820                     return;
10821                 }
10822             }
10823
10824             // find matching schemes subsets
10825             final Iterator<String> schemesIterator = intent.schemesIterator();
10826             if (schemesIterator != null) {
10827                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10828                         schemesIterator);
10829                 if (intentListCopy.size() == 0) {
10830                     // no more intents to match; we're not equivalent
10831                     if (DEBUG_FILTERS) {
10832                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10833                                 + " package: " + applicationInfo.packageName
10834                                 + " activity: " + intent.activity.className
10835                                 + " origPrio: " + intent.getPriority());
10836                     }
10837                     intent.setPriority(0);
10838                     return;
10839                 }
10840             }
10841
10842             // find matching authorities subsets
10843             final Iterator<IntentFilter.AuthorityEntry>
10844                     authoritiesIterator = intent.authoritiesIterator();
10845             if (authoritiesIterator != null) {
10846                 getIntentListSubset(intentListCopy,
10847                         new AuthoritiesIterGenerator(),
10848                         authoritiesIterator);
10849                 if (intentListCopy.size() == 0) {
10850                     // no more intents to match; we're not equivalent
10851                     if (DEBUG_FILTERS) {
10852                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10853                                 + " package: " + applicationInfo.packageName
10854                                 + " activity: " + intent.activity.className
10855                                 + " origPrio: " + intent.getPriority());
10856                     }
10857                     intent.setPriority(0);
10858                     return;
10859                 }
10860             }
10861
10862             // we found matching filter(s); app gets the max priority of all intents
10863             int cappedPriority = 0;
10864             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10865                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10866             }
10867             if (intent.getPriority() > cappedPriority) {
10868                 if (DEBUG_FILTERS) {
10869                     Slog.i(TAG, "Found matching filter(s);"
10870                             + " cap priority to " + cappedPriority + ";"
10871                             + " package: " + applicationInfo.packageName
10872                             + " activity: " + intent.activity.className
10873                             + " origPrio: " + intent.getPriority());
10874                 }
10875                 intent.setPriority(cappedPriority);
10876                 return;
10877             }
10878             // all this for nothing; the requested priority was <= what was on the system
10879         }
10880
10881         public final void addActivity(PackageParser.Activity a, String type) {
10882             mActivities.put(a.getComponentName(), a);
10883             if (DEBUG_SHOW_INFO)
10884                 Log.v(
10885                 TAG, "  " + type + " " +
10886                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10887             if (DEBUG_SHOW_INFO)
10888                 Log.v(TAG, "    Class=" + a.info.name);
10889             final int NI = a.intents.size();
10890             for (int j=0; j<NI; j++) {
10891                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10892                 if ("activity".equals(type)) {
10893                     final PackageSetting ps =
10894                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10895                     final List<PackageParser.Activity> systemActivities =
10896                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
10897                     adjustPriority(systemActivities, intent);
10898                 }
10899                 if (DEBUG_SHOW_INFO) {
10900                     Log.v(TAG, "    IntentFilter:");
10901                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10902                 }
10903                 if (!intent.debugCheck()) {
10904                     Log.w(TAG, "==> For Activity " + a.info.name);
10905                 }
10906                 addFilter(intent);
10907             }
10908         }
10909
10910         public final void removeActivity(PackageParser.Activity a, String type) {
10911             mActivities.remove(a.getComponentName());
10912             if (DEBUG_SHOW_INFO) {
10913                 Log.v(TAG, "  " + type + " "
10914                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10915                                 : a.info.name) + ":");
10916                 Log.v(TAG, "    Class=" + a.info.name);
10917             }
10918             final int NI = a.intents.size();
10919             for (int j=0; j<NI; j++) {
10920                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10921                 if (DEBUG_SHOW_INFO) {
10922                     Log.v(TAG, "    IntentFilter:");
10923                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10924                 }
10925                 removeFilter(intent);
10926             }
10927         }
10928
10929         @Override
10930         protected boolean allowFilterResult(
10931                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10932             ActivityInfo filterAi = filter.activity.info;
10933             for (int i=dest.size()-1; i>=0; i--) {
10934                 ActivityInfo destAi = dest.get(i).activityInfo;
10935                 if (destAi.name == filterAi.name
10936                         && destAi.packageName == filterAi.packageName) {
10937                     return false;
10938                 }
10939             }
10940             return true;
10941         }
10942
10943         @Override
10944         protected ActivityIntentInfo[] newArray(int size) {
10945             return new ActivityIntentInfo[size];
10946         }
10947
10948         @Override
10949         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10950             if (!sUserManager.exists(userId)) return true;
10951             PackageParser.Package p = filter.activity.owner;
10952             if (p != null) {
10953                 PackageSetting ps = (PackageSetting)p.mExtras;
10954                 if (ps != null) {
10955                     // System apps are never considered stopped for purposes of
10956                     // filtering, because there may be no way for the user to
10957                     // actually re-launch them.
10958                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10959                             && ps.getStopped(userId);
10960                 }
10961             }
10962             return false;
10963         }
10964
10965         @Override
10966         protected boolean isPackageForFilter(String packageName,
10967                 PackageParser.ActivityIntentInfo info) {
10968             return packageName.equals(info.activity.owner.packageName);
10969         }
10970
10971         @Override
10972         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10973                 int match, int userId) {
10974             if (!sUserManager.exists(userId)) return null;
10975             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10976                 return null;
10977             }
10978             final PackageParser.Activity activity = info.activity;
10979             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10980             if (ps == null) {
10981                 return null;
10982             }
10983             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10984                     ps.readUserState(userId), userId);
10985             if (ai == null) {
10986                 return null;
10987             }
10988             final ResolveInfo res = new ResolveInfo();
10989             res.activityInfo = ai;
10990             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10991                 res.filter = info;
10992             }
10993             if (info != null) {
10994                 res.handleAllWebDataURI = info.handleAllWebDataURI();
10995             }
10996             res.priority = info.getPriority();
10997             res.preferredOrder = activity.owner.mPreferredOrder;
10998             //System.out.println("Result: " + res.activityInfo.className +
10999             //                   " = " + res.priority);
11000             res.match = match;
11001             res.isDefault = info.hasDefault;
11002             res.labelRes = info.labelRes;
11003             res.nonLocalizedLabel = info.nonLocalizedLabel;
11004             if (userNeedsBadging(userId)) {
11005                 res.noResourceId = true;
11006             } else {
11007                 res.icon = info.icon;
11008             }
11009             res.iconResourceId = info.icon;
11010             res.system = res.activityInfo.applicationInfo.isSystemApp();
11011             return res;
11012         }
11013
11014         @Override
11015         protected void sortResults(List<ResolveInfo> results) {
11016             Collections.sort(results, mResolvePrioritySorter);
11017         }
11018
11019         @Override
11020         protected void dumpFilter(PrintWriter out, String prefix,
11021                 PackageParser.ActivityIntentInfo filter) {
11022             out.print(prefix); out.print(
11023                     Integer.toHexString(System.identityHashCode(filter.activity)));
11024                     out.print(' ');
11025                     filter.activity.printComponentShortName(out);
11026                     out.print(" filter ");
11027                     out.println(Integer.toHexString(System.identityHashCode(filter)));
11028         }
11029
11030         @Override
11031         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11032             return filter.activity;
11033         }
11034
11035         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11036             PackageParser.Activity activity = (PackageParser.Activity)label;
11037             out.print(prefix); out.print(
11038                     Integer.toHexString(System.identityHashCode(activity)));
11039                     out.print(' ');
11040                     activity.printComponentShortName(out);
11041             if (count > 1) {
11042                 out.print(" ("); out.print(count); out.print(" filters)");
11043             }
11044             out.println();
11045         }
11046
11047         // Keys are String (activity class name), values are Activity.
11048         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11049                 = new ArrayMap<ComponentName, PackageParser.Activity>();
11050         private int mFlags;
11051     }
11052
11053     private final class ServiceIntentResolver
11054             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11055         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11056                 boolean defaultOnly, int userId) {
11057             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11058             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11059         }
11060
11061         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11062                 int userId) {
11063             if (!sUserManager.exists(userId)) return null;
11064             mFlags = flags;
11065             return super.queryIntent(intent, resolvedType,
11066                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11067         }
11068
11069         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11070                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11071             if (!sUserManager.exists(userId)) return null;
11072             if (packageServices == null) {
11073                 return null;
11074             }
11075             mFlags = flags;
11076             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11077             final int N = packageServices.size();
11078             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11079                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11080
11081             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11082             for (int i = 0; i < N; ++i) {
11083                 intentFilters = packageServices.get(i).intents;
11084                 if (intentFilters != null && intentFilters.size() > 0) {
11085                     PackageParser.ServiceIntentInfo[] array =
11086                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
11087                     intentFilters.toArray(array);
11088                     listCut.add(array);
11089                 }
11090             }
11091             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11092         }
11093
11094         public final void addService(PackageParser.Service s) {
11095             mServices.put(s.getComponentName(), s);
11096             if (DEBUG_SHOW_INFO) {
11097                 Log.v(TAG, "  "
11098                         + (s.info.nonLocalizedLabel != null
11099                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
11100                 Log.v(TAG, "    Class=" + s.info.name);
11101             }
11102             final int NI = s.intents.size();
11103             int j;
11104             for (j=0; j<NI; j++) {
11105                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11106                 if (DEBUG_SHOW_INFO) {
11107                     Log.v(TAG, "    IntentFilter:");
11108                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11109                 }
11110                 if (!intent.debugCheck()) {
11111                     Log.w(TAG, "==> For Service " + s.info.name);
11112                 }
11113                 addFilter(intent);
11114             }
11115         }
11116
11117         public final void removeService(PackageParser.Service s) {
11118             mServices.remove(s.getComponentName());
11119             if (DEBUG_SHOW_INFO) {
11120                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11121                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
11122                 Log.v(TAG, "    Class=" + s.info.name);
11123             }
11124             final int NI = s.intents.size();
11125             int j;
11126             for (j=0; j<NI; j++) {
11127                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11128                 if (DEBUG_SHOW_INFO) {
11129                     Log.v(TAG, "    IntentFilter:");
11130                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11131                 }
11132                 removeFilter(intent);
11133             }
11134         }
11135
11136         @Override
11137         protected boolean allowFilterResult(
11138                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11139             ServiceInfo filterSi = filter.service.info;
11140             for (int i=dest.size()-1; i>=0; i--) {
11141                 ServiceInfo destAi = dest.get(i).serviceInfo;
11142                 if (destAi.name == filterSi.name
11143                         && destAi.packageName == filterSi.packageName) {
11144                     return false;
11145                 }
11146             }
11147             return true;
11148         }
11149
11150         @Override
11151         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11152             return new PackageParser.ServiceIntentInfo[size];
11153         }
11154
11155         @Override
11156         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11157             if (!sUserManager.exists(userId)) return true;
11158             PackageParser.Package p = filter.service.owner;
11159             if (p != null) {
11160                 PackageSetting ps = (PackageSetting)p.mExtras;
11161                 if (ps != null) {
11162                     // System apps are never considered stopped for purposes of
11163                     // filtering, because there may be no way for the user to
11164                     // actually re-launch them.
11165                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11166                             && ps.getStopped(userId);
11167                 }
11168             }
11169             return false;
11170         }
11171
11172         @Override
11173         protected boolean isPackageForFilter(String packageName,
11174                 PackageParser.ServiceIntentInfo info) {
11175             return packageName.equals(info.service.owner.packageName);
11176         }
11177
11178         @Override
11179         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11180                 int match, int userId) {
11181             if (!sUserManager.exists(userId)) return null;
11182             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11183             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11184                 return null;
11185             }
11186             final PackageParser.Service service = info.service;
11187             PackageSetting ps = (PackageSetting) service.owner.mExtras;
11188             if (ps == null) {
11189                 return null;
11190             }
11191             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11192                     ps.readUserState(userId), userId);
11193             if (si == null) {
11194                 return null;
11195             }
11196             final ResolveInfo res = new ResolveInfo();
11197             res.serviceInfo = si;
11198             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11199                 res.filter = filter;
11200             }
11201             res.priority = info.getPriority();
11202             res.preferredOrder = service.owner.mPreferredOrder;
11203             res.match = match;
11204             res.isDefault = info.hasDefault;
11205             res.labelRes = info.labelRes;
11206             res.nonLocalizedLabel = info.nonLocalizedLabel;
11207             res.icon = info.icon;
11208             res.system = res.serviceInfo.applicationInfo.isSystemApp();
11209             return res;
11210         }
11211
11212         @Override
11213         protected void sortResults(List<ResolveInfo> results) {
11214             Collections.sort(results, mResolvePrioritySorter);
11215         }
11216
11217         @Override
11218         protected void dumpFilter(PrintWriter out, String prefix,
11219                 PackageParser.ServiceIntentInfo filter) {
11220             out.print(prefix); out.print(
11221                     Integer.toHexString(System.identityHashCode(filter.service)));
11222                     out.print(' ');
11223                     filter.service.printComponentShortName(out);
11224                     out.print(" filter ");
11225                     out.println(Integer.toHexString(System.identityHashCode(filter)));
11226         }
11227
11228         @Override
11229         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11230             return filter.service;
11231         }
11232
11233         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11234             PackageParser.Service service = (PackageParser.Service)label;
11235             out.print(prefix); out.print(
11236                     Integer.toHexString(System.identityHashCode(service)));
11237                     out.print(' ');
11238                     service.printComponentShortName(out);
11239             if (count > 1) {
11240                 out.print(" ("); out.print(count); out.print(" filters)");
11241             }
11242             out.println();
11243         }
11244
11245 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11246 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11247 //            final List<ResolveInfo> retList = Lists.newArrayList();
11248 //            while (i.hasNext()) {
11249 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
11250 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
11251 //                    retList.add(resolveInfo);
11252 //                }
11253 //            }
11254 //            return retList;
11255 //        }
11256
11257         // Keys are String (activity class name), values are Activity.
11258         private final ArrayMap<ComponentName, PackageParser.Service> mServices
11259                 = new ArrayMap<ComponentName, PackageParser.Service>();
11260         private int mFlags;
11261     };
11262
11263     private final class ProviderIntentResolver
11264             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11265         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11266                 boolean defaultOnly, int userId) {
11267             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11268             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11269         }
11270
11271         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11272                 int userId) {
11273             if (!sUserManager.exists(userId))
11274                 return null;
11275             mFlags = flags;
11276             return super.queryIntent(intent, resolvedType,
11277                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11278         }
11279
11280         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11281                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11282             if (!sUserManager.exists(userId))
11283                 return null;
11284             if (packageProviders == null) {
11285                 return null;
11286             }
11287             mFlags = flags;
11288             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11289             final int N = packageProviders.size();
11290             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11291                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11292
11293             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11294             for (int i = 0; i < N; ++i) {
11295                 intentFilters = packageProviders.get(i).intents;
11296                 if (intentFilters != null && intentFilters.size() > 0) {
11297                     PackageParser.ProviderIntentInfo[] array =
11298                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
11299                     intentFilters.toArray(array);
11300                     listCut.add(array);
11301                 }
11302             }
11303             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11304         }
11305
11306         public final void addProvider(PackageParser.Provider p) {
11307             if (mProviders.containsKey(p.getComponentName())) {
11308                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11309                 return;
11310             }
11311
11312             mProviders.put(p.getComponentName(), p);
11313             if (DEBUG_SHOW_INFO) {
11314                 Log.v(TAG, "  "
11315                         + (p.info.nonLocalizedLabel != null
11316                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11317                 Log.v(TAG, "    Class=" + p.info.name);
11318             }
11319             final int NI = p.intents.size();
11320             int j;
11321             for (j = 0; j < NI; j++) {
11322                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11323                 if (DEBUG_SHOW_INFO) {
11324                     Log.v(TAG, "    IntentFilter:");
11325                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11326                 }
11327                 if (!intent.debugCheck()) {
11328                     Log.w(TAG, "==> For Provider " + p.info.name);
11329                 }
11330                 addFilter(intent);
11331             }
11332         }
11333
11334         public final void removeProvider(PackageParser.Provider p) {
11335             mProviders.remove(p.getComponentName());
11336             if (DEBUG_SHOW_INFO) {
11337                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11338                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
11339                 Log.v(TAG, "    Class=" + p.info.name);
11340             }
11341             final int NI = p.intents.size();
11342             int j;
11343             for (j = 0; j < NI; j++) {
11344                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11345                 if (DEBUG_SHOW_INFO) {
11346                     Log.v(TAG, "    IntentFilter:");
11347                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11348                 }
11349                 removeFilter(intent);
11350             }
11351         }
11352
11353         @Override
11354         protected boolean allowFilterResult(
11355                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11356             ProviderInfo filterPi = filter.provider.info;
11357             for (int i = dest.size() - 1; i >= 0; i--) {
11358                 ProviderInfo destPi = dest.get(i).providerInfo;
11359                 if (destPi.name == filterPi.name
11360                         && destPi.packageName == filterPi.packageName) {
11361                     return false;
11362                 }
11363             }
11364             return true;
11365         }
11366
11367         @Override
11368         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11369             return new PackageParser.ProviderIntentInfo[size];
11370         }
11371
11372         @Override
11373         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11374             if (!sUserManager.exists(userId))
11375                 return true;
11376             PackageParser.Package p = filter.provider.owner;
11377             if (p != null) {
11378                 PackageSetting ps = (PackageSetting) p.mExtras;
11379                 if (ps != null) {
11380                     // System apps are never considered stopped for purposes of
11381                     // filtering, because there may be no way for the user to
11382                     // actually re-launch them.
11383                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11384                             && ps.getStopped(userId);
11385                 }
11386             }
11387             return false;
11388         }
11389
11390         @Override
11391         protected boolean isPackageForFilter(String packageName,
11392                 PackageParser.ProviderIntentInfo info) {
11393             return packageName.equals(info.provider.owner.packageName);
11394         }
11395
11396         @Override
11397         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11398                 int match, int userId) {
11399             if (!sUserManager.exists(userId))
11400                 return null;
11401             final PackageParser.ProviderIntentInfo info = filter;
11402             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11403                 return null;
11404             }
11405             final PackageParser.Provider provider = info.provider;
11406             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11407             if (ps == null) {
11408                 return null;
11409             }
11410             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11411                     ps.readUserState(userId), userId);
11412             if (pi == null) {
11413                 return null;
11414             }
11415             final ResolveInfo res = new ResolveInfo();
11416             res.providerInfo = pi;
11417             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11418                 res.filter = filter;
11419             }
11420             res.priority = info.getPriority();
11421             res.preferredOrder = provider.owner.mPreferredOrder;
11422             res.match = match;
11423             res.isDefault = info.hasDefault;
11424             res.labelRes = info.labelRes;
11425             res.nonLocalizedLabel = info.nonLocalizedLabel;
11426             res.icon = info.icon;
11427             res.system = res.providerInfo.applicationInfo.isSystemApp();
11428             return res;
11429         }
11430
11431         @Override
11432         protected void sortResults(List<ResolveInfo> results) {
11433             Collections.sort(results, mResolvePrioritySorter);
11434         }
11435
11436         @Override
11437         protected void dumpFilter(PrintWriter out, String prefix,
11438                 PackageParser.ProviderIntentInfo filter) {
11439             out.print(prefix);
11440             out.print(
11441                     Integer.toHexString(System.identityHashCode(filter.provider)));
11442             out.print(' ');
11443             filter.provider.printComponentShortName(out);
11444             out.print(" filter ");
11445             out.println(Integer.toHexString(System.identityHashCode(filter)));
11446         }
11447
11448         @Override
11449         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11450             return filter.provider;
11451         }
11452
11453         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11454             PackageParser.Provider provider = (PackageParser.Provider)label;
11455             out.print(prefix); out.print(
11456                     Integer.toHexString(System.identityHashCode(provider)));
11457                     out.print(' ');
11458                     provider.printComponentShortName(out);
11459             if (count > 1) {
11460                 out.print(" ("); out.print(count); out.print(" filters)");
11461             }
11462             out.println();
11463         }
11464
11465         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11466                 = new ArrayMap<ComponentName, PackageParser.Provider>();
11467         private int mFlags;
11468     }
11469
11470     private static final class EphemeralIntentResolver
11471             extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11472         /**
11473          * The result that has the highest defined order. Ordering applies on a
11474          * per-package basis. Mapping is from package name to Pair of order and
11475          * EphemeralResolveInfo.
11476          * <p>
11477          * NOTE: This is implemented as a field variable for convenience and efficiency.
11478          * By having a field variable, we're able to track filter ordering as soon as
11479          * a non-zero order is defined. Otherwise, multiple loops across the result set
11480          * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11481          * this needs to be contained entirely within {@link #filterResults()}.
11482          */
11483         final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11484
11485         @Override
11486         protected EphemeralResolveIntentInfo[] newArray(int size) {
11487             return new EphemeralResolveIntentInfo[size];
11488         }
11489
11490         @Override
11491         protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11492             return true;
11493         }
11494
11495         @Override
11496         protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11497                 int userId) {
11498             if (!sUserManager.exists(userId)) {
11499                 return null;
11500             }
11501             final String packageName = info.getEphemeralResolveInfo().getPackageName();
11502             final Integer order = info.getOrder();
11503             final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11504                     mOrderResult.get(packageName);
11505             // ordering is enabled and this item's order isn't high enough
11506             if (lastOrderResult != null && lastOrderResult.first >= order) {
11507                 return null;
11508             }
11509             final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11510             if (order > 0) {
11511                 // non-zero order, enable ordering
11512                 mOrderResult.put(packageName, new Pair<>(order, res));
11513             }
11514             return res;
11515         }
11516
11517         @Override
11518         protected void filterResults(List<EphemeralResolveInfo> results) {
11519             // only do work if ordering is enabled [most of the time it won't be]
11520             if (mOrderResult.size() == 0) {
11521                 return;
11522             }
11523             int resultSize = results.size();
11524             for (int i = 0; i < resultSize; i++) {
11525                 final EphemeralResolveInfo info = results.get(i);
11526                 final String packageName = info.getPackageName();
11527                 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11528                 if (savedInfo == null) {
11529                     // package doesn't having ordering
11530                     continue;
11531                 }
11532                 if (savedInfo.second == info) {
11533                     // circled back to the highest ordered item; remove from order list
11534                     mOrderResult.remove(savedInfo);
11535                     if (mOrderResult.size() == 0) {
11536                         // no more ordered items
11537                         break;
11538                     }
11539                     continue;
11540                 }
11541                 // item has a worse order, remove it from the result list
11542                 results.remove(i);
11543                 resultSize--;
11544                 i--;
11545             }
11546         }
11547     }
11548
11549     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11550             new Comparator<ResolveInfo>() {
11551         public int compare(ResolveInfo r1, ResolveInfo r2) {
11552             int v1 = r1.priority;
11553             int v2 = r2.priority;
11554             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11555             if (v1 != v2) {
11556                 return (v1 > v2) ? -1 : 1;
11557             }
11558             v1 = r1.preferredOrder;
11559             v2 = r2.preferredOrder;
11560             if (v1 != v2) {
11561                 return (v1 > v2) ? -1 : 1;
11562             }
11563             if (r1.isDefault != r2.isDefault) {
11564                 return r1.isDefault ? -1 : 1;
11565             }
11566             v1 = r1.match;
11567             v2 = r2.match;
11568             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11569             if (v1 != v2) {
11570                 return (v1 > v2) ? -1 : 1;
11571             }
11572             if (r1.system != r2.system) {
11573                 return r1.system ? -1 : 1;
11574             }
11575             if (r1.activityInfo != null) {
11576                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11577             }
11578             if (r1.serviceInfo != null) {
11579                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11580             }
11581             if (r1.providerInfo != null) {
11582                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11583             }
11584             return 0;
11585         }
11586     };
11587
11588     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11589             new Comparator<ProviderInfo>() {
11590         public int compare(ProviderInfo p1, ProviderInfo p2) {
11591             final int v1 = p1.initOrder;
11592             final int v2 = p2.initOrder;
11593             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11594         }
11595     };
11596
11597     final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11598             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11599             final int[] userIds) {
11600         mHandler.post(new Runnable() {
11601             @Override
11602             public void run() {
11603                 try {
11604                     final IActivityManager am = ActivityManagerNative.getDefault();
11605                     if (am == null) return;
11606                     final int[] resolvedUserIds;
11607                     if (userIds == null) {
11608                         resolvedUserIds = am.getRunningUserIds();
11609                     } else {
11610                         resolvedUserIds = userIds;
11611                     }
11612                     for (int id : resolvedUserIds) {
11613                         final Intent intent = new Intent(action,
11614                                 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11615                         if (extras != null) {
11616                             intent.putExtras(extras);
11617                         }
11618                         if (targetPkg != null) {
11619                             intent.setPackage(targetPkg);
11620                         }
11621                         // Modify the UID when posting to other users
11622                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11623                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
11624                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11625                             intent.putExtra(Intent.EXTRA_UID, uid);
11626                         }
11627                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11628                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11629                         if (DEBUG_BROADCASTS) {
11630                             RuntimeException here = new RuntimeException("here");
11631                             here.fillInStackTrace();
11632                             Slog.d(TAG, "Sending to user " + id + ": "
11633                                     + intent.toShortString(false, true, false, false)
11634                                     + " " + intent.getExtras(), here);
11635                         }
11636                         am.broadcastIntent(null, intent, null, finishedReceiver,
11637                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11638                                 null, finishedReceiver != null, false, id);
11639                     }
11640                 } catch (RemoteException ex) {
11641                 }
11642             }
11643         });
11644     }
11645
11646     /**
11647      * Check if the external storage media is available. This is true if there
11648      * is a mounted external storage medium or if the external storage is
11649      * emulated.
11650      */
11651     private boolean isExternalMediaAvailable() {
11652         return mMediaMounted || Environment.isExternalStorageEmulated();
11653     }
11654
11655     @Override
11656     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11657         // writer
11658         synchronized (mPackages) {
11659             if (!isExternalMediaAvailable()) {
11660                 // If the external storage is no longer mounted at this point,
11661                 // the caller may not have been able to delete all of this
11662                 // packages files and can not delete any more.  Bail.
11663                 return null;
11664             }
11665             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11666             if (lastPackage != null) {
11667                 pkgs.remove(lastPackage);
11668             }
11669             if (pkgs.size() > 0) {
11670                 return pkgs.get(0);
11671             }
11672         }
11673         return null;
11674     }
11675
11676     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11677         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11678                 userId, andCode ? 1 : 0, packageName);
11679         if (mSystemReady) {
11680             msg.sendToTarget();
11681         } else {
11682             if (mPostSystemReadyMessages == null) {
11683                 mPostSystemReadyMessages = new ArrayList<>();
11684             }
11685             mPostSystemReadyMessages.add(msg);
11686         }
11687     }
11688
11689     void startCleaningPackages() {
11690         // reader
11691         if (!isExternalMediaAvailable()) {
11692             return;
11693         }
11694         synchronized (mPackages) {
11695             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11696                 return;
11697             }
11698         }
11699         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11700         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11701         IActivityManager am = ActivityManagerNative.getDefault();
11702         if (am != null) {
11703             try {
11704                 am.startService(null, intent, null, mContext.getOpPackageName(),
11705                         UserHandle.USER_SYSTEM);
11706             } catch (RemoteException e) {
11707             }
11708         }
11709     }
11710
11711     @Override
11712     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11713             int installFlags, String installerPackageName, int userId) {
11714         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11715
11716         final int callingUid = Binder.getCallingUid();
11717         enforceCrossUserPermission(callingUid, userId,
11718                 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11719
11720         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11721             try {
11722                 if (observer != null) {
11723                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11724                 }
11725             } catch (RemoteException re) {
11726             }
11727             return;
11728         }
11729
11730         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11731             installFlags |= PackageManager.INSTALL_FROM_ADB;
11732
11733         } else {
11734             // Caller holds INSTALL_PACKAGES permission, so we're less strict
11735             // about installerPackageName.
11736
11737             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11738             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11739         }
11740
11741         UserHandle user;
11742         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11743             user = UserHandle.ALL;
11744         } else {
11745             user = new UserHandle(userId);
11746         }
11747
11748         // Only system components can circumvent runtime permissions when installing.
11749         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11750                 && mContext.checkCallingOrSelfPermission(Manifest.permission
11751                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11752             throw new SecurityException("You need the "
11753                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11754                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11755         }
11756
11757         final File originFile = new File(originPath);
11758         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11759
11760         final Message msg = mHandler.obtainMessage(INIT_COPY);
11761         final VerificationInfo verificationInfo = new VerificationInfo(
11762                 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11763         final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11764                 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11765                 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11766                 null /*certificates*/);
11767         params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11768         msg.obj = params;
11769
11770         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11771                 System.identityHashCode(msg.obj));
11772         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11773                 System.identityHashCode(msg.obj));
11774
11775         mHandler.sendMessage(msg);
11776     }
11777
11778     void installStage(String packageName, File stagedDir, String stagedCid,
11779             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11780             String installerPackageName, int installerUid, UserHandle user,
11781             Certificate[][] certificates) {
11782         if (DEBUG_EPHEMERAL) {
11783             if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11784                 Slog.d(TAG, "Ephemeral install of " + packageName);
11785             }
11786         }
11787         final VerificationInfo verificationInfo = new VerificationInfo(
11788                 sessionParams.originatingUri, sessionParams.referrerUri,
11789                 sessionParams.originatingUid, installerUid);
11790
11791         final OriginInfo origin;
11792         if (stagedDir != null) {
11793             origin = OriginInfo.fromStagedFile(stagedDir);
11794         } else {
11795             origin = OriginInfo.fromStagedContainer(stagedCid);
11796         }
11797
11798         final Message msg = mHandler.obtainMessage(INIT_COPY);
11799         final InstallParams params = new InstallParams(origin, null, observer,
11800                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11801                 verificationInfo, user, sessionParams.abiOverride,
11802                 sessionParams.grantedRuntimePermissions, certificates);
11803         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11804         msg.obj = params;
11805
11806         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11807                 System.identityHashCode(msg.obj));
11808         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11809                 System.identityHashCode(msg.obj));
11810
11811         mHandler.sendMessage(msg);
11812     }
11813
11814     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11815             int userId) {
11816         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11817         sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11818     }
11819
11820     private void sendPackageAddedForUser(String packageName, boolean isSystem,
11821             int appId, int userId) {
11822         Bundle extras = new Bundle(1);
11823         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11824
11825         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11826                 packageName, extras, 0, null, null, new int[] {userId});
11827         try {
11828             IActivityManager am = ActivityManagerNative.getDefault();
11829             if (isSystem && am.isUserRunning(userId, 0)) {
11830                 // The just-installed/enabled app is bundled on the system, so presumed
11831                 // to be able to run automatically without needing an explicit launch.
11832                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11833                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11834                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11835                         .setPackage(packageName);
11836                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11837                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11838             }
11839         } catch (RemoteException e) {
11840             // shouldn't happen
11841             Slog.w(TAG, "Unable to bootstrap installed package", e);
11842         }
11843     }
11844
11845     @Override
11846     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11847             int userId) {
11848         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11849         PackageSetting pkgSetting;
11850         final int uid = Binder.getCallingUid();
11851         enforceCrossUserPermission(uid, userId,
11852                 true /* requireFullPermission */, true /* checkShell */,
11853                 "setApplicationHiddenSetting for user " + userId);
11854
11855         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11856             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11857             return false;
11858         }
11859
11860         long callingId = Binder.clearCallingIdentity();
11861         try {
11862             boolean sendAdded = false;
11863             boolean sendRemoved = false;
11864             // writer
11865             synchronized (mPackages) {
11866                 pkgSetting = mSettings.mPackages.get(packageName);
11867                 if (pkgSetting == null) {
11868                     return false;
11869                 }
11870                 // Do not allow "android" is being disabled
11871                 if ("android".equals(packageName)) {
11872                     Slog.w(TAG, "Cannot hide package: android");
11873                     return false;
11874                 }
11875                 // Only allow protected packages to hide themselves.
11876                 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11877                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11878                     Slog.w(TAG, "Not hiding protected package: " + packageName);
11879                     return false;
11880                 }
11881
11882                 if (pkgSetting.getHidden(userId) != hidden) {
11883                     pkgSetting.setHidden(hidden, userId);
11884                     mSettings.writePackageRestrictionsLPr(userId);
11885                     if (hidden) {
11886                         sendRemoved = true;
11887                     } else {
11888                         sendAdded = true;
11889                     }
11890                 }
11891             }
11892             if (sendAdded) {
11893                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11894                 return true;
11895             }
11896             if (sendRemoved) {
11897                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11898                         "hiding pkg");
11899                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11900                 return true;
11901             }
11902         } finally {
11903             Binder.restoreCallingIdentity(callingId);
11904         }
11905         return false;
11906     }
11907
11908     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11909             int userId) {
11910         final PackageRemovedInfo info = new PackageRemovedInfo();
11911         info.removedPackage = packageName;
11912         info.removedUsers = new int[] {userId};
11913         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11914         info.sendPackageRemovedBroadcasts(true /*killApp*/);
11915     }
11916
11917     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11918         if (pkgList.length > 0) {
11919             Bundle extras = new Bundle(1);
11920             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11921
11922             sendPackageBroadcast(
11923                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11924                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
11925                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11926                     new int[] {userId});
11927         }
11928     }
11929
11930     /**
11931      * Returns true if application is not found or there was an error. Otherwise it returns
11932      * the hidden state of the package for the given user.
11933      */
11934     @Override
11935     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11936         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11937         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11938                 true /* requireFullPermission */, false /* checkShell */,
11939                 "getApplicationHidden for user " + userId);
11940         PackageSetting pkgSetting;
11941         long callingId = Binder.clearCallingIdentity();
11942         try {
11943             // writer
11944             synchronized (mPackages) {
11945                 pkgSetting = mSettings.mPackages.get(packageName);
11946                 if (pkgSetting == null) {
11947                     return true;
11948                 }
11949                 return pkgSetting.getHidden(userId);
11950             }
11951         } finally {
11952             Binder.restoreCallingIdentity(callingId);
11953         }
11954     }
11955
11956     /**
11957      * @hide
11958      */
11959     @Override
11960     public int installExistingPackageAsUser(String packageName, int userId) {
11961         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11962                 null);
11963         PackageSetting pkgSetting;
11964         final int uid = Binder.getCallingUid();
11965         enforceCrossUserPermission(uid, userId,
11966                 true /* requireFullPermission */, true /* checkShell */,
11967                 "installExistingPackage for user " + userId);
11968         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11969             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11970         }
11971
11972         long callingId = Binder.clearCallingIdentity();
11973         try {
11974             boolean installed = false;
11975
11976             // writer
11977             synchronized (mPackages) {
11978                 pkgSetting = mSettings.mPackages.get(packageName);
11979                 if (pkgSetting == null) {
11980                     return PackageManager.INSTALL_FAILED_INVALID_URI;
11981                 }
11982                 if (!pkgSetting.getInstalled(userId)) {
11983                     pkgSetting.setInstalled(true, userId);
11984                     pkgSetting.setHidden(false, userId);
11985                     mSettings.writePackageRestrictionsLPr(userId);
11986                     installed = true;
11987                 }
11988             }
11989
11990             if (installed) {
11991                 if (pkgSetting.pkg != null) {
11992                     synchronized (mInstallLock) {
11993                         // We don't need to freeze for a brand new install
11994                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11995                     }
11996                 }
11997                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11998             }
11999         } finally {
12000             Binder.restoreCallingIdentity(callingId);
12001         }
12002
12003         return PackageManager.INSTALL_SUCCEEDED;
12004     }
12005
12006     boolean isUserRestricted(int userId, String restrictionKey) {
12007         Bundle restrictions = sUserManager.getUserRestrictions(userId);
12008         if (restrictions.getBoolean(restrictionKey, false)) {
12009             Log.w(TAG, "User is restricted: " + restrictionKey);
12010             return true;
12011         }
12012         return false;
12013     }
12014
12015     @Override
12016     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12017             int userId) {
12018         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12019         enforceCrossUserPermission(Binder.getCallingUid(), userId,
12020                 true /* requireFullPermission */, true /* checkShell */,
12021                 "setPackagesSuspended for user " + userId);
12022
12023         if (ArrayUtils.isEmpty(packageNames)) {
12024             return packageNames;
12025         }
12026
12027         // List of package names for whom the suspended state has changed.
12028         List<String> changedPackages = new ArrayList<>(packageNames.length);
12029         // List of package names for whom the suspended state is not set as requested in this
12030         // method.
12031         List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12032         long callingId = Binder.clearCallingIdentity();
12033         try {
12034             for (int i = 0; i < packageNames.length; i++) {
12035                 String packageName = packageNames[i];
12036                 boolean changed = false;
12037                 final int appId;
12038                 synchronized (mPackages) {
12039                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12040                     if (pkgSetting == null) {
12041                         Slog.w(TAG, "Could not find package setting for package \"" + packageName
12042                                 + "\". Skipping suspending/un-suspending.");
12043                         unactionedPackages.add(packageName);
12044                         continue;
12045                     }
12046                     appId = pkgSetting.appId;
12047                     if (pkgSetting.getSuspended(userId) != suspended) {
12048                         if (!canSuspendPackageForUserLocked(packageName, userId)) {
12049                             unactionedPackages.add(packageName);
12050                             continue;
12051                         }
12052                         pkgSetting.setSuspended(suspended, userId);
12053                         mSettings.writePackageRestrictionsLPr(userId);
12054                         changed = true;
12055                         changedPackages.add(packageName);
12056                     }
12057                 }
12058
12059                 if (changed && suspended) {
12060                     killApplication(packageName, UserHandle.getUid(userId, appId),
12061                             "suspending package");
12062                 }
12063             }
12064         } finally {
12065             Binder.restoreCallingIdentity(callingId);
12066         }
12067
12068         if (!changedPackages.isEmpty()) {
12069             sendPackagesSuspendedForUser(changedPackages.toArray(
12070                     new String[changedPackages.size()]), userId, suspended);
12071         }
12072
12073         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12074     }
12075
12076     @Override
12077     public boolean isPackageSuspendedForUser(String packageName, int userId) {
12078         enforceCrossUserPermission(Binder.getCallingUid(), userId,
12079                 true /* requireFullPermission */, false /* checkShell */,
12080                 "isPackageSuspendedForUser for user " + userId);
12081         synchronized (mPackages) {
12082             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12083             if (pkgSetting == null) {
12084                 throw new IllegalArgumentException("Unknown target package: " + packageName);
12085             }
12086             return pkgSetting.getSuspended(userId);
12087         }
12088     }
12089
12090     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12091         if (isPackageDeviceAdmin(packageName, userId)) {
12092             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12093                     + "\": has an active device admin");
12094             return false;
12095         }
12096
12097         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12098         if (packageName.equals(activeLauncherPackageName)) {
12099             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12100                     + "\": contains the active launcher");
12101             return false;
12102         }
12103
12104         if (packageName.equals(mRequiredInstallerPackage)) {
12105             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12106                     + "\": required for package installation");
12107             return false;
12108         }
12109
12110         if (packageName.equals(mRequiredUninstallerPackage)) {
12111             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12112                     + "\": required for package uninstallation");
12113             return false;
12114         }
12115
12116         if (packageName.equals(mRequiredVerifierPackage)) {
12117             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12118                     + "\": required for package verification");
12119             return false;
12120         }
12121
12122         if (packageName.equals(getDefaultDialerPackageName(userId))) {
12123             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12124                     + "\": is the default dialer");
12125             return false;
12126         }
12127
12128         if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12129             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12130                     + "\": protected package");
12131             return false;
12132         }
12133
12134         return true;
12135     }
12136
12137     private String getActiveLauncherPackageName(int userId) {
12138         Intent intent = new Intent(Intent.ACTION_MAIN);
12139         intent.addCategory(Intent.CATEGORY_HOME);
12140         ResolveInfo resolveInfo = resolveIntent(
12141                 intent,
12142                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12143                 PackageManager.MATCH_DEFAULT_ONLY,
12144                 userId);
12145
12146         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12147     }
12148
12149     private String getDefaultDialerPackageName(int userId) {
12150         synchronized (mPackages) {
12151             return mSettings.getDefaultDialerPackageNameLPw(userId);
12152         }
12153     }
12154
12155     @Override
12156     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12157         mContext.enforceCallingOrSelfPermission(
12158                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12159                 "Only package verification agents can verify applications");
12160
12161         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12162         final PackageVerificationResponse response = new PackageVerificationResponse(
12163                 verificationCode, Binder.getCallingUid());
12164         msg.arg1 = id;
12165         msg.obj = response;
12166         mHandler.sendMessage(msg);
12167     }
12168
12169     @Override
12170     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12171             long millisecondsToDelay) {
12172         mContext.enforceCallingOrSelfPermission(
12173                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12174                 "Only package verification agents can extend verification timeouts");
12175
12176         final PackageVerificationState state = mPendingVerification.get(id);
12177         final PackageVerificationResponse response = new PackageVerificationResponse(
12178                 verificationCodeAtTimeout, Binder.getCallingUid());
12179
12180         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12181             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12182         }
12183         if (millisecondsToDelay < 0) {
12184             millisecondsToDelay = 0;
12185         }
12186         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12187                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12188             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12189         }
12190
12191         if ((state != null) && !state.timeoutExtended()) {
12192             state.extendTimeout();
12193
12194             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12195             msg.arg1 = id;
12196             msg.obj = response;
12197             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12198         }
12199     }
12200
12201     private void broadcastPackageVerified(int verificationId, Uri packageUri,
12202             int verificationCode, UserHandle user) {
12203         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12204         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12205         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12206         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12207         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12208
12209         mContext.sendBroadcastAsUser(intent, user,
12210                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12211     }
12212
12213     private ComponentName matchComponentForVerifier(String packageName,
12214             List<ResolveInfo> receivers) {
12215         ActivityInfo targetReceiver = null;
12216
12217         final int NR = receivers.size();
12218         for (int i = 0; i < NR; i++) {
12219             final ResolveInfo info = receivers.get(i);
12220             if (info.activityInfo == null) {
12221                 continue;
12222             }
12223
12224             if (packageName.equals(info.activityInfo.packageName)) {
12225                 targetReceiver = info.activityInfo;
12226                 break;
12227             }
12228         }
12229
12230         if (targetReceiver == null) {
12231             return null;
12232         }
12233
12234         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12235     }
12236
12237     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12238             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12239         if (pkgInfo.verifiers.length == 0) {
12240             return null;
12241         }
12242
12243         final int N = pkgInfo.verifiers.length;
12244         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12245         for (int i = 0; i < N; i++) {
12246             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12247
12248             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12249                     receivers);
12250             if (comp == null) {
12251                 continue;
12252             }
12253
12254             final int verifierUid = getUidForVerifier(verifierInfo);
12255             if (verifierUid == -1) {
12256                 continue;
12257             }
12258
12259             if (DEBUG_VERIFY) {
12260                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12261                         + " with the correct signature");
12262             }
12263             sufficientVerifiers.add(comp);
12264             verificationState.addSufficientVerifier(verifierUid);
12265         }
12266
12267         return sufficientVerifiers;
12268     }
12269
12270     private int getUidForVerifier(VerifierInfo verifierInfo) {
12271         synchronized (mPackages) {
12272             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12273             if (pkg == null) {
12274                 return -1;
12275             } else if (pkg.mSignatures.length != 1) {
12276                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12277                         + " has more than one signature; ignoring");
12278                 return -1;
12279             }
12280
12281             /*
12282              * If the public key of the package's signature does not match
12283              * our expected public key, then this is a different package and
12284              * we should skip.
12285              */
12286
12287             final byte[] expectedPublicKey;
12288             try {
12289                 final Signature verifierSig = pkg.mSignatures[0];
12290                 final PublicKey publicKey = verifierSig.getPublicKey();
12291                 expectedPublicKey = publicKey.getEncoded();
12292             } catch (CertificateException e) {
12293                 return -1;
12294             }
12295
12296             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12297
12298             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12299                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12300                         + " does not have the expected public key; ignoring");
12301                 return -1;
12302             }
12303
12304             return pkg.applicationInfo.uid;
12305         }
12306     }
12307
12308     @Override
12309     public void finishPackageInstall(int token, boolean didLaunch) {
12310         enforceSystemOrRoot("Only the system is allowed to finish installs");
12311
12312         if (DEBUG_INSTALL) {
12313             Slog.v(TAG, "BM finishing package install for " + token);
12314         }
12315         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12316
12317         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12318         mHandler.sendMessage(msg);
12319     }
12320
12321     /**
12322      * Get the verification agent timeout.
12323      *
12324      * @return verification timeout in milliseconds
12325      */
12326     private long getVerificationTimeout() {
12327         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12328                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12329                 DEFAULT_VERIFICATION_TIMEOUT);
12330     }
12331
12332     /**
12333      * Get the default verification agent response code.
12334      *
12335      * @return default verification response code
12336      */
12337     private int getDefaultVerificationResponse() {
12338         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12339                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12340                 DEFAULT_VERIFICATION_RESPONSE);
12341     }
12342
12343     /**
12344      * Check whether or not package verification has been enabled.
12345      *
12346      * @return true if verification should be performed
12347      */
12348     private boolean isVerificationEnabled(int userId, int installFlags) {
12349         if (!DEFAULT_VERIFY_ENABLE) {
12350             return false;
12351         }
12352         // Ephemeral apps don't get the full verification treatment
12353         if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12354             if (DEBUG_EPHEMERAL) {
12355                 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12356             }
12357             return false;
12358         }
12359
12360         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12361
12362         // Check if installing from ADB
12363         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12364             // Do not run verification in a test harness environment
12365             if (ActivityManager.isRunningInTestHarness()) {
12366                 return false;
12367             }
12368             if (ensureVerifyAppsEnabled) {
12369                 return true;
12370             }
12371             // Check if the developer does not want package verification for ADB installs
12372             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12373                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12374                 return false;
12375             }
12376         }
12377
12378         if (ensureVerifyAppsEnabled) {
12379             return true;
12380         }
12381
12382         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12383                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12384     }
12385
12386     @Override
12387     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12388             throws RemoteException {
12389         mContext.enforceCallingOrSelfPermission(
12390                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12391                 "Only intentfilter verification agents can verify applications");
12392
12393         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12394         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12395                 Binder.getCallingUid(), verificationCode, failedDomains);
12396         msg.arg1 = id;
12397         msg.obj = response;
12398         mHandler.sendMessage(msg);
12399     }
12400
12401     @Override
12402     public int getIntentVerificationStatus(String packageName, int userId) {
12403         synchronized (mPackages) {
12404             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12405         }
12406     }
12407
12408     @Override
12409     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12410         mContext.enforceCallingOrSelfPermission(
12411                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12412
12413         boolean result = false;
12414         synchronized (mPackages) {
12415             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12416         }
12417         if (result) {
12418             scheduleWritePackageRestrictionsLocked(userId);
12419         }
12420         return result;
12421     }
12422
12423     @Override
12424     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12425             String packageName) {
12426         synchronized (mPackages) {
12427             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12428         }
12429     }
12430
12431     @Override
12432     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12433         if (TextUtils.isEmpty(packageName)) {
12434             return ParceledListSlice.emptyList();
12435         }
12436         synchronized (mPackages) {
12437             PackageParser.Package pkg = mPackages.get(packageName);
12438             if (pkg == null || pkg.activities == null) {
12439                 return ParceledListSlice.emptyList();
12440             }
12441             final int count = pkg.activities.size();
12442             ArrayList<IntentFilter> result = new ArrayList<>();
12443             for (int n=0; n<count; n++) {
12444                 PackageParser.Activity activity = pkg.activities.get(n);
12445                 if (activity.intents != null && activity.intents.size() > 0) {
12446                     result.addAll(activity.intents);
12447                 }
12448             }
12449             return new ParceledListSlice<>(result);
12450         }
12451     }
12452
12453     @Override
12454     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12455         mContext.enforceCallingOrSelfPermission(
12456                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12457
12458         synchronized (mPackages) {
12459             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12460             if (packageName != null) {
12461                 result |= updateIntentVerificationStatus(packageName,
12462                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12463                         userId);
12464                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12465                         packageName, userId);
12466             }
12467             return result;
12468         }
12469     }
12470
12471     @Override
12472     public String getDefaultBrowserPackageName(int userId) {
12473         synchronized (mPackages) {
12474             return mSettings.getDefaultBrowserPackageNameLPw(userId);
12475         }
12476     }
12477
12478     /**
12479      * Get the "allow unknown sources" setting.
12480      *
12481      * @return the current "allow unknown sources" setting
12482      */
12483     private int getUnknownSourcesSettings() {
12484         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12485                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12486                 -1);
12487     }
12488
12489     @Override
12490     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12491         final int uid = Binder.getCallingUid();
12492         // writer
12493         synchronized (mPackages) {
12494             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12495             if (targetPackageSetting == null) {
12496                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12497             }
12498
12499             PackageSetting installerPackageSetting;
12500             if (installerPackageName != null) {
12501                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12502                 if (installerPackageSetting == null) {
12503                     throw new IllegalArgumentException("Unknown installer package: "
12504                             + installerPackageName);
12505                 }
12506             } else {
12507                 installerPackageSetting = null;
12508             }
12509
12510             Signature[] callerSignature;
12511             Object obj = mSettings.getUserIdLPr(uid);
12512             if (obj != null) {
12513                 if (obj instanceof SharedUserSetting) {
12514                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12515                 } else if (obj instanceof PackageSetting) {
12516                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12517                 } else {
12518                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
12519                 }
12520             } else {
12521                 throw new SecurityException("Unknown calling UID: " + uid);
12522             }
12523
12524             // Verify: can't set installerPackageName to a package that is
12525             // not signed with the same cert as the caller.
12526             if (installerPackageSetting != null) {
12527                 if (compareSignatures(callerSignature,
12528                         installerPackageSetting.signatures.mSignatures)
12529                         != PackageManager.SIGNATURE_MATCH) {
12530                     throw new SecurityException(
12531                             "Caller does not have same cert as new installer package "
12532                             + installerPackageName);
12533                 }
12534             }
12535
12536             // Verify: if target already has an installer package, it must
12537             // be signed with the same cert as the caller.
12538             if (targetPackageSetting.installerPackageName != null) {
12539                 PackageSetting setting = mSettings.mPackages.get(
12540                         targetPackageSetting.installerPackageName);
12541                 // If the currently set package isn't valid, then it's always
12542                 // okay to change it.
12543                 if (setting != null) {
12544                     if (compareSignatures(callerSignature,
12545                             setting.signatures.mSignatures)
12546                             != PackageManager.SIGNATURE_MATCH) {
12547                         throw new SecurityException(
12548                                 "Caller does not have same cert as old installer package "
12549                                 + targetPackageSetting.installerPackageName);
12550                     }
12551                 }
12552             }
12553
12554             // Okay!
12555             targetPackageSetting.installerPackageName = installerPackageName;
12556             if (installerPackageName != null) {
12557                 mSettings.mInstallerPackages.add(installerPackageName);
12558             }
12559             scheduleWriteSettingsLocked();
12560         }
12561     }
12562
12563     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12564         // Queue up an async operation since the package installation may take a little while.
12565         mHandler.post(new Runnable() {
12566             public void run() {
12567                 mHandler.removeCallbacks(this);
12568                  // Result object to be returned
12569                 PackageInstalledInfo res = new PackageInstalledInfo();
12570                 res.setReturnCode(currentStatus);
12571                 res.uid = -1;
12572                 res.pkg = null;
12573                 res.removedInfo = null;
12574                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12575                     args.doPreInstall(res.returnCode);
12576                     synchronized (mInstallLock) {
12577                         installPackageTracedLI(args, res);
12578                     }
12579                     args.doPostInstall(res.returnCode, res.uid);
12580                 }
12581
12582                 // A restore should be performed at this point if (a) the install
12583                 // succeeded, (b) the operation is not an update, and (c) the new
12584                 // package has not opted out of backup participation.
12585                 final boolean update = res.removedInfo != null
12586                         && res.removedInfo.removedPackage != null;
12587                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12588                 boolean doRestore = !update
12589                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12590
12591                 // Set up the post-install work request bookkeeping.  This will be used
12592                 // and cleaned up by the post-install event handling regardless of whether
12593                 // there's a restore pass performed.  Token values are >= 1.
12594                 int token;
12595                 if (mNextInstallToken < 0) mNextInstallToken = 1;
12596                 token = mNextInstallToken++;
12597
12598                 PostInstallData data = new PostInstallData(args, res);
12599                 mRunningInstalls.put(token, data);
12600                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12601
12602                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12603                     // Pass responsibility to the Backup Manager.  It will perform a
12604                     // restore if appropriate, then pass responsibility back to the
12605                     // Package Manager to run the post-install observer callbacks
12606                     // and broadcasts.
12607                     IBackupManager bm = IBackupManager.Stub.asInterface(
12608                             ServiceManager.getService(Context.BACKUP_SERVICE));
12609                     if (bm != null) {
12610                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12611                                 + " to BM for possible restore");
12612                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12613                         try {
12614                             // TODO: http://b/22388012
12615                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12616                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12617                             } else {
12618                                 doRestore = false;
12619                             }
12620                         } catch (RemoteException e) {
12621                             // can't happen; the backup manager is local
12622                         } catch (Exception e) {
12623                             Slog.e(TAG, "Exception trying to enqueue restore", e);
12624                             doRestore = false;
12625                         }
12626                     } else {
12627                         Slog.e(TAG, "Backup Manager not found!");
12628                         doRestore = false;
12629                     }
12630                 }
12631
12632                 if (!doRestore) {
12633                     // No restore possible, or the Backup Manager was mysteriously not
12634                     // available -- just fire the post-install work request directly.
12635                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12636
12637                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12638
12639                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12640                     mHandler.sendMessage(msg);
12641                 }
12642             }
12643         });
12644     }
12645
12646     /**
12647      * Callback from PackageSettings whenever an app is first transitioned out of the
12648      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12649      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12650      * here whether the app is the target of an ongoing install, and only send the
12651      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12652      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12653      * handling.
12654      */
12655     void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12656         // Serialize this with the rest of the install-process message chain.  In the
12657         // restore-at-install case, this Runnable will necessarily run before the
12658         // POST_INSTALL message is processed, so the contents of mRunningInstalls
12659         // are coherent.  In the non-restore case, the app has already completed install
12660         // and been launched through some other means, so it is not in a problematic
12661         // state for observers to see the FIRST_LAUNCH signal.
12662         mHandler.post(new Runnable() {
12663             @Override
12664             public void run() {
12665                 for (int i = 0; i < mRunningInstalls.size(); i++) {
12666                     final PostInstallData data = mRunningInstalls.valueAt(i);
12667                     if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12668                         continue;
12669                     }
12670                     if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12671                         // right package; but is it for the right user?
12672                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12673                             if (userId == data.res.newUsers[uIndex]) {
12674                                 if (DEBUG_BACKUP) {
12675                                     Slog.i(TAG, "Package " + pkgName
12676                                             + " being restored so deferring FIRST_LAUNCH");
12677                                 }
12678                                 return;
12679                             }
12680                         }
12681                     }
12682                 }
12683                 // didn't find it, so not being restored
12684                 if (DEBUG_BACKUP) {
12685                     Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12686                 }
12687                 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12688             }
12689         });
12690     }
12691
12692     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12693         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12694                 installerPkg, null, userIds);
12695     }
12696
12697     private abstract class HandlerParams {
12698         private static final int MAX_RETRIES = 4;
12699
12700         /**
12701          * Number of times startCopy() has been attempted and had a non-fatal
12702          * error.
12703          */
12704         private int mRetries = 0;
12705
12706         /** User handle for the user requesting the information or installation. */
12707         private final UserHandle mUser;
12708         String traceMethod;
12709         int traceCookie;
12710
12711         HandlerParams(UserHandle user) {
12712             mUser = user;
12713         }
12714
12715         UserHandle getUser() {
12716             return mUser;
12717         }
12718
12719         HandlerParams setTraceMethod(String traceMethod) {
12720             this.traceMethod = traceMethod;
12721             return this;
12722         }
12723
12724         HandlerParams setTraceCookie(int traceCookie) {
12725             this.traceCookie = traceCookie;
12726             return this;
12727         }
12728
12729         final boolean startCopy() {
12730             boolean res;
12731             try {
12732                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12733
12734                 if (++mRetries > MAX_RETRIES) {
12735                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12736                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
12737                     handleServiceError();
12738                     return false;
12739                 } else {
12740                     handleStartCopy();
12741                     res = true;
12742                 }
12743             } catch (RemoteException e) {
12744                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12745                 mHandler.sendEmptyMessage(MCS_RECONNECT);
12746                 res = false;
12747             }
12748             handleReturnCode();
12749             return res;
12750         }
12751
12752         final void serviceError() {
12753             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12754             handleServiceError();
12755             handleReturnCode();
12756         }
12757
12758         abstract void handleStartCopy() throws RemoteException;
12759         abstract void handleServiceError();
12760         abstract void handleReturnCode();
12761     }
12762
12763     class MeasureParams extends HandlerParams {
12764         private final PackageStats mStats;
12765         private boolean mSuccess;
12766
12767         private final IPackageStatsObserver mObserver;
12768
12769         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12770             super(new UserHandle(stats.userHandle));
12771             mObserver = observer;
12772             mStats = stats;
12773         }
12774
12775         @Override
12776         public String toString() {
12777             return "MeasureParams{"
12778                 + Integer.toHexString(System.identityHashCode(this))
12779                 + " " + mStats.packageName + "}";
12780         }
12781
12782         @Override
12783         void handleStartCopy() throws RemoteException {
12784             synchronized (mInstallLock) {
12785                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12786             }
12787
12788             if (mSuccess) {
12789                 boolean mounted = false;
12790                 try {
12791                     final String status = Environment.getExternalStorageState();
12792                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
12793                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12794                 } catch (Exception e) {
12795                 }
12796
12797                 if (mounted) {
12798                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12799
12800                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12801                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12802
12803                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
12804                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12805
12806                     // Always subtract cache size, since it's a subdirectory
12807                     mStats.externalDataSize -= mStats.externalCacheSize;
12808
12809                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12810                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12811
12812                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
12813                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12814                 }
12815             }
12816         }
12817
12818         @Override
12819         void handleReturnCode() {
12820             if (mObserver != null) {
12821                 try {
12822                     mObserver.onGetStatsCompleted(mStats, mSuccess);
12823                 } catch (RemoteException e) {
12824                     Slog.i(TAG, "Observer no longer exists.");
12825                 }
12826             }
12827         }
12828
12829         @Override
12830         void handleServiceError() {
12831             Slog.e(TAG, "Could not measure application " + mStats.packageName
12832                             + " external storage");
12833         }
12834     }
12835
12836     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12837             throws RemoteException {
12838         long result = 0;
12839         for (File path : paths) {
12840             result += mcs.calculateDirectorySize(path.getAbsolutePath());
12841         }
12842         return result;
12843     }
12844
12845     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12846         for (File path : paths) {
12847             try {
12848                 mcs.clearDirectory(path.getAbsolutePath());
12849             } catch (RemoteException e) {
12850             }
12851         }
12852     }
12853
12854     static class OriginInfo {
12855         /**
12856          * Location where install is coming from, before it has been
12857          * copied/renamed into place. This could be a single monolithic APK
12858          * file, or a cluster directory. This location may be untrusted.
12859          */
12860         final File file;
12861         final String cid;
12862
12863         /**
12864          * Flag indicating that {@link #file} or {@link #cid} has already been
12865          * staged, meaning downstream users don't need to defensively copy the
12866          * contents.
12867          */
12868         final boolean staged;
12869
12870         /**
12871          * Flag indicating that {@link #file} or {@link #cid} is an already
12872          * installed app that is being moved.
12873          */
12874         final boolean existing;
12875
12876         final String resolvedPath;
12877         final File resolvedFile;
12878
12879         static OriginInfo fromNothing() {
12880             return new OriginInfo(null, null, false, false);
12881         }
12882
12883         static OriginInfo fromUntrustedFile(File file) {
12884             return new OriginInfo(file, null, false, false);
12885         }
12886
12887         static OriginInfo fromExistingFile(File file) {
12888             return new OriginInfo(file, null, false, true);
12889         }
12890
12891         static OriginInfo fromStagedFile(File file) {
12892             return new OriginInfo(file, null, true, false);
12893         }
12894
12895         static OriginInfo fromStagedContainer(String cid) {
12896             return new OriginInfo(null, cid, true, false);
12897         }
12898
12899         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12900             this.file = file;
12901             this.cid = cid;
12902             this.staged = staged;
12903             this.existing = existing;
12904
12905             if (cid != null) {
12906                 resolvedPath = PackageHelper.getSdDir(cid);
12907                 resolvedFile = new File(resolvedPath);
12908             } else if (file != null) {
12909                 resolvedPath = file.getAbsolutePath();
12910                 resolvedFile = file;
12911             } else {
12912                 resolvedPath = null;
12913                 resolvedFile = null;
12914             }
12915         }
12916     }
12917
12918     static class MoveInfo {
12919         final int moveId;
12920         final String fromUuid;
12921         final String toUuid;
12922         final String packageName;
12923         final String dataAppName;
12924         final int appId;
12925         final String seinfo;
12926         final int targetSdkVersion;
12927
12928         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12929                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12930             this.moveId = moveId;
12931             this.fromUuid = fromUuid;
12932             this.toUuid = toUuid;
12933             this.packageName = packageName;
12934             this.dataAppName = dataAppName;
12935             this.appId = appId;
12936             this.seinfo = seinfo;
12937             this.targetSdkVersion = targetSdkVersion;
12938         }
12939     }
12940
12941     static class VerificationInfo {
12942         /** A constant used to indicate that a uid value is not present. */
12943         public static final int NO_UID = -1;
12944
12945         /** URI referencing where the package was downloaded from. */
12946         final Uri originatingUri;
12947
12948         /** HTTP referrer URI associated with the originatingURI. */
12949         final Uri referrer;
12950
12951         /** UID of the application that the install request originated from. */
12952         final int originatingUid;
12953
12954         /** UID of application requesting the install */
12955         final int installerUid;
12956
12957         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12958             this.originatingUri = originatingUri;
12959             this.referrer = referrer;
12960             this.originatingUid = originatingUid;
12961             this.installerUid = installerUid;
12962         }
12963     }
12964
12965     class InstallParams extends HandlerParams {
12966         final OriginInfo origin;
12967         final MoveInfo move;
12968         final IPackageInstallObserver2 observer;
12969         int installFlags;
12970         final String installerPackageName;
12971         final String volumeUuid;
12972         private InstallArgs mArgs;
12973         private int mRet;
12974         final String packageAbiOverride;
12975         final String[] grantedRuntimePermissions;
12976         final VerificationInfo verificationInfo;
12977         final Certificate[][] certificates;
12978
12979         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12980                 int installFlags, String installerPackageName, String volumeUuid,
12981                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12982                 String[] grantedPermissions, Certificate[][] certificates) {
12983             super(user);
12984             this.origin = origin;
12985             this.move = move;
12986             this.observer = observer;
12987             this.installFlags = installFlags;
12988             this.installerPackageName = installerPackageName;
12989             this.volumeUuid = volumeUuid;
12990             this.verificationInfo = verificationInfo;
12991             this.packageAbiOverride = packageAbiOverride;
12992             this.grantedRuntimePermissions = grantedPermissions;
12993             this.certificates = certificates;
12994         }
12995
12996         @Override
12997         public String toString() {
12998             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12999                     + " file=" + origin.file + " cid=" + origin.cid + "}";
13000         }
13001
13002         private int installLocationPolicy(PackageInfoLite pkgLite) {
13003             String packageName = pkgLite.packageName;
13004             int installLocation = pkgLite.installLocation;
13005             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13006             // reader
13007             synchronized (mPackages) {
13008                 // Currently installed package which the new package is attempting to replace or
13009                 // null if no such package is installed.
13010                 PackageParser.Package installedPkg = mPackages.get(packageName);
13011                 // Package which currently owns the data which the new package will own if installed.
13012                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13013                 // will be null whereas dataOwnerPkg will contain information about the package
13014                 // which was uninstalled while keeping its data.
13015                 PackageParser.Package dataOwnerPkg = installedPkg;
13016                 if (dataOwnerPkg  == null) {
13017                     PackageSetting ps = mSettings.mPackages.get(packageName);
13018                     if (ps != null) {
13019                         dataOwnerPkg = ps.pkg;
13020                     }
13021                 }
13022
13023                 if (dataOwnerPkg != null) {
13024                     // If installed, the package will get access to data left on the device by its
13025                     // predecessor. As a security measure, this is permited only if this is not a
13026                     // version downgrade or if the predecessor package is marked as debuggable and
13027                     // a downgrade is explicitly requested.
13028                     //
13029                     // On debuggable platform builds, downgrades are permitted even for
13030                     // non-debuggable packages to make testing easier. Debuggable platform builds do
13031                     // not offer security guarantees and thus it's OK to disable some security
13032                     // mechanisms to make debugging/testing easier on those builds. However, even on
13033                     // debuggable builds downgrades of packages are permitted only if requested via
13034                     // installFlags. This is because we aim to keep the behavior of debuggable
13035                     // platform builds as close as possible to the behavior of non-debuggable
13036                     // platform builds.
13037                     final boolean downgradeRequested =
13038                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13039                     final boolean packageDebuggable =
13040                                 (dataOwnerPkg.applicationInfo.flags
13041                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13042                     final boolean downgradePermitted =
13043                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13044                     if (!downgradePermitted) {
13045                         try {
13046                             checkDowngrade(dataOwnerPkg, pkgLite);
13047                         } catch (PackageManagerException e) {
13048                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13049                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13050                         }
13051                     }
13052                 }
13053
13054                 if (installedPkg != null) {
13055                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13056                         // Check for updated system application.
13057                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13058                             if (onSd) {
13059                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
13060                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13061                             }
13062                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13063                         } else {
13064                             if (onSd) {
13065                                 // Install flag overrides everything.
13066                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13067                             }
13068                             // If current upgrade specifies particular preference
13069                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13070                                 // Application explicitly specified internal.
13071                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13072                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13073                                 // App explictly prefers external. Let policy decide
13074                             } else {
13075                                 // Prefer previous location
13076                                 if (isExternal(installedPkg)) {
13077                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13078                                 }
13079                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13080                             }
13081                         }
13082                     } else {
13083                         // Invalid install. Return error code
13084                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13085                     }
13086                 }
13087             }
13088             // All the special cases have been taken care of.
13089             // Return result based on recommended install location.
13090             if (onSd) {
13091                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13092             }
13093             return pkgLite.recommendedInstallLocation;
13094         }
13095
13096         /*
13097          * Invoke remote method to get package information and install
13098          * location values. Override install location based on default
13099          * policy if needed and then create install arguments based
13100          * on the install location.
13101          */
13102         public void handleStartCopy() throws RemoteException {
13103             int ret = PackageManager.INSTALL_SUCCEEDED;
13104
13105             // If we're already staged, we've firmly committed to an install location
13106             if (origin.staged) {
13107                 if (origin.file != null) {
13108                     installFlags |= PackageManager.INSTALL_INTERNAL;
13109                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13110                 } else if (origin.cid != null) {
13111                     installFlags |= PackageManager.INSTALL_EXTERNAL;
13112                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
13113                 } else {
13114                     throw new IllegalStateException("Invalid stage location");
13115                 }
13116             }
13117
13118             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13119             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13120             final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13121             PackageInfoLite pkgLite = null;
13122
13123             if (onInt && onSd) {
13124                 // Check if both bits are set.
13125                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13126                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13127             } else if (onSd && ephemeral) {
13128                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13129                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13130             } else {
13131                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13132                         packageAbiOverride);
13133
13134                 if (DEBUG_EPHEMERAL && ephemeral) {
13135                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
13136                 }
13137
13138                 /*
13139                  * If we have too little free space, try to free cache
13140                  * before giving up.
13141                  */
13142                 if (!origin.staged && pkgLite.recommendedInstallLocation
13143                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13144                     // TODO: focus freeing disk space on the target device
13145                     final StorageManager storage = StorageManager.from(mContext);
13146                     final long lowThreshold = storage.getStorageLowBytes(
13147                             Environment.getDataDirectory());
13148
13149                     final long sizeBytes = mContainerService.calculateInstalledSize(
13150                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13151
13152                     try {
13153                         mInstaller.freeCache(null, sizeBytes + lowThreshold);
13154                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13155                                 installFlags, packageAbiOverride);
13156                     } catch (InstallerException e) {
13157                         Slog.w(TAG, "Failed to free cache", e);
13158                     }
13159
13160                     /*
13161                      * The cache free must have deleted the file we
13162                      * downloaded to install.
13163                      *
13164                      * TODO: fix the "freeCache" call to not delete
13165                      *       the file we care about.
13166                      */
13167                     if (pkgLite.recommendedInstallLocation
13168                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13169                         pkgLite.recommendedInstallLocation
13170                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13171                     }
13172                 }
13173             }
13174
13175             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13176                 int loc = pkgLite.recommendedInstallLocation;
13177                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13178                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13179                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13180                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13181                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13182                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13183                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13184                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13185                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13186                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13187                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13188                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13189                 } else {
13190                     // Override with defaults if needed.
13191                     loc = installLocationPolicy(pkgLite);
13192                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13193                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13194                     } else if (!onSd && !onInt) {
13195                         // Override install location with flags
13196                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13197                             // Set the flag to install on external media.
13198                             installFlags |= PackageManager.INSTALL_EXTERNAL;
13199                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
13200                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13201                             if (DEBUG_EPHEMERAL) {
13202                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13203                             }
13204                             installFlags |= PackageManager.INSTALL_EPHEMERAL;
13205                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13206                                     |PackageManager.INSTALL_INTERNAL);
13207                         } else {
13208                             // Make sure the flag for installing on external
13209                             // media is unset
13210                             installFlags |= PackageManager.INSTALL_INTERNAL;
13211                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13212                         }
13213                     }
13214                 }
13215             }
13216
13217             final InstallArgs args = createInstallArgs(this);
13218             mArgs = args;
13219
13220             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13221                 // TODO: http://b/22976637
13222                 // Apps installed for "all" users use the device owner to verify the app
13223                 UserHandle verifierUser = getUser();
13224                 if (verifierUser == UserHandle.ALL) {
13225                     verifierUser = UserHandle.SYSTEM;
13226                 }
13227
13228                 /*
13229                  * Determine if we have any installed package verifiers. If we
13230                  * do, then we'll defer to them to verify the packages.
13231                  */
13232                 final int requiredUid = mRequiredVerifierPackage == null ? -1
13233                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13234                                 verifierUser.getIdentifier());
13235                 if (!origin.existing && requiredUid != -1
13236                         && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13237                     final Intent verification = new Intent(
13238                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13239                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13240                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13241                             PACKAGE_MIME_TYPE);
13242                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13243
13244                     // Query all live verifiers based on current user state
13245                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13246                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13247
13248                     if (DEBUG_VERIFY) {
13249                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13250                                 + verification.toString() + " with " + pkgLite.verifiers.length
13251                                 + " optional verifiers");
13252                     }
13253
13254                     final int verificationId = mPendingVerificationToken++;
13255
13256                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13257
13258                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13259                             installerPackageName);
13260
13261                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13262                             installFlags);
13263
13264                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13265                             pkgLite.packageName);
13266
13267                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13268                             pkgLite.versionCode);
13269
13270                     if (verificationInfo != null) {
13271                         if (verificationInfo.originatingUri != null) {
13272                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13273                                     verificationInfo.originatingUri);
13274                         }
13275                         if (verificationInfo.referrer != null) {
13276                             verification.putExtra(Intent.EXTRA_REFERRER,
13277                                     verificationInfo.referrer);
13278                         }
13279                         if (verificationInfo.originatingUid >= 0) {
13280                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13281                                     verificationInfo.originatingUid);
13282                         }
13283                         if (verificationInfo.installerUid >= 0) {
13284                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13285                                     verificationInfo.installerUid);
13286                         }
13287                     }
13288
13289                     final PackageVerificationState verificationState = new PackageVerificationState(
13290                             requiredUid, args);
13291
13292                     mPendingVerification.append(verificationId, verificationState);
13293
13294                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13295                             receivers, verificationState);
13296
13297                     /*
13298                      * If any sufficient verifiers were listed in the package
13299                      * manifest, attempt to ask them.
13300                      */
13301                     if (sufficientVerifiers != null) {
13302                         final int N = sufficientVerifiers.size();
13303                         if (N == 0) {
13304                             Slog.i(TAG, "Additional verifiers required, but none installed.");
13305                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13306                         } else {
13307                             for (int i = 0; i < N; i++) {
13308                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13309
13310                                 final Intent sufficientIntent = new Intent(verification);
13311                                 sufficientIntent.setComponent(verifierComponent);
13312                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13313                             }
13314                         }
13315                     }
13316
13317                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13318                             mRequiredVerifierPackage, receivers);
13319                     if (ret == PackageManager.INSTALL_SUCCEEDED
13320                             && mRequiredVerifierPackage != null) {
13321                         Trace.asyncTraceBegin(
13322                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13323                         /*
13324                          * Send the intent to the required verification agent,
13325                          * but only start the verification timeout after the
13326                          * target BroadcastReceivers have run.
13327                          */
13328                         verification.setComponent(requiredVerifierComponent);
13329                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13330                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13331                                 new BroadcastReceiver() {
13332                                     @Override
13333                                     public void onReceive(Context context, Intent intent) {
13334                                         final Message msg = mHandler
13335                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
13336                                         msg.arg1 = verificationId;
13337                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13338                                     }
13339                                 }, null, 0, null, null);
13340
13341                         /*
13342                          * We don't want the copy to proceed until verification
13343                          * succeeds, so null out this field.
13344                          */
13345                         mArgs = null;
13346                     }
13347                 } else {
13348                     /*
13349                      * No package verification is enabled, so immediately start
13350                      * the remote call to initiate copy using temporary file.
13351                      */
13352                     ret = args.copyApk(mContainerService, true);
13353                 }
13354             }
13355
13356             mRet = ret;
13357         }
13358
13359         @Override
13360         void handleReturnCode() {
13361             // If mArgs is null, then MCS couldn't be reached. When it
13362             // reconnects, it will try again to install. At that point, this
13363             // will succeed.
13364             if (mArgs != null) {
13365                 processPendingInstall(mArgs, mRet);
13366             }
13367         }
13368
13369         @Override
13370         void handleServiceError() {
13371             mArgs = createInstallArgs(this);
13372             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13373         }
13374
13375         public boolean isForwardLocked() {
13376             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13377         }
13378     }
13379
13380     /**
13381      * Used during creation of InstallArgs
13382      *
13383      * @param installFlags package installation flags
13384      * @return true if should be installed on external storage
13385      */
13386     private static boolean installOnExternalAsec(int installFlags) {
13387         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13388             return false;
13389         }
13390         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13391             return true;
13392         }
13393         return false;
13394     }
13395
13396     /**
13397      * Used during creation of InstallArgs
13398      *
13399      * @param installFlags package installation flags
13400      * @return true if should be installed as forward locked
13401      */
13402     private static boolean installForwardLocked(int installFlags) {
13403         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13404     }
13405
13406     private InstallArgs createInstallArgs(InstallParams params) {
13407         if (params.move != null) {
13408             return new MoveInstallArgs(params);
13409         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13410             return new AsecInstallArgs(params);
13411         } else {
13412             return new FileInstallArgs(params);
13413         }
13414     }
13415
13416     /**
13417      * Create args that describe an existing installed package. Typically used
13418      * when cleaning up old installs, or used as a move source.
13419      */
13420     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13421             String resourcePath, String[] instructionSets) {
13422         final boolean isInAsec;
13423         if (installOnExternalAsec(installFlags)) {
13424             /* Apps on SD card are always in ASEC containers. */
13425             isInAsec = true;
13426         } else if (installForwardLocked(installFlags)
13427                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13428             /*
13429              * Forward-locked apps are only in ASEC containers if they're the
13430              * new style
13431              */
13432             isInAsec = true;
13433         } else {
13434             isInAsec = false;
13435         }
13436
13437         if (isInAsec) {
13438             return new AsecInstallArgs(codePath, instructionSets,
13439                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13440         } else {
13441             return new FileInstallArgs(codePath, resourcePath, instructionSets);
13442         }
13443     }
13444
13445     static abstract class InstallArgs {
13446         /** @see InstallParams#origin */
13447         final OriginInfo origin;
13448         /** @see InstallParams#move */
13449         final MoveInfo move;
13450
13451         final IPackageInstallObserver2 observer;
13452         // Always refers to PackageManager flags only
13453         final int installFlags;
13454         final String installerPackageName;
13455         final String volumeUuid;
13456         final UserHandle user;
13457         final String abiOverride;
13458         final String[] installGrantPermissions;
13459         /** If non-null, drop an async trace when the install completes */
13460         final String traceMethod;
13461         final int traceCookie;
13462         final Certificate[][] certificates;
13463
13464         // The list of instruction sets supported by this app. This is currently
13465         // only used during the rmdex() phase to clean up resources. We can get rid of this
13466         // if we move dex files under the common app path.
13467         /* nullable */ String[] instructionSets;
13468
13469         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13470                 int installFlags, String installerPackageName, String volumeUuid,
13471                 UserHandle user, String[] instructionSets,
13472                 String abiOverride, String[] installGrantPermissions,
13473                 String traceMethod, int traceCookie, Certificate[][] certificates) {
13474             this.origin = origin;
13475             this.move = move;
13476             this.installFlags = installFlags;
13477             this.observer = observer;
13478             this.installerPackageName = installerPackageName;
13479             this.volumeUuid = volumeUuid;
13480             this.user = user;
13481             this.instructionSets = instructionSets;
13482             this.abiOverride = abiOverride;
13483             this.installGrantPermissions = installGrantPermissions;
13484             this.traceMethod = traceMethod;
13485             this.traceCookie = traceCookie;
13486             this.certificates = certificates;
13487         }
13488
13489         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13490         abstract int doPreInstall(int status);
13491
13492         /**
13493          * Rename package into final resting place. All paths on the given
13494          * scanned package should be updated to reflect the rename.
13495          */
13496         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13497         abstract int doPostInstall(int status, int uid);
13498
13499         /** @see PackageSettingBase#codePathString */
13500         abstract String getCodePath();
13501         /** @see PackageSettingBase#resourcePathString */
13502         abstract String getResourcePath();
13503
13504         // Need installer lock especially for dex file removal.
13505         abstract void cleanUpResourcesLI();
13506         abstract boolean doPostDeleteLI(boolean delete);
13507
13508         /**
13509          * Called before the source arguments are copied. This is used mostly
13510          * for MoveParams when it needs to read the source file to put it in the
13511          * destination.
13512          */
13513         int doPreCopy() {
13514             return PackageManager.INSTALL_SUCCEEDED;
13515         }
13516
13517         /**
13518          * Called after the source arguments are copied. This is used mostly for
13519          * MoveParams when it needs to read the source file to put it in the
13520          * destination.
13521          */
13522         int doPostCopy(int uid) {
13523             return PackageManager.INSTALL_SUCCEEDED;
13524         }
13525
13526         protected boolean isFwdLocked() {
13527             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13528         }
13529
13530         protected boolean isExternalAsec() {
13531             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13532         }
13533
13534         protected boolean isEphemeral() {
13535             return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13536         }
13537
13538         UserHandle getUser() {
13539             return user;
13540         }
13541     }
13542
13543     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13544         if (!allCodePaths.isEmpty()) {
13545             if (instructionSets == null) {
13546                 throw new IllegalStateException("instructionSet == null");
13547             }
13548             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13549             for (String codePath : allCodePaths) {
13550                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13551                     try {
13552                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
13553                     } catch (InstallerException ignored) {
13554                     }
13555                 }
13556             }
13557         }
13558     }
13559
13560     /**
13561      * Logic to handle installation of non-ASEC applications, including copying
13562      * and renaming logic.
13563      */
13564     class FileInstallArgs extends InstallArgs {
13565         private File codeFile;
13566         private File resourceFile;
13567
13568         // Example topology:
13569         // /data/app/com.example/base.apk
13570         // /data/app/com.example/split_foo.apk
13571         // /data/app/com.example/lib/arm/libfoo.so
13572         // /data/app/com.example/lib/arm64/libfoo.so
13573         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13574
13575         /** New install */
13576         FileInstallArgs(InstallParams params) {
13577             super(params.origin, params.move, params.observer, params.installFlags,
13578                     params.installerPackageName, params.volumeUuid,
13579                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13580                     params.grantedRuntimePermissions,
13581                     params.traceMethod, params.traceCookie, params.certificates);
13582             if (isFwdLocked()) {
13583                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13584             }
13585         }
13586
13587         /** Existing install */
13588         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13589             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13590                     null, null, null, 0, null /*certificates*/);
13591             this.codeFile = (codePath != null) ? new File(codePath) : null;
13592             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13593         }
13594
13595         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13596             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13597             try {
13598                 return doCopyApk(imcs, temp);
13599             } finally {
13600                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13601             }
13602         }
13603
13604         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13605             if (origin.staged) {
13606                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13607                 codeFile = origin.file;
13608                 resourceFile = origin.file;
13609                 return PackageManager.INSTALL_SUCCEEDED;
13610             }
13611
13612             try {
13613                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13614                 final File tempDir =
13615                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13616                 codeFile = tempDir;
13617                 resourceFile = tempDir;
13618             } catch (IOException e) {
13619                 Slog.w(TAG, "Failed to create copy file: " + e);
13620                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13621             }
13622
13623             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13624                 @Override
13625                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13626                     if (!FileUtils.isValidExtFilename(name)) {
13627                         throw new IllegalArgumentException("Invalid filename: " + name);
13628                     }
13629                     try {
13630                         final File file = new File(codeFile, name);
13631                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13632                                 O_RDWR | O_CREAT, 0644);
13633                         Os.chmod(file.getAbsolutePath(), 0644);
13634                         return new ParcelFileDescriptor(fd);
13635                     } catch (ErrnoException e) {
13636                         throw new RemoteException("Failed to open: " + e.getMessage());
13637                     }
13638                 }
13639             };
13640
13641             int ret = PackageManager.INSTALL_SUCCEEDED;
13642             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13643             if (ret != PackageManager.INSTALL_SUCCEEDED) {
13644                 Slog.e(TAG, "Failed to copy package");
13645                 return ret;
13646             }
13647
13648             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13649             NativeLibraryHelper.Handle handle = null;
13650             try {
13651                 handle = NativeLibraryHelper.Handle.create(codeFile);
13652                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13653                         abiOverride);
13654             } catch (IOException e) {
13655                 Slog.e(TAG, "Copying native libraries failed", e);
13656                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13657             } finally {
13658                 IoUtils.closeQuietly(handle);
13659             }
13660
13661             return ret;
13662         }
13663
13664         int doPreInstall(int status) {
13665             if (status != PackageManager.INSTALL_SUCCEEDED) {
13666                 cleanUp();
13667             }
13668             return status;
13669         }
13670
13671         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13672             if (status != PackageManager.INSTALL_SUCCEEDED) {
13673                 cleanUp();
13674                 return false;
13675             }
13676
13677             final File targetDir = codeFile.getParentFile();
13678             final File beforeCodeFile = codeFile;
13679             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13680
13681             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13682             try {
13683                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13684             } catch (ErrnoException e) {
13685                 Slog.w(TAG, "Failed to rename", e);
13686                 return false;
13687             }
13688
13689             if (!SELinux.restoreconRecursive(afterCodeFile)) {
13690                 Slog.w(TAG, "Failed to restorecon");
13691                 return false;
13692             }
13693
13694             // Reflect the rename internally
13695             codeFile = afterCodeFile;
13696             resourceFile = afterCodeFile;
13697
13698             // Reflect the rename in scanned details
13699             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13700             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13701                     afterCodeFile, pkg.baseCodePath));
13702             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13703                     afterCodeFile, pkg.splitCodePaths));
13704
13705             // Reflect the rename in app info
13706             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13707             pkg.setApplicationInfoCodePath(pkg.codePath);
13708             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13709             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13710             pkg.setApplicationInfoResourcePath(pkg.codePath);
13711             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13712             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13713
13714             return true;
13715         }
13716
13717         int doPostInstall(int status, int uid) {
13718             if (status != PackageManager.INSTALL_SUCCEEDED) {
13719                 cleanUp();
13720             }
13721             return status;
13722         }
13723
13724         @Override
13725         String getCodePath() {
13726             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13727         }
13728
13729         @Override
13730         String getResourcePath() {
13731             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13732         }
13733
13734         private boolean cleanUp() {
13735             if (codeFile == null || !codeFile.exists()) {
13736                 return false;
13737             }
13738
13739             removeCodePathLI(codeFile);
13740
13741             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13742                 resourceFile.delete();
13743             }
13744
13745             return true;
13746         }
13747
13748         void cleanUpResourcesLI() {
13749             // Try enumerating all code paths before deleting
13750             List<String> allCodePaths = Collections.EMPTY_LIST;
13751             if (codeFile != null && codeFile.exists()) {
13752                 try {
13753                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13754                     allCodePaths = pkg.getAllCodePaths();
13755                 } catch (PackageParserException e) {
13756                     // Ignored; we tried our best
13757                 }
13758             }
13759
13760             cleanUp();
13761             removeDexFiles(allCodePaths, instructionSets);
13762         }
13763
13764         boolean doPostDeleteLI(boolean delete) {
13765             // XXX err, shouldn't we respect the delete flag?
13766             cleanUpResourcesLI();
13767             return true;
13768         }
13769     }
13770
13771     private boolean isAsecExternal(String cid) {
13772         final String asecPath = PackageHelper.getSdFilesystem(cid);
13773         return !asecPath.startsWith(mAsecInternalPath);
13774     }
13775
13776     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13777             PackageManagerException {
13778         if (copyRet < 0) {
13779             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13780                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13781                 throw new PackageManagerException(copyRet, message);
13782             }
13783         }
13784     }
13785
13786     /**
13787      * Extract the MountService "container ID" from the full code path of an
13788      * .apk.
13789      */
13790     static String cidFromCodePath(String fullCodePath) {
13791         int eidx = fullCodePath.lastIndexOf("/");
13792         String subStr1 = fullCodePath.substring(0, eidx);
13793         int sidx = subStr1.lastIndexOf("/");
13794         return subStr1.substring(sidx+1, eidx);
13795     }
13796
13797     /**
13798      * Logic to handle installation of ASEC applications, including copying and
13799      * renaming logic.
13800      */
13801     class AsecInstallArgs extends InstallArgs {
13802         static final String RES_FILE_NAME = "pkg.apk";
13803         static final String PUBLIC_RES_FILE_NAME = "res.zip";
13804
13805         String cid;
13806         String packagePath;
13807         String resourcePath;
13808
13809         /** New install */
13810         AsecInstallArgs(InstallParams params) {
13811             super(params.origin, params.move, params.observer, params.installFlags,
13812                     params.installerPackageName, params.volumeUuid,
13813                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13814                     params.grantedRuntimePermissions,
13815                     params.traceMethod, params.traceCookie, params.certificates);
13816         }
13817
13818         /** Existing install */
13819         AsecInstallArgs(String fullCodePath, String[] instructionSets,
13820                         boolean isExternal, boolean isForwardLocked) {
13821             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13822               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13823                     instructionSets, null, null, null, 0, null /*certificates*/);
13824             // Hackily pretend we're still looking at a full code path
13825             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13826                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13827             }
13828
13829             // Extract cid from fullCodePath
13830             int eidx = fullCodePath.lastIndexOf("/");
13831             String subStr1 = fullCodePath.substring(0, eidx);
13832             int sidx = subStr1.lastIndexOf("/");
13833             cid = subStr1.substring(sidx+1, eidx);
13834             setMountPath(subStr1);
13835         }
13836
13837         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13838             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13839               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13840                     instructionSets, null, null, null, 0, null /*certificates*/);
13841             this.cid = cid;
13842             setMountPath(PackageHelper.getSdDir(cid));
13843         }
13844
13845         void createCopyFile() {
13846             cid = mInstallerService.allocateExternalStageCidLegacy();
13847         }
13848
13849         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13850             if (origin.staged && origin.cid != null) {
13851                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13852                 cid = origin.cid;
13853                 setMountPath(PackageHelper.getSdDir(cid));
13854                 return PackageManager.INSTALL_SUCCEEDED;
13855             }
13856
13857             if (temp) {
13858                 createCopyFile();
13859             } else {
13860                 /*
13861                  * Pre-emptively destroy the container since it's destroyed if
13862                  * copying fails due to it existing anyway.
13863                  */
13864                 PackageHelper.destroySdDir(cid);
13865             }
13866
13867             final String newMountPath = imcs.copyPackageToContainer(
13868                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13869                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13870
13871             if (newMountPath != null) {
13872                 setMountPath(newMountPath);
13873                 return PackageManager.INSTALL_SUCCEEDED;
13874             } else {
13875                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13876             }
13877         }
13878
13879         @Override
13880         String getCodePath() {
13881             return packagePath;
13882         }
13883
13884         @Override
13885         String getResourcePath() {
13886             return resourcePath;
13887         }
13888
13889         int doPreInstall(int status) {
13890             if (status != PackageManager.INSTALL_SUCCEEDED) {
13891                 // Destroy container
13892                 PackageHelper.destroySdDir(cid);
13893             } else {
13894                 boolean mounted = PackageHelper.isContainerMounted(cid);
13895                 if (!mounted) {
13896                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13897                             Process.SYSTEM_UID);
13898                     if (newMountPath != null) {
13899                         setMountPath(newMountPath);
13900                     } else {
13901                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13902                     }
13903                 }
13904             }
13905             return status;
13906         }
13907
13908         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13909             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13910             String newMountPath = null;
13911             if (PackageHelper.isContainerMounted(cid)) {
13912                 // Unmount the container
13913                 if (!PackageHelper.unMountSdDir(cid)) {
13914                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13915                     return false;
13916                 }
13917             }
13918             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13919                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13920                         " which might be stale. Will try to clean up.");
13921                 // Clean up the stale container and proceed to recreate.
13922                 if (!PackageHelper.destroySdDir(newCacheId)) {
13923                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13924                     return false;
13925                 }
13926                 // Successfully cleaned up stale container. Try to rename again.
13927                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13928                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13929                             + " inspite of cleaning it up.");
13930                     return false;
13931                 }
13932             }
13933             if (!PackageHelper.isContainerMounted(newCacheId)) {
13934                 Slog.w(TAG, "Mounting container " + newCacheId);
13935                 newMountPath = PackageHelper.mountSdDir(newCacheId,
13936                         getEncryptKey(), Process.SYSTEM_UID);
13937             } else {
13938                 newMountPath = PackageHelper.getSdDir(newCacheId);
13939             }
13940             if (newMountPath == null) {
13941                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13942                 return false;
13943             }
13944             Log.i(TAG, "Succesfully renamed " + cid +
13945                     " to " + newCacheId +
13946                     " at new path: " + newMountPath);
13947             cid = newCacheId;
13948
13949             final File beforeCodeFile = new File(packagePath);
13950             setMountPath(newMountPath);
13951             final File afterCodeFile = new File(packagePath);
13952
13953             // Reflect the rename in scanned details
13954             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13955             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13956                     afterCodeFile, pkg.baseCodePath));
13957             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13958                     afterCodeFile, pkg.splitCodePaths));
13959
13960             // Reflect the rename in app info
13961             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13962             pkg.setApplicationInfoCodePath(pkg.codePath);
13963             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13964             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13965             pkg.setApplicationInfoResourcePath(pkg.codePath);
13966             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13967             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13968
13969             return true;
13970         }
13971
13972         private void setMountPath(String mountPath) {
13973             final File mountFile = new File(mountPath);
13974
13975             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13976             if (monolithicFile.exists()) {
13977                 packagePath = monolithicFile.getAbsolutePath();
13978                 if (isFwdLocked()) {
13979                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13980                 } else {
13981                     resourcePath = packagePath;
13982                 }
13983             } else {
13984                 packagePath = mountFile.getAbsolutePath();
13985                 resourcePath = packagePath;
13986             }
13987         }
13988
13989         int doPostInstall(int status, int uid) {
13990             if (status != PackageManager.INSTALL_SUCCEEDED) {
13991                 cleanUp();
13992             } else {
13993                 final int groupOwner;
13994                 final String protectedFile;
13995                 if (isFwdLocked()) {
13996                     groupOwner = UserHandle.getSharedAppGid(uid);
13997                     protectedFile = RES_FILE_NAME;
13998                 } else {
13999                     groupOwner = -1;
14000                     protectedFile = null;
14001                 }
14002
14003                 if (uid < Process.FIRST_APPLICATION_UID
14004                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14005                     Slog.e(TAG, "Failed to finalize " + cid);
14006                     PackageHelper.destroySdDir(cid);
14007                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14008                 }
14009
14010                 boolean mounted = PackageHelper.isContainerMounted(cid);
14011                 if (!mounted) {
14012                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14013                 }
14014             }
14015             return status;
14016         }
14017
14018         private void cleanUp() {
14019             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14020
14021             // Destroy secure container
14022             PackageHelper.destroySdDir(cid);
14023         }
14024
14025         private List<String> getAllCodePaths() {
14026             final File codeFile = new File(getCodePath());
14027             if (codeFile != null && codeFile.exists()) {
14028                 try {
14029                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14030                     return pkg.getAllCodePaths();
14031                 } catch (PackageParserException e) {
14032                     // Ignored; we tried our best
14033                 }
14034             }
14035             return Collections.EMPTY_LIST;
14036         }
14037
14038         void cleanUpResourcesLI() {
14039             // Enumerate all code paths before deleting
14040             cleanUpResourcesLI(getAllCodePaths());
14041         }
14042
14043         private void cleanUpResourcesLI(List<String> allCodePaths) {
14044             cleanUp();
14045             removeDexFiles(allCodePaths, instructionSets);
14046         }
14047
14048         String getPackageName() {
14049             return getAsecPackageName(cid);
14050         }
14051
14052         boolean doPostDeleteLI(boolean delete) {
14053             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14054             final List<String> allCodePaths = getAllCodePaths();
14055             boolean mounted = PackageHelper.isContainerMounted(cid);
14056             if (mounted) {
14057                 // Unmount first
14058                 if (PackageHelper.unMountSdDir(cid)) {
14059                     mounted = false;
14060                 }
14061             }
14062             if (!mounted && delete) {
14063                 cleanUpResourcesLI(allCodePaths);
14064             }
14065             return !mounted;
14066         }
14067
14068         @Override
14069         int doPreCopy() {
14070             if (isFwdLocked()) {
14071                 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14072                         MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14073                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14074                 }
14075             }
14076
14077             return PackageManager.INSTALL_SUCCEEDED;
14078         }
14079
14080         @Override
14081         int doPostCopy(int uid) {
14082             if (isFwdLocked()) {
14083                 if (uid < Process.FIRST_APPLICATION_UID
14084                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14085                                 RES_FILE_NAME)) {
14086                     Slog.e(TAG, "Failed to finalize " + cid);
14087                     PackageHelper.destroySdDir(cid);
14088                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14089                 }
14090             }
14091
14092             return PackageManager.INSTALL_SUCCEEDED;
14093         }
14094     }
14095
14096     /**
14097      * Logic to handle movement of existing installed applications.
14098      */
14099     class MoveInstallArgs extends InstallArgs {
14100         private File codeFile;
14101         private File resourceFile;
14102
14103         /** New install */
14104         MoveInstallArgs(InstallParams params) {
14105             super(params.origin, params.move, params.observer, params.installFlags,
14106                     params.installerPackageName, params.volumeUuid,
14107                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14108                     params.grantedRuntimePermissions,
14109                     params.traceMethod, params.traceCookie, params.certificates);
14110         }
14111
14112         int copyApk(IMediaContainerService imcs, boolean temp) {
14113             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14114                     + move.fromUuid + " to " + move.toUuid);
14115             synchronized (mInstaller) {
14116                 try {
14117                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14118                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14119                 } catch (InstallerException e) {
14120                     Slog.w(TAG, "Failed to move app", e);
14121                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14122                 }
14123             }
14124
14125             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14126             resourceFile = codeFile;
14127             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14128
14129             return PackageManager.INSTALL_SUCCEEDED;
14130         }
14131
14132         int doPreInstall(int status) {
14133             if (status != PackageManager.INSTALL_SUCCEEDED) {
14134                 cleanUp(move.toUuid);
14135             }
14136             return status;
14137         }
14138
14139         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14140             if (status != PackageManager.INSTALL_SUCCEEDED) {
14141                 cleanUp(move.toUuid);
14142                 return false;
14143             }
14144
14145             // Reflect the move in app info
14146             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14147             pkg.setApplicationInfoCodePath(pkg.codePath);
14148             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14149             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14150             pkg.setApplicationInfoResourcePath(pkg.codePath);
14151             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14152             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14153
14154             return true;
14155         }
14156
14157         int doPostInstall(int status, int uid) {
14158             if (status == PackageManager.INSTALL_SUCCEEDED) {
14159                 cleanUp(move.fromUuid);
14160             } else {
14161                 cleanUp(move.toUuid);
14162             }
14163             return status;
14164         }
14165
14166         @Override
14167         String getCodePath() {
14168             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14169         }
14170
14171         @Override
14172         String getResourcePath() {
14173             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14174         }
14175
14176         private boolean cleanUp(String volumeUuid) {
14177             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14178                     move.dataAppName);
14179             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14180             final int[] userIds = sUserManager.getUserIds();
14181             synchronized (mInstallLock) {
14182                 // Clean up both app data and code
14183                 // All package moves are frozen until finished
14184                 for (int userId : userIds) {
14185                     try {
14186                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14187                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14188                     } catch (InstallerException e) {
14189                         Slog.w(TAG, String.valueOf(e));
14190                     }
14191                 }
14192                 removeCodePathLI(codeFile);
14193             }
14194             return true;
14195         }
14196
14197         void cleanUpResourcesLI() {
14198             throw new UnsupportedOperationException();
14199         }
14200
14201         boolean doPostDeleteLI(boolean delete) {
14202             throw new UnsupportedOperationException();
14203         }
14204     }
14205
14206     static String getAsecPackageName(String packageCid) {
14207         int idx = packageCid.lastIndexOf("-");
14208         if (idx == -1) {
14209             return packageCid;
14210         }
14211         return packageCid.substring(0, idx);
14212     }
14213
14214     // Utility method used to create code paths based on package name and available index.
14215     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14216         String idxStr = "";
14217         int idx = 1;
14218         // Fall back to default value of idx=1 if prefix is not
14219         // part of oldCodePath
14220         if (oldCodePath != null) {
14221             String subStr = oldCodePath;
14222             // Drop the suffix right away
14223             if (suffix != null && subStr.endsWith(suffix)) {
14224                 subStr = subStr.substring(0, subStr.length() - suffix.length());
14225             }
14226             // If oldCodePath already contains prefix find out the
14227             // ending index to either increment or decrement.
14228             int sidx = subStr.lastIndexOf(prefix);
14229             if (sidx != -1) {
14230                 subStr = subStr.substring(sidx + prefix.length());
14231                 if (subStr != null) {
14232                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14233                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14234                     }
14235                     try {
14236                         idx = Integer.parseInt(subStr);
14237                         if (idx <= 1) {
14238                             idx++;
14239                         } else {
14240                             idx--;
14241                         }
14242                     } catch(NumberFormatException e) {
14243                     }
14244                 }
14245             }
14246         }
14247         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14248         return prefix + idxStr;
14249     }
14250
14251     private File getNextCodePath(File targetDir, String packageName) {
14252         int suffix = 1;
14253         File result;
14254         do {
14255             result = new File(targetDir, packageName + "-" + suffix);
14256             suffix++;
14257         } while (result.exists());
14258         return result;
14259     }
14260
14261     // Utility method that returns the relative package path with respect
14262     // to the installation directory. Like say for /data/data/com.test-1.apk
14263     // string com.test-1 is returned.
14264     static String deriveCodePathName(String codePath) {
14265         if (codePath == null) {
14266             return null;
14267         }
14268         final File codeFile = new File(codePath);
14269         final String name = codeFile.getName();
14270         if (codeFile.isDirectory()) {
14271             return name;
14272         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14273             final int lastDot = name.lastIndexOf('.');
14274             return name.substring(0, lastDot);
14275         } else {
14276             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14277             return null;
14278         }
14279     }
14280
14281     static class PackageInstalledInfo {
14282         String name;
14283         int uid;
14284         // The set of users that originally had this package installed.
14285         int[] origUsers;
14286         // The set of users that now have this package installed.
14287         int[] newUsers;
14288         PackageParser.Package pkg;
14289         int returnCode;
14290         String returnMsg;
14291         PackageRemovedInfo removedInfo;
14292         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14293
14294         public void setError(int code, String msg) {
14295             setReturnCode(code);
14296             setReturnMessage(msg);
14297             Slog.w(TAG, msg);
14298         }
14299
14300         public void setError(String msg, PackageParserException e) {
14301             setReturnCode(e.error);
14302             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14303             Slog.w(TAG, msg, e);
14304         }
14305
14306         public void setError(String msg, PackageManagerException e) {
14307             returnCode = e.error;
14308             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14309             Slog.w(TAG, msg, e);
14310         }
14311
14312         public void setReturnCode(int returnCode) {
14313             this.returnCode = returnCode;
14314             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14315             for (int i = 0; i < childCount; i++) {
14316                 addedChildPackages.valueAt(i).returnCode = returnCode;
14317             }
14318         }
14319
14320         private void setReturnMessage(String returnMsg) {
14321             this.returnMsg = returnMsg;
14322             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14323             for (int i = 0; i < childCount; i++) {
14324                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14325             }
14326         }
14327
14328         // In some error cases we want to convey more info back to the observer
14329         String origPackage;
14330         String origPermission;
14331     }
14332
14333     /*
14334      * Install a non-existing package.
14335      */
14336     private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14337             int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14338             PackageInstalledInfo res) {
14339         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14340
14341         // Remember this for later, in case we need to rollback this install
14342         String pkgName = pkg.packageName;
14343
14344         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14345
14346         synchronized(mPackages) {
14347             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14348                 // A package with the same name is already installed, though
14349                 // it has been renamed to an older name.  The package we
14350                 // are trying to install should be installed as an update to
14351                 // the existing one, but that has not been requested, so bail.
14352                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14353                         + " without first uninstalling package running as "
14354                         + mSettings.mRenamedPackages.get(pkgName));
14355                 return;
14356             }
14357             if (mPackages.containsKey(pkgName)) {
14358                 // Don't allow installation over an existing package with the same name.
14359                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14360                         + " without first uninstalling.");
14361                 return;
14362             }
14363         }
14364
14365         try {
14366             PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14367                     System.currentTimeMillis(), user);
14368
14369             updateSettingsLI(newPackage, installerPackageName, null, res, user);
14370
14371             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14372                 prepareAppDataAfterInstallLIF(newPackage);
14373
14374             } else {
14375                 // Remove package from internal structures, but keep around any
14376                 // data that might have already existed
14377                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14378                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14379             }
14380         } catch (PackageManagerException e) {
14381             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14382         }
14383
14384         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14385     }
14386
14387     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14388         // Can't rotate keys during boot or if sharedUser.
14389         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14390                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14391             return false;
14392         }
14393         // app is using upgradeKeySets; make sure all are valid
14394         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14395         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14396         for (int i = 0; i < upgradeKeySets.length; i++) {
14397             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14398                 Slog.wtf(TAG, "Package "
14399                          + (oldPs.name != null ? oldPs.name : "<null>")
14400                          + " contains upgrade-key-set reference to unknown key-set: "
14401                          + upgradeKeySets[i]
14402                          + " reverting to signatures check.");
14403                 return false;
14404             }
14405         }
14406         return true;
14407     }
14408
14409     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14410         // Upgrade keysets are being used.  Determine if new package has a superset of the
14411         // required keys.
14412         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14413         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14414         for (int i = 0; i < upgradeKeySets.length; i++) {
14415             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14416             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14417                 return true;
14418             }
14419         }
14420         return false;
14421     }
14422
14423     private static void updateDigest(MessageDigest digest, File file) throws IOException {
14424         try (DigestInputStream digestStream =
14425                 new DigestInputStream(new FileInputStream(file), digest)) {
14426             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14427         }
14428     }
14429
14430     private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14431             UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14432         final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14433
14434         final PackageParser.Package oldPackage;
14435         final String pkgName = pkg.packageName;
14436         final int[] allUsers;
14437         final int[] installedUsers;
14438
14439         synchronized(mPackages) {
14440             oldPackage = mPackages.get(pkgName);
14441             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14442
14443             // don't allow upgrade to target a release SDK from a pre-release SDK
14444             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14445                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14446             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14447                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14448             if (oldTargetsPreRelease
14449                     && !newTargetsPreRelease
14450                     && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14451                 Slog.w(TAG, "Can't install package targeting released sdk");
14452                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14453                 return;
14454             }
14455
14456             // don't allow an upgrade from full to ephemeral
14457             final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14458             if (isEphemeral && !oldIsEphemeral) {
14459                 // can't downgrade from full to ephemeral
14460                 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14461                 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14462                 return;
14463             }
14464
14465             // verify signatures are valid
14466             final PackageSetting ps = mSettings.mPackages.get(pkgName);
14467             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14468                 if (!checkUpgradeKeySetLP(ps, pkg)) {
14469                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14470                             "New package not signed by keys specified by upgrade-keysets: "
14471                                     + pkgName);
14472                     return;
14473                 }
14474             } else {
14475                 // default to original signature matching
14476                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14477                         != PackageManager.SIGNATURE_MATCH) {
14478                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14479                             "New package has a different signature: " + pkgName);
14480                     return;
14481                 }
14482             }
14483
14484             // don't allow a system upgrade unless the upgrade hash matches
14485             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14486                 byte[] digestBytes = null;
14487                 try {
14488                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14489                     updateDigest(digest, new File(pkg.baseCodePath));
14490                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14491                         for (String path : pkg.splitCodePaths) {
14492                             updateDigest(digest, new File(path));
14493                         }
14494                     }
14495                     digestBytes = digest.digest();
14496                 } catch (NoSuchAlgorithmException | IOException e) {
14497                     res.setError(INSTALL_FAILED_INVALID_APK,
14498                             "Could not compute hash: " + pkgName);
14499                     return;
14500                 }
14501                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14502                     res.setError(INSTALL_FAILED_INVALID_APK,
14503                             "New package fails restrict-update check: " + pkgName);
14504                     return;
14505                 }
14506                 // retain upgrade restriction
14507                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14508             }
14509
14510             // Check for shared user id changes
14511             String invalidPackageName =
14512                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14513             if (invalidPackageName != null) {
14514                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14515                         "Package " + invalidPackageName + " tried to change user "
14516                                 + oldPackage.mSharedUserId);
14517                 return;
14518             }
14519
14520             // In case of rollback, remember per-user/profile install state
14521             allUsers = sUserManager.getUserIds();
14522             installedUsers = ps.queryInstalledUsers(allUsers, true);
14523         }
14524
14525         // Update what is removed
14526         res.removedInfo = new PackageRemovedInfo();
14527         res.removedInfo.uid = oldPackage.applicationInfo.uid;
14528         res.removedInfo.removedPackage = oldPackage.packageName;
14529         res.removedInfo.isUpdate = true;
14530         res.removedInfo.origUsers = installedUsers;
14531         final int childCount = (oldPackage.childPackages != null)
14532                 ? oldPackage.childPackages.size() : 0;
14533         for (int i = 0; i < childCount; i++) {
14534             boolean childPackageUpdated = false;
14535             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14536             if (res.addedChildPackages != null) {
14537                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14538                 if (childRes != null) {
14539                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14540                     childRes.removedInfo.removedPackage = childPkg.packageName;
14541                     childRes.removedInfo.isUpdate = true;
14542                     childPackageUpdated = true;
14543                 }
14544             }
14545             if (!childPackageUpdated) {
14546                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14547                 childRemovedRes.removedPackage = childPkg.packageName;
14548                 childRemovedRes.isUpdate = false;
14549                 childRemovedRes.dataRemoved = true;
14550                 synchronized (mPackages) {
14551                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14552                     if (childPs != null) {
14553                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14554                     }
14555                 }
14556                 if (res.removedInfo.removedChildPackages == null) {
14557                     res.removedInfo.removedChildPackages = new ArrayMap<>();
14558                 }
14559                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14560             }
14561         }
14562
14563         boolean sysPkg = (isSystemApp(oldPackage));
14564         if (sysPkg) {
14565             // Set the system/privileged flags as needed
14566             final boolean privileged =
14567                     (oldPackage.applicationInfo.privateFlags
14568                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14569             final int systemPolicyFlags = policyFlags
14570                     | PackageParser.PARSE_IS_SYSTEM
14571                     | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14572
14573             replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14574                     user, allUsers, installerPackageName, res);
14575         } else {
14576             replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14577                     user, allUsers, installerPackageName, res);
14578         }
14579     }
14580
14581     public List<String> getPreviousCodePaths(String packageName) {
14582         final PackageSetting ps = mSettings.mPackages.get(packageName);
14583         final List<String> result = new ArrayList<String>();
14584         if (ps != null && ps.oldCodePaths != null) {
14585             result.addAll(ps.oldCodePaths);
14586         }
14587         return result;
14588     }
14589
14590     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14591             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14592             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14593         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14594                 + deletedPackage);
14595
14596         String pkgName = deletedPackage.packageName;
14597         boolean deletedPkg = true;
14598         boolean addedPkg = false;
14599         boolean updatedSettings = false;
14600         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14601         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14602                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14603
14604         final long origUpdateTime = (pkg.mExtras != null)
14605                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14606
14607         // First delete the existing package while retaining the data directory
14608         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14609                 res.removedInfo, true, pkg)) {
14610             // If the existing package wasn't successfully deleted
14611             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14612             deletedPkg = false;
14613         } else {
14614             // Successfully deleted the old package; proceed with replace.
14615
14616             // If deleted package lived in a container, give users a chance to
14617             // relinquish resources before killing.
14618             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14619                 if (DEBUG_INSTALL) {
14620                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14621                 }
14622                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14623                 final ArrayList<String> pkgList = new ArrayList<String>(1);
14624                 pkgList.add(deletedPackage.applicationInfo.packageName);
14625                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14626             }
14627
14628             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14629                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14630             clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14631
14632             try {
14633                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14634                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14635                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14636
14637                 // Update the in-memory copy of the previous code paths.
14638                 PackageSetting ps = mSettings.mPackages.get(pkgName);
14639                 if (!killApp) {
14640                     if (ps.oldCodePaths == null) {
14641                         ps.oldCodePaths = new ArraySet<>();
14642                     }
14643                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14644                     if (deletedPackage.splitCodePaths != null) {
14645                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14646                     }
14647                 } else {
14648                     ps.oldCodePaths = null;
14649                 }
14650                 if (ps.childPackageNames != null) {
14651                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14652                         final String childPkgName = ps.childPackageNames.get(i);
14653                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14654                         childPs.oldCodePaths = ps.oldCodePaths;
14655                     }
14656                 }
14657                 prepareAppDataAfterInstallLIF(newPackage);
14658                 addedPkg = true;
14659             } catch (PackageManagerException e) {
14660                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14661             }
14662         }
14663
14664         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14665             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14666
14667             // Revert all internal state mutations and added folders for the failed install
14668             if (addedPkg) {
14669                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14670                         res.removedInfo, true, null);
14671             }
14672
14673             // Restore the old package
14674             if (deletedPkg) {
14675                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14676                 File restoreFile = new File(deletedPackage.codePath);
14677                 // Parse old package
14678                 boolean oldExternal = isExternal(deletedPackage);
14679                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14680                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14681                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14682                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14683                 try {
14684                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14685                             null);
14686                 } catch (PackageManagerException e) {
14687                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14688                             + e.getMessage());
14689                     return;
14690                 }
14691
14692                 synchronized (mPackages) {
14693                     // Ensure the installer package name up to date
14694                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14695
14696                     // Update permissions for restored package
14697                     updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14698
14699                     mSettings.writeLPr();
14700                 }
14701
14702                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14703             }
14704         } else {
14705             synchronized (mPackages) {
14706                 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14707                 if (ps != null) {
14708                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14709                     if (res.removedInfo.removedChildPackages != null) {
14710                         final int childCount = res.removedInfo.removedChildPackages.size();
14711                         // Iterate in reverse as we may modify the collection
14712                         for (int i = childCount - 1; i >= 0; i--) {
14713                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14714                             if (res.addedChildPackages.containsKey(childPackageName)) {
14715                                 res.removedInfo.removedChildPackages.removeAt(i);
14716                             } else {
14717                                 PackageRemovedInfo childInfo = res.removedInfo
14718                                         .removedChildPackages.valueAt(i);
14719                                 childInfo.removedForAllUsers = mPackages.get(
14720                                         childInfo.removedPackage) == null;
14721                             }
14722                         }
14723                     }
14724                 }
14725             }
14726         }
14727     }
14728
14729     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14730             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14731             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14732         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14733                 + ", old=" + deletedPackage);
14734
14735         final boolean disabledSystem;
14736
14737         // Remove existing system package
14738         removePackageLI(deletedPackage, true);
14739
14740         synchronized (mPackages) {
14741             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14742         }
14743         if (!disabledSystem) {
14744             // We didn't need to disable the .apk as a current system package,
14745             // which means we are replacing another update that is already
14746             // installed.  We need to make sure to delete the older one's .apk.
14747             res.removedInfo.args = createInstallArgsForExisting(0,
14748                     deletedPackage.applicationInfo.getCodePath(),
14749                     deletedPackage.applicationInfo.getResourcePath(),
14750                     getAppDexInstructionSets(deletedPackage.applicationInfo));
14751         } else {
14752             res.removedInfo.args = null;
14753         }
14754
14755         // Successfully disabled the old package. Now proceed with re-installation
14756         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14757                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14758         clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14759
14760         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14761         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14762                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14763
14764         PackageParser.Package newPackage = null;
14765         try {
14766             // Add the package to the internal data structures
14767             newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14768
14769             // Set the update and install times
14770             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14771             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14772                     System.currentTimeMillis());
14773
14774             // Update the package dynamic state if succeeded
14775             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14776                 // Now that the install succeeded make sure we remove data
14777                 // directories for any child package the update removed.
14778                 final int deletedChildCount = (deletedPackage.childPackages != null)
14779                         ? deletedPackage.childPackages.size() : 0;
14780                 final int newChildCount = (newPackage.childPackages != null)
14781                         ? newPackage.childPackages.size() : 0;
14782                 for (int i = 0; i < deletedChildCount; i++) {
14783                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14784                     boolean childPackageDeleted = true;
14785                     for (int j = 0; j < newChildCount; j++) {
14786                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14787                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14788                             childPackageDeleted = false;
14789                             break;
14790                         }
14791                     }
14792                     if (childPackageDeleted) {
14793                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14794                                 deletedChildPkg.packageName);
14795                         if (ps != null && res.removedInfo.removedChildPackages != null) {
14796                             PackageRemovedInfo removedChildRes = res.removedInfo
14797                                     .removedChildPackages.get(deletedChildPkg.packageName);
14798                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14799                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14800                         }
14801                     }
14802                 }
14803
14804                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14805                 prepareAppDataAfterInstallLIF(newPackage);
14806             }
14807         } catch (PackageManagerException e) {
14808             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14809             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14810         }
14811
14812         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14813             // Re installation failed. Restore old information
14814             // Remove new pkg information
14815             if (newPackage != null) {
14816                 removeInstalledPackageLI(newPackage, true);
14817             }
14818             // Add back the old system package
14819             try {
14820                 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14821             } catch (PackageManagerException e) {
14822                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14823             }
14824
14825             synchronized (mPackages) {
14826                 if (disabledSystem) {
14827                     enableSystemPackageLPw(deletedPackage);
14828                 }
14829
14830                 // Ensure the installer package name up to date
14831                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14832
14833                 // Update permissions for restored package
14834                 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14835
14836                 mSettings.writeLPr();
14837             }
14838
14839             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14840                     + " after failed upgrade");
14841         }
14842     }
14843
14844     /**
14845      * Checks whether the parent or any of the child packages have a change shared
14846      * user. For a package to be a valid update the shred users of the parent and
14847      * the children should match. We may later support changing child shared users.
14848      * @param oldPkg The updated package.
14849      * @param newPkg The update package.
14850      * @return The shared user that change between the versions.
14851      */
14852     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14853             PackageParser.Package newPkg) {
14854         // Check parent shared user
14855         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14856             return newPkg.packageName;
14857         }
14858         // Check child shared users
14859         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14860         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14861         for (int i = 0; i < newChildCount; i++) {
14862             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14863             // If this child was present, did it have the same shared user?
14864             for (int j = 0; j < oldChildCount; j++) {
14865                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14866                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14867                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14868                     return newChildPkg.packageName;
14869                 }
14870             }
14871         }
14872         return null;
14873     }
14874
14875     private void removeNativeBinariesLI(PackageSetting ps) {
14876         // Remove the lib path for the parent package
14877         if (ps != null) {
14878             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14879             // Remove the lib path for the child packages
14880             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14881             for (int i = 0; i < childCount; i++) {
14882                 PackageSetting childPs = null;
14883                 synchronized (mPackages) {
14884                     childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14885                 }
14886                 if (childPs != null) {
14887                     NativeLibraryHelper.removeNativeBinariesLI(childPs
14888                             .legacyNativeLibraryPathString);
14889                 }
14890             }
14891         }
14892     }
14893
14894     private void enableSystemPackageLPw(PackageParser.Package pkg) {
14895         // Enable the parent package
14896         mSettings.enableSystemPackageLPw(pkg.packageName);
14897         // Enable the child packages
14898         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14899         for (int i = 0; i < childCount; i++) {
14900             PackageParser.Package childPkg = pkg.childPackages.get(i);
14901             mSettings.enableSystemPackageLPw(childPkg.packageName);
14902         }
14903     }
14904
14905     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14906             PackageParser.Package newPkg) {
14907         // Disable the parent package (parent always replaced)
14908         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14909         // Disable the child packages
14910         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14911         for (int i = 0; i < childCount; i++) {
14912             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14913             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14914             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14915         }
14916         return disabled;
14917     }
14918
14919     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14920             String installerPackageName) {
14921         // Enable the parent package
14922         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14923         // Enable the child packages
14924         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14925         for (int i = 0; i < childCount; i++) {
14926             PackageParser.Package childPkg = pkg.childPackages.get(i);
14927             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14928         }
14929     }
14930
14931     private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14932         // Collect all used permissions in the UID
14933         ArraySet<String> usedPermissions = new ArraySet<>();
14934         final int packageCount = su.packages.size();
14935         for (int i = 0; i < packageCount; i++) {
14936             PackageSetting ps = su.packages.valueAt(i);
14937             if (ps.pkg == null) {
14938                 continue;
14939             }
14940             final int requestedPermCount = ps.pkg.requestedPermissions.size();
14941             for (int j = 0; j < requestedPermCount; j++) {
14942                 String permission = ps.pkg.requestedPermissions.get(j);
14943                 BasePermission bp = mSettings.mPermissions.get(permission);
14944                 if (bp != null) {
14945                     usedPermissions.add(permission);
14946                 }
14947             }
14948         }
14949
14950         PermissionsState permissionsState = su.getPermissionsState();
14951         // Prune install permissions
14952         List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14953         final int installPermCount = installPermStates.size();
14954         for (int i = installPermCount - 1; i >= 0;  i--) {
14955             PermissionState permissionState = installPermStates.get(i);
14956             if (!usedPermissions.contains(permissionState.getName())) {
14957                 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14958                 if (bp != null) {
14959                     permissionsState.revokeInstallPermission(bp);
14960                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14961                             PackageManager.MASK_PERMISSION_FLAGS, 0);
14962                 }
14963             }
14964         }
14965
14966         int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14967
14968         // Prune runtime permissions
14969         for (int userId : allUserIds) {
14970             List<PermissionState> runtimePermStates = permissionsState
14971                     .getRuntimePermissionStates(userId);
14972             final int runtimePermCount = runtimePermStates.size();
14973             for (int i = runtimePermCount - 1; i >= 0; i--) {
14974                 PermissionState permissionState = runtimePermStates.get(i);
14975                 if (!usedPermissions.contains(permissionState.getName())) {
14976                     BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14977                     if (bp != null) {
14978                         permissionsState.revokeRuntimePermission(bp, userId);
14979                         permissionsState.updatePermissionFlags(bp, userId,
14980                                 PackageManager.MASK_PERMISSION_FLAGS, 0);
14981                         runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14982                                 runtimePermissionChangedUserIds, userId);
14983                     }
14984                 }
14985             }
14986         }
14987
14988         return runtimePermissionChangedUserIds;
14989     }
14990
14991     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14992             int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14993         // Update the parent package setting
14994         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14995                 res, user);
14996         // Update the child packages setting
14997         final int childCount = (newPackage.childPackages != null)
14998                 ? newPackage.childPackages.size() : 0;
14999         for (int i = 0; i < childCount; i++) {
15000             PackageParser.Package childPackage = newPackage.childPackages.get(i);
15001             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15002             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15003                     childRes.origUsers, childRes, user);
15004         }
15005     }
15006
15007     private void updateSettingsInternalLI(PackageParser.Package newPackage,
15008             String installerPackageName, int[] allUsers, int[] installedForUsers,
15009             PackageInstalledInfo res, UserHandle user) {
15010         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15011
15012         String pkgName = newPackage.packageName;
15013         synchronized (mPackages) {
15014             //write settings. the installStatus will be incomplete at this stage.
15015             //note that the new package setting would have already been
15016             //added to mPackages. It hasn't been persisted yet.
15017             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15018             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15019             mSettings.writeLPr();
15020             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15021         }
15022
15023         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15024         synchronized (mPackages) {
15025             updatePermissionsLPw(newPackage.packageName, newPackage,
15026                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15027                             ? UPDATE_PERMISSIONS_ALL : 0));
15028             // For system-bundled packages, we assume that installing an upgraded version
15029             // of the package implies that the user actually wants to run that new code,
15030             // so we enable the package.
15031             PackageSetting ps = mSettings.mPackages.get(pkgName);
15032             final int userId = user.getIdentifier();
15033             if (ps != null) {
15034                 if (isSystemApp(newPackage)) {
15035                     if (DEBUG_INSTALL) {
15036                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15037                     }
15038                     // Enable system package for requested users
15039                     if (res.origUsers != null) {
15040                         for (int origUserId : res.origUsers) {
15041                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
15042                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15043                                         origUserId, installerPackageName);
15044                             }
15045                         }
15046                     }
15047                     // Also convey the prior install/uninstall state
15048                     if (allUsers != null && installedForUsers != null) {
15049                         for (int currentUserId : allUsers) {
15050                             final boolean installed = ArrayUtils.contains(
15051                                     installedForUsers, currentUserId);
15052                             if (DEBUG_INSTALL) {
15053                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15054                             }
15055                             ps.setInstalled(installed, currentUserId);
15056                         }
15057                         // these install state changes will be persisted in the
15058                         // upcoming call to mSettings.writeLPr().
15059                     }
15060                 }
15061                 // It's implied that when a user requests installation, they want the app to be
15062                 // installed and enabled.
15063                 if (userId != UserHandle.USER_ALL) {
15064                     ps.setInstalled(true, userId);
15065                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15066                 }
15067             }
15068             res.name = pkgName;
15069             res.uid = newPackage.applicationInfo.uid;
15070             res.pkg = newPackage;
15071             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15072             mSettings.setInstallerPackageName(pkgName, installerPackageName);
15073             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15074             //to update install status
15075             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15076             mSettings.writeLPr();
15077             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15078         }
15079
15080         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15081     }
15082
15083     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15084         try {
15085             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15086             installPackageLI(args, res);
15087         } finally {
15088             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15089         }
15090     }
15091
15092     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15093         final int installFlags = args.installFlags;
15094         final String installerPackageName = args.installerPackageName;
15095         final String volumeUuid = args.volumeUuid;
15096         final File tmpPackageFile = new File(args.getCodePath());
15097         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15098         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15099                 || (args.volumeUuid != null));
15100         final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15101         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15102         boolean replace = false;
15103         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15104         if (args.move != null) {
15105             // moving a complete application; perform an initial scan on the new install location
15106             scanFlags |= SCAN_INITIAL;
15107         }
15108         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15109             scanFlags |= SCAN_DONT_KILL_APP;
15110         }
15111
15112         // Result object to be returned
15113         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15114
15115         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15116
15117         // Sanity check
15118         if (ephemeral && (forwardLocked || onExternal)) {
15119             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15120                     + " external=" + onExternal);
15121             res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15122             return;
15123         }
15124
15125         // Retrieve PackageSettings and parse package
15126         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15127                 | PackageParser.PARSE_ENFORCE_CODE
15128                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15129                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15130                 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15131                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15132         PackageParser pp = new PackageParser();
15133         pp.setSeparateProcesses(mSeparateProcesses);
15134         pp.setDisplayMetrics(mMetrics);
15135
15136         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15137         final PackageParser.Package pkg;
15138         try {
15139             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15140         } catch (PackageParserException e) {
15141             res.setError("Failed parse during installPackageLI", e);
15142             return;
15143         } finally {
15144             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15145         }
15146
15147         // If we are installing a clustered package add results for the children
15148         if (pkg.childPackages != null) {
15149             synchronized (mPackages) {
15150                 final int childCount = pkg.childPackages.size();
15151                 for (int i = 0; i < childCount; i++) {
15152                     PackageParser.Package childPkg = pkg.childPackages.get(i);
15153                     PackageInstalledInfo childRes = new PackageInstalledInfo();
15154                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15155                     childRes.pkg = childPkg;
15156                     childRes.name = childPkg.packageName;
15157                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15158                     if (childPs != null) {
15159                         childRes.origUsers = childPs.queryInstalledUsers(
15160                                 sUserManager.getUserIds(), true);
15161                     }
15162                     if ((mPackages.containsKey(childPkg.packageName))) {
15163                         childRes.removedInfo = new PackageRemovedInfo();
15164                         childRes.removedInfo.removedPackage = childPkg.packageName;
15165                     }
15166                     if (res.addedChildPackages == null) {
15167                         res.addedChildPackages = new ArrayMap<>();
15168                     }
15169                     res.addedChildPackages.put(childPkg.packageName, childRes);
15170                 }
15171             }
15172         }
15173
15174         // If package doesn't declare API override, mark that we have an install
15175         // time CPU ABI override.
15176         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15177             pkg.cpuAbiOverride = args.abiOverride;
15178         }
15179
15180         String pkgName = res.name = pkg.packageName;
15181         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15182             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15183                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15184                 return;
15185             }
15186         }
15187
15188         try {
15189             // either use what we've been given or parse directly from the APK
15190             if (args.certificates != null) {
15191                 try {
15192                     PackageParser.populateCertificates(pkg, args.certificates);
15193                 } catch (PackageParserException e) {
15194                     // there was something wrong with the certificates we were given;
15195                     // try to pull them from the APK
15196                     PackageParser.collectCertificates(pkg, parseFlags);
15197                 }
15198             } else {
15199                 PackageParser.collectCertificates(pkg, parseFlags);
15200             }
15201         } catch (PackageParserException e) {
15202             res.setError("Failed collect during installPackageLI", e);
15203             return;
15204         }
15205
15206         // Get rid of all references to package scan path via parser.
15207         pp = null;
15208         String oldCodePath = null;
15209         boolean systemApp = false;
15210         synchronized (mPackages) {
15211             // Check if installing already existing package
15212             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15213                 String oldName = mSettings.mRenamedPackages.get(pkgName);
15214                 if (pkg.mOriginalPackages != null
15215                         && pkg.mOriginalPackages.contains(oldName)
15216                         && mPackages.containsKey(oldName)) {
15217                     // This package is derived from an original package,
15218                     // and this device has been updating from that original
15219                     // name.  We must continue using the original name, so
15220                     // rename the new package here.
15221                     pkg.setPackageName(oldName);
15222                     pkgName = pkg.packageName;
15223                     replace = true;
15224                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15225                             + oldName + " pkgName=" + pkgName);
15226                 } else if (mPackages.containsKey(pkgName)) {
15227                     // This package, under its official name, already exists
15228                     // on the device; we should replace it.
15229                     replace = true;
15230                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15231                 }
15232
15233                 // Child packages are installed through the parent package
15234                 if (pkg.parentPackage != null) {
15235                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15236                             "Package " + pkg.packageName + " is child of package "
15237                                     + pkg.parentPackage.parentPackage + ". Child packages "
15238                                     + "can be updated only through the parent package.");
15239                     return;
15240                 }
15241
15242                 if (replace) {
15243                     // Prevent apps opting out from runtime permissions
15244                     PackageParser.Package oldPackage = mPackages.get(pkgName);
15245                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15246                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15247                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15248                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15249                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15250                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15251                                         + " doesn't support runtime permissions but the old"
15252                                         + " target SDK " + oldTargetSdk + " does.");
15253                         return;
15254                     }
15255
15256                     // Prevent installing of child packages
15257                     if (oldPackage.parentPackage != null) {
15258                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15259                                 "Package " + pkg.packageName + " is child of package "
15260                                         + oldPackage.parentPackage + ". Child packages "
15261                                         + "can be updated only through the parent package.");
15262                         return;
15263                     }
15264                 }
15265             }
15266
15267             PackageSetting ps = mSettings.mPackages.get(pkgName);
15268             if (ps != null) {
15269                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15270
15271                 // Quick sanity check that we're signed correctly if updating;
15272                 // we'll check this again later when scanning, but we want to
15273                 // bail early here before tripping over redefined permissions.
15274                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15275                     if (!checkUpgradeKeySetLP(ps, pkg)) {
15276                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15277                                 + pkg.packageName + " upgrade keys do not match the "
15278                                 + "previously installed version");
15279                         return;
15280                     }
15281                 } else {
15282                     try {
15283                         verifySignaturesLP(ps, pkg);
15284                     } catch (PackageManagerException e) {
15285                         res.setError(e.error, e.getMessage());
15286                         return;
15287                     }
15288                 }
15289
15290                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15291                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15292                     systemApp = (ps.pkg.applicationInfo.flags &
15293                             ApplicationInfo.FLAG_SYSTEM) != 0;
15294                 }
15295                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15296             }
15297
15298             // Check whether the newly-scanned package wants to define an already-defined perm
15299             int N = pkg.permissions.size();
15300             for (int i = N-1; i >= 0; i--) {
15301                 PackageParser.Permission perm = pkg.permissions.get(i);
15302                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15303                 if (bp != null) {
15304                     // If the defining package is signed with our cert, it's okay.  This
15305                     // also includes the "updating the same package" case, of course.
15306                     // "updating same package" could also involve key-rotation.
15307                     final boolean sigsOk;
15308                     if (bp.sourcePackage.equals(pkg.packageName)
15309                             && (bp.packageSetting instanceof PackageSetting)
15310                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15311                                     scanFlags))) {
15312                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15313                     } else {
15314                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15315                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15316                     }
15317                     if (!sigsOk) {
15318                         // If the owning package is the system itself, we log but allow
15319                         // install to proceed; we fail the install on all other permission
15320                         // redefinitions.
15321                         if (!bp.sourcePackage.equals("android")) {
15322                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15323                                     + pkg.packageName + " attempting to redeclare permission "
15324                                     + perm.info.name + " already owned by " + bp.sourcePackage);
15325                             res.origPermission = perm.info.name;
15326                             res.origPackage = bp.sourcePackage;
15327                             return;
15328                         } else {
15329                             Slog.w(TAG, "Package " + pkg.packageName
15330                                     + " attempting to redeclare system permission "
15331                                     + perm.info.name + "; ignoring new declaration");
15332                             pkg.permissions.remove(i);
15333                         }
15334                     } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15335                         // Prevent apps to change protection level to dangerous from any other
15336                         // type as this would allow a privilege escalation where an app adds a
15337                         // normal/signature permission in other app's group and later redefines
15338                         // it as dangerous leading to the group auto-grant.
15339                         if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15340                                 == PermissionInfo.PROTECTION_DANGEROUS) {
15341                             if (bp != null && !bp.isRuntime()) {
15342                                 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15343                                         + "non-runtime permission " + perm.info.name
15344                                         + " to runtime; keeping old protection level");
15345                                 perm.info.protectionLevel = bp.protectionLevel;
15346                             }
15347                         }
15348                     }
15349                 }
15350             }
15351         }
15352
15353         if (systemApp) {
15354             if (onExternal) {
15355                 // Abort update; system app can't be replaced with app on sdcard
15356                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15357                         "Cannot install updates to system apps on sdcard");
15358                 return;
15359             } else if (ephemeral) {
15360                 // Abort update; system app can't be replaced with an ephemeral app
15361                 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15362                         "Cannot update a system app with an ephemeral app");
15363                 return;
15364             }
15365         }
15366
15367         if (args.move != null) {
15368             // We did an in-place move, so dex is ready to roll
15369             scanFlags |= SCAN_NO_DEX;
15370             scanFlags |= SCAN_MOVE;
15371
15372             synchronized (mPackages) {
15373                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15374                 if (ps == null) {
15375                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15376                             "Missing settings for moved package " + pkgName);
15377                 }
15378
15379                 // We moved the entire application as-is, so bring over the
15380                 // previously derived ABI information.
15381                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15382                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15383             }
15384
15385         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15386             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15387             scanFlags |= SCAN_NO_DEX;
15388
15389             try {
15390                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15391                     args.abiOverride : pkg.cpuAbiOverride);
15392                 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15393                         true /* extract libs */);
15394             } catch (PackageManagerException pme) {
15395                 Slog.e(TAG, "Error deriving application ABI", pme);
15396                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15397                 return;
15398             }
15399
15400             // Shared libraries for the package need to be updated.
15401             synchronized (mPackages) {
15402                 try {
15403                     updateSharedLibrariesLPw(pkg, null);
15404                 } catch (PackageManagerException e) {
15405                     Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15406                 }
15407             }
15408             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15409             // Do not run PackageDexOptimizer through the local performDexOpt
15410             // method because `pkg` may not be in `mPackages` yet.
15411             //
15412             // Also, don't fail application installs if the dexopt step fails.
15413             mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15414                     null /* instructionSets */, false /* checkProfiles */,
15415                     getCompilerFilterForReason(REASON_INSTALL),
15416                     getOrCreateCompilerPackageStats(pkg));
15417             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15418
15419             // Notify BackgroundDexOptService that the package has been changed.
15420             // If this is an update of a package which used to fail to compile,
15421             // BDOS will remove it from its blacklist.
15422             BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15423         }
15424
15425         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15426             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15427             return;
15428         }
15429
15430         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15431
15432         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15433                 "installPackageLI")) {
15434             if (replace) {
15435                 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15436                         installerPackageName, res);
15437             } else {
15438                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15439                         args.user, installerPackageName, volumeUuid, res);
15440             }
15441         }
15442         synchronized (mPackages) {
15443             final PackageSetting ps = mSettings.mPackages.get(pkgName);
15444             if (ps != null) {
15445                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15446             }
15447
15448             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15449             for (int i = 0; i < childCount; i++) {
15450                 PackageParser.Package childPkg = pkg.childPackages.get(i);
15451                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15452                 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15453                 if (childPs != null) {
15454                     childRes.newUsers = childPs.queryInstalledUsers(
15455                             sUserManager.getUserIds(), true);
15456                 }
15457             }
15458         }
15459     }
15460
15461     private void startIntentFilterVerifications(int userId, boolean replacing,
15462             PackageParser.Package pkg) {
15463         if (mIntentFilterVerifierComponent == null) {
15464             Slog.w(TAG, "No IntentFilter verification will not be done as "
15465                     + "there is no IntentFilterVerifier available!");
15466             return;
15467         }
15468
15469         final int verifierUid = getPackageUid(
15470                 mIntentFilterVerifierComponent.getPackageName(),
15471                 MATCH_DEBUG_TRIAGED_MISSING,
15472                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15473
15474         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15475         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15476         mHandler.sendMessage(msg);
15477
15478         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15479         for (int i = 0; i < childCount; i++) {
15480             PackageParser.Package childPkg = pkg.childPackages.get(i);
15481             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15482             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15483             mHandler.sendMessage(msg);
15484         }
15485     }
15486
15487     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15488             PackageParser.Package pkg) {
15489         int size = pkg.activities.size();
15490         if (size == 0) {
15491             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15492                     "No activity, so no need to verify any IntentFilter!");
15493             return;
15494         }
15495
15496         final boolean hasDomainURLs = hasDomainURLs(pkg);
15497         if (!hasDomainURLs) {
15498             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15499                     "No domain URLs, so no need to verify any IntentFilter!");
15500             return;
15501         }
15502
15503         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15504                 + " if any IntentFilter from the " + size
15505                 + " Activities needs verification ...");
15506
15507         int count = 0;
15508         final String packageName = pkg.packageName;
15509
15510         synchronized (mPackages) {
15511             // If this is a new install and we see that we've already run verification for this
15512             // package, we have nothing to do: it means the state was restored from backup.
15513             if (!replacing) {
15514                 IntentFilterVerificationInfo ivi =
15515                         mSettings.getIntentFilterVerificationLPr(packageName);
15516                 if (ivi != null) {
15517                     if (DEBUG_DOMAIN_VERIFICATION) {
15518                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
15519                                 + ivi.getStatusString());
15520                     }
15521                     return;
15522                 }
15523             }
15524
15525             // If any filters need to be verified, then all need to be.
15526             boolean needToVerify = false;
15527             for (PackageParser.Activity a : pkg.activities) {
15528                 for (ActivityIntentInfo filter : a.intents) {
15529                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15530                         if (DEBUG_DOMAIN_VERIFICATION) {
15531                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15532                         }
15533                         needToVerify = true;
15534                         break;
15535                     }
15536                 }
15537             }
15538
15539             if (needToVerify) {
15540                 final int verificationId = mIntentFilterVerificationToken++;
15541                 for (PackageParser.Activity a : pkg.activities) {
15542                     for (ActivityIntentInfo filter : a.intents) {
15543                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15544                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15545                                     "Verification needed for IntentFilter:" + filter.toString());
15546                             mIntentFilterVerifier.addOneIntentFilterVerification(
15547                                     verifierUid, userId, verificationId, filter, packageName);
15548                             count++;
15549                         }
15550                     }
15551                 }
15552             }
15553         }
15554
15555         if (count > 0) {
15556             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15557                     + " IntentFilter verification" + (count > 1 ? "s" : "")
15558                     +  " for userId:" + userId);
15559             mIntentFilterVerifier.startVerifications(userId);
15560         } else {
15561             if (DEBUG_DOMAIN_VERIFICATION) {
15562                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15563             }
15564         }
15565     }
15566
15567     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15568         final ComponentName cn  = filter.activity.getComponentName();
15569         final String packageName = cn.getPackageName();
15570
15571         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15572                 packageName);
15573         if (ivi == null) {
15574             return true;
15575         }
15576         int status = ivi.getStatus();
15577         switch (status) {
15578             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15579             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15580                 return true;
15581
15582             default:
15583                 // Nothing to do
15584                 return false;
15585         }
15586     }
15587
15588     private static boolean isMultiArch(ApplicationInfo info) {
15589         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15590     }
15591
15592     private static boolean isExternal(PackageParser.Package pkg) {
15593         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15594     }
15595
15596     private static boolean isExternal(PackageSetting ps) {
15597         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15598     }
15599
15600     private static boolean isEphemeral(PackageParser.Package pkg) {
15601         return pkg.applicationInfo.isEphemeralApp();
15602     }
15603
15604     private static boolean isEphemeral(PackageSetting ps) {
15605         return ps.pkg != null && isEphemeral(ps.pkg);
15606     }
15607
15608     private static boolean isSystemApp(PackageParser.Package pkg) {
15609         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15610     }
15611
15612     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15613         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15614     }
15615
15616     private static boolean hasDomainURLs(PackageParser.Package pkg) {
15617         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15618     }
15619
15620     private static boolean isSystemApp(PackageSetting ps) {
15621         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15622     }
15623
15624     private static boolean isUpdatedSystemApp(PackageSetting ps) {
15625         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15626     }
15627
15628     private int packageFlagsToInstallFlags(PackageSetting ps) {
15629         int installFlags = 0;
15630         if (isEphemeral(ps)) {
15631             installFlags |= PackageManager.INSTALL_EPHEMERAL;
15632         }
15633         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15634             // This existing package was an external ASEC install when we have
15635             // the external flag without a UUID
15636             installFlags |= PackageManager.INSTALL_EXTERNAL;
15637         }
15638         if (ps.isForwardLocked()) {
15639             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15640         }
15641         return installFlags;
15642     }
15643
15644     private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15645         if (isExternal(pkg)) {
15646             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15647                 return StorageManager.UUID_PRIMARY_PHYSICAL;
15648             } else {
15649                 return pkg.volumeUuid;
15650             }
15651         } else {
15652             return StorageManager.UUID_PRIVATE_INTERNAL;
15653         }
15654     }
15655
15656     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15657         if (isExternal(pkg)) {
15658             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15659                 return mSettings.getExternalVersion();
15660             } else {
15661                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15662             }
15663         } else {
15664             return mSettings.getInternalVersion();
15665         }
15666     }
15667
15668     private void deleteTempPackageFiles() {
15669         final FilenameFilter filter = new FilenameFilter() {
15670             public boolean accept(File dir, String name) {
15671                 return name.startsWith("vmdl") && name.endsWith(".tmp");
15672             }
15673         };
15674         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15675             file.delete();
15676         }
15677     }
15678
15679     @Override
15680     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15681             int flags) {
15682         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15683                 flags);
15684     }
15685
15686     @Override
15687     public void deletePackage(final String packageName,
15688             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15689         mContext.enforceCallingOrSelfPermission(
15690                 android.Manifest.permission.DELETE_PACKAGES, null);
15691         Preconditions.checkNotNull(packageName);
15692         Preconditions.checkNotNull(observer);
15693         final int uid = Binder.getCallingUid();
15694         if (!isOrphaned(packageName)
15695                 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15696             try {
15697                 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15698                 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15699                 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15700                 observer.onUserActionRequired(intent);
15701             } catch (RemoteException re) {
15702             }
15703             return;
15704         }
15705         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15706         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15707         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15708             mContext.enforceCallingOrSelfPermission(
15709                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15710                     "deletePackage for user " + userId);
15711         }
15712
15713         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15714             try {
15715                 observer.onPackageDeleted(packageName,
15716                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15717             } catch (RemoteException re) {
15718             }
15719             return;
15720         }
15721
15722         if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15723             try {
15724                 observer.onPackageDeleted(packageName,
15725                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15726             } catch (RemoteException re) {
15727             }
15728             return;
15729         }
15730
15731         if (DEBUG_REMOVE) {
15732             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15733                     + " deleteAllUsers: " + deleteAllUsers );
15734         }
15735         // Queue up an async operation since the package deletion may take a little while.
15736         mHandler.post(new Runnable() {
15737             public void run() {
15738                 mHandler.removeCallbacks(this);
15739                 int returnCode;
15740                 if (!deleteAllUsers) {
15741                     returnCode = deletePackageX(packageName, userId, deleteFlags);
15742                 } else {
15743                     int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15744                     // If nobody is blocking uninstall, proceed with delete for all users
15745                     if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15746                         returnCode = deletePackageX(packageName, userId, deleteFlags);
15747                     } else {
15748                         // Otherwise uninstall individually for users with blockUninstalls=false
15749                         final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15750                         for (int userId : users) {
15751                             if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15752                                 returnCode = deletePackageX(packageName, userId, userFlags);
15753                                 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15754                                     Slog.w(TAG, "Package delete failed for user " + userId
15755                                             + ", returnCode " + returnCode);
15756                                 }
15757                             }
15758                         }
15759                         // The app has only been marked uninstalled for certain users.
15760                         // We still need to report that delete was blocked
15761                         returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15762                     }
15763                 }
15764                 try {
15765                     observer.onPackageDeleted(packageName, returnCode, null);
15766                 } catch (RemoteException e) {
15767                     Log.i(TAG, "Observer no longer exists.");
15768                 } //end catch
15769             } //end run
15770         });
15771     }
15772
15773     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15774         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15775               || callingUid == Process.SYSTEM_UID) {
15776             return true;
15777         }
15778         final int callingUserId = UserHandle.getUserId(callingUid);
15779         // If the caller installed the pkgName, then allow it to silently uninstall.
15780         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15781             return true;
15782         }
15783
15784         // Allow package verifier to silently uninstall.
15785         if (mRequiredVerifierPackage != null &&
15786                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15787             return true;
15788         }
15789
15790         // Allow package uninstaller to silently uninstall.
15791         if (mRequiredUninstallerPackage != null &&
15792                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15793             return true;
15794         }
15795
15796         // Allow storage manager to silently uninstall.
15797         if (mStorageManagerPackage != null &&
15798                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15799             return true;
15800         }
15801         return false;
15802     }
15803
15804     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15805         int[] result = EMPTY_INT_ARRAY;
15806         for (int userId : userIds) {
15807             if (getBlockUninstallForUser(packageName, userId)) {
15808                 result = ArrayUtils.appendInt(result, userId);
15809             }
15810         }
15811         return result;
15812     }
15813
15814     @Override
15815     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15816         final int callingUid = Binder.getCallingUid();
15817         if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
15818                 != PERMISSION_GRANTED) {
15819             EventLog.writeEvent(0x534e4554, "128599183", -1, "");
15820             throw new SecurityException(android.Manifest.permission.MANAGE_USERS
15821                     + " permission is required to call this API");
15822         }
15823         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15824     }
15825
15826     private boolean isPackageDeviceAdmin(String packageName, int userId) {
15827         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15828                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15829         try {
15830             if (dpm != null) {
15831                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15832                         /* callingUserOnly =*/ false);
15833                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15834                         : deviceOwnerComponentName.getPackageName();
15835                 // Does the package contains the device owner?
15836                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15837                 // this check is probably not needed, since DO should be registered as a device
15838                 // admin on some user too. (Original bug for this: b/17657954)
15839                 if (packageName.equals(deviceOwnerPackageName)) {
15840                     return true;
15841                 }
15842                 // Does it contain a device admin for any user?
15843                 int[] users;
15844                 if (userId == UserHandle.USER_ALL) {
15845                     users = sUserManager.getUserIds();
15846                 } else {
15847                     users = new int[]{userId};
15848                 }
15849                 for (int i = 0; i < users.length; ++i) {
15850                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15851                         return true;
15852                     }
15853                 }
15854             }
15855         } catch (RemoteException e) {
15856         }
15857         return false;
15858     }
15859
15860     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15861         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15862     }
15863
15864     /**
15865      *  This method is an internal method that could be get invoked either
15866      *  to delete an installed package or to clean up a failed installation.
15867      *  After deleting an installed package, a broadcast is sent to notify any
15868      *  listeners that the package has been removed. For cleaning up a failed
15869      *  installation, the broadcast is not necessary since the package's
15870      *  installation wouldn't have sent the initial broadcast either
15871      *  The key steps in deleting a package are
15872      *  deleting the package information in internal structures like mPackages,
15873      *  deleting the packages base directories through installd
15874      *  updating mSettings to reflect current status
15875      *  persisting settings for later use
15876      *  sending a broadcast if necessary
15877      */
15878     private int deletePackageX(String packageName, int userId, int deleteFlags) {
15879         final PackageRemovedInfo info = new PackageRemovedInfo();
15880         final boolean res;
15881
15882         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15883                 ? UserHandle.USER_ALL : userId;
15884
15885         if (isPackageDeviceAdmin(packageName, removeUser)) {
15886             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15887             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15888         }
15889
15890         PackageSetting uninstalledPs = null;
15891
15892         // for the uninstall-updates case and restricted profiles, remember the per-
15893         // user handle installed state
15894         int[] allUsers;
15895         synchronized (mPackages) {
15896             uninstalledPs = mSettings.mPackages.get(packageName);
15897             if (uninstalledPs == null) {
15898                 Slog.w(TAG, "Not removing non-existent package " + packageName);
15899                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15900             }
15901             allUsers = sUserManager.getUserIds();
15902             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15903         }
15904
15905         final int freezeUser;
15906         if (isUpdatedSystemApp(uninstalledPs)
15907                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15908             // We're downgrading a system app, which will apply to all users, so
15909             // freeze them all during the downgrade
15910             freezeUser = UserHandle.USER_ALL;
15911         } else {
15912             freezeUser = removeUser;
15913         }
15914
15915         synchronized (mInstallLock) {
15916             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15917             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15918                     deleteFlags, "deletePackageX")) {
15919                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15920                         deleteFlags | REMOVE_CHATTY, info, true, null);
15921             }
15922             synchronized (mPackages) {
15923                 if (res) {
15924                     mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15925                 }
15926             }
15927         }
15928
15929         if (res) {
15930             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15931             info.sendPackageRemovedBroadcasts(killApp);
15932             info.sendSystemPackageUpdatedBroadcasts();
15933             info.sendSystemPackageAppearedBroadcasts();
15934         }
15935         // Force a gc here.
15936         Runtime.getRuntime().gc();
15937         // Delete the resources here after sending the broadcast to let
15938         // other processes clean up before deleting resources.
15939         if (info.args != null) {
15940             synchronized (mInstallLock) {
15941                 info.args.doPostDeleteLI(true);
15942             }
15943         }
15944
15945         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15946     }
15947
15948     class PackageRemovedInfo {
15949         String removedPackage;
15950         int uid = -1;
15951         int removedAppId = -1;
15952         int[] origUsers;
15953         int[] removedUsers = null;
15954         boolean isRemovedPackageSystemUpdate = false;
15955         boolean isUpdate;
15956         boolean dataRemoved;
15957         boolean removedForAllUsers;
15958         // Clean up resources deleted packages.
15959         InstallArgs args = null;
15960         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15961         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15962
15963         void sendPackageRemovedBroadcasts(boolean killApp) {
15964             sendPackageRemovedBroadcastInternal(killApp);
15965             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15966             for (int i = 0; i < childCount; i++) {
15967                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15968                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15969             }
15970         }
15971
15972         void sendSystemPackageUpdatedBroadcasts() {
15973             if (isRemovedPackageSystemUpdate) {
15974                 sendSystemPackageUpdatedBroadcastsInternal();
15975                 final int childCount = (removedChildPackages != null)
15976                         ? removedChildPackages.size() : 0;
15977                 for (int i = 0; i < childCount; i++) {
15978                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15979                     if (childInfo.isRemovedPackageSystemUpdate) {
15980                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15981                     }
15982                 }
15983             }
15984         }
15985
15986         void sendSystemPackageAppearedBroadcasts() {
15987             final int packageCount = (appearedChildPackages != null)
15988                     ? appearedChildPackages.size() : 0;
15989             for (int i = 0; i < packageCount; i++) {
15990                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15991                 for (int userId : installedInfo.newUsers) {
15992                     sendPackageAddedForUser(installedInfo.name, true,
15993                             UserHandle.getAppId(installedInfo.uid), userId);
15994                 }
15995             }
15996         }
15997
15998         private void sendSystemPackageUpdatedBroadcastsInternal() {
15999             Bundle extras = new Bundle(2);
16000             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16001             extras.putBoolean(Intent.EXTRA_REPLACING, true);
16002             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16003                     extras, 0, null, null, null);
16004             sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16005                     extras, 0, null, null, null);
16006             sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16007                     null, 0, removedPackage, null, null);
16008         }
16009
16010         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16011             Bundle extras = new Bundle(2);
16012             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16013             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16014             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16015             if (isUpdate || isRemovedPackageSystemUpdate) {
16016                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
16017             }
16018             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16019             if (removedPackage != null) {
16020                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16021                         extras, 0, null, null, removedUsers);
16022                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
16023                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16024                             removedPackage, extras, 0, null, null, removedUsers);
16025                 }
16026             }
16027             if (removedAppId >= 0) {
16028                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16029                         removedUsers);
16030             }
16031         }
16032     }
16033
16034     /*
16035      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16036      * flag is not set, the data directory is removed as well.
16037      * make sure this flag is set for partially installed apps. If not its meaningless to
16038      * delete a partially installed application.
16039      */
16040     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16041             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16042         String packageName = ps.name;
16043         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16044         // Retrieve object to delete permissions for shared user later on
16045         final PackageParser.Package deletedPkg;
16046         final PackageSetting deletedPs;
16047         // reader
16048         synchronized (mPackages) {
16049             deletedPkg = mPackages.get(packageName);
16050             deletedPs = mSettings.mPackages.get(packageName);
16051             if (outInfo != null) {
16052                 outInfo.removedPackage = packageName;
16053                 outInfo.removedUsers = deletedPs != null
16054                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16055                         : null;
16056             }
16057         }
16058
16059         removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16060
16061         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16062             final PackageParser.Package resolvedPkg;
16063             if (deletedPkg != null) {
16064                 resolvedPkg = deletedPkg;
16065             } else {
16066                 // We don't have a parsed package when it lives on an ejected
16067                 // adopted storage device, so fake something together
16068                 resolvedPkg = new PackageParser.Package(ps.name);
16069                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
16070             }
16071             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16072                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16073             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16074             if (outInfo != null) {
16075                 outInfo.dataRemoved = true;
16076             }
16077             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16078         }
16079
16080         // writer
16081         synchronized (mPackages) {
16082             if (deletedPs != null) {
16083                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16084                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16085                     clearDefaultBrowserIfNeeded(packageName);
16086                     if (outInfo != null) {
16087                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16088                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16089                     }
16090                     updatePermissionsLPw(deletedPs.name, null, 0);
16091                     if (deletedPs.sharedUser != null) {
16092                         // Remove permissions associated with package. Since runtime
16093                         // permissions are per user we have to kill the removed package
16094                         // or packages running under the shared user of the removed
16095                         // package if revoking the permissions requested only by the removed
16096                         // package is successful and this causes a change in gids.
16097                         for (int userId : UserManagerService.getInstance().getUserIds()) {
16098                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16099                                     userId);
16100                             if (userIdToKill == UserHandle.USER_ALL
16101                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
16102                                 // If gids changed for this user, kill all affected packages.
16103                                 mHandler.post(new Runnable() {
16104                                     @Override
16105                                     public void run() {
16106                                         // This has to happen with no lock held.
16107                                         killApplication(deletedPs.name, deletedPs.appId,
16108                                                 KILL_APP_REASON_GIDS_CHANGED);
16109                                     }
16110                                 });
16111                                 break;
16112                             }
16113                         }
16114                     }
16115                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16116                 }
16117                 // make sure to preserve per-user disabled state if this removal was just
16118                 // a downgrade of a system app to the factory package
16119                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16120                     if (DEBUG_REMOVE) {
16121                         Slog.d(TAG, "Propagating install state across downgrade");
16122                     }
16123                     for (int userId : allUserHandles) {
16124                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16125                         if (DEBUG_REMOVE) {
16126                             Slog.d(TAG, "    user " + userId + " => " + installed);
16127                         }
16128                         ps.setInstalled(installed, userId);
16129                     }
16130                 }
16131             }
16132             // can downgrade to reader
16133             if (writeSettings) {
16134                 // Save settings now
16135                 mSettings.writeLPr();
16136             }
16137         }
16138         if (outInfo != null) {
16139             // A user ID was deleted here. Go through all users and remove it
16140             // from KeyStore.
16141             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16142         }
16143     }
16144
16145     static boolean locationIsPrivileged(File path) {
16146         try {
16147             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16148                     .getCanonicalPath();
16149             return path.getCanonicalPath().startsWith(privilegedAppDir);
16150         } catch (IOException e) {
16151             Slog.e(TAG, "Unable to access code path " + path);
16152         }
16153         return false;
16154     }
16155
16156     /*
16157      * Tries to delete system package.
16158      */
16159     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16160             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16161             boolean writeSettings) {
16162         if (deletedPs.parentPackageName != null) {
16163             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16164             return false;
16165         }
16166
16167         final boolean applyUserRestrictions
16168                 = (allUserHandles != null) && (outInfo.origUsers != null);
16169         final PackageSetting disabledPs;
16170         // Confirm if the system package has been updated
16171         // An updated system app can be deleted. This will also have to restore
16172         // the system pkg from system partition
16173         // reader
16174         synchronized (mPackages) {
16175             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16176         }
16177
16178         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16179                 + " disabledPs=" + disabledPs);
16180
16181         if (disabledPs == null) {
16182             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16183             return false;
16184         } else if (DEBUG_REMOVE) {
16185             Slog.d(TAG, "Deleting system pkg from data partition");
16186         }
16187
16188         if (DEBUG_REMOVE) {
16189             if (applyUserRestrictions) {
16190                 Slog.d(TAG, "Remembering install states:");
16191                 for (int userId : allUserHandles) {
16192                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16193                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16194                 }
16195             }
16196         }
16197
16198         // Delete the updated package
16199         outInfo.isRemovedPackageSystemUpdate = true;
16200         if (outInfo.removedChildPackages != null) {
16201             final int childCount = (deletedPs.childPackageNames != null)
16202                     ? deletedPs.childPackageNames.size() : 0;
16203             for (int i = 0; i < childCount; i++) {
16204                 String childPackageName = deletedPs.childPackageNames.get(i);
16205                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16206                         .contains(childPackageName)) {
16207                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16208                             childPackageName);
16209                     if (childInfo != null) {
16210                         childInfo.isRemovedPackageSystemUpdate = true;
16211                     }
16212                 }
16213             }
16214         }
16215
16216         if (disabledPs.versionCode < deletedPs.versionCode) {
16217             // Delete data for downgrades
16218             flags &= ~PackageManager.DELETE_KEEP_DATA;
16219         } else {
16220             // Preserve data by setting flag
16221             flags |= PackageManager.DELETE_KEEP_DATA;
16222         }
16223
16224         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16225                 outInfo, writeSettings, disabledPs.pkg);
16226         if (!ret) {
16227             return false;
16228         }
16229
16230         // writer
16231         synchronized (mPackages) {
16232             // Reinstate the old system package
16233             enableSystemPackageLPw(disabledPs.pkg);
16234             // Remove any native libraries from the upgraded package.
16235             removeNativeBinariesLI(deletedPs);
16236         }
16237
16238         // Install the system package
16239         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16240         int parseFlags = mDefParseFlags
16241                 | PackageParser.PARSE_MUST_BE_APK
16242                 | PackageParser.PARSE_IS_SYSTEM
16243                 | PackageParser.PARSE_IS_SYSTEM_DIR;
16244         if (locationIsPrivileged(disabledPs.codePath)) {
16245             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16246         }
16247
16248         final PackageParser.Package newPkg;
16249         try {
16250             newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16251         } catch (PackageManagerException e) {
16252             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16253                     + e.getMessage());
16254             return false;
16255         }
16256         try {
16257             // update shared libraries for the newly re-installed system package
16258             updateSharedLibrariesLPw(newPkg, null);
16259         } catch (PackageManagerException e) {
16260             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16261         }
16262
16263         prepareAppDataAfterInstallLIF(newPkg);
16264
16265         // writer
16266         synchronized (mPackages) {
16267             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16268
16269             // Propagate the permissions state as we do not want to drop on the floor
16270             // runtime permissions. The update permissions method below will take
16271             // care of removing obsolete permissions and grant install permissions.
16272             ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16273             updatePermissionsLPw(newPkg.packageName, newPkg,
16274                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16275
16276             if (applyUserRestrictions) {
16277                 if (DEBUG_REMOVE) {
16278                     Slog.d(TAG, "Propagating install state across reinstall");
16279                 }
16280                 for (int userId : allUserHandles) {
16281                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16282                     if (DEBUG_REMOVE) {
16283                         Slog.d(TAG, "    user " + userId + " => " + installed);
16284                     }
16285                     ps.setInstalled(installed, userId);
16286
16287                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16288                 }
16289                 // Regardless of writeSettings we need to ensure that this restriction
16290                 // state propagation is persisted
16291                 mSettings.writeAllUsersPackageRestrictionsLPr();
16292             }
16293             // can downgrade to reader here
16294             if (writeSettings) {
16295                 mSettings.writeLPr();
16296             }
16297         }
16298         return true;
16299     }
16300
16301     private boolean deleteInstalledPackageLIF(PackageSetting ps,
16302             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16303             PackageRemovedInfo outInfo, boolean writeSettings,
16304             PackageParser.Package replacingPackage) {
16305         synchronized (mPackages) {
16306             if (outInfo != null) {
16307                 outInfo.uid = ps.appId;
16308             }
16309
16310             if (outInfo != null && outInfo.removedChildPackages != null) {
16311                 final int childCount = (ps.childPackageNames != null)
16312                         ? ps.childPackageNames.size() : 0;
16313                 for (int i = 0; i < childCount; i++) {
16314                     String childPackageName = ps.childPackageNames.get(i);
16315                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16316                     if (childPs == null) {
16317                         return false;
16318                     }
16319                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16320                             childPackageName);
16321                     if (childInfo != null) {
16322                         childInfo.uid = childPs.appId;
16323                     }
16324                 }
16325             }
16326         }
16327
16328         // Delete package data from internal structures and also remove data if flag is set
16329         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16330
16331         // Delete the child packages data
16332         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16333         for (int i = 0; i < childCount; i++) {
16334             PackageSetting childPs;
16335             synchronized (mPackages) {
16336                 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16337             }
16338             if (childPs != null) {
16339                 PackageRemovedInfo childOutInfo = (outInfo != null
16340                         && outInfo.removedChildPackages != null)
16341                         ? outInfo.removedChildPackages.get(childPs.name) : null;
16342                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16343                         && (replacingPackage != null
16344                         && !replacingPackage.hasChildPackage(childPs.name))
16345                         ? flags & ~DELETE_KEEP_DATA : flags;
16346                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16347                         deleteFlags, writeSettings);
16348             }
16349         }
16350
16351         // Delete application code and resources only for parent packages
16352         if (ps.parentPackageName == null) {
16353             if (deleteCodeAndResources && (outInfo != null)) {
16354                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16355                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16356                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16357             }
16358         }
16359
16360         return true;
16361     }
16362
16363     @Override
16364     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16365             int userId) {
16366         mContext.enforceCallingOrSelfPermission(
16367                 android.Manifest.permission.DELETE_PACKAGES, null);
16368         synchronized (mPackages) {
16369             PackageSetting ps = mSettings.mPackages.get(packageName);
16370             if (ps == null) {
16371                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16372                 return false;
16373             }
16374             if (!ps.getInstalled(userId)) {
16375                 // Can't block uninstall for an app that is not installed or enabled.
16376                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16377                 return false;
16378             }
16379             ps.setBlockUninstall(blockUninstall, userId);
16380             mSettings.writePackageRestrictionsLPr(userId);
16381         }
16382         return true;
16383     }
16384
16385     @Override
16386     public boolean getBlockUninstallForUser(String packageName, int userId) {
16387         synchronized (mPackages) {
16388             PackageSetting ps = mSettings.mPackages.get(packageName);
16389             if (ps == null) {
16390                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16391                 return false;
16392             }
16393             return ps.getBlockUninstall(userId);
16394         }
16395     }
16396
16397     @Override
16398     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16399         int callingUid = Binder.getCallingUid();
16400         if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16401             throw new SecurityException(
16402                     "setRequiredForSystemUser can only be run by the system or root");
16403         }
16404         synchronized (mPackages) {
16405             PackageSetting ps = mSettings.mPackages.get(packageName);
16406             if (ps == null) {
16407                 Log.w(TAG, "Package doesn't exist: " + packageName);
16408                 return false;
16409             }
16410             if (systemUserApp) {
16411                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16412             } else {
16413                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16414             }
16415             mSettings.writeLPr();
16416         }
16417         return true;
16418     }
16419
16420     /*
16421      * This method handles package deletion in general
16422      */
16423     private boolean deletePackageLIF(String packageName, UserHandle user,
16424             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16425             PackageRemovedInfo outInfo, boolean writeSettings,
16426             PackageParser.Package replacingPackage) {
16427         if (packageName == null) {
16428             Slog.w(TAG, "Attempt to delete null packageName.");
16429             return false;
16430         }
16431
16432         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16433
16434         PackageSetting ps;
16435
16436         synchronized (mPackages) {
16437             ps = mSettings.mPackages.get(packageName);
16438             if (ps == null) {
16439                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16440                 return false;
16441             }
16442
16443             if (ps.parentPackageName != null && (!isSystemApp(ps)
16444                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16445                 if (DEBUG_REMOVE) {
16446                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16447                             + ((user == null) ? UserHandle.USER_ALL : user));
16448                 }
16449                 final int removedUserId = (user != null) ? user.getIdentifier()
16450                         : UserHandle.USER_ALL;
16451                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16452                     return false;
16453                 }
16454                 markPackageUninstalledForUserLPw(ps, user);
16455                 scheduleWritePackageRestrictionsLocked(user);
16456                 return true;
16457             }
16458         }
16459
16460         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16461                 && user.getIdentifier() != UserHandle.USER_ALL)) {
16462             // The caller is asking that the package only be deleted for a single
16463             // user.  To do this, we just mark its uninstalled state and delete
16464             // its data. If this is a system app, we only allow this to happen if
16465             // they have set the special DELETE_SYSTEM_APP which requests different
16466             // semantics than normal for uninstalling system apps.
16467             markPackageUninstalledForUserLPw(ps, user);
16468
16469             if (!isSystemApp(ps)) {
16470                 // Do not uninstall the APK if an app should be cached
16471                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16472                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16473                     // Other user still have this package installed, so all
16474                     // we need to do is clear this user's data and save that
16475                     // it is uninstalled.
16476                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16477                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16478                         return false;
16479                     }
16480                     scheduleWritePackageRestrictionsLocked(user);
16481                     return true;
16482                 } else {
16483                     // We need to set it back to 'installed' so the uninstall
16484                     // broadcasts will be sent correctly.
16485                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16486                     ps.setInstalled(true, user.getIdentifier());
16487                 }
16488             } else {
16489                 // This is a system app, so we assume that the
16490                 // other users still have this package installed, so all
16491                 // we need to do is clear this user's data and save that
16492                 // it is uninstalled.
16493                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16494                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16495                     return false;
16496                 }
16497                 scheduleWritePackageRestrictionsLocked(user);
16498                 return true;
16499             }
16500         }
16501
16502         // If we are deleting a composite package for all users, keep track
16503         // of result for each child.
16504         if (ps.childPackageNames != null && outInfo != null) {
16505             synchronized (mPackages) {
16506                 final int childCount = ps.childPackageNames.size();
16507                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16508                 for (int i = 0; i < childCount; i++) {
16509                     String childPackageName = ps.childPackageNames.get(i);
16510                     PackageRemovedInfo childInfo = new PackageRemovedInfo();
16511                     childInfo.removedPackage = childPackageName;
16512                     outInfo.removedChildPackages.put(childPackageName, childInfo);
16513                     PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16514                     if (childPs != null) {
16515                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16516                     }
16517                 }
16518             }
16519         }
16520
16521         boolean ret = false;
16522         if (isSystemApp(ps)) {
16523             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16524             // When an updated system application is deleted we delete the existing resources
16525             // as well and fall back to existing code in system partition
16526             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16527         } else {
16528             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16529             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16530                     outInfo, writeSettings, replacingPackage);
16531         }
16532
16533         // Take a note whether we deleted the package for all users
16534         if (outInfo != null) {
16535             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16536             if (outInfo.removedChildPackages != null) {
16537                 synchronized (mPackages) {
16538                     final int childCount = outInfo.removedChildPackages.size();
16539                     for (int i = 0; i < childCount; i++) {
16540                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16541                         if (childInfo != null) {
16542                             childInfo.removedForAllUsers = mPackages.get(
16543                                     childInfo.removedPackage) == null;
16544                         }
16545                     }
16546                 }
16547             }
16548             // If we uninstalled an update to a system app there may be some
16549             // child packages that appeared as they are declared in the system
16550             // app but were not declared in the update.
16551             if (isSystemApp(ps)) {
16552                 synchronized (mPackages) {
16553                     PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16554                     final int childCount = (updatedPs.childPackageNames != null)
16555                             ? updatedPs.childPackageNames.size() : 0;
16556                     for (int i = 0; i < childCount; i++) {
16557                         String childPackageName = updatedPs.childPackageNames.get(i);
16558                         if (outInfo.removedChildPackages == null
16559                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16560                             PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16561                             if (childPs == null) {
16562                                 continue;
16563                             }
16564                             PackageInstalledInfo installRes = new PackageInstalledInfo();
16565                             installRes.name = childPackageName;
16566                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16567                             installRes.pkg = mPackages.get(childPackageName);
16568                             installRes.uid = childPs.pkg.applicationInfo.uid;
16569                             if (outInfo.appearedChildPackages == null) {
16570                                 outInfo.appearedChildPackages = new ArrayMap<>();
16571                             }
16572                             outInfo.appearedChildPackages.put(childPackageName, installRes);
16573                         }
16574                     }
16575                 }
16576             }
16577         }
16578
16579         return ret;
16580     }
16581
16582     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16583         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16584                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16585         for (int nextUserId : userIds) {
16586             if (DEBUG_REMOVE) {
16587                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16588             }
16589             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16590                     false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16591                     false /*hidden*/, false /*suspended*/, null, null, null,
16592                     false /*blockUninstall*/,
16593                     ps.readUserState(nextUserId).domainVerificationStatus, 0);
16594         }
16595     }
16596
16597     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16598             PackageRemovedInfo outInfo) {
16599         final PackageParser.Package pkg;
16600         synchronized (mPackages) {
16601             pkg = mPackages.get(ps.name);
16602         }
16603
16604         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16605                 : new int[] {userId};
16606         for (int nextUserId : userIds) {
16607             if (DEBUG_REMOVE) {
16608                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16609                         + nextUserId);
16610             }
16611
16612             destroyAppDataLIF(pkg, userId,
16613                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16614             destroyAppProfilesLIF(pkg, userId);
16615             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16616             schedulePackageCleaning(ps.name, nextUserId, false);
16617             synchronized (mPackages) {
16618                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16619                     scheduleWritePackageRestrictionsLocked(nextUserId);
16620                 }
16621                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16622             }
16623         }
16624
16625         if (outInfo != null) {
16626             outInfo.removedPackage = ps.name;
16627             outInfo.removedAppId = ps.appId;
16628             outInfo.removedUsers = userIds;
16629         }
16630
16631         return true;
16632     }
16633
16634     private final class ClearStorageConnection implements ServiceConnection {
16635         IMediaContainerService mContainerService;
16636
16637         @Override
16638         public void onServiceConnected(ComponentName name, IBinder service) {
16639             synchronized (this) {
16640                 mContainerService = IMediaContainerService.Stub.asInterface(service);
16641                 notifyAll();
16642             }
16643         }
16644
16645         @Override
16646         public void onServiceDisconnected(ComponentName name) {
16647         }
16648     }
16649
16650     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16651         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16652
16653         final boolean mounted;
16654         if (Environment.isExternalStorageEmulated()) {
16655             mounted = true;
16656         } else {
16657             final String status = Environment.getExternalStorageState();
16658
16659             mounted = status.equals(Environment.MEDIA_MOUNTED)
16660                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16661         }
16662
16663         if (!mounted) {
16664             return;
16665         }
16666
16667         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16668         int[] users;
16669         if (userId == UserHandle.USER_ALL) {
16670             users = sUserManager.getUserIds();
16671         } else {
16672             users = new int[] { userId };
16673         }
16674         final ClearStorageConnection conn = new ClearStorageConnection();
16675         if (mContext.bindServiceAsUser(
16676                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16677             try {
16678                 for (int curUser : users) {
16679                     long timeout = SystemClock.uptimeMillis() + 5000;
16680                     synchronized (conn) {
16681                         long now;
16682                         while (conn.mContainerService == null &&
16683                                 (now = SystemClock.uptimeMillis()) < timeout) {
16684                             try {
16685                                 conn.wait(timeout - now);
16686                             } catch (InterruptedException e) {
16687                             }
16688                         }
16689                     }
16690                     if (conn.mContainerService == null) {
16691                         return;
16692                     }
16693
16694                     final UserEnvironment userEnv = new UserEnvironment(curUser);
16695                     clearDirectory(conn.mContainerService,
16696                             userEnv.buildExternalStorageAppCacheDirs(packageName));
16697                     if (allData) {
16698                         clearDirectory(conn.mContainerService,
16699                                 userEnv.buildExternalStorageAppDataDirs(packageName));
16700                         clearDirectory(conn.mContainerService,
16701                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
16702                     }
16703                 }
16704             } finally {
16705                 mContext.unbindService(conn);
16706             }
16707         }
16708     }
16709
16710     @Override
16711     public void clearApplicationProfileData(String packageName) {
16712         enforceSystemOrRoot("Only the system can clear all profile data");
16713
16714         final PackageParser.Package pkg;
16715         synchronized (mPackages) {
16716             pkg = mPackages.get(packageName);
16717         }
16718
16719         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16720             synchronized (mInstallLock) {
16721                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16722                 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16723                         true /* removeBaseMarker */);
16724             }
16725         }
16726     }
16727
16728     @Override
16729     public void clearApplicationUserData(final String packageName,
16730             final IPackageDataObserver observer, final int userId) {
16731         mContext.enforceCallingOrSelfPermission(
16732                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16733
16734         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16735                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16736
16737         if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16738             throw new SecurityException("Cannot clear data for a protected package: "
16739                     + packageName);
16740         }
16741         // Queue up an async operation since the package deletion may take a little while.
16742         mHandler.post(new Runnable() {
16743             public void run() {
16744                 mHandler.removeCallbacks(this);
16745                 final boolean succeeded;
16746                 try (PackageFreezer freezer = freezePackage(packageName,
16747                         "clearApplicationUserData")) {
16748                     synchronized (mInstallLock) {
16749                         succeeded = clearApplicationUserDataLIF(packageName, userId);
16750                     }
16751                     clearExternalStorageDataSync(packageName, userId, true);
16752                 }
16753                 if (succeeded) {
16754                     // invoke DeviceStorageMonitor's update method to clear any notifications
16755                     DeviceStorageMonitorInternal dsm = LocalServices
16756                             .getService(DeviceStorageMonitorInternal.class);
16757                     if (dsm != null) {
16758                         dsm.checkMemory();
16759                     }
16760                 }
16761                 if(observer != null) {
16762                     try {
16763                         observer.onRemoveCompleted(packageName, succeeded);
16764                     } catch (RemoteException e) {
16765                         Log.i(TAG, "Observer no longer exists.");
16766                     }
16767                 } //end if observer
16768             } //end run
16769         });
16770     }
16771
16772     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16773         if (packageName == null) {
16774             Slog.w(TAG, "Attempt to delete null packageName.");
16775             return false;
16776         }
16777
16778         // Try finding details about the requested package
16779         PackageParser.Package pkg;
16780         synchronized (mPackages) {
16781             pkg = mPackages.get(packageName);
16782             if (pkg == null) {
16783                 final PackageSetting ps = mSettings.mPackages.get(packageName);
16784                 if (ps != null) {
16785                     pkg = ps.pkg;
16786                 }
16787             }
16788
16789             if (pkg == null) {
16790                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16791                 return false;
16792             }
16793
16794             PackageSetting ps = (PackageSetting) pkg.mExtras;
16795             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16796         }
16797
16798         clearAppDataLIF(pkg, userId,
16799                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16800
16801         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16802         removeKeystoreDataIfNeeded(userId, appId);
16803
16804         UserManagerInternal umInternal = getUserManagerInternal();
16805         final int flags;
16806         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16807             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16808         } else if (umInternal.isUserRunning(userId)) {
16809             flags = StorageManager.FLAG_STORAGE_DE;
16810         } else {
16811             flags = 0;
16812         }
16813         prepareAppDataContentsLIF(pkg, userId, flags);
16814
16815         return true;
16816     }
16817
16818     /**
16819      * Reverts user permission state changes (permissions and flags) in
16820      * all packages for a given user.
16821      *
16822      * @param userId The device user for which to do a reset.
16823      */
16824     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16825         final int packageCount = mPackages.size();
16826         for (int i = 0; i < packageCount; i++) {
16827             PackageParser.Package pkg = mPackages.valueAt(i);
16828             PackageSetting ps = (PackageSetting) pkg.mExtras;
16829             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16830         }
16831     }
16832
16833     private void resetNetworkPolicies(int userId) {
16834         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16835     }
16836
16837     /**
16838      * Reverts user permission state changes (permissions and flags).
16839      *
16840      * @param ps The package for which to reset.
16841      * @param userId The device user for which to do a reset.
16842      */
16843     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16844             final PackageSetting ps, final int userId) {
16845         if (ps.pkg == null) {
16846             return;
16847         }
16848
16849         // These are flags that can change base on user actions.
16850         final int userSettableMask = FLAG_PERMISSION_USER_SET
16851                 | FLAG_PERMISSION_USER_FIXED
16852                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16853                 | FLAG_PERMISSION_REVIEW_REQUIRED;
16854
16855         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16856                 | FLAG_PERMISSION_POLICY_FIXED;
16857
16858         boolean writeInstallPermissions = false;
16859         boolean writeRuntimePermissions = false;
16860
16861         final int permissionCount = ps.pkg.requestedPermissions.size();
16862         for (int i = 0; i < permissionCount; i++) {
16863             String permission = ps.pkg.requestedPermissions.get(i);
16864
16865             BasePermission bp = mSettings.mPermissions.get(permission);
16866             if (bp == null) {
16867                 continue;
16868             }
16869
16870             // If shared user we just reset the state to which only this app contributed.
16871             if (ps.sharedUser != null) {
16872                 boolean used = false;
16873                 final int packageCount = ps.sharedUser.packages.size();
16874                 for (int j = 0; j < packageCount; j++) {
16875                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16876                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16877                             && pkg.pkg.requestedPermissions.contains(permission)) {
16878                         used = true;
16879                         break;
16880                     }
16881                 }
16882                 if (used) {
16883                     continue;
16884                 }
16885             }
16886
16887             PermissionsState permissionsState = ps.getPermissionsState();
16888
16889             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16890
16891             // Always clear the user settable flags.
16892             final boolean hasInstallState = permissionsState.getInstallPermissionState(
16893                     bp.name) != null;
16894             // If permission review is enabled and this is a legacy app, mark the
16895             // permission as requiring a review as this is the initial state.
16896             int flags = 0;
16897             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16898                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16899                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16900             }
16901             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16902                 if (hasInstallState) {
16903                     writeInstallPermissions = true;
16904                 } else {
16905                     writeRuntimePermissions = true;
16906                 }
16907             }
16908
16909             // Below is only runtime permission handling.
16910             if (!bp.isRuntime()) {
16911                 continue;
16912             }
16913
16914             // Never clobber system or policy.
16915             if ((oldFlags & policyOrSystemFlags) != 0) {
16916                 continue;
16917             }
16918
16919             // If this permission was granted by default, make sure it is.
16920             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16921                 if (permissionsState.grantRuntimePermission(bp, userId)
16922                         != PERMISSION_OPERATION_FAILURE) {
16923                     writeRuntimePermissions = true;
16924                 }
16925             // If permission review is enabled the permissions for a legacy apps
16926             // are represented as constantly granted runtime ones, so don't revoke.
16927             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16928                 // Otherwise, reset the permission.
16929                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16930                 switch (revokeResult) {
16931                     case PERMISSION_OPERATION_SUCCESS:
16932                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16933                         writeRuntimePermissions = true;
16934                         final int appId = ps.appId;
16935                         mHandler.post(new Runnable() {
16936                             @Override
16937                             public void run() {
16938                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16939                             }
16940                         });
16941                     } break;
16942                 }
16943             }
16944         }
16945
16946         // Synchronously write as we are taking permissions away.
16947         if (writeRuntimePermissions) {
16948             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16949         }
16950
16951         // Synchronously write as we are taking permissions away.
16952         if (writeInstallPermissions) {
16953             mSettings.writeLPr();
16954         }
16955     }
16956
16957     /**
16958      * Remove entries from the keystore daemon. Will only remove it if the
16959      * {@code appId} is valid.
16960      */
16961     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16962         if (appId < 0) {
16963             return;
16964         }
16965
16966         final KeyStore keyStore = KeyStore.getInstance();
16967         if (keyStore != null) {
16968             if (userId == UserHandle.USER_ALL) {
16969                 for (final int individual : sUserManager.getUserIds()) {
16970                     keyStore.clearUid(UserHandle.getUid(individual, appId));
16971                 }
16972             } else {
16973                 keyStore.clearUid(UserHandle.getUid(userId, appId));
16974             }
16975         } else {
16976             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16977         }
16978     }
16979
16980     @Override
16981     public void deleteApplicationCacheFiles(final String packageName,
16982             final IPackageDataObserver observer) {
16983         final int userId = UserHandle.getCallingUserId();
16984         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16985     }
16986
16987     @Override
16988     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16989             final IPackageDataObserver observer) {
16990         mContext.enforceCallingOrSelfPermission(
16991                 android.Manifest.permission.DELETE_CACHE_FILES, null);
16992         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16993                 /* requireFullPermission= */ true, /* checkShell= */ false,
16994                 "delete application cache files");
16995
16996         final PackageParser.Package pkg;
16997         synchronized (mPackages) {
16998             pkg = mPackages.get(packageName);
16999         }
17000
17001         // Queue up an async operation since the package deletion may take a little while.
17002         mHandler.post(new Runnable() {
17003             public void run() {
17004                 synchronized (mInstallLock) {
17005                     final int flags = StorageManager.FLAG_STORAGE_DE
17006                             | StorageManager.FLAG_STORAGE_CE;
17007                     // We're only clearing cache files, so we don't care if the
17008                     // app is unfrozen and still able to run
17009                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17010                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17011                 }
17012                 clearExternalStorageDataSync(packageName, userId, false);
17013                 if (observer != null) {
17014                     try {
17015                         observer.onRemoveCompleted(packageName, true);
17016                     } catch (RemoteException e) {
17017                         Log.i(TAG, "Observer no longer exists.");
17018                     }
17019                 }
17020             }
17021         });
17022     }
17023
17024     @Override
17025     public void getPackageSizeInfo(final String packageName, int userHandle,
17026             final IPackageStatsObserver observer) {
17027         mContext.enforceCallingOrSelfPermission(
17028                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
17029         if (packageName == null) {
17030             throw new IllegalArgumentException("Attempt to get size of null packageName");
17031         }
17032
17033         PackageStats stats = new PackageStats(packageName, userHandle);
17034
17035         /*
17036          * Queue up an async operation since the package measurement may take a
17037          * little while.
17038          */
17039         Message msg = mHandler.obtainMessage(INIT_COPY);
17040         msg.obj = new MeasureParams(stats, observer);
17041         mHandler.sendMessage(msg);
17042     }
17043
17044     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17045         final PackageSetting ps;
17046         synchronized (mPackages) {
17047             ps = mSettings.mPackages.get(packageName);
17048             if (ps == null) {
17049                 Slog.w(TAG, "Failed to find settings for " + packageName);
17050                 return false;
17051             }
17052         }
17053         try {
17054             mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17055                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17056                     ps.getCeDataInode(userId), ps.codePathString, stats);
17057         } catch (InstallerException e) {
17058             Slog.w(TAG, String.valueOf(e));
17059             return false;
17060         }
17061
17062         // For now, ignore code size of packages on system partition
17063         if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17064             stats.codeSize = 0;
17065         }
17066
17067         return true;
17068     }
17069
17070     private int getUidTargetSdkVersionLockedLPr(int uid) {
17071         Object obj = mSettings.getUserIdLPr(uid);
17072         if (obj instanceof SharedUserSetting) {
17073             final SharedUserSetting sus = (SharedUserSetting) obj;
17074             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17075             final Iterator<PackageSetting> it = sus.packages.iterator();
17076             while (it.hasNext()) {
17077                 final PackageSetting ps = it.next();
17078                 if (ps.pkg != null) {
17079                     int v = ps.pkg.applicationInfo.targetSdkVersion;
17080                     if (v < vers) vers = v;
17081                 }
17082             }
17083             return vers;
17084         } else if (obj instanceof PackageSetting) {
17085             final PackageSetting ps = (PackageSetting) obj;
17086             if (ps.pkg != null) {
17087                 return ps.pkg.applicationInfo.targetSdkVersion;
17088             }
17089         }
17090         return Build.VERSION_CODES.CUR_DEVELOPMENT;
17091     }
17092
17093     @Override
17094     public void addPreferredActivity(IntentFilter filter, int match,
17095             ComponentName[] set, ComponentName activity, int userId) {
17096         addPreferredActivityInternal(filter, match, set, activity, true, userId,
17097                 "Adding preferred");
17098     }
17099
17100     private void addPreferredActivityInternal(IntentFilter filter, int match,
17101             ComponentName[] set, ComponentName activity, boolean always, int userId,
17102             String opname) {
17103         // writer
17104         int callingUid = Binder.getCallingUid();
17105         enforceCrossUserPermission(callingUid, userId,
17106                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17107         if (filter.countActions() == 0) {
17108             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17109             return;
17110         }
17111         synchronized (mPackages) {
17112             if (mContext.checkCallingOrSelfPermission(
17113                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17114                     != PackageManager.PERMISSION_GRANTED) {
17115                 if (getUidTargetSdkVersionLockedLPr(callingUid)
17116                         < Build.VERSION_CODES.FROYO) {
17117                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17118                             + callingUid);
17119                     return;
17120                 }
17121                 mContext.enforceCallingOrSelfPermission(
17122                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17123             }
17124
17125             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17126             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17127                     + userId + ":");
17128             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17129             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17130             scheduleWritePackageRestrictionsLocked(userId);
17131             postPreferredActivityChangedBroadcast(userId);
17132         }
17133     }
17134
17135     private void postPreferredActivityChangedBroadcast(int userId) {
17136         mHandler.post(() -> {
17137             final IActivityManager am = ActivityManagerNative.getDefault();
17138             if (am == null) {
17139                 return;
17140             }
17141
17142             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17143             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17144             try {
17145                 am.broadcastIntent(null, intent, null, null,
17146                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
17147                         null, false, false, userId);
17148             } catch (RemoteException e) {
17149             }
17150         });
17151     }
17152
17153     @Override
17154     public void replacePreferredActivity(IntentFilter filter, int match,
17155             ComponentName[] set, ComponentName activity, int userId) {
17156         if (filter.countActions() != 1) {
17157             throw new IllegalArgumentException(
17158                     "replacePreferredActivity expects filter to have only 1 action.");
17159         }
17160         if (filter.countDataAuthorities() != 0
17161                 || filter.countDataPaths() != 0
17162                 || filter.countDataSchemes() > 1
17163                 || filter.countDataTypes() != 0) {
17164             throw new IllegalArgumentException(
17165                     "replacePreferredActivity expects filter to have no data authorities, " +
17166                     "paths, or types; and at most one scheme.");
17167         }
17168
17169         final int callingUid = Binder.getCallingUid();
17170         enforceCrossUserPermission(callingUid, userId,
17171                 true /* requireFullPermission */, false /* checkShell */,
17172                 "replace preferred activity");
17173         synchronized (mPackages) {
17174             if (mContext.checkCallingOrSelfPermission(
17175                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17176                     != PackageManager.PERMISSION_GRANTED) {
17177                 if (getUidTargetSdkVersionLockedLPr(callingUid)
17178                         < Build.VERSION_CODES.FROYO) {
17179                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17180                             + Binder.getCallingUid());
17181                     return;
17182                 }
17183                 mContext.enforceCallingOrSelfPermission(
17184                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17185             }
17186
17187             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17188             if (pir != null) {
17189                 // Get all of the existing entries that exactly match this filter.
17190                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17191                 if (existing != null && existing.size() == 1) {
17192                     PreferredActivity cur = existing.get(0);
17193                     if (DEBUG_PREFERRED) {
17194                         Slog.i(TAG, "Checking replace of preferred:");
17195                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17196                         if (!cur.mPref.mAlways) {
17197                             Slog.i(TAG, "  -- CUR; not mAlways!");
17198                         } else {
17199                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17200                             Slog.i(TAG, "  -- CUR: mSet="
17201                                     + Arrays.toString(cur.mPref.mSetComponents));
17202                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17203                             Slog.i(TAG, "  -- NEW: mMatch="
17204                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
17205                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17206                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17207                         }
17208                     }
17209                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17210                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17211                             && cur.mPref.sameSet(set)) {
17212                         // Setting the preferred activity to what it happens to be already
17213                         if (DEBUG_PREFERRED) {
17214                             Slog.i(TAG, "Replacing with same preferred activity "
17215                                     + cur.mPref.mShortComponent + " for user "
17216                                     + userId + ":");
17217                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17218                         }
17219                         return;
17220                     }
17221                 }
17222
17223                 if (existing != null) {
17224                     if (DEBUG_PREFERRED) {
17225                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
17226                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17227                     }
17228                     for (int i = 0; i < existing.size(); i++) {
17229                         PreferredActivity pa = existing.get(i);
17230                         if (DEBUG_PREFERRED) {
17231                             Slog.i(TAG, "Removing existing preferred activity "
17232                                     + pa.mPref.mComponent + ":");
17233                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17234                         }
17235                         pir.removeFilter(pa);
17236                     }
17237                 }
17238             }
17239             addPreferredActivityInternal(filter, match, set, activity, true, userId,
17240                     "Replacing preferred");
17241         }
17242     }
17243
17244     @Override
17245     public void clearPackagePreferredActivities(String packageName) {
17246         final int uid = Binder.getCallingUid();
17247         // writer
17248         synchronized (mPackages) {
17249             PackageParser.Package pkg = mPackages.get(packageName);
17250             if (pkg == null || pkg.applicationInfo.uid != uid) {
17251                 if (mContext.checkCallingOrSelfPermission(
17252                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17253                         != PackageManager.PERMISSION_GRANTED) {
17254                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17255                             < Build.VERSION_CODES.FROYO) {
17256                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17257                                 + Binder.getCallingUid());
17258                         return;
17259                     }
17260                     mContext.enforceCallingOrSelfPermission(
17261                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17262                 }
17263             }
17264
17265             int user = UserHandle.getCallingUserId();
17266             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17267                 scheduleWritePackageRestrictionsLocked(user);
17268             }
17269         }
17270     }
17271
17272     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17273     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17274         ArrayList<PreferredActivity> removed = null;
17275         boolean changed = false;
17276         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17277             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17278             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17279             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17280                 continue;
17281             }
17282             Iterator<PreferredActivity> it = pir.filterIterator();
17283             while (it.hasNext()) {
17284                 PreferredActivity pa = it.next();
17285                 // Mark entry for removal only if it matches the package name
17286                 // and the entry is of type "always".
17287                 if (packageName == null ||
17288                         (pa.mPref.mComponent.getPackageName().equals(packageName)
17289                                 && pa.mPref.mAlways)) {
17290                     if (removed == null) {
17291                         removed = new ArrayList<PreferredActivity>();
17292                     }
17293                     removed.add(pa);
17294                 }
17295             }
17296             if (removed != null) {
17297                 for (int j=0; j<removed.size(); j++) {
17298                     PreferredActivity pa = removed.get(j);
17299                     pir.removeFilter(pa);
17300                 }
17301                 changed = true;
17302             }
17303         }
17304         if (changed) {
17305             postPreferredActivityChangedBroadcast(userId);
17306         }
17307         return changed;
17308     }
17309
17310     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17311     private void clearIntentFilterVerificationsLPw(int userId) {
17312         final int packageCount = mPackages.size();
17313         for (int i = 0; i < packageCount; i++) {
17314             PackageParser.Package pkg = mPackages.valueAt(i);
17315             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17316         }
17317     }
17318
17319     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17320     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17321         if (userId == UserHandle.USER_ALL) {
17322             if (mSettings.removeIntentFilterVerificationLPw(packageName,
17323                     sUserManager.getUserIds())) {
17324                 for (int oneUserId : sUserManager.getUserIds()) {
17325                     scheduleWritePackageRestrictionsLocked(oneUserId);
17326                 }
17327             }
17328         } else {
17329             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17330                 scheduleWritePackageRestrictionsLocked(userId);
17331             }
17332         }
17333     }
17334
17335     void clearDefaultBrowserIfNeeded(String packageName) {
17336         for (int oneUserId : sUserManager.getUserIds()) {
17337             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17338             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17339             if (packageName.equals(defaultBrowserPackageName)) {
17340                 setDefaultBrowserPackageName(null, oneUserId);
17341             }
17342         }
17343     }
17344
17345     @Override
17346     public void resetApplicationPreferences(int userId) {
17347         mContext.enforceCallingOrSelfPermission(
17348                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17349         final long identity = Binder.clearCallingIdentity();
17350         // writer
17351         try {
17352             synchronized (mPackages) {
17353                 clearPackagePreferredActivitiesLPw(null, userId);
17354                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17355                 // TODO: We have to reset the default SMS and Phone. This requires
17356                 // significant refactoring to keep all default apps in the package
17357                 // manager (cleaner but more work) or have the services provide
17358                 // callbacks to the package manager to request a default app reset.
17359                 applyFactoryDefaultBrowserLPw(userId);
17360                 clearIntentFilterVerificationsLPw(userId);
17361                 primeDomainVerificationsLPw(userId);
17362                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17363                 scheduleWritePackageRestrictionsLocked(userId);
17364             }
17365             resetNetworkPolicies(userId);
17366         } finally {
17367             Binder.restoreCallingIdentity(identity);
17368         }
17369     }
17370
17371     @Override
17372     public int getPreferredActivities(List<IntentFilter> outFilters,
17373             List<ComponentName> outActivities, String packageName) {
17374
17375         int num = 0;
17376         final int userId = UserHandle.getCallingUserId();
17377         // reader
17378         synchronized (mPackages) {
17379             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17380             if (pir != null) {
17381                 final Iterator<PreferredActivity> it = pir.filterIterator();
17382                 while (it.hasNext()) {
17383                     final PreferredActivity pa = it.next();
17384                     if (packageName == null
17385                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
17386                                     && pa.mPref.mAlways)) {
17387                         if (outFilters != null) {
17388                             outFilters.add(new IntentFilter(pa));
17389                         }
17390                         if (outActivities != null) {
17391                             outActivities.add(pa.mPref.mComponent);
17392                         }
17393                     }
17394                 }
17395             }
17396         }
17397
17398         return num;
17399     }
17400
17401     @Override
17402     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17403             int userId) {
17404         int callingUid = Binder.getCallingUid();
17405         if (callingUid != Process.SYSTEM_UID) {
17406             throw new SecurityException(
17407                     "addPersistentPreferredActivity can only be run by the system");
17408         }
17409         if (filter.countActions() == 0) {
17410             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17411             return;
17412         }
17413         synchronized (mPackages) {
17414             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17415                     ":");
17416             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17417             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17418                     new PersistentPreferredActivity(filter, activity));
17419             scheduleWritePackageRestrictionsLocked(userId);
17420             postPreferredActivityChangedBroadcast(userId);
17421         }
17422     }
17423
17424     @Override
17425     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17426         int callingUid = Binder.getCallingUid();
17427         if (callingUid != Process.SYSTEM_UID) {
17428             throw new SecurityException(
17429                     "clearPackagePersistentPreferredActivities can only be run by the system");
17430         }
17431         ArrayList<PersistentPreferredActivity> removed = null;
17432         boolean changed = false;
17433         synchronized (mPackages) {
17434             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17435                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17436                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17437                         .valueAt(i);
17438                 if (userId != thisUserId) {
17439                     continue;
17440                 }
17441                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17442                 while (it.hasNext()) {
17443                     PersistentPreferredActivity ppa = it.next();
17444                     // Mark entry for removal only if it matches the package name.
17445                     if (ppa.mComponent.getPackageName().equals(packageName)) {
17446                         if (removed == null) {
17447                             removed = new ArrayList<PersistentPreferredActivity>();
17448                         }
17449                         removed.add(ppa);
17450                     }
17451                 }
17452                 if (removed != null) {
17453                     for (int j=0; j<removed.size(); j++) {
17454                         PersistentPreferredActivity ppa = removed.get(j);
17455                         ppir.removeFilter(ppa);
17456                     }
17457                     changed = true;
17458                 }
17459             }
17460
17461             if (changed) {
17462                 scheduleWritePackageRestrictionsLocked(userId);
17463                 postPreferredActivityChangedBroadcast(userId);
17464             }
17465         }
17466     }
17467
17468     /**
17469      * Common machinery for picking apart a restored XML blob and passing
17470      * it to a caller-supplied functor to be applied to the running system.
17471      */
17472     private void restoreFromXml(XmlPullParser parser, int userId,
17473             String expectedStartTag, BlobXmlRestorer functor)
17474             throws IOException, XmlPullParserException {
17475         int type;
17476         while ((type = parser.next()) != XmlPullParser.START_TAG
17477                 && type != XmlPullParser.END_DOCUMENT) {
17478         }
17479         if (type != XmlPullParser.START_TAG) {
17480             // oops didn't find a start tag?!
17481             if (DEBUG_BACKUP) {
17482                 Slog.e(TAG, "Didn't find start tag during restore");
17483             }
17484             return;
17485         }
17486 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17487         // this is supposed to be TAG_PREFERRED_BACKUP
17488         if (!expectedStartTag.equals(parser.getName())) {
17489             if (DEBUG_BACKUP) {
17490                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17491             }
17492             return;
17493         }
17494
17495         // skip interfering stuff, then we're aligned with the backing implementation
17496         while ((type = parser.next()) == XmlPullParser.TEXT) { }
17497 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17498         functor.apply(parser, userId);
17499     }
17500
17501     private interface BlobXmlRestorer {
17502         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17503     }
17504
17505     /**
17506      * Non-Binder method, support for the backup/restore mechanism: write the
17507      * full set of preferred activities in its canonical XML format.  Returns the
17508      * XML output as a byte array, or null if there is none.
17509      */
17510     @Override
17511     public byte[] getPreferredActivityBackup(int userId) {
17512         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17513             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17514         }
17515
17516         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17517         try {
17518             final XmlSerializer serializer = new FastXmlSerializer();
17519             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17520             serializer.startDocument(null, true);
17521             serializer.startTag(null, TAG_PREFERRED_BACKUP);
17522
17523             synchronized (mPackages) {
17524                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17525             }
17526
17527             serializer.endTag(null, TAG_PREFERRED_BACKUP);
17528             serializer.endDocument();
17529             serializer.flush();
17530         } catch (Exception e) {
17531             if (DEBUG_BACKUP) {
17532                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17533             }
17534             return null;
17535         }
17536
17537         return dataStream.toByteArray();
17538     }
17539
17540     @Override
17541     public void restorePreferredActivities(byte[] backup, int userId) {
17542         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17543             throw new SecurityException("Only the system may call restorePreferredActivities()");
17544         }
17545
17546         try {
17547             final XmlPullParser parser = Xml.newPullParser();
17548             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17549             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17550                     new BlobXmlRestorer() {
17551                         @Override
17552                         public void apply(XmlPullParser parser, int userId)
17553                                 throws XmlPullParserException, IOException {
17554                             synchronized (mPackages) {
17555                                 mSettings.readPreferredActivitiesLPw(parser, userId);
17556                             }
17557                         }
17558                     } );
17559         } catch (Exception e) {
17560             if (DEBUG_BACKUP) {
17561                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17562             }
17563         }
17564     }
17565
17566     /**
17567      * Non-Binder method, support for the backup/restore mechanism: write the
17568      * default browser (etc) settings in its canonical XML format.  Returns the default
17569      * browser XML representation as a byte array, or null if there is none.
17570      */
17571     @Override
17572     public byte[] getDefaultAppsBackup(int userId) {
17573         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17574             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17575         }
17576
17577         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17578         try {
17579             final XmlSerializer serializer = new FastXmlSerializer();
17580             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17581             serializer.startDocument(null, true);
17582             serializer.startTag(null, TAG_DEFAULT_APPS);
17583
17584             synchronized (mPackages) {
17585                 mSettings.writeDefaultAppsLPr(serializer, userId);
17586             }
17587
17588             serializer.endTag(null, TAG_DEFAULT_APPS);
17589             serializer.endDocument();
17590             serializer.flush();
17591         } catch (Exception e) {
17592             if (DEBUG_BACKUP) {
17593                 Slog.e(TAG, "Unable to write default apps for backup", e);
17594             }
17595             return null;
17596         }
17597
17598         return dataStream.toByteArray();
17599     }
17600
17601     @Override
17602     public void restoreDefaultApps(byte[] backup, int userId) {
17603         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17604             throw new SecurityException("Only the system may call restoreDefaultApps()");
17605         }
17606
17607         try {
17608             final XmlPullParser parser = Xml.newPullParser();
17609             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17610             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17611                     new BlobXmlRestorer() {
17612                         @Override
17613                         public void apply(XmlPullParser parser, int userId)
17614                                 throws XmlPullParserException, IOException {
17615                             synchronized (mPackages) {
17616                                 mSettings.readDefaultAppsLPw(parser, userId);
17617                             }
17618                         }
17619                     } );
17620         } catch (Exception e) {
17621             if (DEBUG_BACKUP) {
17622                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17623             }
17624         }
17625     }
17626
17627     @Override
17628     public byte[] getIntentFilterVerificationBackup(int userId) {
17629         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17630             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17631         }
17632
17633         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17634         try {
17635             final XmlSerializer serializer = new FastXmlSerializer();
17636             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17637             serializer.startDocument(null, true);
17638             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17639
17640             synchronized (mPackages) {
17641                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17642             }
17643
17644             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17645             serializer.endDocument();
17646             serializer.flush();
17647         } catch (Exception e) {
17648             if (DEBUG_BACKUP) {
17649                 Slog.e(TAG, "Unable to write default apps for backup", e);
17650             }
17651             return null;
17652         }
17653
17654         return dataStream.toByteArray();
17655     }
17656
17657     @Override
17658     public void restoreIntentFilterVerification(byte[] backup, int userId) {
17659         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17660             throw new SecurityException("Only the system may call restorePreferredActivities()");
17661         }
17662
17663         try {
17664             final XmlPullParser parser = Xml.newPullParser();
17665             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17666             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17667                     new BlobXmlRestorer() {
17668                         @Override
17669                         public void apply(XmlPullParser parser, int userId)
17670                                 throws XmlPullParserException, IOException {
17671                             synchronized (mPackages) {
17672                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
17673                                 mSettings.writeLPr();
17674                             }
17675                         }
17676                     } );
17677         } catch (Exception e) {
17678             if (DEBUG_BACKUP) {
17679                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17680             }
17681         }
17682     }
17683
17684     @Override
17685     public byte[] getPermissionGrantBackup(int userId) {
17686         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17687             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17688         }
17689
17690         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17691         try {
17692             final XmlSerializer serializer = new FastXmlSerializer();
17693             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17694             serializer.startDocument(null, true);
17695             serializer.startTag(null, TAG_PERMISSION_BACKUP);
17696
17697             synchronized (mPackages) {
17698                 serializeRuntimePermissionGrantsLPr(serializer, userId);
17699             }
17700
17701             serializer.endTag(null, TAG_PERMISSION_BACKUP);
17702             serializer.endDocument();
17703             serializer.flush();
17704         } catch (Exception e) {
17705             if (DEBUG_BACKUP) {
17706                 Slog.e(TAG, "Unable to write default apps for backup", e);
17707             }
17708             return null;
17709         }
17710
17711         return dataStream.toByteArray();
17712     }
17713
17714     @Override
17715     public void restorePermissionGrants(byte[] backup, int userId) {
17716         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17717             throw new SecurityException("Only the system may call restorePermissionGrants()");
17718         }
17719
17720         try {
17721             final XmlPullParser parser = Xml.newPullParser();
17722             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17723             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17724                     new BlobXmlRestorer() {
17725                         @Override
17726                         public void apply(XmlPullParser parser, int userId)
17727                                 throws XmlPullParserException, IOException {
17728                             synchronized (mPackages) {
17729                                 processRestoredPermissionGrantsLPr(parser, userId);
17730                             }
17731                         }
17732                     } );
17733         } catch (Exception e) {
17734             if (DEBUG_BACKUP) {
17735                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17736             }
17737         }
17738     }
17739
17740     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17741             throws IOException {
17742         serializer.startTag(null, TAG_ALL_GRANTS);
17743
17744         final int N = mSettings.mPackages.size();
17745         for (int i = 0; i < N; i++) {
17746             final PackageSetting ps = mSettings.mPackages.valueAt(i);
17747             boolean pkgGrantsKnown = false;
17748
17749             PermissionsState packagePerms = ps.getPermissionsState();
17750
17751             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17752                 final int grantFlags = state.getFlags();
17753                 // only look at grants that are not system/policy fixed
17754                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17755                     final boolean isGranted = state.isGranted();
17756                     // And only back up the user-twiddled state bits
17757                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17758                         final String packageName = mSettings.mPackages.keyAt(i);
17759                         if (!pkgGrantsKnown) {
17760                             serializer.startTag(null, TAG_GRANT);
17761                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17762                             pkgGrantsKnown = true;
17763                         }
17764
17765                         final boolean userSet =
17766                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17767                         final boolean userFixed =
17768                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17769                         final boolean revoke =
17770                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17771
17772                         serializer.startTag(null, TAG_PERMISSION);
17773                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17774                         if (isGranted) {
17775                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
17776                         }
17777                         if (userSet) {
17778                             serializer.attribute(null, ATTR_USER_SET, "true");
17779                         }
17780                         if (userFixed) {
17781                             serializer.attribute(null, ATTR_USER_FIXED, "true");
17782                         }
17783                         if (revoke) {
17784                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17785                         }
17786                         serializer.endTag(null, TAG_PERMISSION);
17787                     }
17788                 }
17789             }
17790
17791             if (pkgGrantsKnown) {
17792                 serializer.endTag(null, TAG_GRANT);
17793             }
17794         }
17795
17796         serializer.endTag(null, TAG_ALL_GRANTS);
17797     }
17798
17799     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17800             throws XmlPullParserException, IOException {
17801         String pkgName = null;
17802         int outerDepth = parser.getDepth();
17803         int type;
17804         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17805                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17806             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17807                 continue;
17808             }
17809
17810             final String tagName = parser.getName();
17811             if (tagName.equals(TAG_GRANT)) {
17812                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17813                 if (DEBUG_BACKUP) {
17814                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17815                 }
17816             } else if (tagName.equals(TAG_PERMISSION)) {
17817
17818                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17819                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17820
17821                 int newFlagSet = 0;
17822                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17823                     newFlagSet |= FLAG_PERMISSION_USER_SET;
17824                 }
17825                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17826                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17827                 }
17828                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17829                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17830                 }
17831                 if (DEBUG_BACKUP) {
17832                     Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17833                             + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17834                 }
17835                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17836                 if (ps != null) {
17837                     // Already installed so we apply the grant immediately
17838                     if (DEBUG_BACKUP) {
17839                         Slog.v(TAG, "        + already installed; applying");
17840                     }
17841                     PermissionsState perms = ps.getPermissionsState();
17842                     BasePermission bp = mSettings.mPermissions.get(permName);
17843                     if (bp != null) {
17844                         if (isGranted) {
17845                             perms.grantRuntimePermission(bp, userId);
17846                         }
17847                         if (newFlagSet != 0) {
17848                             perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17849                         }
17850                     }
17851                 } else {
17852                     // Need to wait for post-restore install to apply the grant
17853                     if (DEBUG_BACKUP) {
17854                         Slog.v(TAG, "        - not yet installed; saving for later");
17855                     }
17856                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17857                             isGranted, newFlagSet, userId);
17858                 }
17859             } else {
17860                 PackageManagerService.reportSettingsProblem(Log.WARN,
17861                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17862                 XmlUtils.skipCurrentTag(parser);
17863             }
17864         }
17865
17866         scheduleWriteSettingsLocked();
17867         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17868     }
17869
17870     @Override
17871     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17872             int sourceUserId, int targetUserId, int flags) {
17873         mContext.enforceCallingOrSelfPermission(
17874                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17875         int callingUid = Binder.getCallingUid();
17876         enforceOwnerRights(ownerPackage, callingUid);
17877         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17878         if (intentFilter.countActions() == 0) {
17879             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17880             return;
17881         }
17882         synchronized (mPackages) {
17883             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17884                     ownerPackage, targetUserId, flags);
17885             CrossProfileIntentResolver resolver =
17886                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17887             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17888             // We have all those whose filter is equal. Now checking if the rest is equal as well.
17889             if (existing != null) {
17890                 int size = existing.size();
17891                 for (int i = 0; i < size; i++) {
17892                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17893                         return;
17894                     }
17895                 }
17896             }
17897             resolver.addFilter(newFilter);
17898             scheduleWritePackageRestrictionsLocked(sourceUserId);
17899         }
17900     }
17901
17902     @Override
17903     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17904         mContext.enforceCallingOrSelfPermission(
17905                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17906         int callingUid = Binder.getCallingUid();
17907         enforceOwnerRights(ownerPackage, callingUid);
17908         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17909         synchronized (mPackages) {
17910             CrossProfileIntentResolver resolver =
17911                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17912             ArraySet<CrossProfileIntentFilter> set =
17913                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17914             for (CrossProfileIntentFilter filter : set) {
17915                 if (filter.getOwnerPackage().equals(ownerPackage)) {
17916                     resolver.removeFilter(filter);
17917                 }
17918             }
17919             scheduleWritePackageRestrictionsLocked(sourceUserId);
17920         }
17921     }
17922
17923     // Enforcing that callingUid is owning pkg on userId
17924     private void enforceOwnerRights(String pkg, int callingUid) {
17925         // The system owns everything.
17926         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17927             return;
17928         }
17929         int callingUserId = UserHandle.getUserId(callingUid);
17930         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17931         if (pi == null) {
17932             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17933                     + callingUserId);
17934         }
17935         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17936             throw new SecurityException("Calling uid " + callingUid
17937                     + " does not own package " + pkg);
17938         }
17939     }
17940
17941     @Override
17942     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17943         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17944     }
17945
17946     private Intent getHomeIntent() {
17947         Intent intent = new Intent(Intent.ACTION_MAIN);
17948         intent.addCategory(Intent.CATEGORY_HOME);
17949         intent.addCategory(Intent.CATEGORY_DEFAULT);
17950         return intent;
17951     }
17952
17953     private IntentFilter getHomeFilter() {
17954         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17955         filter.addCategory(Intent.CATEGORY_HOME);
17956         filter.addCategory(Intent.CATEGORY_DEFAULT);
17957         return filter;
17958     }
17959
17960     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17961             int userId) {
17962         Intent intent  = getHomeIntent();
17963         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17964                 PackageManager.GET_META_DATA, userId);
17965         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17966                 true, false, false, userId);
17967
17968         allHomeCandidates.clear();
17969         if (list != null) {
17970             for (ResolveInfo ri : list) {
17971                 allHomeCandidates.add(ri);
17972             }
17973         }
17974         return (preferred == null || preferred.activityInfo == null)
17975                 ? null
17976                 : new ComponentName(preferred.activityInfo.packageName,
17977                         preferred.activityInfo.name);
17978     }
17979
17980     @Override
17981     public void setHomeActivity(ComponentName comp, int userId) {
17982         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17983         getHomeActivitiesAsUser(homeActivities, userId);
17984
17985         boolean found = false;
17986
17987         final int size = homeActivities.size();
17988         final ComponentName[] set = new ComponentName[size];
17989         for (int i = 0; i < size; i++) {
17990             final ResolveInfo candidate = homeActivities.get(i);
17991             final ActivityInfo info = candidate.activityInfo;
17992             final ComponentName activityName = new ComponentName(info.packageName, info.name);
17993             set[i] = activityName;
17994             if (!found && activityName.equals(comp)) {
17995                 found = true;
17996             }
17997         }
17998         if (!found) {
17999             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18000                     + userId);
18001         }
18002         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18003                 set, comp, userId);
18004     }
18005
18006     private @Nullable String getSetupWizardPackageName() {
18007         final Intent intent = new Intent(Intent.ACTION_MAIN);
18008         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18009
18010         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18011                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18012                         | MATCH_DISABLED_COMPONENTS,
18013                 UserHandle.myUserId());
18014         if (matches.size() == 1) {
18015             return matches.get(0).getComponentInfo().packageName;
18016         } else {
18017             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18018                     + ": matches=" + matches);
18019             return null;
18020         }
18021     }
18022
18023     private @Nullable String getStorageManagerPackageName() {
18024         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18025
18026         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18027                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18028                         | MATCH_DISABLED_COMPONENTS,
18029                 UserHandle.myUserId());
18030         if (matches.size() == 1) {
18031             return matches.get(0).getComponentInfo().packageName;
18032         } else {
18033             Slog.e(TAG, "There should probably be exactly one storage manager; found "
18034                     + matches.size() + ": matches=" + matches);
18035             return null;
18036         }
18037     }
18038
18039     @Override
18040     public void setApplicationEnabledSetting(String appPackageName,
18041             int newState, int flags, int userId, String callingPackage) {
18042         if (!sUserManager.exists(userId)) return;
18043         if (callingPackage == null) {
18044             callingPackage = Integer.toString(Binder.getCallingUid());
18045         }
18046         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18047     }
18048
18049     @Override
18050     public void setComponentEnabledSetting(ComponentName componentName,
18051             int newState, int flags, int userId) {
18052         if (!sUserManager.exists(userId)) return;
18053         setEnabledSetting(componentName.getPackageName(),
18054                 componentName.getClassName(), newState, flags, userId, null);
18055     }
18056
18057     private void setEnabledSetting(final String packageName, String className, int newState,
18058             final int flags, int userId, String callingPackage) {
18059         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18060               || newState == COMPONENT_ENABLED_STATE_ENABLED
18061               || newState == COMPONENT_ENABLED_STATE_DISABLED
18062               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18063               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18064             throw new IllegalArgumentException("Invalid new component state: "
18065                     + newState);
18066         }
18067         PackageSetting pkgSetting;
18068         final int uid = Binder.getCallingUid();
18069         final int permission;
18070         if (uid == Process.SYSTEM_UID) {
18071             permission = PackageManager.PERMISSION_GRANTED;
18072         } else {
18073             permission = mContext.checkCallingOrSelfPermission(
18074                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18075         }
18076         enforceCrossUserPermission(uid, userId,
18077                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
18078         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18079         boolean sendNow = false;
18080         boolean isApp = (className == null);
18081         String componentName = isApp ? packageName : className;
18082         int packageUid = -1;
18083         ArrayList<String> components;
18084
18085         // writer
18086         synchronized (mPackages) {
18087             pkgSetting = mSettings.mPackages.get(packageName);
18088             if (pkgSetting == null) {
18089                 if (className == null) {
18090                     throw new IllegalArgumentException("Unknown package: " + packageName);
18091                 }
18092                 throw new IllegalArgumentException(
18093                         "Unknown component: " + packageName + "/" + className);
18094             }
18095         }
18096
18097         // Limit who can change which apps
18098         if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18099             // Don't allow apps that don't have permission to modify other apps
18100             if (!allowedByPermission) {
18101                 throw new SecurityException(
18102                         "Permission Denial: attempt to change component state from pid="
18103                         + Binder.getCallingPid()
18104                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18105             }
18106             // Don't allow changing protected packages.
18107             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18108                 throw new SecurityException("Cannot disable a protected package: " + packageName);
18109             }
18110         }
18111
18112         synchronized (mPackages) {
18113             if (uid == Process.SHELL_UID) {
18114                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
18115                 int oldState = pkgSetting.getEnabled(userId);
18116                 if (className == null
18117                     &&
18118                     (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18119                      || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18120                      || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18121                     &&
18122                     (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18123                      || newState == COMPONENT_ENABLED_STATE_DEFAULT
18124                      || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18125                     // ok
18126                 } else {
18127                     throw new SecurityException(
18128                             "Shell cannot change component state for " + packageName + "/"
18129                             + className + " to " + newState);
18130                 }
18131             }
18132             if (className == null) {
18133                 // We're dealing with an application/package level state change
18134                 if (pkgSetting.getEnabled(userId) == newState) {
18135                     // Nothing to do
18136                     return;
18137                 }
18138                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18139                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18140                     // Don't care about who enables an app.
18141                     callingPackage = null;
18142                 }
18143                 pkgSetting.setEnabled(newState, userId, callingPackage);
18144                 // pkgSetting.pkg.mSetEnabled = newState;
18145             } else {
18146                 // We're dealing with a component level state change
18147                 // First, verify that this is a valid class name.
18148                 PackageParser.Package pkg = pkgSetting.pkg;
18149                 if (pkg == null || !pkg.hasComponentClassName(className)) {
18150                     if (pkg != null &&
18151                             pkg.applicationInfo.targetSdkVersion >=
18152                                     Build.VERSION_CODES.JELLY_BEAN) {
18153                         throw new IllegalArgumentException("Component class " + className
18154                                 + " does not exist in " + packageName);
18155                     } else {
18156                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18157                                 + className + " does not exist in " + packageName);
18158                     }
18159                 }
18160                 switch (newState) {
18161                 case COMPONENT_ENABLED_STATE_ENABLED:
18162                     if (!pkgSetting.enableComponentLPw(className, userId)) {
18163                         return;
18164                     }
18165                     break;
18166                 case COMPONENT_ENABLED_STATE_DISABLED:
18167                     if (!pkgSetting.disableComponentLPw(className, userId)) {
18168                         return;
18169                     }
18170                     break;
18171                 case COMPONENT_ENABLED_STATE_DEFAULT:
18172                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
18173                         return;
18174                     }
18175                     break;
18176                 default:
18177                     Slog.e(TAG, "Invalid new component state: " + newState);
18178                     return;
18179                 }
18180             }
18181             scheduleWritePackageRestrictionsLocked(userId);
18182             components = mPendingBroadcasts.get(userId, packageName);
18183             final boolean newPackage = components == null;
18184             if (newPackage) {
18185                 components = new ArrayList<String>();
18186             }
18187             if (!components.contains(componentName)) {
18188                 components.add(componentName);
18189             }
18190             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18191                 sendNow = true;
18192                 // Purge entry from pending broadcast list if another one exists already
18193                 // since we are sending one right away.
18194                 mPendingBroadcasts.remove(userId, packageName);
18195             } else {
18196                 if (newPackage) {
18197                     mPendingBroadcasts.put(userId, packageName, components);
18198                 }
18199                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18200                     // Schedule a message
18201                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18202                 }
18203             }
18204         }
18205
18206         long callingId = Binder.clearCallingIdentity();
18207         try {
18208             if (sendNow) {
18209                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18210                 sendPackageChangedBroadcast(packageName,
18211                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18212             }
18213         } finally {
18214             Binder.restoreCallingIdentity(callingId);
18215         }
18216     }
18217
18218     @Override
18219     public void flushPackageRestrictionsAsUser(int userId) {
18220         if (!sUserManager.exists(userId)) {
18221             return;
18222         }
18223         enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18224                 false /* checkShell */, "flushPackageRestrictions");
18225         synchronized (mPackages) {
18226             mSettings.writePackageRestrictionsLPr(userId);
18227             mDirtyUsers.remove(userId);
18228             if (mDirtyUsers.isEmpty()) {
18229                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18230             }
18231         }
18232     }
18233
18234     private void sendPackageChangedBroadcast(String packageName,
18235             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18236         if (DEBUG_INSTALL)
18237             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18238                     + componentNames);
18239         Bundle extras = new Bundle(4);
18240         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18241         String nameList[] = new String[componentNames.size()];
18242         componentNames.toArray(nameList);
18243         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18244         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18245         extras.putInt(Intent.EXTRA_UID, packageUid);
18246         // If this is not reporting a change of the overall package, then only send it
18247         // to registered receivers.  We don't want to launch a swath of apps for every
18248         // little component state change.
18249         final int flags = !componentNames.contains(packageName)
18250                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18251         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18252                 new int[] {UserHandle.getUserId(packageUid)});
18253     }
18254
18255     @Override
18256     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18257         if (!sUserManager.exists(userId)) return;
18258         final int uid = Binder.getCallingUid();
18259         final int permission = mContext.checkCallingOrSelfPermission(
18260                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18261         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18262         enforceCrossUserPermission(uid, userId,
18263                 true /* requireFullPermission */, true /* checkShell */, "stop package");
18264         // writer
18265         synchronized (mPackages) {
18266             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18267                     allowedByPermission, uid, userId)) {
18268                 scheduleWritePackageRestrictionsLocked(userId);
18269             }
18270         }
18271     }
18272
18273     @Override
18274     public String getInstallerPackageName(String packageName) {
18275         // reader
18276         synchronized (mPackages) {
18277             return mSettings.getInstallerPackageNameLPr(packageName);
18278         }
18279     }
18280
18281     public boolean isOrphaned(String packageName) {
18282         // reader
18283         synchronized (mPackages) {
18284             return mSettings.isOrphaned(packageName);
18285         }
18286     }
18287
18288     @Override
18289     public int getApplicationEnabledSetting(String packageName, int userId) {
18290         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18291         int uid = Binder.getCallingUid();
18292         enforceCrossUserPermission(uid, userId,
18293                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18294         // reader
18295         synchronized (mPackages) {
18296             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18297         }
18298     }
18299
18300     @Override
18301     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18302         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18303         int uid = Binder.getCallingUid();
18304         enforceCrossUserPermission(uid, userId,
18305                 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18306         // reader
18307         synchronized (mPackages) {
18308             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18309         }
18310     }
18311
18312     @Override
18313     public void enterSafeMode() {
18314         enforceSystemOrRoot("Only the system can request entering safe mode");
18315
18316         if (!mSystemReady) {
18317             mSafeMode = true;
18318         }
18319     }
18320
18321     @Override
18322     public void systemReady() {
18323         mSystemReady = true;
18324
18325         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18326         // disabled after already being started.
18327         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18328                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18329
18330         // Read the compatibilty setting when the system is ready.
18331         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18332                 mContext.getContentResolver(),
18333                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18334         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18335         if (DEBUG_SETTINGS) {
18336             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18337         }
18338
18339         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18340
18341         synchronized (mPackages) {
18342             // Verify that all of the preferred activity components actually
18343             // exist.  It is possible for applications to be updated and at
18344             // that point remove a previously declared activity component that
18345             // had been set as a preferred activity.  We try to clean this up
18346             // the next time we encounter that preferred activity, but it is
18347             // possible for the user flow to never be able to return to that
18348             // situation so here we do a sanity check to make sure we haven't
18349             // left any junk around.
18350             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18351             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18352                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18353                 removed.clear();
18354                 for (PreferredActivity pa : pir.filterSet()) {
18355                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18356                         removed.add(pa);
18357                     }
18358                 }
18359                 if (removed.size() > 0) {
18360                     for (int r=0; r<removed.size(); r++) {
18361                         PreferredActivity pa = removed.get(r);
18362                         Slog.w(TAG, "Removing dangling preferred activity: "
18363                                 + pa.mPref.mComponent);
18364                         pir.removeFilter(pa);
18365                     }
18366                     mSettings.writePackageRestrictionsLPr(
18367                             mSettings.mPreferredActivities.keyAt(i));
18368                 }
18369             }
18370
18371             for (int userId : UserManagerService.getInstance().getUserIds()) {
18372                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18373                     grantPermissionsUserIds = ArrayUtils.appendInt(
18374                             grantPermissionsUserIds, userId);
18375                 }
18376             }
18377         }
18378         sUserManager.systemReady();
18379
18380         // If we upgraded grant all default permissions before kicking off.
18381         for (int userId : grantPermissionsUserIds) {
18382             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18383         }
18384
18385         // If we did not grant default permissions, we preload from this the
18386         // default permission exceptions lazily to ensure we don't hit the
18387         // disk on a new user creation.
18388         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18389             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18390         }
18391
18392         // Kick off any messages waiting for system ready
18393         if (mPostSystemReadyMessages != null) {
18394             for (Message msg : mPostSystemReadyMessages) {
18395                 msg.sendToTarget();
18396             }
18397             mPostSystemReadyMessages = null;
18398         }
18399
18400         // Watch for external volumes that come and go over time
18401         final StorageManager storage = mContext.getSystemService(StorageManager.class);
18402         storage.registerListener(mStorageListener);
18403
18404         mInstallerService.systemReady();
18405         mPackageDexOptimizer.systemReady();
18406
18407         MountServiceInternal mountServiceInternal = LocalServices.getService(
18408                 MountServiceInternal.class);
18409         mountServiceInternal.addExternalStoragePolicy(
18410                 new MountServiceInternal.ExternalStorageMountPolicy() {
18411             @Override
18412             public int getMountMode(int uid, String packageName) {
18413                 if (Process.isIsolated(uid)) {
18414                     return Zygote.MOUNT_EXTERNAL_NONE;
18415                 }
18416                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18417                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18418                 }
18419                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18420                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18421                 }
18422                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18423                     return Zygote.MOUNT_EXTERNAL_READ;
18424                 }
18425                 return Zygote.MOUNT_EXTERNAL_WRITE;
18426             }
18427
18428             @Override
18429             public boolean hasExternalStorage(int uid, String packageName) {
18430                 return true;
18431             }
18432         });
18433
18434         // Now that we're mostly running, clean up stale users and apps
18435         reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18436         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18437     }
18438
18439     @Override
18440     public boolean isSafeMode() {
18441         return mSafeMode;
18442     }
18443
18444     @Override
18445     public boolean hasSystemUidErrors() {
18446         return mHasSystemUidErrors;
18447     }
18448
18449     static String arrayToString(int[] array) {
18450         StringBuffer buf = new StringBuffer(128);
18451         buf.append('[');
18452         if (array != null) {
18453             for (int i=0; i<array.length; i++) {
18454                 if (i > 0) buf.append(", ");
18455                 buf.append(array[i]);
18456             }
18457         }
18458         buf.append(']');
18459         return buf.toString();
18460     }
18461
18462     static class DumpState {
18463         public static final int DUMP_LIBS = 1 << 0;
18464         public static final int DUMP_FEATURES = 1 << 1;
18465         public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18466         public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18467         public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18468         public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18469         public static final int DUMP_PERMISSIONS = 1 << 6;
18470         public static final int DUMP_PACKAGES = 1 << 7;
18471         public static final int DUMP_SHARED_USERS = 1 << 8;
18472         public static final int DUMP_MESSAGES = 1 << 9;
18473         public static final int DUMP_PROVIDERS = 1 << 10;
18474         public static final int DUMP_VERIFIERS = 1 << 11;
18475         public static final int DUMP_PREFERRED = 1 << 12;
18476         public static final int DUMP_PREFERRED_XML = 1 << 13;
18477         public static final int DUMP_KEYSETS = 1 << 14;
18478         public static final int DUMP_VERSION = 1 << 15;
18479         public static final int DUMP_INSTALLS = 1 << 16;
18480         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18481         public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18482         public static final int DUMP_FROZEN = 1 << 19;
18483         public static final int DUMP_DEXOPT = 1 << 20;
18484         public static final int DUMP_COMPILER_STATS = 1 << 21;
18485
18486         public static final int OPTION_SHOW_FILTERS = 1 << 0;
18487
18488         private int mTypes;
18489
18490         private int mOptions;
18491
18492         private boolean mTitlePrinted;
18493
18494         private SharedUserSetting mSharedUser;
18495
18496         public boolean isDumping(int type) {
18497             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18498                 return true;
18499             }
18500
18501             return (mTypes & type) != 0;
18502         }
18503
18504         public void setDump(int type) {
18505             mTypes |= type;
18506         }
18507
18508         public boolean isOptionEnabled(int option) {
18509             return (mOptions & option) != 0;
18510         }
18511
18512         public void setOptionEnabled(int option) {
18513             mOptions |= option;
18514         }
18515
18516         public boolean onTitlePrinted() {
18517             final boolean printed = mTitlePrinted;
18518             mTitlePrinted = true;
18519             return printed;
18520         }
18521
18522         public boolean getTitlePrinted() {
18523             return mTitlePrinted;
18524         }
18525
18526         public void setTitlePrinted(boolean enabled) {
18527             mTitlePrinted = enabled;
18528         }
18529
18530         public SharedUserSetting getSharedUser() {
18531             return mSharedUser;
18532         }
18533
18534         public void setSharedUser(SharedUserSetting user) {
18535             mSharedUser = user;
18536         }
18537     }
18538
18539     @Override
18540     public void onShellCommand(FileDescriptor in, FileDescriptor out,
18541             FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18542         (new PackageManagerShellCommand(this)).exec(
18543                 this, in, out, err, args, resultReceiver);
18544     }
18545
18546     @Override
18547     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18548         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18549                 != PackageManager.PERMISSION_GRANTED) {
18550             pw.println("Permission Denial: can't dump ActivityManager from from pid="
18551                     + Binder.getCallingPid()
18552                     + ", uid=" + Binder.getCallingUid()
18553                     + " without permission "
18554                     + android.Manifest.permission.DUMP);
18555             return;
18556         }
18557
18558         DumpState dumpState = new DumpState();
18559         boolean fullPreferred = false;
18560         boolean checkin = false;
18561
18562         String packageName = null;
18563         ArraySet<String> permissionNames = null;
18564
18565         int opti = 0;
18566         while (opti < args.length) {
18567             String opt = args[opti];
18568             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18569                 break;
18570             }
18571             opti++;
18572
18573             if ("-a".equals(opt)) {
18574                 // Right now we only know how to print all.
18575             } else if ("-h".equals(opt)) {
18576                 pw.println("Package manager dump options:");
18577                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18578                 pw.println("    --checkin: dump for a checkin");
18579                 pw.println("    -f: print details of intent filters");
18580                 pw.println("    -h: print this help");
18581                 pw.println("  cmd may be one of:");
18582                 pw.println("    l[ibraries]: list known shared libraries");
18583                 pw.println("    f[eatures]: list device features");
18584                 pw.println("    k[eysets]: print known keysets");
18585                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18586                 pw.println("    perm[issions]: dump permissions");
18587                 pw.println("    permission [name ...]: dump declaration and use of given permission");
18588                 pw.println("    pref[erred]: print preferred package settings");
18589                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18590                 pw.println("    prov[iders]: dump content providers");
18591                 pw.println("    p[ackages]: dump installed packages");
18592                 pw.println("    s[hared-users]: dump shared user IDs");
18593                 pw.println("    m[essages]: print collected runtime messages");
18594                 pw.println("    v[erifiers]: print package verifier info");
18595                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18596                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18597                 pw.println("    version: print database version info");
18598                 pw.println("    write: write current settings now");
18599                 pw.println("    installs: details about install sessions");
18600                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18601                 pw.println("    dexopt: dump dexopt state");
18602                 pw.println("    compiler-stats: dump compiler statistics");
18603                 pw.println("    <package.name>: info about given package");
18604                 return;
18605             } else if ("--checkin".equals(opt)) {
18606                 checkin = true;
18607             } else if ("-f".equals(opt)) {
18608                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18609             } else {
18610                 pw.println("Unknown argument: " + opt + "; use -h for help");
18611             }
18612         }
18613
18614         // Is the caller requesting to dump a particular piece of data?
18615         if (opti < args.length) {
18616             String cmd = args[opti];
18617             opti++;
18618             // Is this a package name?
18619             if ("android".equals(cmd) || cmd.contains(".")) {
18620                 packageName = cmd;
18621                 // When dumping a single package, we always dump all of its
18622                 // filter information since the amount of data will be reasonable.
18623                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18624             } else if ("check-permission".equals(cmd)) {
18625                 if (opti >= args.length) {
18626                     pw.println("Error: check-permission missing permission argument");
18627                     return;
18628                 }
18629                 String perm = args[opti];
18630                 opti++;
18631                 if (opti >= args.length) {
18632                     pw.println("Error: check-permission missing package argument");
18633                     return;
18634                 }
18635                 String pkg = args[opti];
18636                 opti++;
18637                 int user = UserHandle.getUserId(Binder.getCallingUid());
18638                 if (opti < args.length) {
18639                     try {
18640                         user = Integer.parseInt(args[opti]);
18641                     } catch (NumberFormatException e) {
18642                         pw.println("Error: check-permission user argument is not a number: "
18643                                 + args[opti]);
18644                         return;
18645                     }
18646                 }
18647                 pw.println(checkPermission(perm, pkg, user));
18648                 return;
18649             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18650                 dumpState.setDump(DumpState.DUMP_LIBS);
18651             } else if ("f".equals(cmd) || "features".equals(cmd)) {
18652                 dumpState.setDump(DumpState.DUMP_FEATURES);
18653             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18654                 if (opti >= args.length) {
18655                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18656                             | DumpState.DUMP_SERVICE_RESOLVERS
18657                             | DumpState.DUMP_RECEIVER_RESOLVERS
18658                             | DumpState.DUMP_CONTENT_RESOLVERS);
18659                 } else {
18660                     while (opti < args.length) {
18661                         String name = args[opti];
18662                         if ("a".equals(name) || "activity".equals(name)) {
18663                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18664                         } else if ("s".equals(name) || "service".equals(name)) {
18665                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18666                         } else if ("r".equals(name) || "receiver".equals(name)) {
18667                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18668                         } else if ("c".equals(name) || "content".equals(name)) {
18669                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18670                         } else {
18671                             pw.println("Error: unknown resolver table type: " + name);
18672                             return;
18673                         }
18674                         opti++;
18675                     }
18676                 }
18677             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18678                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18679             } else if ("permission".equals(cmd)) {
18680                 if (opti >= args.length) {
18681                     pw.println("Error: permission requires permission name");
18682                     return;
18683                 }
18684                 permissionNames = new ArraySet<>();
18685                 while (opti < args.length) {
18686                     permissionNames.add(args[opti]);
18687                     opti++;
18688                 }
18689                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18690                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18691             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18692                 dumpState.setDump(DumpState.DUMP_PREFERRED);
18693             } else if ("preferred-xml".equals(cmd)) {
18694                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18695                 if (opti < args.length && "--full".equals(args[opti])) {
18696                     fullPreferred = true;
18697                     opti++;
18698                 }
18699             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18700                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18701             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18702                 dumpState.setDump(DumpState.DUMP_PACKAGES);
18703             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18704                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18705             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18706                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18707             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18708                 dumpState.setDump(DumpState.DUMP_MESSAGES);
18709             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18710                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18711             } else if ("i".equals(cmd) || "ifv".equals(cmd)
18712                     || "intent-filter-verifiers".equals(cmd)) {
18713                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18714             } else if ("version".equals(cmd)) {
18715                 dumpState.setDump(DumpState.DUMP_VERSION);
18716             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18717                 dumpState.setDump(DumpState.DUMP_KEYSETS);
18718             } else if ("installs".equals(cmd)) {
18719                 dumpState.setDump(DumpState.DUMP_INSTALLS);
18720             } else if ("frozen".equals(cmd)) {
18721                 dumpState.setDump(DumpState.DUMP_FROZEN);
18722             } else if ("dexopt".equals(cmd)) {
18723                 dumpState.setDump(DumpState.DUMP_DEXOPT);
18724             } else if ("compiler-stats".equals(cmd)) {
18725                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18726             } else if ("write".equals(cmd)) {
18727                 synchronized (mPackages) {
18728                     mSettings.writeLPr();
18729                     pw.println("Settings written.");
18730                     return;
18731                 }
18732             }
18733         }
18734
18735         if (checkin) {
18736             pw.println("vers,1");
18737         }
18738
18739         // reader
18740         synchronized (mPackages) {
18741             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18742                 if (!checkin) {
18743                     if (dumpState.onTitlePrinted())
18744                         pw.println();
18745                     pw.println("Database versions:");
18746                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18747                 }
18748             }
18749
18750             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18751                 if (!checkin) {
18752                     if (dumpState.onTitlePrinted())
18753                         pw.println();
18754                     pw.println("Verifiers:");
18755                     pw.print("  Required: ");
18756                     pw.print(mRequiredVerifierPackage);
18757                     pw.print(" (uid=");
18758                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18759                             UserHandle.USER_SYSTEM));
18760                     pw.println(")");
18761                 } else if (mRequiredVerifierPackage != null) {
18762                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18763                     pw.print(",");
18764                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18765                             UserHandle.USER_SYSTEM));
18766                 }
18767             }
18768
18769             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18770                     packageName == null) {
18771                 if (mIntentFilterVerifierComponent != null) {
18772                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18773                     if (!checkin) {
18774                         if (dumpState.onTitlePrinted())
18775                             pw.println();
18776                         pw.println("Intent Filter Verifier:");
18777                         pw.print("  Using: ");
18778                         pw.print(verifierPackageName);
18779                         pw.print(" (uid=");
18780                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18781                                 UserHandle.USER_SYSTEM));
18782                         pw.println(")");
18783                     } else if (verifierPackageName != null) {
18784                         pw.print("ifv,"); pw.print(verifierPackageName);
18785                         pw.print(",");
18786                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18787                                 UserHandle.USER_SYSTEM));
18788                     }
18789                 } else {
18790                     pw.println();
18791                     pw.println("No Intent Filter Verifier available!");
18792                 }
18793             }
18794
18795             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18796                 boolean printedHeader = false;
18797                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18798                 while (it.hasNext()) {
18799                     String name = it.next();
18800                     SharedLibraryEntry ent = mSharedLibraries.get(name);
18801                     if (!checkin) {
18802                         if (!printedHeader) {
18803                             if (dumpState.onTitlePrinted())
18804                                 pw.println();
18805                             pw.println("Libraries:");
18806                             printedHeader = true;
18807                         }
18808                         pw.print("  ");
18809                     } else {
18810                         pw.print("lib,");
18811                     }
18812                     pw.print(name);
18813                     if (!checkin) {
18814                         pw.print(" -> ");
18815                     }
18816                     if (ent.path != null) {
18817                         if (!checkin) {
18818                             pw.print("(jar) ");
18819                             pw.print(ent.path);
18820                         } else {
18821                             pw.print(",jar,");
18822                             pw.print(ent.path);
18823                         }
18824                     } else {
18825                         if (!checkin) {
18826                             pw.print("(apk) ");
18827                             pw.print(ent.apk);
18828                         } else {
18829                             pw.print(",apk,");
18830                             pw.print(ent.apk);
18831                         }
18832                     }
18833                     pw.println();
18834                 }
18835             }
18836
18837             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18838                 if (dumpState.onTitlePrinted())
18839                     pw.println();
18840                 if (!checkin) {
18841                     pw.println("Features:");
18842                 }
18843
18844                 for (FeatureInfo feat : mAvailableFeatures.values()) {
18845                     if (checkin) {
18846                         pw.print("feat,");
18847                         pw.print(feat.name);
18848                         pw.print(",");
18849                         pw.println(feat.version);
18850                     } else {
18851                         pw.print("  ");
18852                         pw.print(feat.name);
18853                         if (feat.version > 0) {
18854                             pw.print(" version=");
18855                             pw.print(feat.version);
18856                         }
18857                         pw.println();
18858                     }
18859                 }
18860             }
18861
18862             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18863                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18864                         : "Activity Resolver Table:", "  ", packageName,
18865                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18866                     dumpState.setTitlePrinted(true);
18867                 }
18868             }
18869             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18870                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18871                         : "Receiver Resolver Table:", "  ", packageName,
18872                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18873                     dumpState.setTitlePrinted(true);
18874                 }
18875             }
18876             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18877                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18878                         : "Service Resolver Table:", "  ", packageName,
18879                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18880                     dumpState.setTitlePrinted(true);
18881                 }
18882             }
18883             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18884                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18885                         : "Provider Resolver Table:", "  ", packageName,
18886                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18887                     dumpState.setTitlePrinted(true);
18888                 }
18889             }
18890
18891             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18892                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18893                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18894                     int user = mSettings.mPreferredActivities.keyAt(i);
18895                     if (pir.dump(pw,
18896                             dumpState.getTitlePrinted()
18897                                 ? "\nPreferred Activities User " + user + ":"
18898                                 : "Preferred Activities User " + user + ":", "  ",
18899                             packageName, true, false)) {
18900                         dumpState.setTitlePrinted(true);
18901                     }
18902                 }
18903             }
18904
18905             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18906                 pw.flush();
18907                 FileOutputStream fout = new FileOutputStream(fd);
18908                 BufferedOutputStream str = new BufferedOutputStream(fout);
18909                 XmlSerializer serializer = new FastXmlSerializer();
18910                 try {
18911                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
18912                     serializer.startDocument(null, true);
18913                     serializer.setFeature(
18914                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18915                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18916                     serializer.endDocument();
18917                     serializer.flush();
18918                 } catch (IllegalArgumentException e) {
18919                     pw.println("Failed writing: " + e);
18920                 } catch (IllegalStateException e) {
18921                     pw.println("Failed writing: " + e);
18922                 } catch (IOException e) {
18923                     pw.println("Failed writing: " + e);
18924                 }
18925             }
18926
18927             if (!checkin
18928                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18929                     && packageName == null) {
18930                 pw.println();
18931                 int count = mSettings.mPackages.size();
18932                 if (count == 0) {
18933                     pw.println("No applications!");
18934                     pw.println();
18935                 } else {
18936                     final String prefix = "  ";
18937                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18938                     if (allPackageSettings.size() == 0) {
18939                         pw.println("No domain preferred apps!");
18940                         pw.println();
18941                     } else {
18942                         pw.println("App verification status:");
18943                         pw.println();
18944                         count = 0;
18945                         for (PackageSetting ps : allPackageSettings) {
18946                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18947                             if (ivi == null || ivi.getPackageName() == null) continue;
18948                             pw.println(prefix + "Package: " + ivi.getPackageName());
18949                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
18950                             pw.println(prefix + "Status:  " + ivi.getStatusString());
18951                             pw.println();
18952                             count++;
18953                         }
18954                         if (count == 0) {
18955                             pw.println(prefix + "No app verification established.");
18956                             pw.println();
18957                         }
18958                         for (int userId : sUserManager.getUserIds()) {
18959                             pw.println("App linkages for user " + userId + ":");
18960                             pw.println();
18961                             count = 0;
18962                             for (PackageSetting ps : allPackageSettings) {
18963                                 final long status = ps.getDomainVerificationStatusForUser(userId);
18964                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18965                                     continue;
18966                                 }
18967                                 pw.println(prefix + "Package: " + ps.name);
18968                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18969                                 String statusStr = IntentFilterVerificationInfo.
18970                                         getStatusStringFromValue(status);
18971                                 pw.println(prefix + "Status:  " + statusStr);
18972                                 pw.println();
18973                                 count++;
18974                             }
18975                             if (count == 0) {
18976                                 pw.println(prefix + "No configured app linkages.");
18977                                 pw.println();
18978                             }
18979                         }
18980                     }
18981                 }
18982             }
18983
18984             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18985                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18986                 if (packageName == null && permissionNames == null) {
18987                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18988                         if (iperm == 0) {
18989                             if (dumpState.onTitlePrinted())
18990                                 pw.println();
18991                             pw.println("AppOp Permissions:");
18992                         }
18993                         pw.print("  AppOp Permission ");
18994                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
18995                         pw.println(":");
18996                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18997                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18998                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18999                         }
19000                     }
19001                 }
19002             }
19003
19004             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19005                 boolean printedSomething = false;
19006                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
19007                     if (packageName != null && !packageName.equals(p.info.packageName)) {
19008                         continue;
19009                     }
19010                     if (!printedSomething) {
19011                         if (dumpState.onTitlePrinted())
19012                             pw.println();
19013                         pw.println("Registered ContentProviders:");
19014                         printedSomething = true;
19015                     }
19016                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19017                     pw.print("    "); pw.println(p.toString());
19018                 }
19019                 printedSomething = false;
19020                 for (Map.Entry<String, PackageParser.Provider> entry :
19021                         mProvidersByAuthority.entrySet()) {
19022                     PackageParser.Provider p = entry.getValue();
19023                     if (packageName != null && !packageName.equals(p.info.packageName)) {
19024                         continue;
19025                     }
19026                     if (!printedSomething) {
19027                         if (dumpState.onTitlePrinted())
19028                             pw.println();
19029                         pw.println("ContentProvider Authorities:");
19030                         printedSomething = true;
19031                     }
19032                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19033                     pw.print("    "); pw.println(p.toString());
19034                     if (p.info != null && p.info.applicationInfo != null) {
19035                         final String appInfo = p.info.applicationInfo.toString();
19036                         pw.print("      applicationInfo="); pw.println(appInfo);
19037                     }
19038                 }
19039             }
19040
19041             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19042                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19043             }
19044
19045             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19046                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19047             }
19048
19049             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19050                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19051             }
19052
19053             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19054                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19055             }
19056
19057             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19058                 // XXX should handle packageName != null by dumping only install data that
19059                 // the given package is involved with.
19060                 if (dumpState.onTitlePrinted()) pw.println();
19061                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19062             }
19063
19064             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19065                 // XXX should handle packageName != null by dumping only install data that
19066                 // the given package is involved with.
19067                 if (dumpState.onTitlePrinted()) pw.println();
19068
19069                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19070                 ipw.println();
19071                 ipw.println("Frozen packages:");
19072                 ipw.increaseIndent();
19073                 if (mFrozenPackages.size() == 0) {
19074                     ipw.println("(none)");
19075                 } else {
19076                     for (int i = 0; i < mFrozenPackages.size(); i++) {
19077                         ipw.println(mFrozenPackages.valueAt(i));
19078                     }
19079                 }
19080                 ipw.decreaseIndent();
19081             }
19082
19083             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19084                 if (dumpState.onTitlePrinted()) pw.println();
19085                 dumpDexoptStateLPr(pw, packageName);
19086             }
19087
19088             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19089                 if (dumpState.onTitlePrinted()) pw.println();
19090                 dumpCompilerStatsLPr(pw, packageName);
19091             }
19092
19093             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19094                 if (dumpState.onTitlePrinted()) pw.println();
19095                 mSettings.dumpReadMessagesLPr(pw, dumpState);
19096
19097                 pw.println();
19098                 pw.println("Package warning messages:");
19099                 BufferedReader in = null;
19100                 String line = null;
19101                 try {
19102                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19103                     while ((line = in.readLine()) != null) {
19104                         if (line.contains("ignored: updated version")) continue;
19105                         pw.println(line);
19106                     }
19107                 } catch (IOException ignored) {
19108                 } finally {
19109                     IoUtils.closeQuietly(in);
19110                 }
19111             }
19112
19113             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19114                 BufferedReader in = null;
19115                 String line = null;
19116                 try {
19117                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19118                     while ((line = in.readLine()) != null) {
19119                         if (line.contains("ignored: updated version")) continue;
19120                         pw.print("msg,");
19121                         pw.println(line);
19122                     }
19123                 } catch (IOException ignored) {
19124                 } finally {
19125                     IoUtils.closeQuietly(in);
19126                 }
19127             }
19128         }
19129     }
19130
19131     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19132         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19133         ipw.println();
19134         ipw.println("Dexopt state:");
19135         ipw.increaseIndent();
19136         Collection<PackageParser.Package> packages = null;
19137         if (packageName != null) {
19138             PackageParser.Package targetPackage = mPackages.get(packageName);
19139             if (targetPackage != null) {
19140                 packages = Collections.singletonList(targetPackage);
19141             } else {
19142                 ipw.println("Unable to find package: " + packageName);
19143                 return;
19144             }
19145         } else {
19146             packages = mPackages.values();
19147         }
19148
19149         for (PackageParser.Package pkg : packages) {
19150             ipw.println("[" + pkg.packageName + "]");
19151             ipw.increaseIndent();
19152             mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19153             ipw.decreaseIndent();
19154         }
19155     }
19156
19157     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19158         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19159         ipw.println();
19160         ipw.println("Compiler stats:");
19161         ipw.increaseIndent();
19162         Collection<PackageParser.Package> packages = null;
19163         if (packageName != null) {
19164             PackageParser.Package targetPackage = mPackages.get(packageName);
19165             if (targetPackage != null) {
19166                 packages = Collections.singletonList(targetPackage);
19167             } else {
19168                 ipw.println("Unable to find package: " + packageName);
19169                 return;
19170             }
19171         } else {
19172             packages = mPackages.values();
19173         }
19174
19175         for (PackageParser.Package pkg : packages) {
19176             ipw.println("[" + pkg.packageName + "]");
19177             ipw.increaseIndent();
19178
19179             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19180             if (stats == null) {
19181                 ipw.println("(No recorded stats)");
19182             } else {
19183                 stats.dump(ipw);
19184             }
19185             ipw.decreaseIndent();
19186         }
19187     }
19188
19189     private String dumpDomainString(String packageName) {
19190         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19191                 .getList();
19192         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19193
19194         ArraySet<String> result = new ArraySet<>();
19195         if (iviList.size() > 0) {
19196             for (IntentFilterVerificationInfo ivi : iviList) {
19197                 for (String host : ivi.getDomains()) {
19198                     result.add(host);
19199                 }
19200             }
19201         }
19202         if (filters != null && filters.size() > 0) {
19203             for (IntentFilter filter : filters) {
19204                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19205                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19206                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19207                     result.addAll(filter.getHostsList());
19208                 }
19209             }
19210         }
19211
19212         StringBuilder sb = new StringBuilder(result.size() * 16);
19213         for (String domain : result) {
19214             if (sb.length() > 0) sb.append(" ");
19215             sb.append(domain);
19216         }
19217         return sb.toString();
19218     }
19219
19220     // ------- apps on sdcard specific code -------
19221     static final boolean DEBUG_SD_INSTALL = false;
19222
19223     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19224
19225     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19226
19227     private boolean mMediaMounted = false;
19228
19229     static String getEncryptKey() {
19230         try {
19231             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19232                     SD_ENCRYPTION_KEYSTORE_NAME);
19233             if (sdEncKey == null) {
19234                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19235                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19236                 if (sdEncKey == null) {
19237                     Slog.e(TAG, "Failed to create encryption keys");
19238                     return null;
19239                 }
19240             }
19241             return sdEncKey;
19242         } catch (NoSuchAlgorithmException nsae) {
19243             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19244             return null;
19245         } catch (IOException ioe) {
19246             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19247             return null;
19248         }
19249     }
19250
19251     /*
19252      * Update media status on PackageManager.
19253      */
19254     @Override
19255     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19256         int callingUid = Binder.getCallingUid();
19257         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19258             throw new SecurityException("Media status can only be updated by the system");
19259         }
19260         // reader; this apparently protects mMediaMounted, but should probably
19261         // be a different lock in that case.
19262         synchronized (mPackages) {
19263             Log.i(TAG, "Updating external media status from "
19264                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
19265                     + (mediaStatus ? "mounted" : "unmounted"));
19266             if (DEBUG_SD_INSTALL)
19267                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19268                         + ", mMediaMounted=" + mMediaMounted);
19269             if (mediaStatus == mMediaMounted) {
19270                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19271                         : 0, -1);
19272                 mHandler.sendMessage(msg);
19273                 return;
19274             }
19275             mMediaMounted = mediaStatus;
19276         }
19277         // Queue up an async operation since the package installation may take a
19278         // little while.
19279         mHandler.post(new Runnable() {
19280             public void run() {
19281                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19282             }
19283         });
19284     }
19285
19286     /**
19287      * Called by MountService when the initial ASECs to scan are available.
19288      * Should block until all the ASEC containers are finished being scanned.
19289      */
19290     public void scanAvailableAsecs() {
19291         updateExternalMediaStatusInner(true, false, false);
19292     }
19293
19294     /*
19295      * Collect information of applications on external media, map them against
19296      * existing containers and update information based on current mount status.
19297      * Please note that we always have to report status if reportStatus has been
19298      * set to true especially when unloading packages.
19299      */
19300     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19301             boolean externalStorage) {
19302         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19303         int[] uidArr = EmptyArray.INT;
19304
19305         final String[] list = PackageHelper.getSecureContainerList();
19306         if (ArrayUtils.isEmpty(list)) {
19307             Log.i(TAG, "No secure containers found");
19308         } else {
19309             // Process list of secure containers and categorize them
19310             // as active or stale based on their package internal state.
19311
19312             // reader
19313             synchronized (mPackages) {
19314                 for (String cid : list) {
19315                     // Leave stages untouched for now; installer service owns them
19316                     if (PackageInstallerService.isStageName(cid)) continue;
19317
19318                     if (DEBUG_SD_INSTALL)
19319                         Log.i(TAG, "Processing container " + cid);
19320                     String pkgName = getAsecPackageName(cid);
19321                     if (pkgName == null) {
19322                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
19323                         continue;
19324                     }
19325                     if (DEBUG_SD_INSTALL)
19326                         Log.i(TAG, "Looking for pkg : " + pkgName);
19327
19328                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
19329                     if (ps == null) {
19330                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19331                         continue;
19332                     }
19333
19334                     /*
19335                      * Skip packages that are not external if we're unmounting
19336                      * external storage.
19337                      */
19338                     if (externalStorage && !isMounted && !isExternal(ps)) {
19339                         continue;
19340                     }
19341
19342                     final AsecInstallArgs args = new AsecInstallArgs(cid,
19343                             getAppDexInstructionSets(ps), ps.isForwardLocked());
19344                     // The package status is changed only if the code path
19345                     // matches between settings and the container id.
19346                     if (ps.codePathString != null
19347                             && ps.codePathString.startsWith(args.getCodePath())) {
19348                         if (DEBUG_SD_INSTALL) {
19349                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19350                                     + " at code path: " + ps.codePathString);
19351                         }
19352
19353                         // We do have a valid package installed on sdcard
19354                         processCids.put(args, ps.codePathString);
19355                         final int uid = ps.appId;
19356                         if (uid != -1) {
19357                             uidArr = ArrayUtils.appendInt(uidArr, uid);
19358                         }
19359                     } else {
19360                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19361                                 + ps.codePathString);
19362                     }
19363                 }
19364             }
19365
19366             Arrays.sort(uidArr);
19367         }
19368
19369         // Process packages with valid entries.
19370         if (isMounted) {
19371             if (DEBUG_SD_INSTALL)
19372                 Log.i(TAG, "Loading packages");
19373             loadMediaPackages(processCids, uidArr, externalStorage);
19374             startCleaningPackages();
19375             mInstallerService.onSecureContainersAvailable();
19376         } else {
19377             if (DEBUG_SD_INSTALL)
19378                 Log.i(TAG, "Unloading packages");
19379             unloadMediaPackages(processCids, uidArr, reportStatus);
19380         }
19381     }
19382
19383     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19384             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19385         final int size = infos.size();
19386         final String[] packageNames = new String[size];
19387         final int[] packageUids = new int[size];
19388         for (int i = 0; i < size; i++) {
19389             final ApplicationInfo info = infos.get(i);
19390             packageNames[i] = info.packageName;
19391             packageUids[i] = info.uid;
19392         }
19393         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19394                 finishedReceiver);
19395     }
19396
19397     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19398             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19399         sendResourcesChangedBroadcast(mediaStatus, replacing,
19400                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19401     }
19402
19403     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19404             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19405         int size = pkgList.length;
19406         if (size > 0) {
19407             // Send broadcasts here
19408             Bundle extras = new Bundle();
19409             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19410             if (uidArr != null) {
19411                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19412             }
19413             if (replacing) {
19414                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19415             }
19416             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19417                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19418             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19419         }
19420     }
19421
19422    /*
19423      * Look at potentially valid container ids from processCids If package
19424      * information doesn't match the one on record or package scanning fails,
19425      * the cid is added to list of removeCids. We currently don't delete stale
19426      * containers.
19427      */
19428     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19429             boolean externalStorage) {
19430         ArrayList<String> pkgList = new ArrayList<String>();
19431         Set<AsecInstallArgs> keys = processCids.keySet();
19432
19433         for (AsecInstallArgs args : keys) {
19434             String codePath = processCids.get(args);
19435             if (DEBUG_SD_INSTALL)
19436                 Log.i(TAG, "Loading container : " + args.cid);
19437             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19438             try {
19439                 // Make sure there are no container errors first.
19440                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19441                     Slog.e(TAG, "Failed to mount cid : " + args.cid
19442                             + " when installing from sdcard");
19443                     continue;
19444                 }
19445                 // Check code path here.
19446                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19447                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19448                             + " does not match one in settings " + codePath);
19449                     continue;
19450                 }
19451                 // Parse package
19452                 int parseFlags = mDefParseFlags;
19453                 if (args.isExternalAsec()) {
19454                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19455                 }
19456                 if (args.isFwdLocked()) {
19457                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19458                 }
19459
19460                 synchronized (mInstallLock) {
19461                     PackageParser.Package pkg = null;
19462                     try {
19463                         // Sadly we don't know the package name yet to freeze it
19464                         pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19465                                 SCAN_IGNORE_FROZEN, 0, null);
19466                     } catch (PackageManagerException e) {
19467                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19468                     }
19469                     // Scan the package
19470                     if (pkg != null) {
19471                         /*
19472                          * TODO why is the lock being held? doPostInstall is
19473                          * called in other places without the lock. This needs
19474                          * to be straightened out.
19475                          */
19476                         // writer
19477                         synchronized (mPackages) {
19478                             retCode = PackageManager.INSTALL_SUCCEEDED;
19479                             pkgList.add(pkg.packageName);
19480                             // Post process args
19481                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19482                                     pkg.applicationInfo.uid);
19483                         }
19484                     } else {
19485                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19486                     }
19487                 }
19488
19489             } finally {
19490                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19491                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19492                 }
19493             }
19494         }
19495         // writer
19496         synchronized (mPackages) {
19497             // If the platform SDK has changed since the last time we booted,
19498             // we need to re-grant app permission to catch any new ones that
19499             // appear. This is really a hack, and means that apps can in some
19500             // cases get permissions that the user didn't initially explicitly
19501             // allow... it would be nice to have some better way to handle
19502             // this situation.
19503             final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19504                     : mSettings.getInternalVersion();
19505             final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19506                     : StorageManager.UUID_PRIVATE_INTERNAL;
19507
19508             int updateFlags = UPDATE_PERMISSIONS_ALL;
19509             if (ver.sdkVersion != mSdkVersion) {
19510                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19511                         + mSdkVersion + "; regranting permissions for external");
19512                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19513             }
19514             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19515
19516             // Yay, everything is now upgraded
19517             ver.forceCurrent();
19518
19519             // can downgrade to reader
19520             // Persist settings
19521             mSettings.writeLPr();
19522         }
19523         // Send a broadcast to let everyone know we are done processing
19524         if (pkgList.size() > 0) {
19525             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19526         }
19527     }
19528
19529    /*
19530      * Utility method to unload a list of specified containers
19531      */
19532     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19533         // Just unmount all valid containers.
19534         for (AsecInstallArgs arg : cidArgs) {
19535             synchronized (mInstallLock) {
19536                 arg.doPostDeleteLI(false);
19537            }
19538        }
19539    }
19540
19541     /*
19542      * Unload packages mounted on external media. This involves deleting package
19543      * data from internal structures, sending broadcasts about disabled packages,
19544      * gc'ing to free up references, unmounting all secure containers
19545      * corresponding to packages on external media, and posting a
19546      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19547      * that we always have to post this message if status has been requested no
19548      * matter what.
19549      */
19550     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19551             final boolean reportStatus) {
19552         if (DEBUG_SD_INSTALL)
19553             Log.i(TAG, "unloading media packages");
19554         ArrayList<String> pkgList = new ArrayList<String>();
19555         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19556         final Set<AsecInstallArgs> keys = processCids.keySet();
19557         for (AsecInstallArgs args : keys) {
19558             String pkgName = args.getPackageName();
19559             if (DEBUG_SD_INSTALL)
19560                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19561             // Delete package internally
19562             PackageRemovedInfo outInfo = new PackageRemovedInfo();
19563             synchronized (mInstallLock) {
19564                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19565                 final boolean res;
19566                 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19567                         "unloadMediaPackages")) {
19568                     res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19569                             null);
19570                 }
19571                 if (res) {
19572                     pkgList.add(pkgName);
19573                 } else {
19574                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19575                     failedList.add(args);
19576                 }
19577             }
19578         }
19579
19580         // reader
19581         synchronized (mPackages) {
19582             // We didn't update the settings after removing each package;
19583             // write them now for all packages.
19584             mSettings.writeLPr();
19585         }
19586
19587         // We have to absolutely send UPDATED_MEDIA_STATUS only
19588         // after confirming that all the receivers processed the ordered
19589         // broadcast when packages get disabled, force a gc to clean things up.
19590         // and unload all the containers.
19591         if (pkgList.size() > 0) {
19592             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19593                     new IIntentReceiver.Stub() {
19594                 public void performReceive(Intent intent, int resultCode, String data,
19595                         Bundle extras, boolean ordered, boolean sticky,
19596                         int sendingUser) throws RemoteException {
19597                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19598                             reportStatus ? 1 : 0, 1, keys);
19599                     mHandler.sendMessage(msg);
19600                 }
19601             });
19602         } else {
19603             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19604                     keys);
19605             mHandler.sendMessage(msg);
19606         }
19607     }
19608
19609     private void loadPrivatePackages(final VolumeInfo vol) {
19610         mHandler.post(new Runnable() {
19611             @Override
19612             public void run() {
19613                 loadPrivatePackagesInner(vol);
19614             }
19615         });
19616     }
19617
19618     private void loadPrivatePackagesInner(VolumeInfo vol) {
19619         final String volumeUuid = vol.fsUuid;
19620         if (TextUtils.isEmpty(volumeUuid)) {
19621             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19622             return;
19623         }
19624
19625         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19626         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19627         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19628
19629         final VersionInfo ver;
19630         final List<PackageSetting> packages;
19631         synchronized (mPackages) {
19632             ver = mSettings.findOrCreateVersion(volumeUuid);
19633             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19634         }
19635
19636         for (PackageSetting ps : packages) {
19637             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19638             synchronized (mInstallLock) {
19639                 final PackageParser.Package pkg;
19640                 try {
19641                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19642                     loaded.add(pkg.applicationInfo);
19643
19644                 } catch (PackageManagerException e) {
19645                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19646                 }
19647
19648                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19649                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19650                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19651                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19652                 }
19653             }
19654         }
19655
19656         // Reconcile app data for all started/unlocked users
19657         final StorageManager sm = mContext.getSystemService(StorageManager.class);
19658         final UserManager um = mContext.getSystemService(UserManager.class);
19659         UserManagerInternal umInternal = getUserManagerInternal();
19660         for (UserInfo user : um.getUsers()) {
19661             final int flags;
19662             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19663                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19664             } else if (umInternal.isUserRunning(user.id)) {
19665                 flags = StorageManager.FLAG_STORAGE_DE;
19666             } else {
19667                 continue;
19668             }
19669
19670             try {
19671                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19672                 synchronized (mInstallLock) {
19673                     reconcileAppsDataLI(volumeUuid, user.id, flags);
19674                 }
19675             } catch (IllegalStateException e) {
19676                 // Device was probably ejected, and we'll process that event momentarily
19677                 Slog.w(TAG, "Failed to prepare storage: " + e);
19678             }
19679         }
19680
19681         synchronized (mPackages) {
19682             int updateFlags = UPDATE_PERMISSIONS_ALL;
19683             if (ver.sdkVersion != mSdkVersion) {
19684                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19685                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
19686                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19687             }
19688             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19689
19690             // Yay, everything is now upgraded
19691             ver.forceCurrent();
19692
19693             mSettings.writeLPr();
19694         }
19695
19696         for (PackageFreezer freezer : freezers) {
19697             freezer.close();
19698         }
19699
19700         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19701         sendResourcesChangedBroadcast(true, false, loaded, null);
19702     }
19703
19704     private void unloadPrivatePackages(final VolumeInfo vol) {
19705         mHandler.post(new Runnable() {
19706             @Override
19707             public void run() {
19708                 unloadPrivatePackagesInner(vol);
19709             }
19710         });
19711     }
19712
19713     private void unloadPrivatePackagesInner(VolumeInfo vol) {
19714         final String volumeUuid = vol.fsUuid;
19715         if (TextUtils.isEmpty(volumeUuid)) {
19716             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19717             return;
19718         }
19719
19720         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19721         synchronized (mInstallLock) {
19722         synchronized (mPackages) {
19723             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19724             for (PackageSetting ps : packages) {
19725                 if (ps.pkg == null) continue;
19726
19727                 final ApplicationInfo info = ps.pkg.applicationInfo;
19728                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19729                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19730
19731                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19732                         "unloadPrivatePackagesInner")) {
19733                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19734                             false, null)) {
19735                         unloaded.add(info);
19736                     } else {
19737                         Slog.w(TAG, "Failed to unload " + ps.codePath);
19738                     }
19739                 }
19740
19741                 // Try very hard to release any references to this package
19742                 // so we don't risk the system server being killed due to
19743                 // open FDs
19744                 AttributeCache.instance().removePackage(ps.name);
19745             }
19746
19747             mSettings.writeLPr();
19748         }
19749         }
19750
19751         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19752         sendResourcesChangedBroadcast(false, false, unloaded, null);
19753
19754         // Try very hard to release any references to this path so we don't risk
19755         // the system server being killed due to open FDs
19756         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19757
19758         for (int i = 0; i < 3; i++) {
19759             System.gc();
19760             System.runFinalization();
19761         }
19762     }
19763
19764     /**
19765      * Prepare storage areas for given user on all mounted devices.
19766      */
19767     void prepareUserData(int userId, int userSerial, int flags) {
19768         synchronized (mInstallLock) {
19769             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19770             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19771                 final String volumeUuid = vol.getFsUuid();
19772                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19773             }
19774         }
19775     }
19776
19777     private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19778             boolean allowRecover) {
19779         // Prepare storage and verify that serial numbers are consistent; if
19780         // there's a mismatch we need to destroy to avoid leaking data
19781         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19782         try {
19783             storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19784
19785             if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19786                 UserManagerService.enforceSerialNumber(
19787                         Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19788                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19789                     UserManagerService.enforceSerialNumber(
19790                             Environment.getDataSystemDeDirectory(userId), userSerial);
19791                 }
19792             }
19793             if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19794                 UserManagerService.enforceSerialNumber(
19795                         Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19796                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19797                     UserManagerService.enforceSerialNumber(
19798                             Environment.getDataSystemCeDirectory(userId), userSerial);
19799                 }
19800             }
19801
19802             synchronized (mInstallLock) {
19803                 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19804             }
19805         } catch (Exception e) {
19806             logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19807                     + " because we failed to prepare: " + e);
19808             destroyUserDataLI(volumeUuid, userId,
19809                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19810
19811             if (allowRecover) {
19812                 // Try one last time; if we fail again we're really in trouble
19813                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19814             }
19815         }
19816     }
19817
19818     /**
19819      * Destroy storage areas for given user on all mounted devices.
19820      */
19821     void destroyUserData(int userId, int flags) {
19822         synchronized (mInstallLock) {
19823             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19824             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19825                 final String volumeUuid = vol.getFsUuid();
19826                 destroyUserDataLI(volumeUuid, userId, flags);
19827             }
19828         }
19829     }
19830
19831     private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19832         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19833         try {
19834             // Clean up app data, profile data, and media data
19835             mInstaller.destroyUserData(volumeUuid, userId, flags);
19836
19837             // Clean up system data
19838             if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19839                 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19840                     FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19841                     FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19842                 }
19843                 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19844                     FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19845                 }
19846             }
19847
19848             // Data with special labels is now gone, so finish the job
19849             storage.destroyUserStorage(volumeUuid, userId, flags);
19850
19851         } catch (Exception e) {
19852             logCriticalInfo(Log.WARN,
19853                     "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19854         }
19855     }
19856
19857     /**
19858      * Examine all users present on given mounted volume, and destroy data
19859      * belonging to users that are no longer valid, or whose user ID has been
19860      * recycled.
19861      */
19862     private void reconcileUsers(String volumeUuid) {
19863         final List<File> files = new ArrayList<>();
19864         Collections.addAll(files, FileUtils
19865                 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19866         Collections.addAll(files, FileUtils
19867                 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19868         Collections.addAll(files, FileUtils
19869                 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19870         Collections.addAll(files, FileUtils
19871                 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19872         for (File file : files) {
19873             if (!file.isDirectory()) continue;
19874
19875             final int userId;
19876             final UserInfo info;
19877             try {
19878                 userId = Integer.parseInt(file.getName());
19879                 info = sUserManager.getUserInfo(userId);
19880             } catch (NumberFormatException e) {
19881                 Slog.w(TAG, "Invalid user directory " + file);
19882                 continue;
19883             }
19884
19885             boolean destroyUser = false;
19886             if (info == null) {
19887                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19888                         + " because no matching user was found");
19889                 destroyUser = true;
19890             } else if (!mOnlyCore) {
19891                 try {
19892                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
19893                 } catch (IOException e) {
19894                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
19895                             + " because we failed to enforce serial number: " + e);
19896                     destroyUser = true;
19897                 }
19898             }
19899
19900             if (destroyUser) {
19901                 synchronized (mInstallLock) {
19902                     destroyUserDataLI(volumeUuid, userId,
19903                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19904                 }
19905             }
19906         }
19907     }
19908
19909     private void assertPackageKnown(String volumeUuid, String packageName)
19910             throws PackageManagerException {
19911         synchronized (mPackages) {
19912             // Normalize package name to handle renamed packages
19913             packageName = normalizePackageNameLPr(packageName);
19914
19915             final PackageSetting ps = mSettings.mPackages.get(packageName);
19916             if (ps == null) {
19917                 throw new PackageManagerException("Package " + packageName + " is unknown");
19918             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19919                 throw new PackageManagerException(
19920                         "Package " + packageName + " found on unknown volume " + volumeUuid
19921                                 + "; expected volume " + ps.volumeUuid);
19922             }
19923         }
19924     }
19925
19926     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19927             throws PackageManagerException {
19928         synchronized (mPackages) {
19929             // Normalize package name to handle renamed packages
19930             packageName = normalizePackageNameLPr(packageName);
19931
19932             final PackageSetting ps = mSettings.mPackages.get(packageName);
19933             if (ps == null) {
19934                 throw new PackageManagerException("Package " + packageName + " is unknown");
19935             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19936                 throw new PackageManagerException(
19937                         "Package " + packageName + " found on unknown volume " + volumeUuid
19938                                 + "; expected volume " + ps.volumeUuid);
19939             } else if (!ps.getInstalled(userId)) {
19940                 throw new PackageManagerException(
19941                         "Package " + packageName + " not installed for user " + userId);
19942             }
19943         }
19944     }
19945
19946     /**
19947      * Examine all apps present on given mounted volume, and destroy apps that
19948      * aren't expected, either due to uninstallation or reinstallation on
19949      * another volume.
19950      */
19951     private void reconcileApps(String volumeUuid) {
19952         final File[] files = FileUtils
19953                 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19954         for (File file : files) {
19955             final boolean isPackage = (isApkFile(file) || file.isDirectory())
19956                     && !PackageInstallerService.isStageName(file.getName());
19957             if (!isPackage) {
19958                 // Ignore entries which are not packages
19959                 continue;
19960             }
19961
19962             try {
19963                 final PackageLite pkg = PackageParser.parsePackageLite(file,
19964                         PackageParser.PARSE_MUST_BE_APK);
19965                 assertPackageKnown(volumeUuid, pkg.packageName);
19966
19967             } catch (PackageParserException | PackageManagerException e) {
19968                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19969                 synchronized (mInstallLock) {
19970                     removeCodePathLI(file);
19971                 }
19972             }
19973         }
19974     }
19975
19976     /**
19977      * Reconcile all app data for the given user.
19978      * <p>
19979      * Verifies that directories exist and that ownership and labeling is
19980      * correct for all installed apps on all mounted volumes.
19981      */
19982     void reconcileAppsData(int userId, int flags) {
19983         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19984         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19985             final String volumeUuid = vol.getFsUuid();
19986             synchronized (mInstallLock) {
19987                 reconcileAppsDataLI(volumeUuid, userId, flags);
19988             }
19989         }
19990     }
19991
19992     /**
19993      * Reconcile all app data on given mounted volume.
19994      * <p>
19995      * Destroys app data that isn't expected, either due to uninstallation or
19996      * reinstallation on another volume.
19997      * <p>
19998      * Verifies that directories exist and that ownership and labeling is
19999      * correct for all installed apps.
20000      */
20001     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
20002         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20003                 + Integer.toHexString(flags));
20004
20005         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20006         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20007
20008         // First look for stale data that doesn't belong, and check if things
20009         // have changed since we did our last restorecon
20010         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20011             if (StorageManager.isFileEncryptedNativeOrEmulated()
20012                     && !StorageManager.isUserKeyUnlocked(userId)) {
20013                 throw new RuntimeException(
20014                         "Yikes, someone asked us to reconcile CE storage while " + userId
20015                                 + " was still locked; this would have caused massive data loss!");
20016             }
20017
20018             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20019             for (File file : files) {
20020                 final String packageName = file.getName();
20021                 try {
20022                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20023                 } catch (PackageManagerException e) {
20024                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20025                     try {
20026                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
20027                                 StorageManager.FLAG_STORAGE_CE, 0);
20028                     } catch (InstallerException e2) {
20029                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20030                     }
20031                 }
20032             }
20033         }
20034         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20035             final File[] files = FileUtils.listFilesOrEmpty(deDir);
20036             for (File file : files) {
20037                 final String packageName = file.getName();
20038                 try {
20039                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20040                 } catch (PackageManagerException e) {
20041                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20042                     try {
20043                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
20044                                 StorageManager.FLAG_STORAGE_DE, 0);
20045                     } catch (InstallerException e2) {
20046                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20047                     }
20048                 }
20049             }
20050         }
20051
20052         // Ensure that data directories are ready to roll for all packages
20053         // installed for this volume and user
20054         final List<PackageSetting> packages;
20055         synchronized (mPackages) {
20056             packages = mSettings.getVolumePackagesLPr(volumeUuid);
20057         }
20058         int preparedCount = 0;
20059         for (PackageSetting ps : packages) {
20060             final String packageName = ps.name;
20061             if (ps.pkg == null) {
20062                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
20063                 // TODO: might be due to legacy ASEC apps; we should circle back
20064                 // and reconcile again once they're scanned
20065                 continue;
20066             }
20067
20068             if (ps.getInstalled(userId)) {
20069                 prepareAppDataLIF(ps.pkg, userId, flags);
20070
20071                 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
20072                     // We may have just shuffled around app data directories, so
20073                     // prepare them one more time
20074                     prepareAppDataLIF(ps.pkg, userId, flags);
20075                 }
20076
20077                 preparedCount++;
20078             }
20079         }
20080
20081         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20082     }
20083
20084     /**
20085      * Prepare app data for the given app just after it was installed or
20086      * upgraded. This method carefully only touches users that it's installed
20087      * for, and it forces a restorecon to handle any seinfo changes.
20088      * <p>
20089      * Verifies that directories exist and that ownership and labeling is
20090      * correct for all installed apps. If there is an ownership mismatch, it
20091      * will try recovering system apps by wiping data; third-party app data is
20092      * left intact.
20093      * <p>
20094      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20095      */
20096     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20097         final PackageSetting ps;
20098         synchronized (mPackages) {
20099             ps = mSettings.mPackages.get(pkg.packageName);
20100             mSettings.writeKernelMappingLPr(ps);
20101         }
20102
20103         final UserManager um = mContext.getSystemService(UserManager.class);
20104         UserManagerInternal umInternal = getUserManagerInternal();
20105         for (UserInfo user : um.getUsers()) {
20106             final int flags;
20107             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20108                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20109             } else if (umInternal.isUserRunning(user.id)) {
20110                 flags = StorageManager.FLAG_STORAGE_DE;
20111             } else {
20112                 continue;
20113             }
20114
20115             if (ps.getInstalled(user.id)) {
20116                 // TODO: when user data is locked, mark that we're still dirty
20117                 prepareAppDataLIF(pkg, user.id, flags);
20118             }
20119         }
20120     }
20121
20122     /**
20123      * Prepare app data for the given app.
20124      * <p>
20125      * Verifies that directories exist and that ownership and labeling is
20126      * correct for all installed apps. If there is an ownership mismatch, this
20127      * will try recovering system apps by wiping data; third-party app data is
20128      * left intact.
20129      */
20130     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20131         if (pkg == null) {
20132             Slog.wtf(TAG, "Package was null!", new Throwable());
20133             return;
20134         }
20135         prepareAppDataLeafLIF(pkg, userId, flags);
20136         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20137         for (int i = 0; i < childCount; i++) {
20138             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20139         }
20140     }
20141
20142     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20143         if (DEBUG_APP_DATA) {
20144             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20145                     + Integer.toHexString(flags));
20146         }
20147
20148         final String volumeUuid = pkg.volumeUuid;
20149         final String packageName = pkg.packageName;
20150         final ApplicationInfo app = pkg.applicationInfo;
20151         final int appId = UserHandle.getAppId(app.uid);
20152
20153         Preconditions.checkNotNull(app.seinfo);
20154
20155         try {
20156             mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20157                     appId, app.seinfo, app.targetSdkVersion);
20158         } catch (InstallerException e) {
20159             if (app.isSystemApp()) {
20160                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20161                         + ", but trying to recover: " + e);
20162                 destroyAppDataLeafLIF(pkg, userId, flags);
20163                 try {
20164                     mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20165                             appId, app.seinfo, app.targetSdkVersion);
20166                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20167                 } catch (InstallerException e2) {
20168                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
20169                 }
20170             } else {
20171                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20172             }
20173         }
20174
20175         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20176             try {
20177                 // CE storage is unlocked right now, so read out the inode and
20178                 // remember for use later when it's locked
20179                 // TODO: mark this structure as dirty so we persist it!
20180                 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20181                         StorageManager.FLAG_STORAGE_CE);
20182                 synchronized (mPackages) {
20183                     final PackageSetting ps = mSettings.mPackages.get(packageName);
20184                     if (ps != null) {
20185                         ps.setCeDataInode(ceDataInode, userId);
20186                     }
20187                 }
20188             } catch (InstallerException e) {
20189                 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20190             }
20191         }
20192
20193         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20194     }
20195
20196     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20197         if (pkg == null) {
20198             Slog.wtf(TAG, "Package was null!", new Throwable());
20199             return;
20200         }
20201         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20202         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20203         for (int i = 0; i < childCount; i++) {
20204             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20205         }
20206     }
20207
20208     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20209         final String volumeUuid = pkg.volumeUuid;
20210         final String packageName = pkg.packageName;
20211         final ApplicationInfo app = pkg.applicationInfo;
20212
20213         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20214             // Create a native library symlink only if we have native libraries
20215             // and if the native libraries are 32 bit libraries. We do not provide
20216             // this symlink for 64 bit libraries.
20217             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20218                 final String nativeLibPath = app.nativeLibraryDir;
20219                 try {
20220                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20221                             nativeLibPath, userId);
20222                 } catch (InstallerException e) {
20223                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20224                 }
20225             }
20226         }
20227     }
20228
20229     /**
20230      * For system apps on non-FBE devices, this method migrates any existing
20231      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20232      * requested by the app.
20233      */
20234     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20235         if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20236                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20237             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20238                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20239             try {
20240                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20241                         storageTarget);
20242             } catch (InstallerException e) {
20243                 logCriticalInfo(Log.WARN,
20244                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20245             }
20246             return true;
20247         } else {
20248             return false;
20249         }
20250     }
20251
20252     public PackageFreezer freezePackage(String packageName, String killReason) {
20253         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20254     }
20255
20256     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20257         return new PackageFreezer(packageName, userId, killReason);
20258     }
20259
20260     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20261             String killReason) {
20262         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20263     }
20264
20265     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20266             String killReason) {
20267         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20268             return new PackageFreezer();
20269         } else {
20270             return freezePackage(packageName, userId, killReason);
20271         }
20272     }
20273
20274     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20275             String killReason) {
20276         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20277     }
20278
20279     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20280             String killReason) {
20281         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20282             return new PackageFreezer();
20283         } else {
20284             return freezePackage(packageName, userId, killReason);
20285         }
20286     }
20287
20288     /**
20289      * Class that freezes and kills the given package upon creation, and
20290      * unfreezes it upon closing. This is typically used when doing surgery on
20291      * app code/data to prevent the app from running while you're working.
20292      */
20293     private class PackageFreezer implements AutoCloseable {
20294         private final String mPackageName;
20295         private final PackageFreezer[] mChildren;
20296
20297         private final boolean mWeFroze;
20298
20299         private final AtomicBoolean mClosed = new AtomicBoolean();
20300         private final CloseGuard mCloseGuard = CloseGuard.get();
20301
20302         /**
20303          * Create and return a stub freezer that doesn't actually do anything,
20304          * typically used when someone requested
20305          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20306          * {@link PackageManager#DELETE_DONT_KILL_APP}.
20307          */
20308         public PackageFreezer() {
20309             mPackageName = null;
20310             mChildren = null;
20311             mWeFroze = false;
20312             mCloseGuard.open("close");
20313         }
20314
20315         public PackageFreezer(String packageName, int userId, String killReason) {
20316             synchronized (mPackages) {
20317                 mPackageName = packageName;
20318                 mWeFroze = mFrozenPackages.add(mPackageName);
20319
20320                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20321                 if (ps != null) {
20322                     killApplication(ps.name, ps.appId, userId, killReason);
20323                 }
20324
20325                 final PackageParser.Package p = mPackages.get(packageName);
20326                 if (p != null && p.childPackages != null) {
20327                     final int N = p.childPackages.size();
20328                     mChildren = new PackageFreezer[N];
20329                     for (int i = 0; i < N; i++) {
20330                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20331                                 userId, killReason);
20332                     }
20333                 } else {
20334                     mChildren = null;
20335                 }
20336             }
20337             mCloseGuard.open("close");
20338         }
20339
20340         @Override
20341         protected void finalize() throws Throwable {
20342             try {
20343                 mCloseGuard.warnIfOpen();
20344                 close();
20345             } finally {
20346                 super.finalize();
20347             }
20348         }
20349
20350         @Override
20351         public void close() {
20352             mCloseGuard.close();
20353             if (mClosed.compareAndSet(false, true)) {
20354                 synchronized (mPackages) {
20355                     if (mWeFroze) {
20356                         mFrozenPackages.remove(mPackageName);
20357                     }
20358
20359                     if (mChildren != null) {
20360                         for (PackageFreezer freezer : mChildren) {
20361                             freezer.close();
20362                         }
20363                     }
20364                 }
20365             }
20366         }
20367     }
20368
20369     /**
20370      * Verify that given package is currently frozen.
20371      */
20372     private void checkPackageFrozen(String packageName) {
20373         synchronized (mPackages) {
20374             if (!mFrozenPackages.contains(packageName)) {
20375                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20376             }
20377         }
20378     }
20379
20380     @Override
20381     public int movePackage(final String packageName, final String volumeUuid) {
20382         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20383
20384         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20385         final int moveId = mNextMoveId.getAndIncrement();
20386         mHandler.post(new Runnable() {
20387             @Override
20388             public void run() {
20389                 try {
20390                     movePackageInternal(packageName, volumeUuid, moveId, user);
20391                 } catch (PackageManagerException e) {
20392                     Slog.w(TAG, "Failed to move " + packageName, e);
20393                     mMoveCallbacks.notifyStatusChanged(moveId,
20394                             PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20395                 }
20396             }
20397         });
20398         return moveId;
20399     }
20400
20401     private void movePackageInternal(final String packageName, final String volumeUuid,
20402             final int moveId, UserHandle user) throws PackageManagerException {
20403         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20404         final PackageManager pm = mContext.getPackageManager();
20405
20406         final boolean currentAsec;
20407         final String currentVolumeUuid;
20408         final File codeFile;
20409         final String installerPackageName;
20410         final String packageAbiOverride;
20411         final int appId;
20412         final String seinfo;
20413         final String label;
20414         final int targetSdkVersion;
20415         final PackageFreezer freezer;
20416         final int[] installedUserIds;
20417
20418         // reader
20419         synchronized (mPackages) {
20420             final PackageParser.Package pkg = mPackages.get(packageName);
20421             final PackageSetting ps = mSettings.mPackages.get(packageName);
20422             if (pkg == null || ps == null) {
20423                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20424             }
20425
20426             if (pkg.applicationInfo.isSystemApp()) {
20427                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20428                         "Cannot move system application");
20429             }
20430
20431             if (pkg.applicationInfo.isExternalAsec()) {
20432                 currentAsec = true;
20433                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20434             } else if (pkg.applicationInfo.isForwardLocked()) {
20435                 currentAsec = true;
20436                 currentVolumeUuid = "forward_locked";
20437             } else {
20438                 currentAsec = false;
20439                 currentVolumeUuid = ps.volumeUuid;
20440
20441                 final File probe = new File(pkg.codePath);
20442                 final File probeOat = new File(probe, "oat");
20443                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20444                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20445                             "Move only supported for modern cluster style installs");
20446                 }
20447             }
20448
20449             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20450                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20451                         "Package already moved to " + volumeUuid);
20452             }
20453             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20454                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20455                         "Device admin cannot be moved");
20456             }
20457
20458             if (mFrozenPackages.contains(packageName)) {
20459                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20460                         "Failed to move already frozen package");
20461             }
20462
20463             codeFile = new File(pkg.codePath);
20464             installerPackageName = ps.installerPackageName;
20465             packageAbiOverride = ps.cpuAbiOverrideString;
20466             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20467             seinfo = pkg.applicationInfo.seinfo;
20468             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20469             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20470             freezer = freezePackage(packageName, "movePackageInternal");
20471             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20472         }
20473
20474         final Bundle extras = new Bundle();
20475         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20476         extras.putString(Intent.EXTRA_TITLE, label);
20477         mMoveCallbacks.notifyCreated(moveId, extras);
20478
20479         int installFlags;
20480         final boolean moveCompleteApp;
20481         final File measurePath;
20482
20483         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20484             installFlags = INSTALL_INTERNAL;
20485             moveCompleteApp = !currentAsec;
20486             measurePath = Environment.getDataAppDirectory(volumeUuid);
20487         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20488             installFlags = INSTALL_EXTERNAL;
20489             moveCompleteApp = false;
20490             measurePath = storage.getPrimaryPhysicalVolume().getPath();
20491         } else {
20492             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20493             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20494                     || !volume.isMountedWritable()) {
20495                 freezer.close();
20496                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20497                         "Move location not mounted private volume");
20498             }
20499
20500             Preconditions.checkState(!currentAsec);
20501
20502             installFlags = INSTALL_INTERNAL;
20503             moveCompleteApp = true;
20504             measurePath = Environment.getDataAppDirectory(volumeUuid);
20505         }
20506
20507         final PackageStats stats = new PackageStats(null, -1);
20508         synchronized (mInstaller) {
20509             for (int userId : installedUserIds) {
20510                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20511                     freezer.close();
20512                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20513                             "Failed to measure package size");
20514                 }
20515             }
20516         }
20517
20518         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20519                 + stats.dataSize);
20520
20521         final long startFreeBytes = measurePath.getFreeSpace();
20522         final long sizeBytes;
20523         if (moveCompleteApp) {
20524             sizeBytes = stats.codeSize + stats.dataSize;
20525         } else {
20526             sizeBytes = stats.codeSize;
20527         }
20528
20529         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20530             freezer.close();
20531             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20532                     "Not enough free space to move");
20533         }
20534
20535         mMoveCallbacks.notifyStatusChanged(moveId, 10);
20536
20537         final CountDownLatch installedLatch = new CountDownLatch(1);
20538         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20539             @Override
20540             public void onUserActionRequired(Intent intent) throws RemoteException {
20541                 throw new IllegalStateException();
20542             }
20543
20544             @Override
20545             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20546                     Bundle extras) throws RemoteException {
20547                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20548                         + PackageManager.installStatusToString(returnCode, msg));
20549
20550                 installedLatch.countDown();
20551                 freezer.close();
20552
20553                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20554                 switch (status) {
20555                     case PackageInstaller.STATUS_SUCCESS:
20556                         mMoveCallbacks.notifyStatusChanged(moveId,
20557                                 PackageManager.MOVE_SUCCEEDED);
20558                         break;
20559                     case PackageInstaller.STATUS_FAILURE_STORAGE:
20560                         mMoveCallbacks.notifyStatusChanged(moveId,
20561                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20562                         break;
20563                     default:
20564                         mMoveCallbacks.notifyStatusChanged(moveId,
20565                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20566                         break;
20567                 }
20568             }
20569         };
20570
20571         final MoveInfo move;
20572         if (moveCompleteApp) {
20573             // Kick off a thread to report progress estimates
20574             new Thread() {
20575                 @Override
20576                 public void run() {
20577                     while (true) {
20578                         try {
20579                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
20580                                 break;
20581                             }
20582                         } catch (InterruptedException ignored) {
20583                         }
20584
20585                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20586                         final int progress = 10 + (int) MathUtils.constrain(
20587                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20588                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
20589                     }
20590                 }
20591             }.start();
20592
20593             final String dataAppName = codeFile.getName();
20594             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20595                     dataAppName, appId, seinfo, targetSdkVersion);
20596         } else {
20597             move = null;
20598         }
20599
20600         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20601
20602         final Message msg = mHandler.obtainMessage(INIT_COPY);
20603         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20604         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20605                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20606                 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20607         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20608         msg.obj = params;
20609
20610         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20611                 System.identityHashCode(msg.obj));
20612         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20613                 System.identityHashCode(msg.obj));
20614
20615         mHandler.sendMessage(msg);
20616     }
20617
20618     @Override
20619     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20620         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20621
20622         final int realMoveId = mNextMoveId.getAndIncrement();
20623         final Bundle extras = new Bundle();
20624         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20625         mMoveCallbacks.notifyCreated(realMoveId, extras);
20626
20627         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20628             @Override
20629             public void onCreated(int moveId, Bundle extras) {
20630                 // Ignored
20631             }
20632
20633             @Override
20634             public void onStatusChanged(int moveId, int status, long estMillis) {
20635                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20636             }
20637         };
20638
20639         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20640         storage.setPrimaryStorageUuid(volumeUuid, callback);
20641         return realMoveId;
20642     }
20643
20644     @Override
20645     public int getMoveStatus(int moveId) {
20646         mContext.enforceCallingOrSelfPermission(
20647                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20648         return mMoveCallbacks.mLastStatus.get(moveId);
20649     }
20650
20651     @Override
20652     public void registerMoveCallback(IPackageMoveObserver callback) {
20653         mContext.enforceCallingOrSelfPermission(
20654                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20655         mMoveCallbacks.register(callback);
20656     }
20657
20658     @Override
20659     public void unregisterMoveCallback(IPackageMoveObserver callback) {
20660         mContext.enforceCallingOrSelfPermission(
20661                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20662         mMoveCallbacks.unregister(callback);
20663     }
20664
20665     @Override
20666     public boolean setInstallLocation(int loc) {
20667         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20668                 null);
20669         if (getInstallLocation() == loc) {
20670             return true;
20671         }
20672         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20673                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20674             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20675                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20676             return true;
20677         }
20678         return false;
20679    }
20680
20681     @Override
20682     public int getInstallLocation() {
20683         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20684                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20685                 PackageHelper.APP_INSTALL_AUTO);
20686     }
20687
20688     /** Called by UserManagerService */
20689     void cleanUpUser(UserManagerService userManager, int userHandle) {
20690         synchronized (mPackages) {
20691             mDirtyUsers.remove(userHandle);
20692             mUserNeedsBadging.delete(userHandle);
20693             mSettings.removeUserLPw(userHandle);
20694             mPendingBroadcasts.remove(userHandle);
20695             mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20696             removeUnusedPackagesLPw(userManager, userHandle);
20697         }
20698     }
20699
20700     /**
20701      * We're removing userHandle and would like to remove any downloaded packages
20702      * that are no longer in use by any other user.
20703      * @param userHandle the user being removed
20704      */
20705     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20706         final boolean DEBUG_CLEAN_APKS = false;
20707         int [] users = userManager.getUserIds();
20708         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20709         while (psit.hasNext()) {
20710             PackageSetting ps = psit.next();
20711             if (ps.pkg == null) {
20712                 continue;
20713             }
20714             final String packageName = ps.pkg.packageName;
20715             // Skip over if system app
20716             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20717                 continue;
20718             }
20719             if (DEBUG_CLEAN_APKS) {
20720                 Slog.i(TAG, "Checking package " + packageName);
20721             }
20722             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20723             if (keep) {
20724                 if (DEBUG_CLEAN_APKS) {
20725                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20726                 }
20727             } else {
20728                 for (int i = 0; i < users.length; i++) {
20729                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
20730                         keep = true;
20731                         if (DEBUG_CLEAN_APKS) {
20732                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
20733                                     + users[i]);
20734                         }
20735                         break;
20736                     }
20737                 }
20738             }
20739             if (!keep) {
20740                 if (DEBUG_CLEAN_APKS) {
20741                     Slog.i(TAG, "  Removing package " + packageName);
20742                 }
20743                 mHandler.post(new Runnable() {
20744                     public void run() {
20745                         deletePackageX(packageName, userHandle, 0);
20746                     } //end run
20747                 });
20748             }
20749         }
20750     }
20751
20752     /** Called by UserManagerService */
20753     void createNewUser(int userId) {
20754         synchronized (mInstallLock) {
20755             mSettings.createNewUserLI(this, mInstaller, userId);
20756         }
20757         synchronized (mPackages) {
20758             scheduleWritePackageRestrictionsLocked(userId);
20759             scheduleWritePackageListLocked(userId);
20760             applyFactoryDefaultBrowserLPw(userId);
20761             primeDomainVerificationsLPw(userId);
20762         }
20763     }
20764
20765     void onNewUserCreated(final int userId) {
20766         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20767         // If permission review for legacy apps is required, we represent
20768         // dagerous permissions for such apps as always granted runtime
20769         // permissions to keep per user flag state whether review is needed.
20770         // Hence, if a new user is added we have to propagate dangerous
20771         // permission grants for these legacy apps.
20772         if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20773             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20774                     | UPDATE_PERMISSIONS_REPLACE_ALL);
20775         }
20776     }
20777
20778     @Override
20779     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20780         mContext.enforceCallingOrSelfPermission(
20781                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20782                 "Only package verification agents can read the verifier device identity");
20783
20784         synchronized (mPackages) {
20785             return mSettings.getVerifierDeviceIdentityLPw();
20786         }
20787     }
20788
20789     @Override
20790     public void setPermissionEnforced(String permission, boolean enforced) {
20791         // TODO: Now that we no longer change GID for storage, this should to away.
20792         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20793                 "setPermissionEnforced");
20794         if (READ_EXTERNAL_STORAGE.equals(permission)) {
20795             synchronized (mPackages) {
20796                 if (mSettings.mReadExternalStorageEnforced == null
20797                         || mSettings.mReadExternalStorageEnforced != enforced) {
20798                     mSettings.mReadExternalStorageEnforced = enforced;
20799                     mSettings.writeLPr();
20800                 }
20801             }
20802             // kill any non-foreground processes so we restart them and
20803             // grant/revoke the GID.
20804             final IActivityManager am = ActivityManagerNative.getDefault();
20805             if (am != null) {
20806                 final long token = Binder.clearCallingIdentity();
20807                 try {
20808                     am.killProcessesBelowForeground("setPermissionEnforcement");
20809                 } catch (RemoteException e) {
20810                 } finally {
20811                     Binder.restoreCallingIdentity(token);
20812                 }
20813             }
20814         } else {
20815             throw new IllegalArgumentException("No selective enforcement for " + permission);
20816         }
20817     }
20818
20819     @Override
20820     @Deprecated
20821     public boolean isPermissionEnforced(String permission) {
20822         return true;
20823     }
20824
20825     @Override
20826     public boolean isStorageLow() {
20827         final long token = Binder.clearCallingIdentity();
20828         try {
20829             final DeviceStorageMonitorInternal
20830                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20831             if (dsm != null) {
20832                 return dsm.isMemoryLow();
20833             } else {
20834                 return false;
20835             }
20836         } finally {
20837             Binder.restoreCallingIdentity(token);
20838         }
20839     }
20840
20841     @Override
20842     public IPackageInstaller getPackageInstaller() {
20843         return mInstallerService;
20844     }
20845
20846     private boolean userNeedsBadging(int userId) {
20847         int index = mUserNeedsBadging.indexOfKey(userId);
20848         if (index < 0) {
20849             final UserInfo userInfo;
20850             final long token = Binder.clearCallingIdentity();
20851             try {
20852                 userInfo = sUserManager.getUserInfo(userId);
20853             } finally {
20854                 Binder.restoreCallingIdentity(token);
20855             }
20856             final boolean b;
20857             if (userInfo != null && userInfo.isManagedProfile()) {
20858                 b = true;
20859             } else {
20860                 b = false;
20861             }
20862             mUserNeedsBadging.put(userId, b);
20863             return b;
20864         }
20865         return mUserNeedsBadging.valueAt(index);
20866     }
20867
20868     @Override
20869     public KeySet getKeySetByAlias(String packageName, String alias) {
20870         if (packageName == null || alias == null) {
20871             return null;
20872         }
20873         synchronized(mPackages) {
20874             final PackageParser.Package pkg = mPackages.get(packageName);
20875             if (pkg == null) {
20876                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20877                 throw new IllegalArgumentException("Unknown package: " + packageName);
20878             }
20879             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20880             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20881         }
20882     }
20883
20884     @Override
20885     public KeySet getSigningKeySet(String packageName) {
20886         if (packageName == null) {
20887             return null;
20888         }
20889         synchronized(mPackages) {
20890             final PackageParser.Package pkg = mPackages.get(packageName);
20891             if (pkg == null) {
20892                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20893                 throw new IllegalArgumentException("Unknown package: " + packageName);
20894             }
20895             if (pkg.applicationInfo.uid != Binder.getCallingUid()
20896                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
20897                 throw new SecurityException("May not access signing KeySet of other apps.");
20898             }
20899             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20900             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20901         }
20902     }
20903
20904     @Override
20905     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20906         if (packageName == null || ks == null) {
20907             return false;
20908         }
20909         synchronized(mPackages) {
20910             final PackageParser.Package pkg = mPackages.get(packageName);
20911             if (pkg == null) {
20912                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20913                 throw new IllegalArgumentException("Unknown package: " + packageName);
20914             }
20915             IBinder ksh = ks.getToken();
20916             if (ksh instanceof KeySetHandle) {
20917                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20918                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20919             }
20920             return false;
20921         }
20922     }
20923
20924     @Override
20925     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20926         if (packageName == null || ks == null) {
20927             return false;
20928         }
20929         synchronized(mPackages) {
20930             final PackageParser.Package pkg = mPackages.get(packageName);
20931             if (pkg == null) {
20932                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20933                 throw new IllegalArgumentException("Unknown package: " + packageName);
20934             }
20935             IBinder ksh = ks.getToken();
20936             if (ksh instanceof KeySetHandle) {
20937                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20938                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20939             }
20940             return false;
20941         }
20942     }
20943
20944     private void deletePackageIfUnusedLPr(final String packageName) {
20945         PackageSetting ps = mSettings.mPackages.get(packageName);
20946         if (ps == null) {
20947             return;
20948         }
20949         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20950             // TODO Implement atomic delete if package is unused
20951             // It is currently possible that the package will be deleted even if it is installed
20952             // after this method returns.
20953             mHandler.post(new Runnable() {
20954                 public void run() {
20955                     deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20956                 }
20957             });
20958         }
20959     }
20960
20961     /**
20962      * Check and throw if the given before/after packages would be considered a
20963      * downgrade.
20964      */
20965     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20966             throws PackageManagerException {
20967         if (after.versionCode < before.mVersionCode) {
20968             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20969                     "Update version code " + after.versionCode + " is older than current "
20970                     + before.mVersionCode);
20971         } else if (after.versionCode == before.mVersionCode) {
20972             if (after.baseRevisionCode < before.baseRevisionCode) {
20973                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20974                         "Update base revision code " + after.baseRevisionCode
20975                         + " is older than current " + before.baseRevisionCode);
20976             }
20977
20978             if (!ArrayUtils.isEmpty(after.splitNames)) {
20979                 for (int i = 0; i < after.splitNames.length; i++) {
20980                     final String splitName = after.splitNames[i];
20981                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20982                     if (j != -1) {
20983                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20984                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20985                                     "Update split " + splitName + " revision code "
20986                                     + after.splitRevisionCodes[i] + " is older than current "
20987                                     + before.splitRevisionCodes[j]);
20988                         }
20989                     }
20990                 }
20991             }
20992         }
20993     }
20994
20995     private static class MoveCallbacks extends Handler {
20996         private static final int MSG_CREATED = 1;
20997         private static final int MSG_STATUS_CHANGED = 2;
20998
20999         private final RemoteCallbackList<IPackageMoveObserver>
21000                 mCallbacks = new RemoteCallbackList<>();
21001
21002         private final SparseIntArray mLastStatus = new SparseIntArray();
21003
21004         public MoveCallbacks(Looper looper) {
21005             super(looper);
21006         }
21007
21008         public void register(IPackageMoveObserver callback) {
21009             mCallbacks.register(callback);
21010         }
21011
21012         public void unregister(IPackageMoveObserver callback) {
21013             mCallbacks.unregister(callback);
21014         }
21015
21016         @Override
21017         public void handleMessage(Message msg) {
21018             final SomeArgs args = (SomeArgs) msg.obj;
21019             final int n = mCallbacks.beginBroadcast();
21020             for (int i = 0; i < n; i++) {
21021                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21022                 try {
21023                     invokeCallback(callback, msg.what, args);
21024                 } catch (RemoteException ignored) {
21025                 }
21026             }
21027             mCallbacks.finishBroadcast();
21028             args.recycle();
21029         }
21030
21031         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21032                 throws RemoteException {
21033             switch (what) {
21034                 case MSG_CREATED: {
21035                     callback.onCreated(args.argi1, (Bundle) args.arg2);
21036                     break;
21037                 }
21038                 case MSG_STATUS_CHANGED: {
21039                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21040                     break;
21041                 }
21042             }
21043         }
21044
21045         private void notifyCreated(int moveId, Bundle extras) {
21046             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21047
21048             final SomeArgs args = SomeArgs.obtain();
21049             args.argi1 = moveId;
21050             args.arg2 = extras;
21051             obtainMessage(MSG_CREATED, args).sendToTarget();
21052         }
21053
21054         private void notifyStatusChanged(int moveId, int status) {
21055             notifyStatusChanged(moveId, status, -1);
21056         }
21057
21058         private void notifyStatusChanged(int moveId, int status, long estMillis) {
21059             Slog.v(TAG, "Move " + moveId + " status " + status);
21060
21061             final SomeArgs args = SomeArgs.obtain();
21062             args.argi1 = moveId;
21063             args.argi2 = status;
21064             args.arg3 = estMillis;
21065             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21066
21067             synchronized (mLastStatus) {
21068                 mLastStatus.put(moveId, status);
21069             }
21070         }
21071     }
21072
21073     private final static class OnPermissionChangeListeners extends Handler {
21074         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21075
21076         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21077                 new RemoteCallbackList<>();
21078
21079         public OnPermissionChangeListeners(Looper looper) {
21080             super(looper);
21081         }
21082
21083         @Override
21084         public void handleMessage(Message msg) {
21085             switch (msg.what) {
21086                 case MSG_ON_PERMISSIONS_CHANGED: {
21087                     final int uid = msg.arg1;
21088                     handleOnPermissionsChanged(uid);
21089                 } break;
21090             }
21091         }
21092
21093         public void addListenerLocked(IOnPermissionsChangeListener listener) {
21094             mPermissionListeners.register(listener);
21095
21096         }
21097
21098         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21099             mPermissionListeners.unregister(listener);
21100         }
21101
21102         public void onPermissionsChanged(int uid) {
21103             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21104                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21105             }
21106         }
21107
21108         private void handleOnPermissionsChanged(int uid) {
21109             final int count = mPermissionListeners.beginBroadcast();
21110             try {
21111                 for (int i = 0; i < count; i++) {
21112                     IOnPermissionsChangeListener callback = mPermissionListeners
21113                             .getBroadcastItem(i);
21114                     try {
21115                         callback.onPermissionsChanged(uid);
21116                     } catch (RemoteException e) {
21117                         Log.e(TAG, "Permission listener is dead", e);
21118                     }
21119                 }
21120             } finally {
21121                 mPermissionListeners.finishBroadcast();
21122             }
21123         }
21124     }
21125
21126     private class PackageManagerInternalImpl extends PackageManagerInternal {
21127         @Override
21128         public void setLocationPackagesProvider(PackagesProvider provider) {
21129             synchronized (mPackages) {
21130                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21131             }
21132         }
21133
21134         @Override
21135         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21136             synchronized (mPackages) {
21137                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21138             }
21139         }
21140
21141         @Override
21142         public void setSmsAppPackagesProvider(PackagesProvider provider) {
21143             synchronized (mPackages) {
21144                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21145             }
21146         }
21147
21148         @Override
21149         public void setDialerAppPackagesProvider(PackagesProvider provider) {
21150             synchronized (mPackages) {
21151                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21152             }
21153         }
21154
21155         @Override
21156         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21157             synchronized (mPackages) {
21158                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21159             }
21160         }
21161
21162         @Override
21163         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21164             synchronized (mPackages) {
21165                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21166             }
21167         }
21168
21169         @Override
21170         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21171             synchronized (mPackages) {
21172                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21173                         packageName, userId);
21174             }
21175         }
21176
21177         @Override
21178         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21179             synchronized (mPackages) {
21180                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21181                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21182                         packageName, userId);
21183             }
21184         }
21185
21186         @Override
21187         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21188             synchronized (mPackages) {
21189                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21190                         packageName, userId);
21191             }
21192         }
21193
21194         @Override
21195         public void setKeepUninstalledPackages(final List<String> packageList) {
21196             Preconditions.checkNotNull(packageList);
21197             List<String> removedFromList = null;
21198             synchronized (mPackages) {
21199                 if (mKeepUninstalledPackages != null) {
21200                     final int packagesCount = mKeepUninstalledPackages.size();
21201                     for (int i = 0; i < packagesCount; i++) {
21202                         String oldPackage = mKeepUninstalledPackages.get(i);
21203                         if (packageList != null && packageList.contains(oldPackage)) {
21204                             continue;
21205                         }
21206                         if (removedFromList == null) {
21207                             removedFromList = new ArrayList<>();
21208                         }
21209                         removedFromList.add(oldPackage);
21210                     }
21211                 }
21212                 mKeepUninstalledPackages = new ArrayList<>(packageList);
21213                 if (removedFromList != null) {
21214                     final int removedCount = removedFromList.size();
21215                     for (int i = 0; i < removedCount; i++) {
21216                         deletePackageIfUnusedLPr(removedFromList.get(i));
21217                     }
21218                 }
21219             }
21220         }
21221
21222         @Override
21223         public boolean isPermissionsReviewRequired(String packageName, int userId) {
21224             synchronized (mPackages) {
21225                 // If we do not support permission review, done.
21226                 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21227                     return false;
21228                 }
21229
21230                 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21231                 if (packageSetting == null) {
21232                     return false;
21233                 }
21234
21235                 // Permission review applies only to apps not supporting the new permission model.
21236                 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21237                     return false;
21238                 }
21239
21240                 // Legacy apps have the permission and get user consent on launch.
21241                 PermissionsState permissionsState = packageSetting.getPermissionsState();
21242                 return permissionsState.isPermissionReviewRequired(userId);
21243             }
21244         }
21245
21246         @Override
21247         public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21248             return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21249         }
21250
21251         @Override
21252         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21253                 int userId) {
21254             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21255         }
21256
21257         @Override
21258         public void setDeviceAndProfileOwnerPackages(
21259                 int deviceOwnerUserId, String deviceOwnerPackage,
21260                 SparseArray<String> profileOwnerPackages) {
21261             mProtectedPackages.setDeviceAndProfileOwnerPackages(
21262                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21263         }
21264
21265         @Override
21266         public boolean isPackageDataProtected(int userId, String packageName) {
21267             return mProtectedPackages.isPackageDataProtected(userId, packageName);
21268         }
21269
21270         @Override
21271         public boolean wasPackageEverLaunched(String packageName, int userId) {
21272             synchronized (mPackages) {
21273                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21274             }
21275         }
21276
21277         @Override
21278         public String getNameForUid(int uid) {
21279             return PackageManagerService.this.getNameForUid(uid);
21280         }
21281     }
21282
21283     @Override
21284     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21285         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21286         synchronized (mPackages) {
21287             final long identity = Binder.clearCallingIdentity();
21288             try {
21289                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21290                         packageNames, userId);
21291             } finally {
21292                 Binder.restoreCallingIdentity(identity);
21293             }
21294         }
21295     }
21296
21297     private static void enforceSystemOrPhoneCaller(String tag) {
21298         int callingUid = Binder.getCallingUid();
21299         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21300             throw new SecurityException(
21301                     "Cannot call " + tag + " from UID " + callingUid);
21302         }
21303     }
21304
21305     boolean isHistoricalPackageUsageAvailable() {
21306         return mPackageUsage.isHistoricalPackageUsageAvailable();
21307     }
21308
21309     /**
21310      * Return a <b>copy</b> of the collection of packages known to the package manager.
21311      * @return A copy of the values of mPackages.
21312      */
21313     Collection<PackageParser.Package> getPackages() {
21314         synchronized (mPackages) {
21315             return new ArrayList<>(mPackages.values());
21316         }
21317     }
21318
21319     /**
21320      * Logs process start information (including base APK hash) to the security log.
21321      * @hide
21322      */
21323     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21324             String apkFile, int pid) {
21325         if (!SecurityLog.isLoggingEnabled()) {
21326             return;
21327         }
21328         Bundle data = new Bundle();
21329         data.putLong("startTimestamp", System.currentTimeMillis());
21330         data.putString("processName", processName);
21331         data.putInt("uid", uid);
21332         data.putString("seinfo", seinfo);
21333         data.putString("apkFile", apkFile);
21334         data.putInt("pid", pid);
21335         Message msg = mProcessLoggingHandler.obtainMessage(
21336                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21337         msg.setData(data);
21338         mProcessLoggingHandler.sendMessage(msg);
21339     }
21340
21341     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21342         return mCompilerStats.getPackageStats(pkgName);
21343     }
21344
21345     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21346         return getOrCreateCompilerPackageStats(pkg.packageName);
21347     }
21348
21349     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21350         return mCompilerStats.getOrCreatePackageStats(pkgName);
21351     }
21352
21353     public void deleteCompilerPackageStats(String pkgName) {
21354         mCompilerStats.deletePackageStats(pkgName);
21355     }
21356 }