PackageManagerService.java revision 02424676c68e23f44432ef0e379d65ddd9c3a786
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
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.security.KeyStore;
199import android.security.SystemKeyStore;
200import android.system.ErrnoException;
201import android.system.Os;
202import android.text.TextUtils;
203import android.text.format.DateUtils;
204import android.util.ArrayMap;
205import android.util.ArraySet;
206import android.util.AtomicFile;
207import android.util.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.view.Display;
220
221import com.android.internal.R;
222import com.android.internal.annotations.GuardedBy;
223import com.android.internal.app.IMediaContainerService;
224import com.android.internal.app.ResolverActivity;
225import com.android.internal.content.NativeLibraryHelper;
226import com.android.internal.content.PackageHelper;
227import com.android.internal.os.IParcelFileDescriptorFactory;
228import com.android.internal.os.InstallerConnection.InstallerException;
229import com.android.internal.os.SomeArgs;
230import com.android.internal.os.Zygote;
231import com.android.internal.util.ArrayUtils;
232import com.android.internal.util.FastPrintWriter;
233import com.android.internal.util.FastXmlSerializer;
234import com.android.internal.util.IndentingPrintWriter;
235import com.android.internal.util.Preconditions;
236import com.android.internal.util.XmlUtils;
237import com.android.server.EventLogTags;
238import com.android.server.FgThread;
239import com.android.server.IntentResolver;
240import com.android.server.LocalServices;
241import com.android.server.ServiceThread;
242import com.android.server.SystemConfig;
243import com.android.server.Watchdog;
244import com.android.server.pm.PermissionsState.PermissionState;
245import com.android.server.pm.Settings.DatabaseVersion;
246import com.android.server.pm.Settings.VersionInfo;
247import com.android.server.storage.DeviceStorageMonitorInternal;
248
249import dalvik.system.DexFile;
250import dalvik.system.VMRuntime;
251
252import libcore.io.IoUtils;
253import libcore.util.EmptyArray;
254
255import org.xmlpull.v1.XmlPullParser;
256import org.xmlpull.v1.XmlPullParserException;
257import org.xmlpull.v1.XmlSerializer;
258
259import java.io.BufferedInputStream;
260import java.io.BufferedOutputStream;
261import java.io.BufferedReader;
262import java.io.ByteArrayInputStream;
263import java.io.ByteArrayOutputStream;
264import java.io.File;
265import java.io.FileDescriptor;
266import java.io.FileNotFoundException;
267import java.io.FileOutputStream;
268import java.io.FileReader;
269import java.io.FilenameFilter;
270import java.io.IOException;
271import java.io.InputStream;
272import java.io.PrintWriter;
273import java.nio.charset.StandardCharsets;
274import java.security.MessageDigest;
275import java.security.NoSuchAlgorithmException;
276import java.security.PublicKey;
277import java.security.cert.CertificateEncodingException;
278import java.security.cert.CertificateException;
279import java.text.SimpleDateFormat;
280import java.util.ArrayList;
281import java.util.Arrays;
282import java.util.Collection;
283import java.util.Collections;
284import java.util.Comparator;
285import java.util.Date;
286import java.util.HashSet;
287import java.util.Iterator;
288import java.util.List;
289import java.util.Map;
290import java.util.Objects;
291import java.util.Set;
292import java.util.concurrent.CountDownLatch;
293import java.util.concurrent.TimeUnit;
294import java.util.concurrent.atomic.AtomicBoolean;
295import java.util.concurrent.atomic.AtomicInteger;
296import java.util.concurrent.atomic.AtomicLong;
297
298/**
299 * Keep track of all those .apks everywhere.
300 *
301 * This is very central to the platform's security; please run the unit
302 * tests whenever making modifications here:
303 *
304runtest -c android.content.pm.PackageManagerTests frameworks-core
305 *
306 * {@hide}
307 */
308public class PackageManagerService extends IPackageManager.Stub {
309    static final String TAG = "PackageManager";
310    static final boolean DEBUG_SETTINGS = false;
311    static final boolean DEBUG_PREFERRED = false;
312    static final boolean DEBUG_UPGRADE = false;
313    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
314    private static final boolean DEBUG_BACKUP = false;
315    private static final boolean DEBUG_INSTALL = false;
316    private static final boolean DEBUG_REMOVE = false;
317    private static final boolean DEBUG_BROADCASTS = false;
318    private static final boolean DEBUG_SHOW_INFO = false;
319    private static final boolean DEBUG_PACKAGE_INFO = false;
320    private static final boolean DEBUG_INTENT_MATCHING = false;
321    private static final boolean DEBUG_PACKAGE_SCANNING = false;
322    private static final boolean DEBUG_VERIFY = false;
323
324    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
325    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
326    // user, but by default initialize to this.
327    static final boolean DEBUG_DEXOPT = false;
328
329    private static final boolean DEBUG_ABI_SELECTION = false;
330    private static final boolean DEBUG_EPHEMERAL = false;
331    private static final boolean DEBUG_TRIAGED_MISSING = false;
332    private static final boolean DEBUG_APP_DATA = false;
333
334    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
335
336    private static final boolean DISABLE_EPHEMERAL_APPS = true;
337
338    private static final int RADIO_UID = Process.PHONE_UID;
339    private static final int LOG_UID = Process.LOG_UID;
340    private static final int NFC_UID = Process.NFC_UID;
341    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
342    private static final int SHELL_UID = Process.SHELL_UID;
343
344    // Cap the size of permission trees that 3rd party apps can define
345    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
346
347    // Suffix used during package installation when copying/moving
348    // package apks to install directory.
349    private static final String INSTALL_PACKAGE_SUFFIX = "-";
350
351    static final int SCAN_NO_DEX = 1<<1;
352    static final int SCAN_FORCE_DEX = 1<<2;
353    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
354    static final int SCAN_NEW_INSTALL = 1<<4;
355    static final int SCAN_NO_PATHS = 1<<5;
356    static final int SCAN_UPDATE_TIME = 1<<6;
357    static final int SCAN_DEFER_DEX = 1<<7;
358    static final int SCAN_BOOTING = 1<<8;
359    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
360    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
361    static final int SCAN_REPLACING = 1<<11;
362    static final int SCAN_REQUIRE_KNOWN = 1<<12;
363    static final int SCAN_MOVE = 1<<13;
364    static final int SCAN_INITIAL = 1<<14;
365    static final int SCAN_CHECK_ONLY = 1<<15;
366    static final int SCAN_DONT_KILL_APP = 1<<17;
367
368    static final int REMOVE_CHATTY = 1<<16;
369
370    private static final int[] EMPTY_INT_ARRAY = new int[0];
371
372    /**
373     * Timeout (in milliseconds) after which the watchdog should declare that
374     * our handler thread is wedged.  The usual default for such things is one
375     * minute but we sometimes do very lengthy I/O operations on this thread,
376     * such as installing multi-gigabyte applications, so ours needs to be longer.
377     */
378    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
379
380    /**
381     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
382     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
383     * settings entry if available, otherwise we use the hardcoded default.  If it's been
384     * more than this long since the last fstrim, we force one during the boot sequence.
385     *
386     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
387     * one gets run at the next available charging+idle time.  This final mandatory
388     * no-fstrim check kicks in only of the other scheduling criteria is never met.
389     */
390    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
391
392    /**
393     * Whether verification is enabled by default.
394     */
395    private static final boolean DEFAULT_VERIFY_ENABLE = true;
396
397    /**
398     * The default maximum time to wait for the verification agent to return in
399     * milliseconds.
400     */
401    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
402
403    /**
404     * The default response for package verification timeout.
405     *
406     * This can be either PackageManager.VERIFICATION_ALLOW or
407     * PackageManager.VERIFICATION_REJECT.
408     */
409    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
410
411    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
412
413    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
414            DEFAULT_CONTAINER_PACKAGE,
415            "com.android.defcontainer.DefaultContainerService");
416
417    private static final String KILL_APP_REASON_GIDS_CHANGED =
418            "permission grant or revoke changed gids";
419
420    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
421            "permissions revoked";
422
423    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
424
425    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
426
427    /** Permission grant: not grant the permission. */
428    private static final int GRANT_DENIED = 1;
429
430    /** Permission grant: grant the permission as an install permission. */
431    private static final int GRANT_INSTALL = 2;
432
433    /** Permission grant: grant the permission as a runtime one. */
434    private static final int GRANT_RUNTIME = 3;
435
436    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
437    private static final int GRANT_UPGRADE = 4;
438
439    /** Canonical intent used to identify what counts as a "web browser" app */
440    private static final Intent sBrowserIntent;
441    static {
442        sBrowserIntent = new Intent();
443        sBrowserIntent.setAction(Intent.ACTION_VIEW);
444        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
445        sBrowserIntent.setData(Uri.parse("http:"));
446    }
447
448    // Compilation reasons.
449    public static final int REASON_FIRST_BOOT = 0;
450    public static final int REASON_BOOT = 1;
451    public static final int REASON_INSTALL = 2;
452    public static final int REASON_BACKGROUND_DEXOPT = 3;
453    public static final int REASON_AB_OTA = 4;
454    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
455    public static final int REASON_SHARED_APK = 6;
456    public static final int REASON_FORCED_DEXOPT = 7;
457
458    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
459
460    final ServiceThread mHandlerThread;
461
462    final PackageHandler mHandler;
463
464    private final ProcessLoggingHandler mProcessLoggingHandler;
465
466    /**
467     * Messages for {@link #mHandler} that need to wait for system ready before
468     * being dispatched.
469     */
470    private ArrayList<Message> mPostSystemReadyMessages;
471
472    final int mSdkVersion = Build.VERSION.SDK_INT;
473
474    final Context mContext;
475    final boolean mFactoryTest;
476    final boolean mOnlyCore;
477    final DisplayMetrics mMetrics;
478    final int mDefParseFlags;
479    final String[] mSeparateProcesses;
480    final boolean mIsUpgrade;
481    final boolean mIsPreNUpgrade;
482
483    /** The location for ASEC container files on internal storage. */
484    final String mAsecInternalPath;
485
486    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
487    // LOCK HELD.  Can be called with mInstallLock held.
488    @GuardedBy("mInstallLock")
489    final Installer mInstaller;
490
491    /** Directory where installed third-party apps stored */
492    final File mAppInstallDir;
493    final File mEphemeralInstallDir;
494
495    /**
496     * Directory to which applications installed internally have their
497     * 32 bit native libraries copied.
498     */
499    private File mAppLib32InstallDir;
500
501    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
502    // apps.
503    final File mDrmAppPrivateInstallDir;
504
505    // ----------------------------------------------------------------
506
507    // Lock for state used when installing and doing other long running
508    // operations.  Methods that must be called with this lock held have
509    // the suffix "LI".
510    final Object mInstallLock = new Object();
511
512    // ----------------------------------------------------------------
513
514    // Keys are String (package name), values are Package.  This also serves
515    // as the lock for the global state.  Methods that must be called with
516    // this lock held have the prefix "LP".
517    @GuardedBy("mPackages")
518    final ArrayMap<String, PackageParser.Package> mPackages =
519            new ArrayMap<String, PackageParser.Package>();
520
521    final ArrayMap<String, Set<String>> mKnownCodebase =
522            new ArrayMap<String, Set<String>>();
523
524    // Tracks available target package names -> overlay package paths.
525    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
526        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
527
528    /**
529     * Tracks new system packages [received in an OTA] that we expect to
530     * find updated user-installed versions. Keys are package name, values
531     * are package location.
532     */
533    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
534
535    /**
536     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
537     */
538    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
539    /**
540     * Whether or not system app permissions should be promoted from install to runtime.
541     */
542    boolean mPromoteSystemApps;
543
544    final Settings mSettings;
545    boolean mRestoredSettings;
546
547    // System configuration read by SystemConfig.
548    final int[] mGlobalGids;
549    final SparseArray<ArraySet<String>> mSystemPermissions;
550    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
551
552    // If mac_permissions.xml was found for seinfo labeling.
553    boolean mFoundPolicyFile;
554
555    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
556
557    public static final class SharedLibraryEntry {
558        public final String path;
559        public final String apk;
560
561        SharedLibraryEntry(String _path, String _apk) {
562            path = _path;
563            apk = _apk;
564        }
565    }
566
567    // Currently known shared libraries.
568    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
569            new ArrayMap<String, SharedLibraryEntry>();
570
571    // All available activities, for your resolving pleasure.
572    final ActivityIntentResolver mActivities =
573            new ActivityIntentResolver();
574
575    // All available receivers, for your resolving pleasure.
576    final ActivityIntentResolver mReceivers =
577            new ActivityIntentResolver();
578
579    // All available services, for your resolving pleasure.
580    final ServiceIntentResolver mServices = new ServiceIntentResolver();
581
582    // All available providers, for your resolving pleasure.
583    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
584
585    // Mapping from provider base names (first directory in content URI codePath)
586    // to the provider information.
587    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
588            new ArrayMap<String, PackageParser.Provider>();
589
590    // Mapping from instrumentation class names to info about them.
591    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
592            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
593
594    // Mapping from permission names to info about them.
595    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
596            new ArrayMap<String, PackageParser.PermissionGroup>();
597
598    // Packages whose data we have transfered into another package, thus
599    // should no longer exist.
600    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
601
602    // Broadcast actions that are only available to the system.
603    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
604
605    /** List of packages waiting for verification. */
606    final SparseArray<PackageVerificationState> mPendingVerification
607            = new SparseArray<PackageVerificationState>();
608
609    /** Set of packages associated with each app op permission. */
610    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
611
612    final PackageInstallerService mInstallerService;
613
614    private final PackageDexOptimizer mPackageDexOptimizer;
615
616    private AtomicInteger mNextMoveId = new AtomicInteger();
617    private final MoveCallbacks mMoveCallbacks;
618
619    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
620
621    // Cache of users who need badging.
622    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
623
624    /** Token for keys in mPendingVerification. */
625    private int mPendingVerificationToken = 0;
626
627    volatile boolean mSystemReady;
628    volatile boolean mSafeMode;
629    volatile boolean mHasSystemUidErrors;
630
631    ApplicationInfo mAndroidApplication;
632    final ActivityInfo mResolveActivity = new ActivityInfo();
633    final ResolveInfo mResolveInfo = new ResolveInfo();
634    ComponentName mResolveComponentName;
635    PackageParser.Package mPlatformPackage;
636    ComponentName mCustomResolverComponentName;
637
638    boolean mResolverReplaced = false;
639
640    private final @Nullable ComponentName mIntentFilterVerifierComponent;
641    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
642
643    private int mIntentFilterVerificationToken = 0;
644
645    /** Component that knows whether or not an ephemeral application exists */
646    final ComponentName mEphemeralResolverComponent;
647    /** The service connection to the ephemeral resolver */
648    final EphemeralResolverConnection mEphemeralResolverConnection;
649
650    /** Component used to install ephemeral applications */
651    final ComponentName mEphemeralInstallerComponent;
652    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
653    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
654
655    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
656            = new SparseArray<IntentFilterVerificationState>();
657
658    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
659            new DefaultPermissionGrantPolicy(this);
660
661    // List of packages names to keep cached, even if they are uninstalled for all users
662    private List<String> mKeepUninstalledPackages;
663
664    private static class IFVerificationParams {
665        PackageParser.Package pkg;
666        boolean replacing;
667        int userId;
668        int verifierUid;
669
670        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
671                int _userId, int _verifierUid) {
672            pkg = _pkg;
673            replacing = _replacing;
674            userId = _userId;
675            replacing = _replacing;
676            verifierUid = _verifierUid;
677        }
678    }
679
680    private interface IntentFilterVerifier<T extends IntentFilter> {
681        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
682                                               T filter, String packageName);
683        void startVerifications(int userId);
684        void receiveVerificationResponse(int verificationId);
685    }
686
687    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
688        private Context mContext;
689        private ComponentName mIntentFilterVerifierComponent;
690        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
691
692        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
693            mContext = context;
694            mIntentFilterVerifierComponent = verifierComponent;
695        }
696
697        private String getDefaultScheme() {
698            return IntentFilter.SCHEME_HTTPS;
699        }
700
701        @Override
702        public void startVerifications(int userId) {
703            // Launch verifications requests
704            int count = mCurrentIntentFilterVerifications.size();
705            for (int n=0; n<count; n++) {
706                int verificationId = mCurrentIntentFilterVerifications.get(n);
707                final IntentFilterVerificationState ivs =
708                        mIntentFilterVerificationStates.get(verificationId);
709
710                String packageName = ivs.getPackageName();
711
712                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
713                final int filterCount = filters.size();
714                ArraySet<String> domainsSet = new ArraySet<>();
715                for (int m=0; m<filterCount; m++) {
716                    PackageParser.ActivityIntentInfo filter = filters.get(m);
717                    domainsSet.addAll(filter.getHostsList());
718                }
719                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
720                synchronized (mPackages) {
721                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
722                            packageName, domainsList) != null) {
723                        scheduleWriteSettingsLocked();
724                    }
725                }
726                sendVerificationRequest(userId, verificationId, ivs);
727            }
728            mCurrentIntentFilterVerifications.clear();
729        }
730
731        private void sendVerificationRequest(int userId, int verificationId,
732                IntentFilterVerificationState ivs) {
733
734            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
735            verificationIntent.putExtra(
736                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
737                    verificationId);
738            verificationIntent.putExtra(
739                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
740                    getDefaultScheme());
741            verificationIntent.putExtra(
742                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
743                    ivs.getHostsString());
744            verificationIntent.putExtra(
745                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
746                    ivs.getPackageName());
747            verificationIntent.setComponent(mIntentFilterVerifierComponent);
748            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
749
750            UserHandle user = new UserHandle(userId);
751            mContext.sendBroadcastAsUser(verificationIntent, user);
752            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
753                    "Sending IntentFilter verification broadcast");
754        }
755
756        public void receiveVerificationResponse(int verificationId) {
757            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
758
759            final boolean verified = ivs.isVerified();
760
761            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
762            final int count = filters.size();
763            if (DEBUG_DOMAIN_VERIFICATION) {
764                Slog.i(TAG, "Received verification response " + verificationId
765                        + " for " + count + " filters, verified=" + verified);
766            }
767            for (int n=0; n<count; n++) {
768                PackageParser.ActivityIntentInfo filter = filters.get(n);
769                filter.setVerified(verified);
770
771                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
772                        + " verified with result:" + verified + " and hosts:"
773                        + ivs.getHostsString());
774            }
775
776            mIntentFilterVerificationStates.remove(verificationId);
777
778            final String packageName = ivs.getPackageName();
779            IntentFilterVerificationInfo ivi = null;
780
781            synchronized (mPackages) {
782                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
783            }
784            if (ivi == null) {
785                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
786                        + verificationId + " packageName:" + packageName);
787                return;
788            }
789            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
790                    "Updating IntentFilterVerificationInfo for package " + packageName
791                            +" verificationId:" + verificationId);
792
793            synchronized (mPackages) {
794                if (verified) {
795                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
796                } else {
797                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
798                }
799                scheduleWriteSettingsLocked();
800
801                final int userId = ivs.getUserId();
802                if (userId != UserHandle.USER_ALL) {
803                    final int userStatus =
804                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
805
806                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
807                    boolean needUpdate = false;
808
809                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
810                    // already been set by the User thru the Disambiguation dialog
811                    switch (userStatus) {
812                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
813                            if (verified) {
814                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
815                            } else {
816                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
817                            }
818                            needUpdate = true;
819                            break;
820
821                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
822                            if (verified) {
823                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
824                                needUpdate = true;
825                            }
826                            break;
827
828                        default:
829                            // Nothing to do
830                    }
831
832                    if (needUpdate) {
833                        mSettings.updateIntentFilterVerificationStatusLPw(
834                                packageName, updatedStatus, userId);
835                        scheduleWritePackageRestrictionsLocked(userId);
836                    }
837                }
838            }
839        }
840
841        @Override
842        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
843                    ActivityIntentInfo filter, String packageName) {
844            if (!hasValidDomains(filter)) {
845                return false;
846            }
847            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
848            if (ivs == null) {
849                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
850                        packageName);
851            }
852            if (DEBUG_DOMAIN_VERIFICATION) {
853                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
854            }
855            ivs.addFilter(filter);
856            return true;
857        }
858
859        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
860                int userId, int verificationId, String packageName) {
861            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
862                    verifierUid, userId, packageName);
863            ivs.setPendingState();
864            synchronized (mPackages) {
865                mIntentFilterVerificationStates.append(verificationId, ivs);
866                mCurrentIntentFilterVerifications.add(verificationId);
867            }
868            return ivs;
869        }
870    }
871
872    private static boolean hasValidDomains(ActivityIntentInfo filter) {
873        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
874                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
875                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
876    }
877
878    // Set of pending broadcasts for aggregating enable/disable of components.
879    static class PendingPackageBroadcasts {
880        // for each user id, a map of <package name -> components within that package>
881        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
882
883        public PendingPackageBroadcasts() {
884            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
885        }
886
887        public ArrayList<String> get(int userId, String packageName) {
888            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
889            return packages.get(packageName);
890        }
891
892        public void put(int userId, String packageName, ArrayList<String> components) {
893            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
894            packages.put(packageName, components);
895        }
896
897        public void remove(int userId, String packageName) {
898            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
899            if (packages != null) {
900                packages.remove(packageName);
901            }
902        }
903
904        public void remove(int userId) {
905            mUidMap.remove(userId);
906        }
907
908        public int userIdCount() {
909            return mUidMap.size();
910        }
911
912        public int userIdAt(int n) {
913            return mUidMap.keyAt(n);
914        }
915
916        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
917            return mUidMap.get(userId);
918        }
919
920        public int size() {
921            // total number of pending broadcast entries across all userIds
922            int num = 0;
923            for (int i = 0; i< mUidMap.size(); i++) {
924                num += mUidMap.valueAt(i).size();
925            }
926            return num;
927        }
928
929        public void clear() {
930            mUidMap.clear();
931        }
932
933        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
934            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
935            if (map == null) {
936                map = new ArrayMap<String, ArrayList<String>>();
937                mUidMap.put(userId, map);
938            }
939            return map;
940        }
941    }
942    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
943
944    // Service Connection to remote media container service to copy
945    // package uri's from external media onto secure containers
946    // or internal storage.
947    private IMediaContainerService mContainerService = null;
948
949    static final int SEND_PENDING_BROADCAST = 1;
950    static final int MCS_BOUND = 3;
951    static final int END_COPY = 4;
952    static final int INIT_COPY = 5;
953    static final int MCS_UNBIND = 6;
954    static final int START_CLEANING_PACKAGE = 7;
955    static final int FIND_INSTALL_LOC = 8;
956    static final int POST_INSTALL = 9;
957    static final int MCS_RECONNECT = 10;
958    static final int MCS_GIVE_UP = 11;
959    static final int UPDATED_MEDIA_STATUS = 12;
960    static final int WRITE_SETTINGS = 13;
961    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
962    static final int PACKAGE_VERIFIED = 15;
963    static final int CHECK_PENDING_VERIFICATION = 16;
964    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
965    static final int INTENT_FILTER_VERIFIED = 18;
966
967    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
968
969    // Delay time in millisecs
970    static final int BROADCAST_DELAY = 10 * 1000;
971
972    static UserManagerService sUserManager;
973
974    // Stores a list of users whose package restrictions file needs to be updated
975    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
976
977    final private DefaultContainerConnection mDefContainerConn =
978            new DefaultContainerConnection();
979    class DefaultContainerConnection implements ServiceConnection {
980        public void onServiceConnected(ComponentName name, IBinder service) {
981            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
982            IMediaContainerService imcs =
983                IMediaContainerService.Stub.asInterface(service);
984            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
985        }
986
987        public void onServiceDisconnected(ComponentName name) {
988            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
989        }
990    }
991
992    // Recordkeeping of restore-after-install operations that are currently in flight
993    // between the Package Manager and the Backup Manager
994    static class PostInstallData {
995        public InstallArgs args;
996        public PackageInstalledInfo res;
997
998        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
999            args = _a;
1000            res = _r;
1001        }
1002    }
1003
1004    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1005    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1006
1007    // XML tags for backup/restore of various bits of state
1008    private static final String TAG_PREFERRED_BACKUP = "pa";
1009    private static final String TAG_DEFAULT_APPS = "da";
1010    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1011
1012    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1013    private static final String TAG_ALL_GRANTS = "rt-grants";
1014    private static final String TAG_GRANT = "grant";
1015    private static final String ATTR_PACKAGE_NAME = "pkg";
1016
1017    private static final String TAG_PERMISSION = "perm";
1018    private static final String ATTR_PERMISSION_NAME = "name";
1019    private static final String ATTR_IS_GRANTED = "g";
1020    private static final String ATTR_USER_SET = "set";
1021    private static final String ATTR_USER_FIXED = "fixed";
1022    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1023
1024    // System/policy permission grants are not backed up
1025    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1026            FLAG_PERMISSION_POLICY_FIXED
1027            | FLAG_PERMISSION_SYSTEM_FIXED
1028            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1029
1030    // And we back up these user-adjusted states
1031    private static final int USER_RUNTIME_GRANT_MASK =
1032            FLAG_PERMISSION_USER_SET
1033            | FLAG_PERMISSION_USER_FIXED
1034            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1035
1036    final @Nullable String mRequiredVerifierPackage;
1037    final @Nullable String mRequiredInstallerPackage;
1038
1039    private final PackageUsage mPackageUsage = new PackageUsage();
1040
1041    private class PackageUsage {
1042        private static final int WRITE_INTERVAL
1043            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1044
1045        private final Object mFileLock = new Object();
1046        private final AtomicLong mLastWritten = new AtomicLong(0);
1047        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1048
1049        private boolean mIsHistoricalPackageUsageAvailable = true;
1050
1051        boolean isHistoricalPackageUsageAvailable() {
1052            return mIsHistoricalPackageUsageAvailable;
1053        }
1054
1055        void write(boolean force) {
1056            if (force) {
1057                writeInternal();
1058                return;
1059            }
1060            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1061                && !DEBUG_DEXOPT) {
1062                return;
1063            }
1064            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1065                new Thread("PackageUsage_DiskWriter") {
1066                    @Override
1067                    public void run() {
1068                        try {
1069                            writeInternal();
1070                        } finally {
1071                            mBackgroundWriteRunning.set(false);
1072                        }
1073                    }
1074                }.start();
1075            }
1076        }
1077
1078        private void writeInternal() {
1079            synchronized (mPackages) {
1080                synchronized (mFileLock) {
1081                    AtomicFile file = getFile();
1082                    FileOutputStream f = null;
1083                    try {
1084                        f = file.startWrite();
1085                        BufferedOutputStream out = new BufferedOutputStream(f);
1086                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1087                        StringBuilder sb = new StringBuilder();
1088                        for (PackageParser.Package pkg : mPackages.values()) {
1089                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1090                                continue;
1091                            }
1092                            sb.setLength(0);
1093                            sb.append(pkg.packageName);
1094                            sb.append(' ');
1095                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1096                            sb.append('\n');
1097                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1098                        }
1099                        out.flush();
1100                        file.finishWrite(f);
1101                    } catch (IOException e) {
1102                        if (f != null) {
1103                            file.failWrite(f);
1104                        }
1105                        Log.e(TAG, "Failed to write package usage times", e);
1106                    }
1107                }
1108            }
1109            mLastWritten.set(SystemClock.elapsedRealtime());
1110        }
1111
1112        void readLP() {
1113            synchronized (mFileLock) {
1114                AtomicFile file = getFile();
1115                BufferedInputStream in = null;
1116                try {
1117                    in = new BufferedInputStream(file.openRead());
1118                    StringBuffer sb = new StringBuffer();
1119                    while (true) {
1120                        String packageName = readToken(in, sb, ' ');
1121                        if (packageName == null) {
1122                            break;
1123                        }
1124                        String timeInMillisString = readToken(in, sb, '\n');
1125                        if (timeInMillisString == null) {
1126                            throw new IOException("Failed to find last usage time for package "
1127                                                  + packageName);
1128                        }
1129                        PackageParser.Package pkg = mPackages.get(packageName);
1130                        if (pkg == null) {
1131                            continue;
1132                        }
1133                        long timeInMillis;
1134                        try {
1135                            timeInMillis = Long.parseLong(timeInMillisString);
1136                        } catch (NumberFormatException e) {
1137                            throw new IOException("Failed to parse " + timeInMillisString
1138                                                  + " as a long.", e);
1139                        }
1140                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1141                    }
1142                } catch (FileNotFoundException expected) {
1143                    mIsHistoricalPackageUsageAvailable = false;
1144                } catch (IOException e) {
1145                    Log.w(TAG, "Failed to read package usage times", e);
1146                } finally {
1147                    IoUtils.closeQuietly(in);
1148                }
1149            }
1150            mLastWritten.set(SystemClock.elapsedRealtime());
1151        }
1152
1153        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1154                throws IOException {
1155            sb.setLength(0);
1156            while (true) {
1157                int ch = in.read();
1158                if (ch == -1) {
1159                    if (sb.length() == 0) {
1160                        return null;
1161                    }
1162                    throw new IOException("Unexpected EOF");
1163                }
1164                if (ch == endOfToken) {
1165                    return sb.toString();
1166                }
1167                sb.append((char)ch);
1168            }
1169        }
1170
1171        private AtomicFile getFile() {
1172            File dataDir = Environment.getDataDirectory();
1173            File systemDir = new File(dataDir, "system");
1174            File fname = new File(systemDir, "package-usage.list");
1175            return new AtomicFile(fname);
1176        }
1177    }
1178
1179    class PackageHandler extends Handler {
1180        private boolean mBound = false;
1181        final ArrayList<HandlerParams> mPendingInstalls =
1182            new ArrayList<HandlerParams>();
1183
1184        private boolean connectToService() {
1185            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1186                    " DefaultContainerService");
1187            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1188            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1189            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1190                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1191                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1192                mBound = true;
1193                return true;
1194            }
1195            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1196            return false;
1197        }
1198
1199        private void disconnectService() {
1200            mContainerService = null;
1201            mBound = false;
1202            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1203            mContext.unbindService(mDefContainerConn);
1204            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1205        }
1206
1207        PackageHandler(Looper looper) {
1208            super(looper);
1209        }
1210
1211        public void handleMessage(Message msg) {
1212            try {
1213                doHandleMessage(msg);
1214            } finally {
1215                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1216            }
1217        }
1218
1219        void doHandleMessage(Message msg) {
1220            switch (msg.what) {
1221                case INIT_COPY: {
1222                    HandlerParams params = (HandlerParams) msg.obj;
1223                    int idx = mPendingInstalls.size();
1224                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1225                    // If a bind was already initiated we dont really
1226                    // need to do anything. The pending install
1227                    // will be processed later on.
1228                    if (!mBound) {
1229                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1230                                System.identityHashCode(mHandler));
1231                        // If this is the only one pending we might
1232                        // have to bind to the service again.
1233                        if (!connectToService()) {
1234                            Slog.e(TAG, "Failed to bind to media container service");
1235                            params.serviceError();
1236                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1237                                    System.identityHashCode(mHandler));
1238                            if (params.traceMethod != null) {
1239                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1240                                        params.traceCookie);
1241                            }
1242                            return;
1243                        } else {
1244                            // Once we bind to the service, the first
1245                            // pending request will be processed.
1246                            mPendingInstalls.add(idx, params);
1247                        }
1248                    } else {
1249                        mPendingInstalls.add(idx, params);
1250                        // Already bound to the service. Just make
1251                        // sure we trigger off processing the first request.
1252                        if (idx == 0) {
1253                            mHandler.sendEmptyMessage(MCS_BOUND);
1254                        }
1255                    }
1256                    break;
1257                }
1258                case MCS_BOUND: {
1259                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1260                    if (msg.obj != null) {
1261                        mContainerService = (IMediaContainerService) msg.obj;
1262                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1263                                System.identityHashCode(mHandler));
1264                    }
1265                    if (mContainerService == null) {
1266                        if (!mBound) {
1267                            // Something seriously wrong since we are not bound and we are not
1268                            // waiting for connection. Bail out.
1269                            Slog.e(TAG, "Cannot bind to media container service");
1270                            for (HandlerParams params : mPendingInstalls) {
1271                                // Indicate service bind error
1272                                params.serviceError();
1273                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1274                                        System.identityHashCode(params));
1275                                if (params.traceMethod != null) {
1276                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1277                                            params.traceMethod, params.traceCookie);
1278                                }
1279                                return;
1280                            }
1281                            mPendingInstalls.clear();
1282                        } else {
1283                            Slog.w(TAG, "Waiting to connect to media container service");
1284                        }
1285                    } else if (mPendingInstalls.size() > 0) {
1286                        HandlerParams params = mPendingInstalls.get(0);
1287                        if (params != null) {
1288                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1289                                    System.identityHashCode(params));
1290                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1291                            if (params.startCopy()) {
1292                                // We are done...  look for more work or to
1293                                // go idle.
1294                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1295                                        "Checking for more work or unbind...");
1296                                // Delete pending install
1297                                if (mPendingInstalls.size() > 0) {
1298                                    mPendingInstalls.remove(0);
1299                                }
1300                                if (mPendingInstalls.size() == 0) {
1301                                    if (mBound) {
1302                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1303                                                "Posting delayed MCS_UNBIND");
1304                                        removeMessages(MCS_UNBIND);
1305                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1306                                        // Unbind after a little delay, to avoid
1307                                        // continual thrashing.
1308                                        sendMessageDelayed(ubmsg, 10000);
1309                                    }
1310                                } else {
1311                                    // There are more pending requests in queue.
1312                                    // Just post MCS_BOUND message to trigger processing
1313                                    // of next pending install.
1314                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1315                                            "Posting MCS_BOUND for next work");
1316                                    mHandler.sendEmptyMessage(MCS_BOUND);
1317                                }
1318                            }
1319                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1320                        }
1321                    } else {
1322                        // Should never happen ideally.
1323                        Slog.w(TAG, "Empty queue");
1324                    }
1325                    break;
1326                }
1327                case MCS_RECONNECT: {
1328                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1329                    if (mPendingInstalls.size() > 0) {
1330                        if (mBound) {
1331                            disconnectService();
1332                        }
1333                        if (!connectToService()) {
1334                            Slog.e(TAG, "Failed to bind to media container service");
1335                            for (HandlerParams params : mPendingInstalls) {
1336                                // Indicate service bind error
1337                                params.serviceError();
1338                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                                        System.identityHashCode(params));
1340                            }
1341                            mPendingInstalls.clear();
1342                        }
1343                    }
1344                    break;
1345                }
1346                case MCS_UNBIND: {
1347                    // If there is no actual work left, then time to unbind.
1348                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1349
1350                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1351                        if (mBound) {
1352                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1353
1354                            disconnectService();
1355                        }
1356                    } else if (mPendingInstalls.size() > 0) {
1357                        // There are more pending requests in queue.
1358                        // Just post MCS_BOUND message to trigger processing
1359                        // of next pending install.
1360                        mHandler.sendEmptyMessage(MCS_BOUND);
1361                    }
1362
1363                    break;
1364                }
1365                case MCS_GIVE_UP: {
1366                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1367                    HandlerParams params = mPendingInstalls.remove(0);
1368                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1369                            System.identityHashCode(params));
1370                    break;
1371                }
1372                case SEND_PENDING_BROADCAST: {
1373                    String packages[];
1374                    ArrayList<String> components[];
1375                    int size = 0;
1376                    int uids[];
1377                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1378                    synchronized (mPackages) {
1379                        if (mPendingBroadcasts == null) {
1380                            return;
1381                        }
1382                        size = mPendingBroadcasts.size();
1383                        if (size <= 0) {
1384                            // Nothing to be done. Just return
1385                            return;
1386                        }
1387                        packages = new String[size];
1388                        components = new ArrayList[size];
1389                        uids = new int[size];
1390                        int i = 0;  // filling out the above arrays
1391
1392                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1393                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1394                            Iterator<Map.Entry<String, ArrayList<String>>> it
1395                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1396                                            .entrySet().iterator();
1397                            while (it.hasNext() && i < size) {
1398                                Map.Entry<String, ArrayList<String>> ent = it.next();
1399                                packages[i] = ent.getKey();
1400                                components[i] = ent.getValue();
1401                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1402                                uids[i] = (ps != null)
1403                                        ? UserHandle.getUid(packageUserId, ps.appId)
1404                                        : -1;
1405                                i++;
1406                            }
1407                        }
1408                        size = i;
1409                        mPendingBroadcasts.clear();
1410                    }
1411                    // Send broadcasts
1412                    for (int i = 0; i < size; i++) {
1413                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1414                    }
1415                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                    break;
1417                }
1418                case START_CLEANING_PACKAGE: {
1419                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420                    final String packageName = (String)msg.obj;
1421                    final int userId = msg.arg1;
1422                    final boolean andCode = msg.arg2 != 0;
1423                    synchronized (mPackages) {
1424                        if (userId == UserHandle.USER_ALL) {
1425                            int[] users = sUserManager.getUserIds();
1426                            for (int user : users) {
1427                                mSettings.addPackageToCleanLPw(
1428                                        new PackageCleanItem(user, packageName, andCode));
1429                            }
1430                        } else {
1431                            mSettings.addPackageToCleanLPw(
1432                                    new PackageCleanItem(userId, packageName, andCode));
1433                        }
1434                    }
1435                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436                    startCleaningPackages();
1437                } break;
1438                case POST_INSTALL: {
1439                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1440
1441                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1442                    mRunningInstalls.delete(msg.arg1);
1443
1444                    if (data != null) {
1445                        InstallArgs args = data.args;
1446                        PackageInstalledInfo parentRes = data.res;
1447
1448                        final boolean grantPermissions = (args.installFlags
1449                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1450                        final boolean killApp = (args.installFlags
1451                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1452                        final String[] grantedPermissions = args.installGrantPermissions;
1453
1454                        // Handle the parent package
1455                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1456                                grantedPermissions, args.observer);
1457
1458                        // Handle the child packages
1459                        final int childCount = (parentRes.addedChildPackages != null)
1460                                ? parentRes.addedChildPackages.size() : 0;
1461                        for (int i = 0; i < childCount; i++) {
1462                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1463                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1464                                    grantedPermissions, args.observer);
1465                        }
1466
1467                        // Log tracing if needed
1468                        if (args.traceMethod != null) {
1469                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1470                                    args.traceCookie);
1471                        }
1472                    } else {
1473                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1474                    }
1475
1476                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1477                } break;
1478                case UPDATED_MEDIA_STATUS: {
1479                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1480                    boolean reportStatus = msg.arg1 == 1;
1481                    boolean doGc = msg.arg2 == 1;
1482                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1483                    if (doGc) {
1484                        // Force a gc to clear up stale containers.
1485                        Runtime.getRuntime().gc();
1486                    }
1487                    if (msg.obj != null) {
1488                        @SuppressWarnings("unchecked")
1489                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1490                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1491                        // Unload containers
1492                        unloadAllContainers(args);
1493                    }
1494                    if (reportStatus) {
1495                        try {
1496                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1497                            PackageHelper.getMountService().finishMediaUpdate();
1498                        } catch (RemoteException e) {
1499                            Log.e(TAG, "MountService not running?");
1500                        }
1501                    }
1502                } break;
1503                case WRITE_SETTINGS: {
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1505                    synchronized (mPackages) {
1506                        removeMessages(WRITE_SETTINGS);
1507                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1508                        mSettings.writeLPr();
1509                        mDirtyUsers.clear();
1510                    }
1511                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1512                } break;
1513                case WRITE_PACKAGE_RESTRICTIONS: {
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1515                    synchronized (mPackages) {
1516                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1517                        for (int userId : mDirtyUsers) {
1518                            mSettings.writePackageRestrictionsLPr(userId);
1519                        }
1520                        mDirtyUsers.clear();
1521                    }
1522                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1523                } break;
1524                case CHECK_PENDING_VERIFICATION: {
1525                    final int verificationId = msg.arg1;
1526                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1527
1528                    if ((state != null) && !state.timeoutExtended()) {
1529                        final InstallArgs args = state.getInstallArgs();
1530                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1531
1532                        Slog.i(TAG, "Verification timed out for " + originUri);
1533                        mPendingVerification.remove(verificationId);
1534
1535                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1536
1537                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1538                            Slog.i(TAG, "Continuing with installation of " + originUri);
1539                            state.setVerifierResponse(Binder.getCallingUid(),
1540                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1541                            broadcastPackageVerified(verificationId, originUri,
1542                                    PackageManager.VERIFICATION_ALLOW,
1543                                    state.getInstallArgs().getUser());
1544                            try {
1545                                ret = args.copyApk(mContainerService, true);
1546                            } catch (RemoteException e) {
1547                                Slog.e(TAG, "Could not contact the ContainerService");
1548                            }
1549                        } else {
1550                            broadcastPackageVerified(verificationId, originUri,
1551                                    PackageManager.VERIFICATION_REJECT,
1552                                    state.getInstallArgs().getUser());
1553                        }
1554
1555                        Trace.asyncTraceEnd(
1556                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1557
1558                        processPendingInstall(args, ret);
1559                        mHandler.sendEmptyMessage(MCS_UNBIND);
1560                    }
1561                    break;
1562                }
1563                case PACKAGE_VERIFIED: {
1564                    final int verificationId = msg.arg1;
1565
1566                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1567                    if (state == null) {
1568                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1569                        break;
1570                    }
1571
1572                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1573
1574                    state.setVerifierResponse(response.callerUid, response.code);
1575
1576                    if (state.isVerificationComplete()) {
1577                        mPendingVerification.remove(verificationId);
1578
1579                        final InstallArgs args = state.getInstallArgs();
1580                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1581
1582                        int ret;
1583                        if (state.isInstallAllowed()) {
1584                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1585                            broadcastPackageVerified(verificationId, originUri,
1586                                    response.code, state.getInstallArgs().getUser());
1587                            try {
1588                                ret = args.copyApk(mContainerService, true);
1589                            } catch (RemoteException e) {
1590                                Slog.e(TAG, "Could not contact the ContainerService");
1591                            }
1592                        } else {
1593                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1594                        }
1595
1596                        Trace.asyncTraceEnd(
1597                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1598
1599                        processPendingInstall(args, ret);
1600                        mHandler.sendEmptyMessage(MCS_UNBIND);
1601                    }
1602
1603                    break;
1604                }
1605                case START_INTENT_FILTER_VERIFICATIONS: {
1606                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1607                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1608                            params.replacing, params.pkg);
1609                    break;
1610                }
1611                case INTENT_FILTER_VERIFIED: {
1612                    final int verificationId = msg.arg1;
1613
1614                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1615                            verificationId);
1616                    if (state == null) {
1617                        Slog.w(TAG, "Invalid IntentFilter verification token "
1618                                + verificationId + " received");
1619                        break;
1620                    }
1621
1622                    final int userId = state.getUserId();
1623
1624                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                            "Processing IntentFilter verification with token:"
1626                            + verificationId + " and userId:" + userId);
1627
1628                    final IntentFilterVerificationResponse response =
1629                            (IntentFilterVerificationResponse) msg.obj;
1630
1631                    state.setVerifierResponse(response.callerUid, response.code);
1632
1633                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1634                            "IntentFilter verification with token:" + verificationId
1635                            + " and userId:" + userId
1636                            + " is settings verifier response with response code:"
1637                            + response.code);
1638
1639                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1640                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1641                                + response.getFailedDomainsString());
1642                    }
1643
1644                    if (state.isVerificationComplete()) {
1645                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1646                    } else {
1647                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1648                                "IntentFilter verification with token:" + verificationId
1649                                + " was not said to be complete");
1650                    }
1651
1652                    break;
1653                }
1654            }
1655        }
1656    }
1657
1658    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1659            boolean killApp, String[] grantedPermissions,
1660            IPackageInstallObserver2 installObserver) {
1661        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1662            // Send the removed broadcasts
1663            if (res.removedInfo != null) {
1664                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1665            }
1666
1667            // Now that we successfully installed the package, grant runtime
1668            // permissions if requested before broadcasting the install.
1669            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1670                    >= Build.VERSION_CODES.M) {
1671                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1672            }
1673
1674            final boolean update = res.removedInfo != null
1675                    && res.removedInfo.removedPackage != null;
1676
1677            // If this is the first time we have child packages for a disabled privileged
1678            // app that had no children, we grant requested runtime permissions to the new
1679            // children if the parent on the system image had them already granted.
1680            if (res.pkg.parentPackage != null) {
1681                synchronized (mPackages) {
1682                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1683                }
1684            }
1685
1686            synchronized (mPackages) {
1687                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1688            }
1689
1690            final String packageName = res.pkg.applicationInfo.packageName;
1691            Bundle extras = new Bundle(1);
1692            extras.putInt(Intent.EXTRA_UID, res.uid);
1693
1694            // Determine the set of users who are adding this package for
1695            // the first time vs. those who are seeing an update.
1696            int[] firstUsers = EMPTY_INT_ARRAY;
1697            int[] updateUsers = EMPTY_INT_ARRAY;
1698            if (res.origUsers == null || res.origUsers.length == 0) {
1699                firstUsers = res.newUsers;
1700            } else {
1701                for (int newUser : res.newUsers) {
1702                    boolean isNew = true;
1703                    for (int origUser : res.origUsers) {
1704                        if (origUser == newUser) {
1705                            isNew = false;
1706                            break;
1707                        }
1708                    }
1709                    if (isNew) {
1710                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1711                    } else {
1712                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1713                    }
1714                }
1715            }
1716
1717            // Send installed broadcasts if the install/update is not ephemeral
1718            if (!isEphemeral(res.pkg)) {
1719                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1720
1721                // Send added for users that see the package for the first time
1722                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1723                        extras, 0 /*flags*/, null /*targetPackage*/,
1724                        null /*finishedReceiver*/, firstUsers);
1725
1726                // Send added for users that don't see the package for the first time
1727                if (update) {
1728                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1729                }
1730                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1731                        extras, 0 /*flags*/, null /*targetPackage*/,
1732                        null /*finishedReceiver*/, updateUsers);
1733
1734                // Send replaced for users that don't see the package for the first time
1735                if (update) {
1736                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1737                            packageName, extras, 0 /*flags*/,
1738                            null /*targetPackage*/, null /*finishedReceiver*/,
1739                            updateUsers);
1740                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1741                            null /*package*/, null /*extras*/, 0 /*flags*/,
1742                            packageName /*targetPackage*/,
1743                            null /*finishedReceiver*/, updateUsers);
1744                }
1745
1746                // Send broadcast package appeared if forward locked/external for all users
1747                // treat asec-hosted packages like removable media on upgrade
1748                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1749                    if (DEBUG_INSTALL) {
1750                        Slog.i(TAG, "upgrading pkg " + res.pkg
1751                                + " is ASEC-hosted -> AVAILABLE");
1752                    }
1753                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1754                    ArrayList<String> pkgList = new ArrayList<>(1);
1755                    pkgList.add(packageName);
1756                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1757                }
1758            }
1759
1760            // Work that needs to happen on first install within each user
1761            if (firstUsers != null && firstUsers.length > 0) {
1762                synchronized (mPackages) {
1763                    for (int userId : firstUsers) {
1764                        // If this app is a browser and it's newly-installed for some
1765                        // users, clear any default-browser state in those users. The
1766                        // app's nature doesn't depend on the user, so we can just check
1767                        // its browser nature in any user and generalize.
1768                        if (packageIsBrowser(packageName, userId)) {
1769                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1770                        }
1771
1772                        // We may also need to apply pending (restored) runtime
1773                        // permission grants within these users.
1774                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1775                    }
1776                }
1777            }
1778
1779            // Log current value of "unknown sources" setting
1780            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1781                    getUnknownSourcesSettings());
1782
1783            // Force a gc to clear up things
1784            Runtime.getRuntime().gc();
1785
1786            // Remove the replaced package's older resources safely now
1787            // We delete after a gc for applications  on sdcard.
1788            if (res.removedInfo != null && res.removedInfo.args != null) {
1789                synchronized (mInstallLock) {
1790                    res.removedInfo.args.doPostDeleteLI(true);
1791                }
1792            }
1793        }
1794
1795        // If someone is watching installs - notify them
1796        if (installObserver != null) {
1797            try {
1798                Bundle extras = extrasForInstallResult(res);
1799                installObserver.onPackageInstalled(res.name, res.returnCode,
1800                        res.returnMsg, extras);
1801            } catch (RemoteException e) {
1802                Slog.i(TAG, "Observer no longer exists.");
1803            }
1804        }
1805    }
1806
1807    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1808            PackageParser.Package pkg) {
1809        if (pkg.parentPackage == null) {
1810            return;
1811        }
1812        if (pkg.requestedPermissions == null) {
1813            return;
1814        }
1815        final PackageSetting disabledSysParentPs = mSettings
1816                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1817        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1818                || !disabledSysParentPs.isPrivileged()
1819                || (disabledSysParentPs.childPackageNames != null
1820                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1821            return;
1822        }
1823        final int[] allUserIds = sUserManager.getUserIds();
1824        final int permCount = pkg.requestedPermissions.size();
1825        for (int i = 0; i < permCount; i++) {
1826            String permission = pkg.requestedPermissions.get(i);
1827            BasePermission bp = mSettings.mPermissions.get(permission);
1828            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1829                continue;
1830            }
1831            for (int userId : allUserIds) {
1832                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1833                        permission, userId)) {
1834                    grantRuntimePermission(pkg.packageName, permission, userId);
1835                }
1836            }
1837        }
1838    }
1839
1840    private StorageEventListener mStorageListener = new StorageEventListener() {
1841        @Override
1842        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1843            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1844                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1845                    final String volumeUuid = vol.getFsUuid();
1846
1847                    // Clean up any users or apps that were removed or recreated
1848                    // while this volume was missing
1849                    reconcileUsers(volumeUuid);
1850                    reconcileApps(volumeUuid);
1851
1852                    // Clean up any install sessions that expired or were
1853                    // cancelled while this volume was missing
1854                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1855
1856                    loadPrivatePackages(vol);
1857
1858                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1859                    unloadPrivatePackages(vol);
1860                }
1861            }
1862
1863            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1864                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1865                    updateExternalMediaStatus(true, false);
1866                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1867                    updateExternalMediaStatus(false, false);
1868                }
1869            }
1870        }
1871
1872        @Override
1873        public void onVolumeForgotten(String fsUuid) {
1874            if (TextUtils.isEmpty(fsUuid)) {
1875                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1876                return;
1877            }
1878
1879            // Remove any apps installed on the forgotten volume
1880            synchronized (mPackages) {
1881                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1882                for (PackageSetting ps : packages) {
1883                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1884                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1885                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1886                }
1887
1888                mSettings.onVolumeForgotten(fsUuid);
1889                mSettings.writeLPr();
1890            }
1891        }
1892    };
1893
1894    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1895            String[] grantedPermissions) {
1896        for (int userId : userIds) {
1897            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1898        }
1899
1900        // We could have touched GID membership, so flush out packages.list
1901        synchronized (mPackages) {
1902            mSettings.writePackageListLPr();
1903        }
1904    }
1905
1906    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1907            String[] grantedPermissions) {
1908        SettingBase sb = (SettingBase) pkg.mExtras;
1909        if (sb == null) {
1910            return;
1911        }
1912
1913        PermissionsState permissionsState = sb.getPermissionsState();
1914
1915        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1916                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1917
1918        synchronized (mPackages) {
1919            for (String permission : pkg.requestedPermissions) {
1920                BasePermission bp = mSettings.mPermissions.get(permission);
1921                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1922                        && (grantedPermissions == null
1923                               || ArrayUtils.contains(grantedPermissions, permission))) {
1924                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1925                    // Installer cannot change immutable permissions.
1926                    if ((flags & immutableFlags) == 0) {
1927                        grantRuntimePermission(pkg.packageName, permission, userId);
1928                    }
1929                }
1930            }
1931        }
1932    }
1933
1934    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1935        Bundle extras = null;
1936        switch (res.returnCode) {
1937            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1938                extras = new Bundle();
1939                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1940                        res.origPermission);
1941                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1942                        res.origPackage);
1943                break;
1944            }
1945            case PackageManager.INSTALL_SUCCEEDED: {
1946                extras = new Bundle();
1947                extras.putBoolean(Intent.EXTRA_REPLACING,
1948                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1949                break;
1950            }
1951        }
1952        return extras;
1953    }
1954
1955    void scheduleWriteSettingsLocked() {
1956        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1957            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1958        }
1959    }
1960
1961    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1962        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1963        scheduleWritePackageRestrictionsLocked(userId);
1964    }
1965
1966    void scheduleWritePackageRestrictionsLocked(int userId) {
1967        final int[] userIds = (userId == UserHandle.USER_ALL)
1968                ? sUserManager.getUserIds() : new int[]{userId};
1969        for (int nextUserId : userIds) {
1970            if (!sUserManager.exists(nextUserId)) return;
1971            mDirtyUsers.add(nextUserId);
1972            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1973                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1974            }
1975        }
1976    }
1977
1978    public static PackageManagerService main(Context context, Installer installer,
1979            boolean factoryTest, boolean onlyCore) {
1980        // Self-check for initial settings.
1981        PackageManagerServiceCompilerMapping.checkProperties();
1982
1983        PackageManagerService m = new PackageManagerService(context, installer,
1984                factoryTest, onlyCore);
1985        m.enableSystemUserPackages();
1986        ServiceManager.addService("package", m);
1987        return m;
1988    }
1989
1990    private void enableSystemUserPackages() {
1991        if (!UserManager.isSplitSystemUser()) {
1992            return;
1993        }
1994        // For system user, enable apps based on the following conditions:
1995        // - app is whitelisted or belong to one of these groups:
1996        //   -- system app which has no launcher icons
1997        //   -- system app which has INTERACT_ACROSS_USERS permission
1998        //   -- system IME app
1999        // - app is not in the blacklist
2000        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2001        Set<String> enableApps = new ArraySet<>();
2002        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2003                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2004                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2005        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2006        enableApps.addAll(wlApps);
2007        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2008                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2009        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2010        enableApps.removeAll(blApps);
2011        Log.i(TAG, "Applications installed for system user: " + enableApps);
2012        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2013                UserHandle.SYSTEM);
2014        final int allAppsSize = allAps.size();
2015        synchronized (mPackages) {
2016            for (int i = 0; i < allAppsSize; i++) {
2017                String pName = allAps.get(i);
2018                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2019                // Should not happen, but we shouldn't be failing if it does
2020                if (pkgSetting == null) {
2021                    continue;
2022                }
2023                boolean install = enableApps.contains(pName);
2024                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2025                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2026                            + " for system user");
2027                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2028                }
2029            }
2030        }
2031    }
2032
2033    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2034        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2035                Context.DISPLAY_SERVICE);
2036        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2037    }
2038
2039    public PackageManagerService(Context context, Installer installer,
2040            boolean factoryTest, boolean onlyCore) {
2041        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2042                SystemClock.uptimeMillis());
2043
2044        if (mSdkVersion <= 0) {
2045            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2046        }
2047
2048        mContext = context;
2049        mFactoryTest = factoryTest;
2050        mOnlyCore = onlyCore;
2051        mMetrics = new DisplayMetrics();
2052        mSettings = new Settings(mPackages);
2053        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2054                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2055        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2056                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2057        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2058                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2059        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2060                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2061        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2062                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2063        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2064                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2065
2066        String separateProcesses = SystemProperties.get("debug.separate_processes");
2067        if (separateProcesses != null && separateProcesses.length() > 0) {
2068            if ("*".equals(separateProcesses)) {
2069                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2070                mSeparateProcesses = null;
2071                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2072            } else {
2073                mDefParseFlags = 0;
2074                mSeparateProcesses = separateProcesses.split(",");
2075                Slog.w(TAG, "Running with debug.separate_processes: "
2076                        + separateProcesses);
2077            }
2078        } else {
2079            mDefParseFlags = 0;
2080            mSeparateProcesses = null;
2081        }
2082
2083        mInstaller = installer;
2084        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2085                "*dexopt*");
2086        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2087
2088        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2089                FgThread.get().getLooper());
2090
2091        getDefaultDisplayMetrics(context, mMetrics);
2092
2093        SystemConfig systemConfig = SystemConfig.getInstance();
2094        mGlobalGids = systemConfig.getGlobalGids();
2095        mSystemPermissions = systemConfig.getSystemPermissions();
2096        mAvailableFeatures = systemConfig.getAvailableFeatures();
2097
2098        synchronized (mInstallLock) {
2099        // writer
2100        synchronized (mPackages) {
2101            mHandlerThread = new ServiceThread(TAG,
2102                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2103            mHandlerThread.start();
2104            mHandler = new PackageHandler(mHandlerThread.getLooper());
2105            mProcessLoggingHandler = new ProcessLoggingHandler();
2106            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2107
2108            File dataDir = Environment.getDataDirectory();
2109            mAppInstallDir = new File(dataDir, "app");
2110            mAppLib32InstallDir = new File(dataDir, "app-lib");
2111            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2112            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2113            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2114
2115            sUserManager = new UserManagerService(context, this, mPackages);
2116
2117            // Propagate permission configuration in to package manager.
2118            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2119                    = systemConfig.getPermissions();
2120            for (int i=0; i<permConfig.size(); i++) {
2121                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2122                BasePermission bp = mSettings.mPermissions.get(perm.name);
2123                if (bp == null) {
2124                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2125                    mSettings.mPermissions.put(perm.name, bp);
2126                }
2127                if (perm.gids != null) {
2128                    bp.setGids(perm.gids, perm.perUser);
2129                }
2130            }
2131
2132            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2133            for (int i=0; i<libConfig.size(); i++) {
2134                mSharedLibraries.put(libConfig.keyAt(i),
2135                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2136            }
2137
2138            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2139
2140            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2141
2142            String customResolverActivity = Resources.getSystem().getString(
2143                    R.string.config_customResolverActivity);
2144            if (TextUtils.isEmpty(customResolverActivity)) {
2145                customResolverActivity = null;
2146            } else {
2147                mCustomResolverComponentName = ComponentName.unflattenFromString(
2148                        customResolverActivity);
2149            }
2150
2151            long startTime = SystemClock.uptimeMillis();
2152
2153            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2154                    startTime);
2155
2156            // Set flag to monitor and not change apk file paths when
2157            // scanning install directories.
2158            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2159
2160            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2161            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2162
2163            if (bootClassPath == null) {
2164                Slog.w(TAG, "No BOOTCLASSPATH found!");
2165            }
2166
2167            if (systemServerClassPath == null) {
2168                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2169            }
2170
2171            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2172            final String[] dexCodeInstructionSets =
2173                    getDexCodeInstructionSets(
2174                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2175
2176            /**
2177             * Ensure all external libraries have had dexopt run on them.
2178             */
2179            if (mSharedLibraries.size() > 0) {
2180                // NOTE: For now, we're compiling these system "shared libraries"
2181                // (and framework jars) into all available architectures. It's possible
2182                // to compile them only when we come across an app that uses them (there's
2183                // already logic for that in scanPackageLI) but that adds some complexity.
2184                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2185                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2186                        final String lib = libEntry.path;
2187                        if (lib == null) {
2188                            continue;
2189                        }
2190
2191                        try {
2192                            // Shared libraries do not have profiles so we perform a full
2193                            // AOT compilation (if needed).
2194                            int dexoptNeeded = DexFile.getDexOptNeeded(
2195                                    lib, dexCodeInstructionSet,
2196                                    getCompilerFilterForReason(REASON_SHARED_APK),
2197                                    false /* newProfile */);
2198                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2199                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2200                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2201                                        getCompilerFilterForReason(REASON_SHARED_APK),
2202                                        StorageManager.UUID_PRIVATE_INTERNAL);
2203                            }
2204                        } catch (FileNotFoundException e) {
2205                            Slog.w(TAG, "Library not found: " + lib);
2206                        } catch (IOException | InstallerException e) {
2207                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2208                                    + e.getMessage());
2209                        }
2210                    }
2211                }
2212            }
2213
2214            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2215
2216            final VersionInfo ver = mSettings.getInternalVersion();
2217            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2218
2219            // when upgrading from pre-M, promote system app permissions from install to runtime
2220            mPromoteSystemApps =
2221                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2222
2223            // save off the names of pre-existing system packages prior to scanning; we don't
2224            // want to automatically grant runtime permissions for new system apps
2225            if (mPromoteSystemApps) {
2226                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2227                while (pkgSettingIter.hasNext()) {
2228                    PackageSetting ps = pkgSettingIter.next();
2229                    if (isSystemApp(ps)) {
2230                        mExistingSystemPackages.add(ps.name);
2231                    }
2232                }
2233            }
2234
2235            // When upgrading from pre-N, we need to handle package extraction like first boot,
2236            // as there is no profiling data available.
2237            mIsPreNUpgrade = !mSettings.isNWorkDone();
2238            mSettings.setNWorkDone();
2239
2240            // Collect vendor overlay packages.
2241            // (Do this before scanning any apps.)
2242            // For security and version matching reason, only consider
2243            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2244            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2245            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2246                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2247
2248            // Find base frameworks (resource packages without code).
2249            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2250                    | PackageParser.PARSE_IS_SYSTEM_DIR
2251                    | PackageParser.PARSE_IS_PRIVILEGED,
2252                    scanFlags | SCAN_NO_DEX, 0);
2253
2254            // Collected privileged system packages.
2255            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2256            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2257                    | PackageParser.PARSE_IS_SYSTEM_DIR
2258                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2259
2260            // Collect ordinary system packages.
2261            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2262            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2263                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2264
2265            // Collect all vendor packages.
2266            File vendorAppDir = new File("/vendor/app");
2267            try {
2268                vendorAppDir = vendorAppDir.getCanonicalFile();
2269            } catch (IOException e) {
2270                // failed to look up canonical path, continue with original one
2271            }
2272            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2273                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2274
2275            // Collect all OEM packages.
2276            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2277            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2278                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2279
2280            // Prune any system packages that no longer exist.
2281            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2282            if (!mOnlyCore) {
2283                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2284                while (psit.hasNext()) {
2285                    PackageSetting ps = psit.next();
2286
2287                    /*
2288                     * If this is not a system app, it can't be a
2289                     * disable system app.
2290                     */
2291                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2292                        continue;
2293                    }
2294
2295                    /*
2296                     * If the package is scanned, it's not erased.
2297                     */
2298                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2299                    if (scannedPkg != null) {
2300                        /*
2301                         * If the system app is both scanned and in the
2302                         * disabled packages list, then it must have been
2303                         * added via OTA. Remove it from the currently
2304                         * scanned package so the previously user-installed
2305                         * application can be scanned.
2306                         */
2307                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2308                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2309                                    + ps.name + "; removing system app.  Last known codePath="
2310                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2311                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2312                                    + scannedPkg.mVersionCode);
2313                            removePackageLI(scannedPkg, true);
2314                            mExpectingBetter.put(ps.name, ps.codePath);
2315                        }
2316
2317                        continue;
2318                    }
2319
2320                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2321                        psit.remove();
2322                        logCriticalInfo(Log.WARN, "System package " + ps.name
2323                                + " no longer exists; wiping its data");
2324                        removeDataDirsLI(null, ps.name);
2325                    } else {
2326                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2327                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2328                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2329                        }
2330                    }
2331                }
2332            }
2333
2334            //look for any incomplete package installations
2335            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2336            //clean up list
2337            for(int i = 0; i < deletePkgsList.size(); i++) {
2338                //clean up here
2339                cleanupInstallFailedPackage(deletePkgsList.get(i));
2340            }
2341            //delete tmp files
2342            deleteTempPackageFiles();
2343
2344            // Remove any shared userIDs that have no associated packages
2345            mSettings.pruneSharedUsersLPw();
2346
2347            if (!mOnlyCore) {
2348                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2349                        SystemClock.uptimeMillis());
2350                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2351
2352                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2353                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2354
2355                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2356                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2357
2358                /**
2359                 * Remove disable package settings for any updated system
2360                 * apps that were removed via an OTA. If they're not a
2361                 * previously-updated app, remove them completely.
2362                 * Otherwise, just revoke their system-level permissions.
2363                 */
2364                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2365                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2366                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2367
2368                    String msg;
2369                    if (deletedPkg == null) {
2370                        msg = "Updated system package " + deletedAppName
2371                                + " no longer exists; wiping its data";
2372                        removeDataDirsLI(null, deletedAppName);
2373                    } else {
2374                        msg = "Updated system app + " + deletedAppName
2375                                + " no longer present; removing system privileges for "
2376                                + deletedAppName;
2377
2378                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2379
2380                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2381                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2382                    }
2383                    logCriticalInfo(Log.WARN, msg);
2384                }
2385
2386                /**
2387                 * Make sure all system apps that we expected to appear on
2388                 * the userdata partition actually showed up. If they never
2389                 * appeared, crawl back and revive the system version.
2390                 */
2391                for (int i = 0; i < mExpectingBetter.size(); i++) {
2392                    final String packageName = mExpectingBetter.keyAt(i);
2393                    if (!mPackages.containsKey(packageName)) {
2394                        final File scanFile = mExpectingBetter.valueAt(i);
2395
2396                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2397                                + " but never showed up; reverting to system");
2398
2399                        final int reparseFlags;
2400                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2401                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2402                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2403                                    | PackageParser.PARSE_IS_PRIVILEGED;
2404                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2405                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2406                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2407                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2408                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2409                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2410                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2411                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2412                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2413                        } else {
2414                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2415                            continue;
2416                        }
2417
2418                        mSettings.enableSystemPackageLPw(packageName);
2419
2420                        try {
2421                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2422                        } catch (PackageManagerException e) {
2423                            Slog.e(TAG, "Failed to parse original system package: "
2424                                    + e.getMessage());
2425                        }
2426                    }
2427                }
2428            }
2429            mExpectingBetter.clear();
2430
2431            // Now that we know all of the shared libraries, update all clients to have
2432            // the correct library paths.
2433            updateAllSharedLibrariesLPw();
2434
2435            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2436                // NOTE: We ignore potential failures here during a system scan (like
2437                // the rest of the commands above) because there's precious little we
2438                // can do about it. A settings error is reported, though.
2439                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2440                        false /* boot complete */);
2441            }
2442
2443            // Now that we know all the packages we are keeping,
2444            // read and update their last usage times.
2445            mPackageUsage.readLP();
2446
2447            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2448                    SystemClock.uptimeMillis());
2449            Slog.i(TAG, "Time to scan packages: "
2450                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2451                    + " seconds");
2452
2453            // If the platform SDK has changed since the last time we booted,
2454            // we need to re-grant app permission to catch any new ones that
2455            // appear.  This is really a hack, and means that apps can in some
2456            // cases get permissions that the user didn't initially explicitly
2457            // allow...  it would be nice to have some better way to handle
2458            // this situation.
2459            int updateFlags = UPDATE_PERMISSIONS_ALL;
2460            if (ver.sdkVersion != mSdkVersion) {
2461                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2462                        + mSdkVersion + "; regranting permissions for internal storage");
2463                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2464            }
2465            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2466            ver.sdkVersion = mSdkVersion;
2467
2468            // If this is the first boot or an update from pre-M, and it is a normal
2469            // boot, then we need to initialize the default preferred apps across
2470            // all defined users.
2471            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2472                for (UserInfo user : sUserManager.getUsers(true)) {
2473                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2474                    applyFactoryDefaultBrowserLPw(user.id);
2475                    primeDomainVerificationsLPw(user.id);
2476                }
2477            }
2478
2479            // Prepare storage for system user really early during boot,
2480            // since core system apps like SettingsProvider and SystemUI
2481            // can't wait for user to start
2482            final int storageFlags;
2483            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2484                storageFlags = StorageManager.FLAG_STORAGE_DE;
2485            } else {
2486                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2487            }
2488            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2489                    storageFlags);
2490
2491            // If this is first boot after an OTA, and a normal boot, then
2492            // we need to clear code cache directories.
2493            if (mIsUpgrade && !onlyCore) {
2494                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2495                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2496                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2497                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2498                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2499                    }
2500                }
2501                ver.fingerprint = Build.FINGERPRINT;
2502            }
2503
2504            checkDefaultBrowser();
2505
2506            // clear only after permissions and other defaults have been updated
2507            mExistingSystemPackages.clear();
2508            mPromoteSystemApps = false;
2509
2510            // All the changes are done during package scanning.
2511            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2512
2513            // can downgrade to reader
2514            mSettings.writeLPr();
2515
2516            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2517                    SystemClock.uptimeMillis());
2518
2519            if (!mOnlyCore) {
2520                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2521                mRequiredInstallerPackage = getRequiredInstallerLPr();
2522                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2523                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2524                        mIntentFilterVerifierComponent);
2525            } else {
2526                mRequiredVerifierPackage = null;
2527                mRequiredInstallerPackage = null;
2528                mIntentFilterVerifierComponent = null;
2529                mIntentFilterVerifier = null;
2530            }
2531
2532            mInstallerService = new PackageInstallerService(context, this);
2533
2534            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2535            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2536            // both the installer and resolver must be present to enable ephemeral
2537            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2538                if (DEBUG_EPHEMERAL) {
2539                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2540                            + " installer:" + ephemeralInstallerComponent);
2541                }
2542                mEphemeralResolverComponent = ephemeralResolverComponent;
2543                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2544                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2545                mEphemeralResolverConnection =
2546                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2547            } else {
2548                if (DEBUG_EPHEMERAL) {
2549                    final String missingComponent =
2550                            (ephemeralResolverComponent == null)
2551                            ? (ephemeralInstallerComponent == null)
2552                                    ? "resolver and installer"
2553                                    : "resolver"
2554                            : "installer";
2555                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2556                }
2557                mEphemeralResolverComponent = null;
2558                mEphemeralInstallerComponent = null;
2559                mEphemeralResolverConnection = null;
2560            }
2561
2562            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2563        } // synchronized (mPackages)
2564        } // synchronized (mInstallLock)
2565
2566        // Now after opening every single application zip, make sure they
2567        // are all flushed.  Not really needed, but keeps things nice and
2568        // tidy.
2569        Runtime.getRuntime().gc();
2570
2571        // The initial scanning above does many calls into installd while
2572        // holding the mPackages lock, but we're mostly interested in yelling
2573        // once we have a booted system.
2574        mInstaller.setWarnIfHeld(mPackages);
2575
2576        // Expose private service for system components to use.
2577        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2578    }
2579
2580    @Override
2581    public boolean isFirstBoot() {
2582        return !mRestoredSettings;
2583    }
2584
2585    @Override
2586    public boolean isOnlyCoreApps() {
2587        return mOnlyCore;
2588    }
2589
2590    @Override
2591    public boolean isUpgrade() {
2592        return mIsUpgrade;
2593    }
2594
2595    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2596        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2597
2598        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2599                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2600                UserHandle.USER_SYSTEM);
2601        if (matches.size() == 1) {
2602            return matches.get(0).getComponentInfo().packageName;
2603        } else {
2604            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2605            return null;
2606        }
2607    }
2608
2609    private @NonNull String getRequiredInstallerLPr() {
2610        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2611        intent.addCategory(Intent.CATEGORY_DEFAULT);
2612        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2613
2614        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2615                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2616                UserHandle.USER_SYSTEM);
2617        if (matches.size() == 1) {
2618            return matches.get(0).getComponentInfo().packageName;
2619        } else {
2620            throw new RuntimeException("There must be exactly one installer; found " + matches);
2621        }
2622    }
2623
2624    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2625        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2626
2627        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2628                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2629                UserHandle.USER_SYSTEM);
2630        ResolveInfo best = null;
2631        final int N = matches.size();
2632        for (int i = 0; i < N; i++) {
2633            final ResolveInfo cur = matches.get(i);
2634            final String packageName = cur.getComponentInfo().packageName;
2635            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2636                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2637                continue;
2638            }
2639
2640            if (best == null || cur.priority > best.priority) {
2641                best = cur;
2642            }
2643        }
2644
2645        if (best != null) {
2646            return best.getComponentInfo().getComponentName();
2647        } else {
2648            throw new RuntimeException("There must be at least one intent filter verifier");
2649        }
2650    }
2651
2652    private @Nullable ComponentName getEphemeralResolverLPr() {
2653        final String[] packageArray =
2654                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2655        if (packageArray.length == 0) {
2656            if (DEBUG_EPHEMERAL) {
2657                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2658            }
2659            return null;
2660        }
2661
2662        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2663        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2664                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2665                UserHandle.USER_SYSTEM);
2666
2667        final int N = resolvers.size();
2668        if (N == 0) {
2669            if (DEBUG_EPHEMERAL) {
2670                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2671            }
2672            return null;
2673        }
2674
2675        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2676        for (int i = 0; i < N; i++) {
2677            final ResolveInfo info = resolvers.get(i);
2678
2679            if (info.serviceInfo == null) {
2680                continue;
2681            }
2682
2683            final String packageName = info.serviceInfo.packageName;
2684            if (!possiblePackages.contains(packageName)) {
2685                if (DEBUG_EPHEMERAL) {
2686                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2687                            + " pkg: " + packageName + ", info:" + info);
2688                }
2689                continue;
2690            }
2691
2692            if (DEBUG_EPHEMERAL) {
2693                Slog.v(TAG, "Ephemeral resolver found;"
2694                        + " pkg: " + packageName + ", info:" + info);
2695            }
2696            return new ComponentName(packageName, info.serviceInfo.name);
2697        }
2698        if (DEBUG_EPHEMERAL) {
2699            Slog.v(TAG, "Ephemeral resolver NOT found");
2700        }
2701        return null;
2702    }
2703
2704    private @Nullable ComponentName getEphemeralInstallerLPr() {
2705        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2706        intent.addCategory(Intent.CATEGORY_DEFAULT);
2707        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2708
2709        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2710                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2711                UserHandle.USER_SYSTEM);
2712        if (matches.size() == 0) {
2713            return null;
2714        } else if (matches.size() == 1) {
2715            return matches.get(0).getComponentInfo().getComponentName();
2716        } else {
2717            throw new RuntimeException(
2718                    "There must be at most one ephemeral installer; found " + matches);
2719        }
2720    }
2721
2722    private void primeDomainVerificationsLPw(int userId) {
2723        if (DEBUG_DOMAIN_VERIFICATION) {
2724            Slog.d(TAG, "Priming domain verifications in user " + userId);
2725        }
2726
2727        SystemConfig systemConfig = SystemConfig.getInstance();
2728        ArraySet<String> packages = systemConfig.getLinkedApps();
2729        ArraySet<String> domains = new ArraySet<String>();
2730
2731        for (String packageName : packages) {
2732            PackageParser.Package pkg = mPackages.get(packageName);
2733            if (pkg != null) {
2734                if (!pkg.isSystemApp()) {
2735                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2736                    continue;
2737                }
2738
2739                domains.clear();
2740                for (PackageParser.Activity a : pkg.activities) {
2741                    for (ActivityIntentInfo filter : a.intents) {
2742                        if (hasValidDomains(filter)) {
2743                            domains.addAll(filter.getHostsList());
2744                        }
2745                    }
2746                }
2747
2748                if (domains.size() > 0) {
2749                    if (DEBUG_DOMAIN_VERIFICATION) {
2750                        Slog.v(TAG, "      + " + packageName);
2751                    }
2752                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2753                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2754                    // and then 'always' in the per-user state actually used for intent resolution.
2755                    final IntentFilterVerificationInfo ivi;
2756                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2757                            new ArrayList<String>(domains));
2758                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2759                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2760                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2761                } else {
2762                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2763                            + "' does not handle web links");
2764                }
2765            } else {
2766                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2767            }
2768        }
2769
2770        scheduleWritePackageRestrictionsLocked(userId);
2771        scheduleWriteSettingsLocked();
2772    }
2773
2774    private void applyFactoryDefaultBrowserLPw(int userId) {
2775        // The default browser app's package name is stored in a string resource,
2776        // with a product-specific overlay used for vendor customization.
2777        String browserPkg = mContext.getResources().getString(
2778                com.android.internal.R.string.default_browser);
2779        if (!TextUtils.isEmpty(browserPkg)) {
2780            // non-empty string => required to be a known package
2781            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2782            if (ps == null) {
2783                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2784                browserPkg = null;
2785            } else {
2786                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2787            }
2788        }
2789
2790        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2791        // default.  If there's more than one, just leave everything alone.
2792        if (browserPkg == null) {
2793            calculateDefaultBrowserLPw(userId);
2794        }
2795    }
2796
2797    private void calculateDefaultBrowserLPw(int userId) {
2798        List<String> allBrowsers = resolveAllBrowserApps(userId);
2799        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2800        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2801    }
2802
2803    private List<String> resolveAllBrowserApps(int userId) {
2804        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2805        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2806                PackageManager.MATCH_ALL, userId);
2807
2808        final int count = list.size();
2809        List<String> result = new ArrayList<String>(count);
2810        for (int i=0; i<count; i++) {
2811            ResolveInfo info = list.get(i);
2812            if (info.activityInfo == null
2813                    || !info.handleAllWebDataURI
2814                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2815                    || result.contains(info.activityInfo.packageName)) {
2816                continue;
2817            }
2818            result.add(info.activityInfo.packageName);
2819        }
2820
2821        return result;
2822    }
2823
2824    private boolean packageIsBrowser(String packageName, int userId) {
2825        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2826                PackageManager.MATCH_ALL, userId);
2827        final int N = list.size();
2828        for (int i = 0; i < N; i++) {
2829            ResolveInfo info = list.get(i);
2830            if (packageName.equals(info.activityInfo.packageName)) {
2831                return true;
2832            }
2833        }
2834        return false;
2835    }
2836
2837    private void checkDefaultBrowser() {
2838        final int myUserId = UserHandle.myUserId();
2839        final String packageName = getDefaultBrowserPackageName(myUserId);
2840        if (packageName != null) {
2841            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2842            if (info == null) {
2843                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2844                synchronized (mPackages) {
2845                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2846                }
2847            }
2848        }
2849    }
2850
2851    @Override
2852    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2853            throws RemoteException {
2854        try {
2855            return super.onTransact(code, data, reply, flags);
2856        } catch (RuntimeException e) {
2857            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2858                Slog.wtf(TAG, "Package Manager Crash", e);
2859            }
2860            throw e;
2861        }
2862    }
2863
2864    void cleanupInstallFailedPackage(PackageSetting ps) {
2865        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2866
2867        removeDataDirsLI(ps.volumeUuid, ps.name);
2868        if (ps.codePath != null) {
2869            removeCodePathLI(ps.codePath);
2870        }
2871        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2872            if (ps.resourcePath.isDirectory()) {
2873                FileUtils.deleteContents(ps.resourcePath);
2874            }
2875            ps.resourcePath.delete();
2876        }
2877        mSettings.removePackageLPw(ps.name);
2878    }
2879
2880    static int[] appendInts(int[] cur, int[] add) {
2881        if (add == null) return cur;
2882        if (cur == null) return add;
2883        final int N = add.length;
2884        for (int i=0; i<N; i++) {
2885            cur = appendInt(cur, add[i]);
2886        }
2887        return cur;
2888    }
2889
2890    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
2891        if (!sUserManager.exists(userId)) return null;
2892        if (ps == null) {
2893            return null;
2894        }
2895        final PackageParser.Package p = ps.pkg;
2896        if (p == null) {
2897            return null;
2898        }
2899
2900        final PermissionsState permissionsState = ps.getPermissionsState();
2901
2902        final int[] gids = permissionsState.computeGids(userId);
2903        final Set<String> permissions = permissionsState.getPermissions(userId);
2904        final PackageUserState state = ps.readUserState(userId);
2905
2906        return PackageParser.generatePackageInfo(p, gids, flags,
2907                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2908    }
2909
2910    @Override
2911    public void checkPackageStartable(String packageName, int userId) {
2912        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2913
2914        synchronized (mPackages) {
2915            final PackageSetting ps = mSettings.mPackages.get(packageName);
2916            if (ps == null) {
2917                throw new SecurityException("Package " + packageName + " was not found!");
2918            }
2919
2920            if (!ps.getInstalled(userId)) {
2921                throw new SecurityException(
2922                        "Package " + packageName + " was not installed for user " + userId + "!");
2923            }
2924
2925            if (mSafeMode && !ps.isSystem()) {
2926                throw new SecurityException("Package " + packageName + " not a system app!");
2927            }
2928
2929            if (ps.frozen) {
2930                throw new SecurityException("Package " + packageName + " is currently frozen!");
2931            }
2932
2933            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2934                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2935                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2936            }
2937        }
2938    }
2939
2940    @Override
2941    public boolean isPackageAvailable(String packageName, int userId) {
2942        if (!sUserManager.exists(userId)) return false;
2943        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2944                false /* requireFullPermission */, false /* checkShell */, "is package available");
2945        synchronized (mPackages) {
2946            PackageParser.Package p = mPackages.get(packageName);
2947            if (p != null) {
2948                final PackageSetting ps = (PackageSetting) p.mExtras;
2949                if (ps != null) {
2950                    final PackageUserState state = ps.readUserState(userId);
2951                    if (state != null) {
2952                        return PackageParser.isAvailable(state);
2953                    }
2954                }
2955            }
2956        }
2957        return false;
2958    }
2959
2960    @Override
2961    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2962        if (!sUserManager.exists(userId)) return null;
2963        flags = updateFlagsForPackage(flags, userId, packageName);
2964        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2965                false /* requireFullPermission */, false /* checkShell */, "get package info");
2966        // reader
2967        synchronized (mPackages) {
2968            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
2969            PackageParser.Package p = null;
2970            if (matchFactoryOnly) {
2971                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
2972                if (ps != null) {
2973                    return generatePackageInfo(ps, flags, userId);
2974                }
2975            }
2976            if (p == null) {
2977                p = mPackages.get(packageName);
2978                if (matchFactoryOnly && !isSystemApp(p)) {
2979                    return null;
2980                }
2981            }
2982            if (DEBUG_PACKAGE_INFO)
2983                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2984            if (p != null) {
2985                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
2986            }
2987            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2988                final PackageSetting ps = mSettings.mPackages.get(packageName);
2989                return generatePackageInfo(ps, flags, userId);
2990            }
2991        }
2992        return null;
2993    }
2994
2995    @Override
2996    public String[] currentToCanonicalPackageNames(String[] names) {
2997        String[] out = new String[names.length];
2998        // reader
2999        synchronized (mPackages) {
3000            for (int i=names.length-1; i>=0; i--) {
3001                PackageSetting ps = mSettings.mPackages.get(names[i]);
3002                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3003            }
3004        }
3005        return out;
3006    }
3007
3008    @Override
3009    public String[] canonicalToCurrentPackageNames(String[] names) {
3010        String[] out = new String[names.length];
3011        // reader
3012        synchronized (mPackages) {
3013            for (int i=names.length-1; i>=0; i--) {
3014                String cur = mSettings.mRenamedPackages.get(names[i]);
3015                out[i] = cur != null ? cur : names[i];
3016            }
3017        }
3018        return out;
3019    }
3020
3021    @Override
3022    public int getPackageUid(String packageName, int flags, int userId) {
3023        if (!sUserManager.exists(userId)) return -1;
3024        flags = updateFlagsForPackage(flags, userId, packageName);
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3026                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3027
3028        // reader
3029        synchronized (mPackages) {
3030            final PackageParser.Package p = mPackages.get(packageName);
3031            if (p != null && p.isMatch(flags)) {
3032                return UserHandle.getUid(userId, p.applicationInfo.uid);
3033            }
3034            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3035                final PackageSetting ps = mSettings.mPackages.get(packageName);
3036                if (ps != null && ps.isMatch(flags)) {
3037                    return UserHandle.getUid(userId, ps.appId);
3038                }
3039            }
3040        }
3041
3042        return -1;
3043    }
3044
3045    @Override
3046    public int[] getPackageGids(String packageName, int flags, int userId) {
3047        if (!sUserManager.exists(userId)) return null;
3048        flags = updateFlagsForPackage(flags, userId, packageName);
3049        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3050                false /* requireFullPermission */, false /* checkShell */,
3051                "getPackageGids");
3052
3053        // reader
3054        synchronized (mPackages) {
3055            final PackageParser.Package p = mPackages.get(packageName);
3056            if (p != null && p.isMatch(flags)) {
3057                PackageSetting ps = (PackageSetting) p.mExtras;
3058                return ps.getPermissionsState().computeGids(userId);
3059            }
3060            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3061                final PackageSetting ps = mSettings.mPackages.get(packageName);
3062                if (ps != null && ps.isMatch(flags)) {
3063                    return ps.getPermissionsState().computeGids(userId);
3064                }
3065            }
3066        }
3067
3068        return null;
3069    }
3070
3071    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3072        if (bp.perm != null) {
3073            return PackageParser.generatePermissionInfo(bp.perm, flags);
3074        }
3075        PermissionInfo pi = new PermissionInfo();
3076        pi.name = bp.name;
3077        pi.packageName = bp.sourcePackage;
3078        pi.nonLocalizedLabel = bp.name;
3079        pi.protectionLevel = bp.protectionLevel;
3080        return pi;
3081    }
3082
3083    @Override
3084    public PermissionInfo getPermissionInfo(String name, int flags) {
3085        // reader
3086        synchronized (mPackages) {
3087            final BasePermission p = mSettings.mPermissions.get(name);
3088            if (p != null) {
3089                return generatePermissionInfo(p, flags);
3090            }
3091            return null;
3092        }
3093    }
3094
3095    @Override
3096    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3097            int flags) {
3098        // reader
3099        synchronized (mPackages) {
3100            if (group != null && !mPermissionGroups.containsKey(group)) {
3101                // This is thrown as NameNotFoundException
3102                return null;
3103            }
3104
3105            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3106            for (BasePermission p : mSettings.mPermissions.values()) {
3107                if (group == null) {
3108                    if (p.perm == null || p.perm.info.group == null) {
3109                        out.add(generatePermissionInfo(p, flags));
3110                    }
3111                } else {
3112                    if (p.perm != null && group.equals(p.perm.info.group)) {
3113                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3114                    }
3115                }
3116            }
3117            return new ParceledListSlice<>(out);
3118        }
3119    }
3120
3121    @Override
3122    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3123        // reader
3124        synchronized (mPackages) {
3125            return PackageParser.generatePermissionGroupInfo(
3126                    mPermissionGroups.get(name), flags);
3127        }
3128    }
3129
3130    @Override
3131    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3132        // reader
3133        synchronized (mPackages) {
3134            final int N = mPermissionGroups.size();
3135            ArrayList<PermissionGroupInfo> out
3136                    = new ArrayList<PermissionGroupInfo>(N);
3137            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3138                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3139            }
3140            return new ParceledListSlice<>(out);
3141        }
3142    }
3143
3144    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3145            int userId) {
3146        if (!sUserManager.exists(userId)) return null;
3147        PackageSetting ps = mSettings.mPackages.get(packageName);
3148        if (ps != null) {
3149            if (ps.pkg == null) {
3150                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3151                if (pInfo != null) {
3152                    return pInfo.applicationInfo;
3153                }
3154                return null;
3155            }
3156            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3157                    ps.readUserState(userId), userId);
3158        }
3159        return null;
3160    }
3161
3162    @Override
3163    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3164        if (!sUserManager.exists(userId)) return null;
3165        flags = updateFlagsForApplication(flags, userId, packageName);
3166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3167                false /* requireFullPermission */, false /* checkShell */, "get application info");
3168        // writer
3169        synchronized (mPackages) {
3170            PackageParser.Package p = mPackages.get(packageName);
3171            if (DEBUG_PACKAGE_INFO) Log.v(
3172                    TAG, "getApplicationInfo " + packageName
3173                    + ": " + p);
3174            if (p != null) {
3175                PackageSetting ps = mSettings.mPackages.get(packageName);
3176                if (ps == null) return null;
3177                // Note: isEnabledLP() does not apply here - always return info
3178                return PackageParser.generateApplicationInfo(
3179                        p, flags, ps.readUserState(userId), userId);
3180            }
3181            if ("android".equals(packageName)||"system".equals(packageName)) {
3182                return mAndroidApplication;
3183            }
3184            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3185                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3186            }
3187        }
3188        return null;
3189    }
3190
3191    @Override
3192    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3193            final IPackageDataObserver observer) {
3194        mContext.enforceCallingOrSelfPermission(
3195                android.Manifest.permission.CLEAR_APP_CACHE, null);
3196        // Queue up an async operation since clearing cache may take a little while.
3197        mHandler.post(new Runnable() {
3198            public void run() {
3199                mHandler.removeCallbacks(this);
3200                boolean success = true;
3201                synchronized (mInstallLock) {
3202                    try {
3203                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3204                    } catch (InstallerException e) {
3205                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3206                        success = false;
3207                    }
3208                }
3209                if (observer != null) {
3210                    try {
3211                        observer.onRemoveCompleted(null, success);
3212                    } catch (RemoteException e) {
3213                        Slog.w(TAG, "RemoveException when invoking call back");
3214                    }
3215                }
3216            }
3217        });
3218    }
3219
3220    @Override
3221    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3222            final IntentSender pi) {
3223        mContext.enforceCallingOrSelfPermission(
3224                android.Manifest.permission.CLEAR_APP_CACHE, null);
3225        // Queue up an async operation since clearing cache may take a little while.
3226        mHandler.post(new Runnable() {
3227            public void run() {
3228                mHandler.removeCallbacks(this);
3229                boolean success = true;
3230                synchronized (mInstallLock) {
3231                    try {
3232                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3233                    } catch (InstallerException e) {
3234                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3235                        success = false;
3236                    }
3237                }
3238                if(pi != null) {
3239                    try {
3240                        // Callback via pending intent
3241                        int code = success ? 1 : 0;
3242                        pi.sendIntent(null, code, null,
3243                                null, null);
3244                    } catch (SendIntentException e1) {
3245                        Slog.i(TAG, "Failed to send pending intent");
3246                    }
3247                }
3248            }
3249        });
3250    }
3251
3252    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3253        synchronized (mInstallLock) {
3254            try {
3255                mInstaller.freeCache(volumeUuid, freeStorageSize);
3256            } catch (InstallerException e) {
3257                throw new IOException("Failed to free enough space", e);
3258            }
3259        }
3260    }
3261
3262    /**
3263     * Return if the user key is currently unlocked.
3264     */
3265    private boolean isUserKeyUnlocked(int userId) {
3266        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3267            final IMountService mount = IMountService.Stub
3268                    .asInterface(ServiceManager.getService("mount"));
3269            if (mount == null) {
3270                Slog.w(TAG, "Early during boot, assuming locked");
3271                return false;
3272            }
3273            final long token = Binder.clearCallingIdentity();
3274            try {
3275                return mount.isUserKeyUnlocked(userId);
3276            } catch (RemoteException e) {
3277                throw e.rethrowAsRuntimeException();
3278            } finally {
3279                Binder.restoreCallingIdentity(token);
3280            }
3281        } else {
3282            return true;
3283        }
3284    }
3285
3286    /**
3287     * Update given flags based on encryption status of current user.
3288     */
3289    private int updateFlags(int flags, int userId) {
3290        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3291                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3292            // Caller expressed an explicit opinion about what encryption
3293            // aware/unaware components they want to see, so fall through and
3294            // give them what they want
3295        } else {
3296            // Caller expressed no opinion, so match based on user state
3297            if (isUserKeyUnlocked(userId)) {
3298                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3299            } else {
3300                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3301            }
3302        }
3303        return flags;
3304    }
3305
3306    /**
3307     * Update given flags when being used to request {@link PackageInfo}.
3308     */
3309    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3310        boolean triaged = true;
3311        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3312                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3313            // Caller is asking for component details, so they'd better be
3314            // asking for specific encryption matching behavior, or be triaged
3315            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3316                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3317                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3318                triaged = false;
3319            }
3320        }
3321        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3322                | PackageManager.MATCH_SYSTEM_ONLY
3323                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3324            triaged = false;
3325        }
3326        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3327            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3328                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3329        }
3330        return updateFlags(flags, userId);
3331    }
3332
3333    /**
3334     * Update given flags when being used to request {@link ApplicationInfo}.
3335     */
3336    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3337        return updateFlagsForPackage(flags, userId, cookie);
3338    }
3339
3340    /**
3341     * Update given flags when being used to request {@link ComponentInfo}.
3342     */
3343    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3344        if (cookie instanceof Intent) {
3345            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3346                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3347            }
3348        }
3349
3350        boolean triaged = true;
3351        // Caller is asking for component details, so they'd better be
3352        // asking for specific encryption matching behavior, or be triaged
3353        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3354                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3355                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3356            triaged = false;
3357        }
3358        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3359            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3360                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3361        }
3362
3363        return updateFlags(flags, userId);
3364    }
3365
3366    /**
3367     * Update given flags when being used to request {@link ResolveInfo}.
3368     */
3369    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3370        // Safe mode means we shouldn't match any third-party components
3371        if (mSafeMode) {
3372            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3373        }
3374
3375        return updateFlagsForComponent(flags, userId, cookie);
3376    }
3377
3378    @Override
3379    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3380        if (!sUserManager.exists(userId)) return null;
3381        flags = updateFlagsForComponent(flags, userId, component);
3382        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3383                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3384        synchronized (mPackages) {
3385            PackageParser.Activity a = mActivities.mActivities.get(component);
3386
3387            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3388            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3389                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3390                if (ps == null) return null;
3391                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3392                        userId);
3393            }
3394            if (mResolveComponentName.equals(component)) {
3395                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3396                        new PackageUserState(), userId);
3397            }
3398        }
3399        return null;
3400    }
3401
3402    @Override
3403    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3404            String resolvedType) {
3405        synchronized (mPackages) {
3406            if (component.equals(mResolveComponentName)) {
3407                // The resolver supports EVERYTHING!
3408                return true;
3409            }
3410            PackageParser.Activity a = mActivities.mActivities.get(component);
3411            if (a == null) {
3412                return false;
3413            }
3414            for (int i=0; i<a.intents.size(); i++) {
3415                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3416                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3417                    return true;
3418                }
3419            }
3420            return false;
3421        }
3422    }
3423
3424    @Override
3425    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3426        if (!sUserManager.exists(userId)) return null;
3427        flags = updateFlagsForComponent(flags, userId, component);
3428        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3429                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3430        synchronized (mPackages) {
3431            PackageParser.Activity a = mReceivers.mActivities.get(component);
3432            if (DEBUG_PACKAGE_INFO) Log.v(
3433                TAG, "getReceiverInfo " + component + ": " + a);
3434            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3435                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3436                if (ps == null) return null;
3437                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3438                        userId);
3439            }
3440        }
3441        return null;
3442    }
3443
3444    @Override
3445    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3446        if (!sUserManager.exists(userId)) return null;
3447        flags = updateFlagsForComponent(flags, userId, component);
3448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3449                false /* requireFullPermission */, false /* checkShell */, "get service info");
3450        synchronized (mPackages) {
3451            PackageParser.Service s = mServices.mServices.get(component);
3452            if (DEBUG_PACKAGE_INFO) Log.v(
3453                TAG, "getServiceInfo " + component + ": " + s);
3454            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3455                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3456                if (ps == null) return null;
3457                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3458                        userId);
3459            }
3460        }
3461        return null;
3462    }
3463
3464    @Override
3465    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3466        if (!sUserManager.exists(userId)) return null;
3467        flags = updateFlagsForComponent(flags, userId, component);
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3469                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3470        synchronized (mPackages) {
3471            PackageParser.Provider p = mProviders.mProviders.get(component);
3472            if (DEBUG_PACKAGE_INFO) Log.v(
3473                TAG, "getProviderInfo " + component + ": " + p);
3474            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3475                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3476                if (ps == null) return null;
3477                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3478                        userId);
3479            }
3480        }
3481        return null;
3482    }
3483
3484    @Override
3485    public String[] getSystemSharedLibraryNames() {
3486        Set<String> libSet;
3487        synchronized (mPackages) {
3488            libSet = mSharedLibraries.keySet();
3489            int size = libSet.size();
3490            if (size > 0) {
3491                String[] libs = new String[size];
3492                libSet.toArray(libs);
3493                return libs;
3494            }
3495        }
3496        return null;
3497    }
3498
3499    @Override
3500    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3501        synchronized (mPackages) {
3502            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3503                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3504            if (libraryEntry != null) {
3505                return libraryEntry.apk;
3506            }
3507        }
3508        return null;
3509    }
3510
3511    @Override
3512    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3513        synchronized (mPackages) {
3514            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3515
3516            final FeatureInfo fi = new FeatureInfo();
3517            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3518                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3519            res.add(fi);
3520
3521            return new ParceledListSlice<>(res);
3522        }
3523    }
3524
3525    @Override
3526    public boolean hasSystemFeature(String name, int version) {
3527        synchronized (mPackages) {
3528            final FeatureInfo feat = mAvailableFeatures.get(name);
3529            if (feat == null) {
3530                return false;
3531            } else {
3532                return feat.version >= version;
3533            }
3534        }
3535    }
3536
3537    @Override
3538    public int checkPermission(String permName, String pkgName, int userId) {
3539        if (!sUserManager.exists(userId)) {
3540            return PackageManager.PERMISSION_DENIED;
3541        }
3542
3543        synchronized (mPackages) {
3544            final PackageParser.Package p = mPackages.get(pkgName);
3545            if (p != null && p.mExtras != null) {
3546                final PackageSetting ps = (PackageSetting) p.mExtras;
3547                final PermissionsState permissionsState = ps.getPermissionsState();
3548                if (permissionsState.hasPermission(permName, userId)) {
3549                    return PackageManager.PERMISSION_GRANTED;
3550                }
3551                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3552                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3553                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3554                    return PackageManager.PERMISSION_GRANTED;
3555                }
3556            }
3557        }
3558
3559        return PackageManager.PERMISSION_DENIED;
3560    }
3561
3562    @Override
3563    public int checkUidPermission(String permName, int uid) {
3564        final int userId = UserHandle.getUserId(uid);
3565
3566        if (!sUserManager.exists(userId)) {
3567            return PackageManager.PERMISSION_DENIED;
3568        }
3569
3570        synchronized (mPackages) {
3571            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3572            if (obj != null) {
3573                final SettingBase ps = (SettingBase) obj;
3574                final PermissionsState permissionsState = ps.getPermissionsState();
3575                if (permissionsState.hasPermission(permName, userId)) {
3576                    return PackageManager.PERMISSION_GRANTED;
3577                }
3578                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3579                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3580                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3581                    return PackageManager.PERMISSION_GRANTED;
3582                }
3583            } else {
3584                ArraySet<String> perms = mSystemPermissions.get(uid);
3585                if (perms != null) {
3586                    if (perms.contains(permName)) {
3587                        return PackageManager.PERMISSION_GRANTED;
3588                    }
3589                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3590                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3591                        return PackageManager.PERMISSION_GRANTED;
3592                    }
3593                }
3594            }
3595        }
3596
3597        return PackageManager.PERMISSION_DENIED;
3598    }
3599
3600    @Override
3601    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3602        if (UserHandle.getCallingUserId() != userId) {
3603            mContext.enforceCallingPermission(
3604                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3605                    "isPermissionRevokedByPolicy for user " + userId);
3606        }
3607
3608        if (checkPermission(permission, packageName, userId)
3609                == PackageManager.PERMISSION_GRANTED) {
3610            return false;
3611        }
3612
3613        final long identity = Binder.clearCallingIdentity();
3614        try {
3615            final int flags = getPermissionFlags(permission, packageName, userId);
3616            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3617        } finally {
3618            Binder.restoreCallingIdentity(identity);
3619        }
3620    }
3621
3622    @Override
3623    public String getPermissionControllerPackageName() {
3624        synchronized (mPackages) {
3625            return mRequiredInstallerPackage;
3626        }
3627    }
3628
3629    /**
3630     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3631     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3632     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3633     * @param message the message to log on security exception
3634     */
3635    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3636            boolean checkShell, String message) {
3637        if (userId < 0) {
3638            throw new IllegalArgumentException("Invalid userId " + userId);
3639        }
3640        if (checkShell) {
3641            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3642        }
3643        if (userId == UserHandle.getUserId(callingUid)) return;
3644        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3645            if (requireFullPermission) {
3646                mContext.enforceCallingOrSelfPermission(
3647                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3648            } else {
3649                try {
3650                    mContext.enforceCallingOrSelfPermission(
3651                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3652                } catch (SecurityException se) {
3653                    mContext.enforceCallingOrSelfPermission(
3654                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3655                }
3656            }
3657        }
3658    }
3659
3660    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3661        if (callingUid == Process.SHELL_UID) {
3662            if (userHandle >= 0
3663                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3664                throw new SecurityException("Shell does not have permission to access user "
3665                        + userHandle);
3666            } else if (userHandle < 0) {
3667                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3668                        + Debug.getCallers(3));
3669            }
3670        }
3671    }
3672
3673    private BasePermission findPermissionTreeLP(String permName) {
3674        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3675            if (permName.startsWith(bp.name) &&
3676                    permName.length() > bp.name.length() &&
3677                    permName.charAt(bp.name.length()) == '.') {
3678                return bp;
3679            }
3680        }
3681        return null;
3682    }
3683
3684    private BasePermission checkPermissionTreeLP(String permName) {
3685        if (permName != null) {
3686            BasePermission bp = findPermissionTreeLP(permName);
3687            if (bp != null) {
3688                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3689                    return bp;
3690                }
3691                throw new SecurityException("Calling uid "
3692                        + Binder.getCallingUid()
3693                        + " is not allowed to add to permission tree "
3694                        + bp.name + " owned by uid " + bp.uid);
3695            }
3696        }
3697        throw new SecurityException("No permission tree found for " + permName);
3698    }
3699
3700    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3701        if (s1 == null) {
3702            return s2 == null;
3703        }
3704        if (s2 == null) {
3705            return false;
3706        }
3707        if (s1.getClass() != s2.getClass()) {
3708            return false;
3709        }
3710        return s1.equals(s2);
3711    }
3712
3713    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3714        if (pi1.icon != pi2.icon) return false;
3715        if (pi1.logo != pi2.logo) return false;
3716        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3717        if (!compareStrings(pi1.name, pi2.name)) return false;
3718        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3719        // We'll take care of setting this one.
3720        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3721        // These are not currently stored in settings.
3722        //if (!compareStrings(pi1.group, pi2.group)) return false;
3723        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3724        //if (pi1.labelRes != pi2.labelRes) return false;
3725        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3726        return true;
3727    }
3728
3729    int permissionInfoFootprint(PermissionInfo info) {
3730        int size = info.name.length();
3731        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3732        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3733        return size;
3734    }
3735
3736    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3737        int size = 0;
3738        for (BasePermission perm : mSettings.mPermissions.values()) {
3739            if (perm.uid == tree.uid) {
3740                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3741            }
3742        }
3743        return size;
3744    }
3745
3746    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3747        // We calculate the max size of permissions defined by this uid and throw
3748        // if that plus the size of 'info' would exceed our stated maximum.
3749        if (tree.uid != Process.SYSTEM_UID) {
3750            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3751            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3752                throw new SecurityException("Permission tree size cap exceeded");
3753            }
3754        }
3755    }
3756
3757    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3758        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3759            throw new SecurityException("Label must be specified in permission");
3760        }
3761        BasePermission tree = checkPermissionTreeLP(info.name);
3762        BasePermission bp = mSettings.mPermissions.get(info.name);
3763        boolean added = bp == null;
3764        boolean changed = true;
3765        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3766        if (added) {
3767            enforcePermissionCapLocked(info, tree);
3768            bp = new BasePermission(info.name, tree.sourcePackage,
3769                    BasePermission.TYPE_DYNAMIC);
3770        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3771            throw new SecurityException(
3772                    "Not allowed to modify non-dynamic permission "
3773                    + info.name);
3774        } else {
3775            if (bp.protectionLevel == fixedLevel
3776                    && bp.perm.owner.equals(tree.perm.owner)
3777                    && bp.uid == tree.uid
3778                    && comparePermissionInfos(bp.perm.info, info)) {
3779                changed = false;
3780            }
3781        }
3782        bp.protectionLevel = fixedLevel;
3783        info = new PermissionInfo(info);
3784        info.protectionLevel = fixedLevel;
3785        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3786        bp.perm.info.packageName = tree.perm.info.packageName;
3787        bp.uid = tree.uid;
3788        if (added) {
3789            mSettings.mPermissions.put(info.name, bp);
3790        }
3791        if (changed) {
3792            if (!async) {
3793                mSettings.writeLPr();
3794            } else {
3795                scheduleWriteSettingsLocked();
3796            }
3797        }
3798        return added;
3799    }
3800
3801    @Override
3802    public boolean addPermission(PermissionInfo info) {
3803        synchronized (mPackages) {
3804            return addPermissionLocked(info, false);
3805        }
3806    }
3807
3808    @Override
3809    public boolean addPermissionAsync(PermissionInfo info) {
3810        synchronized (mPackages) {
3811            return addPermissionLocked(info, true);
3812        }
3813    }
3814
3815    @Override
3816    public void removePermission(String name) {
3817        synchronized (mPackages) {
3818            checkPermissionTreeLP(name);
3819            BasePermission bp = mSettings.mPermissions.get(name);
3820            if (bp != null) {
3821                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3822                    throw new SecurityException(
3823                            "Not allowed to modify non-dynamic permission "
3824                            + name);
3825                }
3826                mSettings.mPermissions.remove(name);
3827                mSettings.writeLPr();
3828            }
3829        }
3830    }
3831
3832    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3833            BasePermission bp) {
3834        int index = pkg.requestedPermissions.indexOf(bp.name);
3835        if (index == -1) {
3836            throw new SecurityException("Package " + pkg.packageName
3837                    + " has not requested permission " + bp.name);
3838        }
3839        if (!bp.isRuntime() && !bp.isDevelopment()) {
3840            throw new SecurityException("Permission " + bp.name
3841                    + " is not a changeable permission type");
3842        }
3843    }
3844
3845    @Override
3846    public void grantRuntimePermission(String packageName, String name, final int userId) {
3847        if (!sUserManager.exists(userId)) {
3848            Log.e(TAG, "No such user:" + userId);
3849            return;
3850        }
3851
3852        mContext.enforceCallingOrSelfPermission(
3853                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3854                "grantRuntimePermission");
3855
3856        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3857                true /* requireFullPermission */, true /* checkShell */,
3858                "grantRuntimePermission");
3859
3860        final int uid;
3861        final SettingBase sb;
3862
3863        synchronized (mPackages) {
3864            final PackageParser.Package pkg = mPackages.get(packageName);
3865            if (pkg == null) {
3866                throw new IllegalArgumentException("Unknown package: " + packageName);
3867            }
3868
3869            final BasePermission bp = mSettings.mPermissions.get(name);
3870            if (bp == null) {
3871                throw new IllegalArgumentException("Unknown permission: " + name);
3872            }
3873
3874            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3875
3876            // If a permission review is required for legacy apps we represent
3877            // their permissions as always granted runtime ones since we need
3878            // to keep the review required permission flag per user while an
3879            // install permission's state is shared across all users.
3880            if (Build.PERMISSIONS_REVIEW_REQUIRED
3881                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3882                    && bp.isRuntime()) {
3883                return;
3884            }
3885
3886            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3887            sb = (SettingBase) pkg.mExtras;
3888            if (sb == null) {
3889                throw new IllegalArgumentException("Unknown package: " + packageName);
3890            }
3891
3892            final PermissionsState permissionsState = sb.getPermissionsState();
3893
3894            final int flags = permissionsState.getPermissionFlags(name, userId);
3895            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3896                throw new SecurityException("Cannot grant system fixed permission "
3897                        + name + " for package " + packageName);
3898            }
3899
3900            if (bp.isDevelopment()) {
3901                // Development permissions must be handled specially, since they are not
3902                // normal runtime permissions.  For now they apply to all users.
3903                if (permissionsState.grantInstallPermission(bp) !=
3904                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3905                    scheduleWriteSettingsLocked();
3906                }
3907                return;
3908            }
3909
3910            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3911                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3912                return;
3913            }
3914
3915            final int result = permissionsState.grantRuntimePermission(bp, userId);
3916            switch (result) {
3917                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3918                    return;
3919                }
3920
3921                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3922                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3923                    mHandler.post(new Runnable() {
3924                        @Override
3925                        public void run() {
3926                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3927                        }
3928                    });
3929                }
3930                break;
3931            }
3932
3933            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3934
3935            // Not critical if that is lost - app has to request again.
3936            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3937        }
3938
3939        // Only need to do this if user is initialized. Otherwise it's a new user
3940        // and there are no processes running as the user yet and there's no need
3941        // to make an expensive call to remount processes for the changed permissions.
3942        if (READ_EXTERNAL_STORAGE.equals(name)
3943                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3944            final long token = Binder.clearCallingIdentity();
3945            try {
3946                if (sUserManager.isInitialized(userId)) {
3947                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3948                            MountServiceInternal.class);
3949                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3950                }
3951            } finally {
3952                Binder.restoreCallingIdentity(token);
3953            }
3954        }
3955    }
3956
3957    @Override
3958    public void revokeRuntimePermission(String packageName, String name, int userId) {
3959        if (!sUserManager.exists(userId)) {
3960            Log.e(TAG, "No such user:" + userId);
3961            return;
3962        }
3963
3964        mContext.enforceCallingOrSelfPermission(
3965                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3966                "revokeRuntimePermission");
3967
3968        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3969                true /* requireFullPermission */, true /* checkShell */,
3970                "revokeRuntimePermission");
3971
3972        final int appId;
3973
3974        synchronized (mPackages) {
3975            final PackageParser.Package pkg = mPackages.get(packageName);
3976            if (pkg == null) {
3977                throw new IllegalArgumentException("Unknown package: " + packageName);
3978            }
3979
3980            final BasePermission bp = mSettings.mPermissions.get(name);
3981            if (bp == null) {
3982                throw new IllegalArgumentException("Unknown permission: " + name);
3983            }
3984
3985            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3986
3987            // If a permission review is required for legacy apps we represent
3988            // their permissions as always granted runtime ones since we need
3989            // to keep the review required permission flag per user while an
3990            // install permission's state is shared across all users.
3991            if (Build.PERMISSIONS_REVIEW_REQUIRED
3992                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3993                    && bp.isRuntime()) {
3994                return;
3995            }
3996
3997            SettingBase sb = (SettingBase) pkg.mExtras;
3998            if (sb == null) {
3999                throw new IllegalArgumentException("Unknown package: " + packageName);
4000            }
4001
4002            final PermissionsState permissionsState = sb.getPermissionsState();
4003
4004            final int flags = permissionsState.getPermissionFlags(name, userId);
4005            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4006                throw new SecurityException("Cannot revoke system fixed permission "
4007                        + name + " for package " + packageName);
4008            }
4009
4010            if (bp.isDevelopment()) {
4011                // Development permissions must be handled specially, since they are not
4012                // normal runtime permissions.  For now they apply to all users.
4013                if (permissionsState.revokeInstallPermission(bp) !=
4014                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4015                    scheduleWriteSettingsLocked();
4016                }
4017                return;
4018            }
4019
4020            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4021                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4022                return;
4023            }
4024
4025            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4026
4027            // Critical, after this call app should never have the permission.
4028            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4029
4030            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4031        }
4032
4033        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4034    }
4035
4036    @Override
4037    public void resetRuntimePermissions() {
4038        mContext.enforceCallingOrSelfPermission(
4039                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4040                "revokeRuntimePermission");
4041
4042        int callingUid = Binder.getCallingUid();
4043        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4044            mContext.enforceCallingOrSelfPermission(
4045                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4046                    "resetRuntimePermissions");
4047        }
4048
4049        synchronized (mPackages) {
4050            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4051            for (int userId : UserManagerService.getInstance().getUserIds()) {
4052                final int packageCount = mPackages.size();
4053                for (int i = 0; i < packageCount; i++) {
4054                    PackageParser.Package pkg = mPackages.valueAt(i);
4055                    if (!(pkg.mExtras instanceof PackageSetting)) {
4056                        continue;
4057                    }
4058                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4059                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4060                }
4061            }
4062        }
4063    }
4064
4065    @Override
4066    public int getPermissionFlags(String name, String packageName, int userId) {
4067        if (!sUserManager.exists(userId)) {
4068            return 0;
4069        }
4070
4071        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4072
4073        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4074                true /* requireFullPermission */, false /* checkShell */,
4075                "getPermissionFlags");
4076
4077        synchronized (mPackages) {
4078            final PackageParser.Package pkg = mPackages.get(packageName);
4079            if (pkg == null) {
4080                throw new IllegalArgumentException("Unknown package: " + packageName);
4081            }
4082
4083            final BasePermission bp = mSettings.mPermissions.get(name);
4084            if (bp == null) {
4085                throw new IllegalArgumentException("Unknown permission: " + name);
4086            }
4087
4088            SettingBase sb = (SettingBase) pkg.mExtras;
4089            if (sb == null) {
4090                throw new IllegalArgumentException("Unknown package: " + packageName);
4091            }
4092
4093            PermissionsState permissionsState = sb.getPermissionsState();
4094            return permissionsState.getPermissionFlags(name, userId);
4095        }
4096    }
4097
4098    @Override
4099    public void updatePermissionFlags(String name, String packageName, int flagMask,
4100            int flagValues, int userId) {
4101        if (!sUserManager.exists(userId)) {
4102            return;
4103        }
4104
4105        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4106
4107        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4108                true /* requireFullPermission */, true /* checkShell */,
4109                "updatePermissionFlags");
4110
4111        // Only the system can change these flags and nothing else.
4112        if (getCallingUid() != Process.SYSTEM_UID) {
4113            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4114            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4115            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4116            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4117            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4118        }
4119
4120        synchronized (mPackages) {
4121            final PackageParser.Package pkg = mPackages.get(packageName);
4122            if (pkg == null) {
4123                throw new IllegalArgumentException("Unknown package: " + packageName);
4124            }
4125
4126            final BasePermission bp = mSettings.mPermissions.get(name);
4127            if (bp == null) {
4128                throw new IllegalArgumentException("Unknown permission: " + name);
4129            }
4130
4131            SettingBase sb = (SettingBase) pkg.mExtras;
4132            if (sb == null) {
4133                throw new IllegalArgumentException("Unknown package: " + packageName);
4134            }
4135
4136            PermissionsState permissionsState = sb.getPermissionsState();
4137
4138            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4139
4140            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4141                // Install and runtime permissions are stored in different places,
4142                // so figure out what permission changed and persist the change.
4143                if (permissionsState.getInstallPermissionState(name) != null) {
4144                    scheduleWriteSettingsLocked();
4145                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4146                        || hadState) {
4147                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4148                }
4149            }
4150        }
4151    }
4152
4153    /**
4154     * Update the permission flags for all packages and runtime permissions of a user in order
4155     * to allow device or profile owner to remove POLICY_FIXED.
4156     */
4157    @Override
4158    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4159        if (!sUserManager.exists(userId)) {
4160            return;
4161        }
4162
4163        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4164
4165        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4166                true /* requireFullPermission */, true /* checkShell */,
4167                "updatePermissionFlagsForAllApps");
4168
4169        // Only the system can change system fixed flags.
4170        if (getCallingUid() != Process.SYSTEM_UID) {
4171            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4172            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4173        }
4174
4175        synchronized (mPackages) {
4176            boolean changed = false;
4177            final int packageCount = mPackages.size();
4178            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4179                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4180                SettingBase sb = (SettingBase) pkg.mExtras;
4181                if (sb == null) {
4182                    continue;
4183                }
4184                PermissionsState permissionsState = sb.getPermissionsState();
4185                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4186                        userId, flagMask, flagValues);
4187            }
4188            if (changed) {
4189                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4190            }
4191        }
4192    }
4193
4194    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4195        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4196                != PackageManager.PERMISSION_GRANTED
4197            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4198                != PackageManager.PERMISSION_GRANTED) {
4199            throw new SecurityException(message + " requires "
4200                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4201                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4202        }
4203    }
4204
4205    @Override
4206    public boolean shouldShowRequestPermissionRationale(String permissionName,
4207            String packageName, int userId) {
4208        if (UserHandle.getCallingUserId() != userId) {
4209            mContext.enforceCallingPermission(
4210                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4211                    "canShowRequestPermissionRationale for user " + userId);
4212        }
4213
4214        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4215        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4216            return false;
4217        }
4218
4219        if (checkPermission(permissionName, packageName, userId)
4220                == PackageManager.PERMISSION_GRANTED) {
4221            return false;
4222        }
4223
4224        final int flags;
4225
4226        final long identity = Binder.clearCallingIdentity();
4227        try {
4228            flags = getPermissionFlags(permissionName,
4229                    packageName, userId);
4230        } finally {
4231            Binder.restoreCallingIdentity(identity);
4232        }
4233
4234        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4235                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4236                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4237
4238        if ((flags & fixedFlags) != 0) {
4239            return false;
4240        }
4241
4242        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4243    }
4244
4245    @Override
4246    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4247        mContext.enforceCallingOrSelfPermission(
4248                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4249                "addOnPermissionsChangeListener");
4250
4251        synchronized (mPackages) {
4252            mOnPermissionChangeListeners.addListenerLocked(listener);
4253        }
4254    }
4255
4256    @Override
4257    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4258        synchronized (mPackages) {
4259            mOnPermissionChangeListeners.removeListenerLocked(listener);
4260        }
4261    }
4262
4263    @Override
4264    public boolean isProtectedBroadcast(String actionName) {
4265        synchronized (mPackages) {
4266            if (mProtectedBroadcasts.contains(actionName)) {
4267                return true;
4268            } else if (actionName != null) {
4269                // TODO: remove these terrible hacks
4270                if (actionName.startsWith("android.net.netmon.lingerExpired")
4271                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4272                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4273                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4274                    return true;
4275                }
4276            }
4277        }
4278        return false;
4279    }
4280
4281    @Override
4282    public int checkSignatures(String pkg1, String pkg2) {
4283        synchronized (mPackages) {
4284            final PackageParser.Package p1 = mPackages.get(pkg1);
4285            final PackageParser.Package p2 = mPackages.get(pkg2);
4286            if (p1 == null || p1.mExtras == null
4287                    || p2 == null || p2.mExtras == null) {
4288                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4289            }
4290            return compareSignatures(p1.mSignatures, p2.mSignatures);
4291        }
4292    }
4293
4294    @Override
4295    public int checkUidSignatures(int uid1, int uid2) {
4296        // Map to base uids.
4297        uid1 = UserHandle.getAppId(uid1);
4298        uid2 = UserHandle.getAppId(uid2);
4299        // reader
4300        synchronized (mPackages) {
4301            Signature[] s1;
4302            Signature[] s2;
4303            Object obj = mSettings.getUserIdLPr(uid1);
4304            if (obj != null) {
4305                if (obj instanceof SharedUserSetting) {
4306                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4307                } else if (obj instanceof PackageSetting) {
4308                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4309                } else {
4310                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4311                }
4312            } else {
4313                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4314            }
4315            obj = mSettings.getUserIdLPr(uid2);
4316            if (obj != null) {
4317                if (obj instanceof SharedUserSetting) {
4318                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4319                } else if (obj instanceof PackageSetting) {
4320                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4321                } else {
4322                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4323                }
4324            } else {
4325                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4326            }
4327            return compareSignatures(s1, s2);
4328        }
4329    }
4330
4331    private void killUid(int appId, int userId, String reason) {
4332        final long identity = Binder.clearCallingIdentity();
4333        try {
4334            IActivityManager am = ActivityManagerNative.getDefault();
4335            if (am != null) {
4336                try {
4337                    am.killUid(appId, userId, reason);
4338                } catch (RemoteException e) {
4339                    /* ignore - same process */
4340                }
4341            }
4342        } finally {
4343            Binder.restoreCallingIdentity(identity);
4344        }
4345    }
4346
4347    /**
4348     * Compares two sets of signatures. Returns:
4349     * <br />
4350     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4351     * <br />
4352     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4353     * <br />
4354     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4355     * <br />
4356     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4357     * <br />
4358     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4359     */
4360    static int compareSignatures(Signature[] s1, Signature[] s2) {
4361        if (s1 == null) {
4362            return s2 == null
4363                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4364                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4365        }
4366
4367        if (s2 == null) {
4368            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4369        }
4370
4371        if (s1.length != s2.length) {
4372            return PackageManager.SIGNATURE_NO_MATCH;
4373        }
4374
4375        // Since both signature sets are of size 1, we can compare without HashSets.
4376        if (s1.length == 1) {
4377            return s1[0].equals(s2[0]) ?
4378                    PackageManager.SIGNATURE_MATCH :
4379                    PackageManager.SIGNATURE_NO_MATCH;
4380        }
4381
4382        ArraySet<Signature> set1 = new ArraySet<Signature>();
4383        for (Signature sig : s1) {
4384            set1.add(sig);
4385        }
4386        ArraySet<Signature> set2 = new ArraySet<Signature>();
4387        for (Signature sig : s2) {
4388            set2.add(sig);
4389        }
4390        // Make sure s2 contains all signatures in s1.
4391        if (set1.equals(set2)) {
4392            return PackageManager.SIGNATURE_MATCH;
4393        }
4394        return PackageManager.SIGNATURE_NO_MATCH;
4395    }
4396
4397    /**
4398     * If the database version for this type of package (internal storage or
4399     * external storage) is less than the version where package signatures
4400     * were updated, return true.
4401     */
4402    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4403        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4404        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4405    }
4406
4407    /**
4408     * Used for backward compatibility to make sure any packages with
4409     * certificate chains get upgraded to the new style. {@code existingSigs}
4410     * will be in the old format (since they were stored on disk from before the
4411     * system upgrade) and {@code scannedSigs} will be in the newer format.
4412     */
4413    private int compareSignaturesCompat(PackageSignatures existingSigs,
4414            PackageParser.Package scannedPkg) {
4415        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4416            return PackageManager.SIGNATURE_NO_MATCH;
4417        }
4418
4419        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4420        for (Signature sig : existingSigs.mSignatures) {
4421            existingSet.add(sig);
4422        }
4423        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4424        for (Signature sig : scannedPkg.mSignatures) {
4425            try {
4426                Signature[] chainSignatures = sig.getChainSignatures();
4427                for (Signature chainSig : chainSignatures) {
4428                    scannedCompatSet.add(chainSig);
4429                }
4430            } catch (CertificateEncodingException e) {
4431                scannedCompatSet.add(sig);
4432            }
4433        }
4434        /*
4435         * Make sure the expanded scanned set contains all signatures in the
4436         * existing one.
4437         */
4438        if (scannedCompatSet.equals(existingSet)) {
4439            // Migrate the old signatures to the new scheme.
4440            existingSigs.assignSignatures(scannedPkg.mSignatures);
4441            // The new KeySets will be re-added later in the scanning process.
4442            synchronized (mPackages) {
4443                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4444            }
4445            return PackageManager.SIGNATURE_MATCH;
4446        }
4447        return PackageManager.SIGNATURE_NO_MATCH;
4448    }
4449
4450    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4451        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4452        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4453    }
4454
4455    private int compareSignaturesRecover(PackageSignatures existingSigs,
4456            PackageParser.Package scannedPkg) {
4457        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4458            return PackageManager.SIGNATURE_NO_MATCH;
4459        }
4460
4461        String msg = null;
4462        try {
4463            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4464                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4465                        + scannedPkg.packageName);
4466                return PackageManager.SIGNATURE_MATCH;
4467            }
4468        } catch (CertificateException e) {
4469            msg = e.getMessage();
4470        }
4471
4472        logCriticalInfo(Log.INFO,
4473                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4474        return PackageManager.SIGNATURE_NO_MATCH;
4475    }
4476
4477    @Override
4478    public List<String> getAllPackages() {
4479        synchronized (mPackages) {
4480            return new ArrayList<String>(mPackages.keySet());
4481        }
4482    }
4483
4484    @Override
4485    public String[] getPackagesForUid(int uid) {
4486        uid = UserHandle.getAppId(uid);
4487        // reader
4488        synchronized (mPackages) {
4489            Object obj = mSettings.getUserIdLPr(uid);
4490            if (obj instanceof SharedUserSetting) {
4491                final SharedUserSetting sus = (SharedUserSetting) obj;
4492                final int N = sus.packages.size();
4493                final String[] res = new String[N];
4494                final Iterator<PackageSetting> it = sus.packages.iterator();
4495                int i = 0;
4496                while (it.hasNext()) {
4497                    res[i++] = it.next().name;
4498                }
4499                return res;
4500            } else if (obj instanceof PackageSetting) {
4501                final PackageSetting ps = (PackageSetting) obj;
4502                return new String[] { ps.name };
4503            }
4504        }
4505        return null;
4506    }
4507
4508    @Override
4509    public String getNameForUid(int uid) {
4510        // reader
4511        synchronized (mPackages) {
4512            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4513            if (obj instanceof SharedUserSetting) {
4514                final SharedUserSetting sus = (SharedUserSetting) obj;
4515                return sus.name + ":" + sus.userId;
4516            } else if (obj instanceof PackageSetting) {
4517                final PackageSetting ps = (PackageSetting) obj;
4518                return ps.name;
4519            }
4520        }
4521        return null;
4522    }
4523
4524    @Override
4525    public int getUidForSharedUser(String sharedUserName) {
4526        if(sharedUserName == null) {
4527            return -1;
4528        }
4529        // reader
4530        synchronized (mPackages) {
4531            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4532            if (suid == null) {
4533                return -1;
4534            }
4535            return suid.userId;
4536        }
4537    }
4538
4539    @Override
4540    public int getFlagsForUid(int uid) {
4541        synchronized (mPackages) {
4542            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4543            if (obj instanceof SharedUserSetting) {
4544                final SharedUserSetting sus = (SharedUserSetting) obj;
4545                return sus.pkgFlags;
4546            } else if (obj instanceof PackageSetting) {
4547                final PackageSetting ps = (PackageSetting) obj;
4548                return ps.pkgFlags;
4549            }
4550        }
4551        return 0;
4552    }
4553
4554    @Override
4555    public int getPrivateFlagsForUid(int uid) {
4556        synchronized (mPackages) {
4557            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4558            if (obj instanceof SharedUserSetting) {
4559                final SharedUserSetting sus = (SharedUserSetting) obj;
4560                return sus.pkgPrivateFlags;
4561            } else if (obj instanceof PackageSetting) {
4562                final PackageSetting ps = (PackageSetting) obj;
4563                return ps.pkgPrivateFlags;
4564            }
4565        }
4566        return 0;
4567    }
4568
4569    @Override
4570    public boolean isUidPrivileged(int uid) {
4571        uid = UserHandle.getAppId(uid);
4572        // reader
4573        synchronized (mPackages) {
4574            Object obj = mSettings.getUserIdLPr(uid);
4575            if (obj instanceof SharedUserSetting) {
4576                final SharedUserSetting sus = (SharedUserSetting) obj;
4577                final Iterator<PackageSetting> it = sus.packages.iterator();
4578                while (it.hasNext()) {
4579                    if (it.next().isPrivileged()) {
4580                        return true;
4581                    }
4582                }
4583            } else if (obj instanceof PackageSetting) {
4584                final PackageSetting ps = (PackageSetting) obj;
4585                return ps.isPrivileged();
4586            }
4587        }
4588        return false;
4589    }
4590
4591    @Override
4592    public String[] getAppOpPermissionPackages(String permissionName) {
4593        synchronized (mPackages) {
4594            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4595            if (pkgs == null) {
4596                return null;
4597            }
4598            return pkgs.toArray(new String[pkgs.size()]);
4599        }
4600    }
4601
4602    @Override
4603    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4604            int flags, int userId) {
4605        if (!sUserManager.exists(userId)) return null;
4606        flags = updateFlagsForResolve(flags, userId, intent);
4607        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4608                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4609        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4610                userId);
4611        final ResolveInfo bestChoice =
4612                chooseBestActivity(intent, resolvedType, flags, query, userId);
4613
4614        if (isEphemeralAllowed(intent, query, userId)) {
4615            final EphemeralResolveInfo ai =
4616                    getEphemeralResolveInfo(intent, resolvedType, userId);
4617            if (ai != null) {
4618                if (DEBUG_EPHEMERAL) {
4619                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4620                }
4621                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4622                bestChoice.ephemeralResolveInfo = ai;
4623            }
4624        }
4625        return bestChoice;
4626    }
4627
4628    @Override
4629    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4630            IntentFilter filter, int match, ComponentName activity) {
4631        final int userId = UserHandle.getCallingUserId();
4632        if (DEBUG_PREFERRED) {
4633            Log.v(TAG, "setLastChosenActivity intent=" + intent
4634                + " resolvedType=" + resolvedType
4635                + " flags=" + flags
4636                + " filter=" + filter
4637                + " match=" + match
4638                + " activity=" + activity);
4639            filter.dump(new PrintStreamPrinter(System.out), "    ");
4640        }
4641        intent.setComponent(null);
4642        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4643                userId);
4644        // Find any earlier preferred or last chosen entries and nuke them
4645        findPreferredActivity(intent, resolvedType,
4646                flags, query, 0, false, true, false, userId);
4647        // Add the new activity as the last chosen for this filter
4648        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4649                "Setting last chosen");
4650    }
4651
4652    @Override
4653    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4654        final int userId = UserHandle.getCallingUserId();
4655        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4656        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4657                userId);
4658        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4659                false, false, false, userId);
4660    }
4661
4662
4663    private boolean isEphemeralAllowed(
4664            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4665        // Short circuit and return early if possible.
4666        if (DISABLE_EPHEMERAL_APPS) {
4667            return false;
4668        }
4669        final int callingUser = UserHandle.getCallingUserId();
4670        if (callingUser != UserHandle.USER_SYSTEM) {
4671            return false;
4672        }
4673        if (mEphemeralResolverConnection == null) {
4674            return false;
4675        }
4676        if (intent.getComponent() != null) {
4677            return false;
4678        }
4679        if (intent.getPackage() != null) {
4680            return false;
4681        }
4682        final boolean isWebUri = hasWebURI(intent);
4683        if (!isWebUri) {
4684            return false;
4685        }
4686        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4687        synchronized (mPackages) {
4688            final int count = resolvedActivites.size();
4689            for (int n = 0; n < count; n++) {
4690                ResolveInfo info = resolvedActivites.get(n);
4691                String packageName = info.activityInfo.packageName;
4692                PackageSetting ps = mSettings.mPackages.get(packageName);
4693                if (ps != null) {
4694                    // Try to get the status from User settings first
4695                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4696                    int status = (int) (packedStatus >> 32);
4697                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4698                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4699                        if (DEBUG_EPHEMERAL) {
4700                            Slog.v(TAG, "DENY ephemeral apps;"
4701                                + " pkg: " + packageName + ", status: " + status);
4702                        }
4703                        return false;
4704                    }
4705                }
4706            }
4707        }
4708        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4709        return true;
4710    }
4711
4712    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4713            int userId) {
4714        MessageDigest digest = null;
4715        try {
4716            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4717        } catch (NoSuchAlgorithmException e) {
4718            // If we can't create a digest, ignore ephemeral apps.
4719            return null;
4720        }
4721
4722        final byte[] hostBytes = intent.getData().getHost().getBytes();
4723        final byte[] digestBytes = digest.digest(hostBytes);
4724        int shaPrefix =
4725                digestBytes[0] << 24
4726                | digestBytes[1] << 16
4727                | digestBytes[2] << 8
4728                | digestBytes[3] << 0;
4729        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4730                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4731        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4732            // No hash prefix match; there are no ephemeral apps for this domain.
4733            return null;
4734        }
4735        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4736            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4737            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4738                continue;
4739            }
4740            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4741            // No filters; this should never happen.
4742            if (filters.isEmpty()) {
4743                continue;
4744            }
4745            // We have a domain match; resolve the filters to see if anything matches.
4746            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4747            for (int j = filters.size() - 1; j >= 0; --j) {
4748                final EphemeralResolveIntentInfo intentInfo =
4749                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4750                ephemeralResolver.addFilter(intentInfo);
4751            }
4752            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4753                    intent, resolvedType, false /*defaultOnly*/, userId);
4754            if (!matchedResolveInfoList.isEmpty()) {
4755                return matchedResolveInfoList.get(0);
4756            }
4757        }
4758        // Hash or filter mis-match; no ephemeral apps for this domain.
4759        return null;
4760    }
4761
4762    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4763            int flags, List<ResolveInfo> query, int userId) {
4764        if (query != null) {
4765            final int N = query.size();
4766            if (N == 1) {
4767                return query.get(0);
4768            } else if (N > 1) {
4769                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4770                // If there is more than one activity with the same priority,
4771                // then let the user decide between them.
4772                ResolveInfo r0 = query.get(0);
4773                ResolveInfo r1 = query.get(1);
4774                if (DEBUG_INTENT_MATCHING || debug) {
4775                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4776                            + r1.activityInfo.name + "=" + r1.priority);
4777                }
4778                // If the first activity has a higher priority, or a different
4779                // default, then it is always desirable to pick it.
4780                if (r0.priority != r1.priority
4781                        || r0.preferredOrder != r1.preferredOrder
4782                        || r0.isDefault != r1.isDefault) {
4783                    return query.get(0);
4784                }
4785                // If we have saved a preference for a preferred activity for
4786                // this Intent, use that.
4787                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4788                        flags, query, r0.priority, true, false, debug, userId);
4789                if (ri != null) {
4790                    return ri;
4791                }
4792                ri = new ResolveInfo(mResolveInfo);
4793                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4794                ri.activityInfo.applicationInfo = new ApplicationInfo(
4795                        ri.activityInfo.applicationInfo);
4796                if (userId != 0) {
4797                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4798                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4799                }
4800                // Make sure that the resolver is displayable in car mode
4801                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4802                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4803                return ri;
4804            }
4805        }
4806        return null;
4807    }
4808
4809    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4810            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4811        final int N = query.size();
4812        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4813                .get(userId);
4814        // Get the list of persistent preferred activities that handle the intent
4815        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4816        List<PersistentPreferredActivity> pprefs = ppir != null
4817                ? ppir.queryIntent(intent, resolvedType,
4818                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4819                : null;
4820        if (pprefs != null && pprefs.size() > 0) {
4821            final int M = pprefs.size();
4822            for (int i=0; i<M; i++) {
4823                final PersistentPreferredActivity ppa = pprefs.get(i);
4824                if (DEBUG_PREFERRED || debug) {
4825                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4826                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4827                            + "\n  component=" + ppa.mComponent);
4828                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4829                }
4830                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4831                        flags | MATCH_DISABLED_COMPONENTS, userId);
4832                if (DEBUG_PREFERRED || debug) {
4833                    Slog.v(TAG, "Found persistent preferred activity:");
4834                    if (ai != null) {
4835                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4836                    } else {
4837                        Slog.v(TAG, "  null");
4838                    }
4839                }
4840                if (ai == null) {
4841                    // This previously registered persistent preferred activity
4842                    // component is no longer known. Ignore it and do NOT remove it.
4843                    continue;
4844                }
4845                for (int j=0; j<N; j++) {
4846                    final ResolveInfo ri = query.get(j);
4847                    if (!ri.activityInfo.applicationInfo.packageName
4848                            .equals(ai.applicationInfo.packageName)) {
4849                        continue;
4850                    }
4851                    if (!ri.activityInfo.name.equals(ai.name)) {
4852                        continue;
4853                    }
4854                    //  Found a persistent preference that can handle the intent.
4855                    if (DEBUG_PREFERRED || debug) {
4856                        Slog.v(TAG, "Returning persistent preferred activity: " +
4857                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4858                    }
4859                    return ri;
4860                }
4861            }
4862        }
4863        return null;
4864    }
4865
4866    // TODO: handle preferred activities missing while user has amnesia
4867    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4868            List<ResolveInfo> query, int priority, boolean always,
4869            boolean removeMatches, boolean debug, int userId) {
4870        if (!sUserManager.exists(userId)) return null;
4871        flags = updateFlagsForResolve(flags, userId, intent);
4872        // writer
4873        synchronized (mPackages) {
4874            if (intent.getSelector() != null) {
4875                intent = intent.getSelector();
4876            }
4877            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4878
4879            // Try to find a matching persistent preferred activity.
4880            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4881                    debug, userId);
4882
4883            // If a persistent preferred activity matched, use it.
4884            if (pri != null) {
4885                return pri;
4886            }
4887
4888            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4889            // Get the list of preferred activities that handle the intent
4890            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4891            List<PreferredActivity> prefs = pir != null
4892                    ? pir.queryIntent(intent, resolvedType,
4893                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4894                    : null;
4895            if (prefs != null && prefs.size() > 0) {
4896                boolean changed = false;
4897                try {
4898                    // First figure out how good the original match set is.
4899                    // We will only allow preferred activities that came
4900                    // from the same match quality.
4901                    int match = 0;
4902
4903                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4904
4905                    final int N = query.size();
4906                    for (int j=0; j<N; j++) {
4907                        final ResolveInfo ri = query.get(j);
4908                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4909                                + ": 0x" + Integer.toHexString(match));
4910                        if (ri.match > match) {
4911                            match = ri.match;
4912                        }
4913                    }
4914
4915                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4916                            + Integer.toHexString(match));
4917
4918                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4919                    final int M = prefs.size();
4920                    for (int i=0; i<M; i++) {
4921                        final PreferredActivity pa = prefs.get(i);
4922                        if (DEBUG_PREFERRED || debug) {
4923                            Slog.v(TAG, "Checking PreferredActivity ds="
4924                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4925                                    + "\n  component=" + pa.mPref.mComponent);
4926                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4927                        }
4928                        if (pa.mPref.mMatch != match) {
4929                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4930                                    + Integer.toHexString(pa.mPref.mMatch));
4931                            continue;
4932                        }
4933                        // If it's not an "always" type preferred activity and that's what we're
4934                        // looking for, skip it.
4935                        if (always && !pa.mPref.mAlways) {
4936                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4937                            continue;
4938                        }
4939                        final ActivityInfo ai = getActivityInfo(
4940                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
4941                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
4942                                userId);
4943                        if (DEBUG_PREFERRED || debug) {
4944                            Slog.v(TAG, "Found preferred activity:");
4945                            if (ai != null) {
4946                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4947                            } else {
4948                                Slog.v(TAG, "  null");
4949                            }
4950                        }
4951                        if (ai == null) {
4952                            // This previously registered preferred activity
4953                            // component is no longer known.  Most likely an update
4954                            // to the app was installed and in the new version this
4955                            // component no longer exists.  Clean it up by removing
4956                            // it from the preferred activities list, and skip it.
4957                            Slog.w(TAG, "Removing dangling preferred activity: "
4958                                    + pa.mPref.mComponent);
4959                            pir.removeFilter(pa);
4960                            changed = true;
4961                            continue;
4962                        }
4963                        for (int j=0; j<N; j++) {
4964                            final ResolveInfo ri = query.get(j);
4965                            if (!ri.activityInfo.applicationInfo.packageName
4966                                    .equals(ai.applicationInfo.packageName)) {
4967                                continue;
4968                            }
4969                            if (!ri.activityInfo.name.equals(ai.name)) {
4970                                continue;
4971                            }
4972
4973                            if (removeMatches) {
4974                                pir.removeFilter(pa);
4975                                changed = true;
4976                                if (DEBUG_PREFERRED) {
4977                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4978                                }
4979                                break;
4980                            }
4981
4982                            // Okay we found a previously set preferred or last chosen app.
4983                            // If the result set is different from when this
4984                            // was created, we need to clear it and re-ask the
4985                            // user their preference, if we're looking for an "always" type entry.
4986                            if (always && !pa.mPref.sameSet(query)) {
4987                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4988                                        + intent + " type " + resolvedType);
4989                                if (DEBUG_PREFERRED) {
4990                                    Slog.v(TAG, "Removing preferred activity since set changed "
4991                                            + pa.mPref.mComponent);
4992                                }
4993                                pir.removeFilter(pa);
4994                                // Re-add the filter as a "last chosen" entry (!always)
4995                                PreferredActivity lastChosen = new PreferredActivity(
4996                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4997                                pir.addFilter(lastChosen);
4998                                changed = true;
4999                                return null;
5000                            }
5001
5002                            // Yay! Either the set matched or we're looking for the last chosen
5003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5004                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5005                            return ri;
5006                        }
5007                    }
5008                } finally {
5009                    if (changed) {
5010                        if (DEBUG_PREFERRED) {
5011                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5012                        }
5013                        scheduleWritePackageRestrictionsLocked(userId);
5014                    }
5015                }
5016            }
5017        }
5018        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5019        return null;
5020    }
5021
5022    /*
5023     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5024     */
5025    @Override
5026    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5027            int targetUserId) {
5028        mContext.enforceCallingOrSelfPermission(
5029                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5030        List<CrossProfileIntentFilter> matches =
5031                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5032        if (matches != null) {
5033            int size = matches.size();
5034            for (int i = 0; i < size; i++) {
5035                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5036            }
5037        }
5038        if (hasWebURI(intent)) {
5039            // cross-profile app linking works only towards the parent.
5040            final UserInfo parent = getProfileParent(sourceUserId);
5041            synchronized(mPackages) {
5042                int flags = updateFlagsForResolve(0, parent.id, intent);
5043                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5044                        intent, resolvedType, flags, sourceUserId, parent.id);
5045                return xpDomainInfo != null;
5046            }
5047        }
5048        return false;
5049    }
5050
5051    private UserInfo getProfileParent(int userId) {
5052        final long identity = Binder.clearCallingIdentity();
5053        try {
5054            return sUserManager.getProfileParent(userId);
5055        } finally {
5056            Binder.restoreCallingIdentity(identity);
5057        }
5058    }
5059
5060    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5061            String resolvedType, int userId) {
5062        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5063        if (resolver != null) {
5064            return resolver.queryIntent(intent, resolvedType, false, userId);
5065        }
5066        return null;
5067    }
5068
5069    @Override
5070    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5071            String resolvedType, int flags, int userId) {
5072        return new ParceledListSlice<>(
5073                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5074    }
5075
5076    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5077            String resolvedType, int flags, int userId) {
5078        if (!sUserManager.exists(userId)) return Collections.emptyList();
5079        flags = updateFlagsForResolve(flags, userId, intent);
5080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5081                false /* requireFullPermission */, false /* checkShell */,
5082                "query intent activities");
5083        ComponentName comp = intent.getComponent();
5084        if (comp == null) {
5085            if (intent.getSelector() != null) {
5086                intent = intent.getSelector();
5087                comp = intent.getComponent();
5088            }
5089        }
5090
5091        if (comp != null) {
5092            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5093            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5094            if (ai != null) {
5095                final ResolveInfo ri = new ResolveInfo();
5096                ri.activityInfo = ai;
5097                list.add(ri);
5098            }
5099            return list;
5100        }
5101
5102        // reader
5103        synchronized (mPackages) {
5104            final String pkgName = intent.getPackage();
5105            if (pkgName == null) {
5106                List<CrossProfileIntentFilter> matchingFilters =
5107                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5108                // Check for results that need to skip the current profile.
5109                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5110                        resolvedType, flags, userId);
5111                if (xpResolveInfo != null) {
5112                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5113                    result.add(xpResolveInfo);
5114                    return filterIfNotSystemUser(result, userId);
5115                }
5116
5117                // Check for results in the current profile.
5118                List<ResolveInfo> result = mActivities.queryIntent(
5119                        intent, resolvedType, flags, userId);
5120                result = filterIfNotSystemUser(result, userId);
5121
5122                // Check for cross profile results.
5123                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5124                xpResolveInfo = queryCrossProfileIntents(
5125                        matchingFilters, intent, resolvedType, flags, userId,
5126                        hasNonNegativePriorityResult);
5127                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5128                    boolean isVisibleToUser = filterIfNotSystemUser(
5129                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5130                    if (isVisibleToUser) {
5131                        result.add(xpResolveInfo);
5132                        Collections.sort(result, mResolvePrioritySorter);
5133                    }
5134                }
5135                if (hasWebURI(intent)) {
5136                    CrossProfileDomainInfo xpDomainInfo = null;
5137                    final UserInfo parent = getProfileParent(userId);
5138                    if (parent != null) {
5139                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5140                                flags, userId, parent.id);
5141                    }
5142                    if (xpDomainInfo != null) {
5143                        if (xpResolveInfo != null) {
5144                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5145                            // in the result.
5146                            result.remove(xpResolveInfo);
5147                        }
5148                        if (result.size() == 0) {
5149                            result.add(xpDomainInfo.resolveInfo);
5150                            return result;
5151                        }
5152                    } else if (result.size() <= 1) {
5153                        return result;
5154                    }
5155                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5156                            xpDomainInfo, userId);
5157                    Collections.sort(result, mResolvePrioritySorter);
5158                }
5159                return result;
5160            }
5161            final PackageParser.Package pkg = mPackages.get(pkgName);
5162            if (pkg != null) {
5163                return filterIfNotSystemUser(
5164                        mActivities.queryIntentForPackage(
5165                                intent, resolvedType, flags, pkg.activities, userId),
5166                        userId);
5167            }
5168            return new ArrayList<ResolveInfo>();
5169        }
5170    }
5171
5172    private static class CrossProfileDomainInfo {
5173        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5174        ResolveInfo resolveInfo;
5175        /* Best domain verification status of the activities found in the other profile */
5176        int bestDomainVerificationStatus;
5177    }
5178
5179    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5180            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5181        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5182                sourceUserId)) {
5183            return null;
5184        }
5185        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5186                resolvedType, flags, parentUserId);
5187
5188        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5189            return null;
5190        }
5191        CrossProfileDomainInfo result = null;
5192        int size = resultTargetUser.size();
5193        for (int i = 0; i < size; i++) {
5194            ResolveInfo riTargetUser = resultTargetUser.get(i);
5195            // Intent filter verification is only for filters that specify a host. So don't return
5196            // those that handle all web uris.
5197            if (riTargetUser.handleAllWebDataURI) {
5198                continue;
5199            }
5200            String packageName = riTargetUser.activityInfo.packageName;
5201            PackageSetting ps = mSettings.mPackages.get(packageName);
5202            if (ps == null) {
5203                continue;
5204            }
5205            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5206            int status = (int)(verificationState >> 32);
5207            if (result == null) {
5208                result = new CrossProfileDomainInfo();
5209                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5210                        sourceUserId, parentUserId);
5211                result.bestDomainVerificationStatus = status;
5212            } else {
5213                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5214                        result.bestDomainVerificationStatus);
5215            }
5216        }
5217        // Don't consider matches with status NEVER across profiles.
5218        if (result != null && result.bestDomainVerificationStatus
5219                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5220            return null;
5221        }
5222        return result;
5223    }
5224
5225    /**
5226     * Verification statuses are ordered from the worse to the best, except for
5227     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5228     */
5229    private int bestDomainVerificationStatus(int status1, int status2) {
5230        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5231            return status2;
5232        }
5233        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5234            return status1;
5235        }
5236        return (int) MathUtils.max(status1, status2);
5237    }
5238
5239    private boolean isUserEnabled(int userId) {
5240        long callingId = Binder.clearCallingIdentity();
5241        try {
5242            UserInfo userInfo = sUserManager.getUserInfo(userId);
5243            return userInfo != null && userInfo.isEnabled();
5244        } finally {
5245            Binder.restoreCallingIdentity(callingId);
5246        }
5247    }
5248
5249    /**
5250     * Filter out activities with systemUserOnly flag set, when current user is not System.
5251     *
5252     * @return filtered list
5253     */
5254    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5255        if (userId == UserHandle.USER_SYSTEM) {
5256            return resolveInfos;
5257        }
5258        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5259            ResolveInfo info = resolveInfos.get(i);
5260            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5261                resolveInfos.remove(i);
5262            }
5263        }
5264        return resolveInfos;
5265    }
5266
5267    /**
5268     * @param resolveInfos list of resolve infos in descending priority order
5269     * @return if the list contains a resolve info with non-negative priority
5270     */
5271    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5272        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5273    }
5274
5275    private static boolean hasWebURI(Intent intent) {
5276        if (intent.getData() == null) {
5277            return false;
5278        }
5279        final String scheme = intent.getScheme();
5280        if (TextUtils.isEmpty(scheme)) {
5281            return false;
5282        }
5283        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5284    }
5285
5286    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5287            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5288            int userId) {
5289        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5290
5291        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5292            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5293                    candidates.size());
5294        }
5295
5296        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5297        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5298        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5299        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5300        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5301        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5302
5303        synchronized (mPackages) {
5304            final int count = candidates.size();
5305            // First, try to use linked apps. Partition the candidates into four lists:
5306            // one for the final results, one for the "do not use ever", one for "undefined status"
5307            // and finally one for "browser app type".
5308            for (int n=0; n<count; n++) {
5309                ResolveInfo info = candidates.get(n);
5310                String packageName = info.activityInfo.packageName;
5311                PackageSetting ps = mSettings.mPackages.get(packageName);
5312                if (ps != null) {
5313                    // Add to the special match all list (Browser use case)
5314                    if (info.handleAllWebDataURI) {
5315                        matchAllList.add(info);
5316                        continue;
5317                    }
5318                    // Try to get the status from User settings first
5319                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5320                    int status = (int)(packedStatus >> 32);
5321                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5322                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5323                        if (DEBUG_DOMAIN_VERIFICATION) {
5324                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5325                                    + " : linkgen=" + linkGeneration);
5326                        }
5327                        // Use link-enabled generation as preferredOrder, i.e.
5328                        // prefer newly-enabled over earlier-enabled.
5329                        info.preferredOrder = linkGeneration;
5330                        alwaysList.add(info);
5331                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5332                        if (DEBUG_DOMAIN_VERIFICATION) {
5333                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5334                        }
5335                        neverList.add(info);
5336                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5337                        if (DEBUG_DOMAIN_VERIFICATION) {
5338                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5339                        }
5340                        alwaysAskList.add(info);
5341                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5342                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5343                        if (DEBUG_DOMAIN_VERIFICATION) {
5344                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5345                        }
5346                        undefinedList.add(info);
5347                    }
5348                }
5349            }
5350
5351            // We'll want to include browser possibilities in a few cases
5352            boolean includeBrowser = false;
5353
5354            // First try to add the "always" resolution(s) for the current user, if any
5355            if (alwaysList.size() > 0) {
5356                result.addAll(alwaysList);
5357            } else {
5358                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5359                result.addAll(undefinedList);
5360                // Maybe add one for the other profile.
5361                if (xpDomainInfo != null && (
5362                        xpDomainInfo.bestDomainVerificationStatus
5363                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5364                    result.add(xpDomainInfo.resolveInfo);
5365                }
5366                includeBrowser = true;
5367            }
5368
5369            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5370            // If there were 'always' entries their preferred order has been set, so we also
5371            // back that off to make the alternatives equivalent
5372            if (alwaysAskList.size() > 0) {
5373                for (ResolveInfo i : result) {
5374                    i.preferredOrder = 0;
5375                }
5376                result.addAll(alwaysAskList);
5377                includeBrowser = true;
5378            }
5379
5380            if (includeBrowser) {
5381                // Also add browsers (all of them or only the default one)
5382                if (DEBUG_DOMAIN_VERIFICATION) {
5383                    Slog.v(TAG, "   ...including browsers in candidate set");
5384                }
5385                if ((matchFlags & MATCH_ALL) != 0) {
5386                    result.addAll(matchAllList);
5387                } else {
5388                    // Browser/generic handling case.  If there's a default browser, go straight
5389                    // to that (but only if there is no other higher-priority match).
5390                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5391                    int maxMatchPrio = 0;
5392                    ResolveInfo defaultBrowserMatch = null;
5393                    final int numCandidates = matchAllList.size();
5394                    for (int n = 0; n < numCandidates; n++) {
5395                        ResolveInfo info = matchAllList.get(n);
5396                        // track the highest overall match priority...
5397                        if (info.priority > maxMatchPrio) {
5398                            maxMatchPrio = info.priority;
5399                        }
5400                        // ...and the highest-priority default browser match
5401                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5402                            if (defaultBrowserMatch == null
5403                                    || (defaultBrowserMatch.priority < info.priority)) {
5404                                if (debug) {
5405                                    Slog.v(TAG, "Considering default browser match " + info);
5406                                }
5407                                defaultBrowserMatch = info;
5408                            }
5409                        }
5410                    }
5411                    if (defaultBrowserMatch != null
5412                            && defaultBrowserMatch.priority >= maxMatchPrio
5413                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5414                    {
5415                        if (debug) {
5416                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5417                        }
5418                        result.add(defaultBrowserMatch);
5419                    } else {
5420                        result.addAll(matchAllList);
5421                    }
5422                }
5423
5424                // If there is nothing selected, add all candidates and remove the ones that the user
5425                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5426                if (result.size() == 0) {
5427                    result.addAll(candidates);
5428                    result.removeAll(neverList);
5429                }
5430            }
5431        }
5432        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5433            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5434                    result.size());
5435            for (ResolveInfo info : result) {
5436                Slog.v(TAG, "  + " + info.activityInfo);
5437            }
5438        }
5439        return result;
5440    }
5441
5442    // Returns a packed value as a long:
5443    //
5444    // high 'int'-sized word: link status: undefined/ask/never/always.
5445    // low 'int'-sized word: relative priority among 'always' results.
5446    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5447        long result = ps.getDomainVerificationStatusForUser(userId);
5448        // if none available, get the master status
5449        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5450            if (ps.getIntentFilterVerificationInfo() != null) {
5451                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5452            }
5453        }
5454        return result;
5455    }
5456
5457    private ResolveInfo querySkipCurrentProfileIntents(
5458            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5459            int flags, int sourceUserId) {
5460        if (matchingFilters != null) {
5461            int size = matchingFilters.size();
5462            for (int i = 0; i < size; i ++) {
5463                CrossProfileIntentFilter filter = matchingFilters.get(i);
5464                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5465                    // Checking if there are activities in the target user that can handle the
5466                    // intent.
5467                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5468                            resolvedType, flags, sourceUserId);
5469                    if (resolveInfo != null) {
5470                        return resolveInfo;
5471                    }
5472                }
5473            }
5474        }
5475        return null;
5476    }
5477
5478    // Return matching ResolveInfo in target user if any.
5479    private ResolveInfo queryCrossProfileIntents(
5480            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5481            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5482        if (matchingFilters != null) {
5483            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5484            // match the same intent. For performance reasons, it is better not to
5485            // run queryIntent twice for the same userId
5486            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5487            int size = matchingFilters.size();
5488            for (int i = 0; i < size; i++) {
5489                CrossProfileIntentFilter filter = matchingFilters.get(i);
5490                int targetUserId = filter.getTargetUserId();
5491                boolean skipCurrentProfile =
5492                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5493                boolean skipCurrentProfileIfNoMatchFound =
5494                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5495                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5496                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5497                    // Checking if there are activities in the target user that can handle the
5498                    // intent.
5499                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5500                            resolvedType, flags, sourceUserId);
5501                    if (resolveInfo != null) return resolveInfo;
5502                    alreadyTriedUserIds.put(targetUserId, true);
5503                }
5504            }
5505        }
5506        return null;
5507    }
5508
5509    /**
5510     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5511     * will forward the intent to the filter's target user.
5512     * Otherwise, returns null.
5513     */
5514    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5515            String resolvedType, int flags, int sourceUserId) {
5516        int targetUserId = filter.getTargetUserId();
5517        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5518                resolvedType, flags, targetUserId);
5519        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5520            // If all the matches in the target profile are suspended, return null.
5521            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5522                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5523                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5524                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5525                            targetUserId);
5526                }
5527            }
5528        }
5529        return null;
5530    }
5531
5532    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5533            int sourceUserId, int targetUserId) {
5534        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5535        long ident = Binder.clearCallingIdentity();
5536        boolean targetIsProfile;
5537        try {
5538            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5539        } finally {
5540            Binder.restoreCallingIdentity(ident);
5541        }
5542        String className;
5543        if (targetIsProfile) {
5544            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5545        } else {
5546            className = FORWARD_INTENT_TO_PARENT;
5547        }
5548        ComponentName forwardingActivityComponentName = new ComponentName(
5549                mAndroidApplication.packageName, className);
5550        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5551                sourceUserId);
5552        if (!targetIsProfile) {
5553            forwardingActivityInfo.showUserIcon = targetUserId;
5554            forwardingResolveInfo.noResourceId = true;
5555        }
5556        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5557        forwardingResolveInfo.priority = 0;
5558        forwardingResolveInfo.preferredOrder = 0;
5559        forwardingResolveInfo.match = 0;
5560        forwardingResolveInfo.isDefault = true;
5561        forwardingResolveInfo.filter = filter;
5562        forwardingResolveInfo.targetUserId = targetUserId;
5563        return forwardingResolveInfo;
5564    }
5565
5566    @Override
5567    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5568            Intent[] specifics, String[] specificTypes, Intent intent,
5569            String resolvedType, int flags, int userId) {
5570        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5571                specificTypes, intent, resolvedType, flags, userId));
5572    }
5573
5574    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5575            Intent[] specifics, String[] specificTypes, Intent intent,
5576            String resolvedType, int flags, int userId) {
5577        if (!sUserManager.exists(userId)) return Collections.emptyList();
5578        flags = updateFlagsForResolve(flags, userId, intent);
5579        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5580                false /* requireFullPermission */, false /* checkShell */,
5581                "query intent activity options");
5582        final String resultsAction = intent.getAction();
5583
5584        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5585                | PackageManager.GET_RESOLVED_FILTER, userId);
5586
5587        if (DEBUG_INTENT_MATCHING) {
5588            Log.v(TAG, "Query " + intent + ": " + results);
5589        }
5590
5591        int specificsPos = 0;
5592        int N;
5593
5594        // todo: note that the algorithm used here is O(N^2).  This
5595        // isn't a problem in our current environment, but if we start running
5596        // into situations where we have more than 5 or 10 matches then this
5597        // should probably be changed to something smarter...
5598
5599        // First we go through and resolve each of the specific items
5600        // that were supplied, taking care of removing any corresponding
5601        // duplicate items in the generic resolve list.
5602        if (specifics != null) {
5603            for (int i=0; i<specifics.length; i++) {
5604                final Intent sintent = specifics[i];
5605                if (sintent == null) {
5606                    continue;
5607                }
5608
5609                if (DEBUG_INTENT_MATCHING) {
5610                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5611                }
5612
5613                String action = sintent.getAction();
5614                if (resultsAction != null && resultsAction.equals(action)) {
5615                    // If this action was explicitly requested, then don't
5616                    // remove things that have it.
5617                    action = null;
5618                }
5619
5620                ResolveInfo ri = null;
5621                ActivityInfo ai = null;
5622
5623                ComponentName comp = sintent.getComponent();
5624                if (comp == null) {
5625                    ri = resolveIntent(
5626                        sintent,
5627                        specificTypes != null ? specificTypes[i] : null,
5628                            flags, userId);
5629                    if (ri == null) {
5630                        continue;
5631                    }
5632                    if (ri == mResolveInfo) {
5633                        // ACK!  Must do something better with this.
5634                    }
5635                    ai = ri.activityInfo;
5636                    comp = new ComponentName(ai.applicationInfo.packageName,
5637                            ai.name);
5638                } else {
5639                    ai = getActivityInfo(comp, flags, userId);
5640                    if (ai == null) {
5641                        continue;
5642                    }
5643                }
5644
5645                // Look for any generic query activities that are duplicates
5646                // of this specific one, and remove them from the results.
5647                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5648                N = results.size();
5649                int j;
5650                for (j=specificsPos; j<N; j++) {
5651                    ResolveInfo sri = results.get(j);
5652                    if ((sri.activityInfo.name.equals(comp.getClassName())
5653                            && sri.activityInfo.applicationInfo.packageName.equals(
5654                                    comp.getPackageName()))
5655                        || (action != null && sri.filter.matchAction(action))) {
5656                        results.remove(j);
5657                        if (DEBUG_INTENT_MATCHING) Log.v(
5658                            TAG, "Removing duplicate item from " + j
5659                            + " due to specific " + specificsPos);
5660                        if (ri == null) {
5661                            ri = sri;
5662                        }
5663                        j--;
5664                        N--;
5665                    }
5666                }
5667
5668                // Add this specific item to its proper place.
5669                if (ri == null) {
5670                    ri = new ResolveInfo();
5671                    ri.activityInfo = ai;
5672                }
5673                results.add(specificsPos, ri);
5674                ri.specificIndex = i;
5675                specificsPos++;
5676            }
5677        }
5678
5679        // Now we go through the remaining generic results and remove any
5680        // duplicate actions that are found here.
5681        N = results.size();
5682        for (int i=specificsPos; i<N-1; i++) {
5683            final ResolveInfo rii = results.get(i);
5684            if (rii.filter == null) {
5685                continue;
5686            }
5687
5688            // Iterate over all of the actions of this result's intent
5689            // filter...  typically this should be just one.
5690            final Iterator<String> it = rii.filter.actionsIterator();
5691            if (it == null) {
5692                continue;
5693            }
5694            while (it.hasNext()) {
5695                final String action = it.next();
5696                if (resultsAction != null && resultsAction.equals(action)) {
5697                    // If this action was explicitly requested, then don't
5698                    // remove things that have it.
5699                    continue;
5700                }
5701                for (int j=i+1; j<N; j++) {
5702                    final ResolveInfo rij = results.get(j);
5703                    if (rij.filter != null && rij.filter.hasAction(action)) {
5704                        results.remove(j);
5705                        if (DEBUG_INTENT_MATCHING) Log.v(
5706                            TAG, "Removing duplicate item from " + j
5707                            + " due to action " + action + " at " + i);
5708                        j--;
5709                        N--;
5710                    }
5711                }
5712            }
5713
5714            // If the caller didn't request filter information, drop it now
5715            // so we don't have to marshall/unmarshall it.
5716            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5717                rii.filter = null;
5718            }
5719        }
5720
5721        // Filter out the caller activity if so requested.
5722        if (caller != null) {
5723            N = results.size();
5724            for (int i=0; i<N; i++) {
5725                ActivityInfo ainfo = results.get(i).activityInfo;
5726                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5727                        && caller.getClassName().equals(ainfo.name)) {
5728                    results.remove(i);
5729                    break;
5730                }
5731            }
5732        }
5733
5734        // If the caller didn't request filter information,
5735        // drop them now so we don't have to
5736        // marshall/unmarshall it.
5737        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5738            N = results.size();
5739            for (int i=0; i<N; i++) {
5740                results.get(i).filter = null;
5741            }
5742        }
5743
5744        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5745        return results;
5746    }
5747
5748    @Override
5749    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5750            String resolvedType, int flags, int userId) {
5751        return new ParceledListSlice<>(
5752                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5753    }
5754
5755    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5756            String resolvedType, int flags, int userId) {
5757        if (!sUserManager.exists(userId)) return Collections.emptyList();
5758        flags = updateFlagsForResolve(flags, userId, intent);
5759        ComponentName comp = intent.getComponent();
5760        if (comp == null) {
5761            if (intent.getSelector() != null) {
5762                intent = intent.getSelector();
5763                comp = intent.getComponent();
5764            }
5765        }
5766        if (comp != null) {
5767            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5768            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5769            if (ai != null) {
5770                ResolveInfo ri = new ResolveInfo();
5771                ri.activityInfo = ai;
5772                list.add(ri);
5773            }
5774            return list;
5775        }
5776
5777        // reader
5778        synchronized (mPackages) {
5779            String pkgName = intent.getPackage();
5780            if (pkgName == null) {
5781                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5782            }
5783            final PackageParser.Package pkg = mPackages.get(pkgName);
5784            if (pkg != null) {
5785                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5786                        userId);
5787            }
5788            return Collections.emptyList();
5789        }
5790    }
5791
5792    @Override
5793    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5794        if (!sUserManager.exists(userId)) return null;
5795        flags = updateFlagsForResolve(flags, userId, intent);
5796        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5797        if (query != null) {
5798            if (query.size() >= 1) {
5799                // If there is more than one service with the same priority,
5800                // just arbitrarily pick the first one.
5801                return query.get(0);
5802            }
5803        }
5804        return null;
5805    }
5806
5807    @Override
5808    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5809            String resolvedType, int flags, int userId) {
5810        return new ParceledListSlice<>(
5811                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5812    }
5813
5814    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5815            String resolvedType, int flags, int userId) {
5816        if (!sUserManager.exists(userId)) return Collections.emptyList();
5817        flags = updateFlagsForResolve(flags, userId, intent);
5818        ComponentName comp = intent.getComponent();
5819        if (comp == null) {
5820            if (intent.getSelector() != null) {
5821                intent = intent.getSelector();
5822                comp = intent.getComponent();
5823            }
5824        }
5825        if (comp != null) {
5826            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5827            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5828            if (si != null) {
5829                final ResolveInfo ri = new ResolveInfo();
5830                ri.serviceInfo = si;
5831                list.add(ri);
5832            }
5833            return list;
5834        }
5835
5836        // reader
5837        synchronized (mPackages) {
5838            String pkgName = intent.getPackage();
5839            if (pkgName == null) {
5840                return mServices.queryIntent(intent, resolvedType, flags, userId);
5841            }
5842            final PackageParser.Package pkg = mPackages.get(pkgName);
5843            if (pkg != null) {
5844                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5845                        userId);
5846            }
5847            return Collections.emptyList();
5848        }
5849    }
5850
5851    @Override
5852    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5853            String resolvedType, int flags, int userId) {
5854        return new ParceledListSlice<>(
5855                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5856    }
5857
5858    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5859            Intent intent, String resolvedType, int flags, int userId) {
5860        if (!sUserManager.exists(userId)) return Collections.emptyList();
5861        flags = updateFlagsForResolve(flags, userId, intent);
5862        ComponentName comp = intent.getComponent();
5863        if (comp == null) {
5864            if (intent.getSelector() != null) {
5865                intent = intent.getSelector();
5866                comp = intent.getComponent();
5867            }
5868        }
5869        if (comp != null) {
5870            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5871            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5872            if (pi != null) {
5873                final ResolveInfo ri = new ResolveInfo();
5874                ri.providerInfo = pi;
5875                list.add(ri);
5876            }
5877            return list;
5878        }
5879
5880        // reader
5881        synchronized (mPackages) {
5882            String pkgName = intent.getPackage();
5883            if (pkgName == null) {
5884                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5885            }
5886            final PackageParser.Package pkg = mPackages.get(pkgName);
5887            if (pkg != null) {
5888                return mProviders.queryIntentForPackage(
5889                        intent, resolvedType, flags, pkg.providers, userId);
5890            }
5891            return Collections.emptyList();
5892        }
5893    }
5894
5895    @Override
5896    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5897        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5898        flags = updateFlagsForPackage(flags, userId, null);
5899        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5900        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5901                true /* requireFullPermission */, false /* checkShell */,
5902                "get installed packages");
5903
5904        // writer
5905        synchronized (mPackages) {
5906            ArrayList<PackageInfo> list;
5907            if (listUninstalled) {
5908                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5909                for (PackageSetting ps : mSettings.mPackages.values()) {
5910                    final PackageInfo pi;
5911                    if (ps.pkg != null) {
5912                        pi = generatePackageInfo(ps, flags, userId);
5913                    } else {
5914                        pi = generatePackageInfo(ps, flags, userId);
5915                    }
5916                    if (pi != null) {
5917                        list.add(pi);
5918                    }
5919                }
5920            } else {
5921                list = new ArrayList<PackageInfo>(mPackages.size());
5922                for (PackageParser.Package p : mPackages.values()) {
5923                    final PackageInfo pi =
5924                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
5925                    if (pi != null) {
5926                        list.add(pi);
5927                    }
5928                }
5929            }
5930
5931            return new ParceledListSlice<PackageInfo>(list);
5932        }
5933    }
5934
5935    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5936            String[] permissions, boolean[] tmp, int flags, int userId) {
5937        int numMatch = 0;
5938        final PermissionsState permissionsState = ps.getPermissionsState();
5939        for (int i=0; i<permissions.length; i++) {
5940            final String permission = permissions[i];
5941            if (permissionsState.hasPermission(permission, userId)) {
5942                tmp[i] = true;
5943                numMatch++;
5944            } else {
5945                tmp[i] = false;
5946            }
5947        }
5948        if (numMatch == 0) {
5949            return;
5950        }
5951        final PackageInfo pi;
5952        if (ps.pkg != null) {
5953            pi = generatePackageInfo(ps, flags, userId);
5954        } else {
5955            pi = generatePackageInfo(ps, flags, userId);
5956        }
5957        // The above might return null in cases of uninstalled apps or install-state
5958        // skew across users/profiles.
5959        if (pi != null) {
5960            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5961                if (numMatch == permissions.length) {
5962                    pi.requestedPermissions = permissions;
5963                } else {
5964                    pi.requestedPermissions = new String[numMatch];
5965                    numMatch = 0;
5966                    for (int i=0; i<permissions.length; i++) {
5967                        if (tmp[i]) {
5968                            pi.requestedPermissions[numMatch] = permissions[i];
5969                            numMatch++;
5970                        }
5971                    }
5972                }
5973            }
5974            list.add(pi);
5975        }
5976    }
5977
5978    @Override
5979    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5980            String[] permissions, int flags, int userId) {
5981        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5982        flags = updateFlagsForPackage(flags, userId, permissions);
5983        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5984
5985        // writer
5986        synchronized (mPackages) {
5987            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5988            boolean[] tmpBools = new boolean[permissions.length];
5989            if (listUninstalled) {
5990                for (PackageSetting ps : mSettings.mPackages.values()) {
5991                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5992                }
5993            } else {
5994                for (PackageParser.Package pkg : mPackages.values()) {
5995                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5996                    if (ps != null) {
5997                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5998                                userId);
5999                    }
6000                }
6001            }
6002
6003            return new ParceledListSlice<PackageInfo>(list);
6004        }
6005    }
6006
6007    @Override
6008    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6009        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6010        flags = updateFlagsForApplication(flags, userId, null);
6011        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6012
6013        // writer
6014        synchronized (mPackages) {
6015            ArrayList<ApplicationInfo> list;
6016            if (listUninstalled) {
6017                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6018                for (PackageSetting ps : mSettings.mPackages.values()) {
6019                    ApplicationInfo ai;
6020                    if (ps.pkg != null) {
6021                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6022                                ps.readUserState(userId), userId);
6023                    } else {
6024                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6025                    }
6026                    if (ai != null) {
6027                        list.add(ai);
6028                    }
6029                }
6030            } else {
6031                list = new ArrayList<ApplicationInfo>(mPackages.size());
6032                for (PackageParser.Package p : mPackages.values()) {
6033                    if (p.mExtras != null) {
6034                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6035                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6036                        if (ai != null) {
6037                            list.add(ai);
6038                        }
6039                    }
6040                }
6041            }
6042
6043            return new ParceledListSlice<ApplicationInfo>(list);
6044        }
6045    }
6046
6047    @Override
6048    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6049        if (DISABLE_EPHEMERAL_APPS) {
6050            return null;
6051        }
6052
6053        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6054                "getEphemeralApplications");
6055        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6056                true /* requireFullPermission */, false /* checkShell */,
6057                "getEphemeralApplications");
6058        synchronized (mPackages) {
6059            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6060                    .getEphemeralApplicationsLPw(userId);
6061            if (ephemeralApps != null) {
6062                return new ParceledListSlice<>(ephemeralApps);
6063            }
6064        }
6065        return null;
6066    }
6067
6068    @Override
6069    public boolean isEphemeralApplication(String packageName, int userId) {
6070        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6071                true /* requireFullPermission */, false /* checkShell */,
6072                "isEphemeral");
6073        if (DISABLE_EPHEMERAL_APPS) {
6074            return false;
6075        }
6076
6077        if (!isCallerSameApp(packageName)) {
6078            return false;
6079        }
6080        synchronized (mPackages) {
6081            PackageParser.Package pkg = mPackages.get(packageName);
6082            if (pkg != null) {
6083                return pkg.applicationInfo.isEphemeralApp();
6084            }
6085        }
6086        return false;
6087    }
6088
6089    @Override
6090    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6091        if (DISABLE_EPHEMERAL_APPS) {
6092            return null;
6093        }
6094
6095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6096                true /* requireFullPermission */, false /* checkShell */,
6097                "getCookie");
6098        if (!isCallerSameApp(packageName)) {
6099            return null;
6100        }
6101        synchronized (mPackages) {
6102            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6103                    packageName, userId);
6104        }
6105    }
6106
6107    @Override
6108    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6109        if (DISABLE_EPHEMERAL_APPS) {
6110            return true;
6111        }
6112
6113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6114                true /* requireFullPermission */, true /* checkShell */,
6115                "setCookie");
6116        if (!isCallerSameApp(packageName)) {
6117            return false;
6118        }
6119        synchronized (mPackages) {
6120            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6121                    packageName, cookie, userId);
6122        }
6123    }
6124
6125    @Override
6126    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6127        if (DISABLE_EPHEMERAL_APPS) {
6128            return null;
6129        }
6130
6131        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6132                "getEphemeralApplicationIcon");
6133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6134                true /* requireFullPermission */, false /* checkShell */,
6135                "getEphemeralApplicationIcon");
6136        synchronized (mPackages) {
6137            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6138                    packageName, userId);
6139        }
6140    }
6141
6142    private boolean isCallerSameApp(String packageName) {
6143        PackageParser.Package pkg = mPackages.get(packageName);
6144        return pkg != null
6145                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6146    }
6147
6148    @Override
6149    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6150        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6151    }
6152
6153    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6154        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6155
6156        // reader
6157        synchronized (mPackages) {
6158            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6159            final int userId = UserHandle.getCallingUserId();
6160            while (i.hasNext()) {
6161                final PackageParser.Package p = i.next();
6162                if (p.applicationInfo == null) continue;
6163
6164                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6165                        && !p.applicationInfo.isDirectBootAware();
6166                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6167                        && p.applicationInfo.isDirectBootAware();
6168
6169                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6170                        && (!mSafeMode || isSystemApp(p))
6171                        && (matchesUnaware || matchesAware)) {
6172                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6173                    if (ps != null) {
6174                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6175                                ps.readUserState(userId), userId);
6176                        if (ai != null) {
6177                            finalList.add(ai);
6178                        }
6179                    }
6180                }
6181            }
6182        }
6183
6184        return finalList;
6185    }
6186
6187    @Override
6188    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6189        if (!sUserManager.exists(userId)) return null;
6190        flags = updateFlagsForComponent(flags, userId, name);
6191        // reader
6192        synchronized (mPackages) {
6193            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6194            PackageSetting ps = provider != null
6195                    ? mSettings.mPackages.get(provider.owner.packageName)
6196                    : null;
6197            return ps != null
6198                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6199                    ? PackageParser.generateProviderInfo(provider, flags,
6200                            ps.readUserState(userId), userId)
6201                    : null;
6202        }
6203    }
6204
6205    /**
6206     * @deprecated
6207     */
6208    @Deprecated
6209    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6210        // reader
6211        synchronized (mPackages) {
6212            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6213                    .entrySet().iterator();
6214            final int userId = UserHandle.getCallingUserId();
6215            while (i.hasNext()) {
6216                Map.Entry<String, PackageParser.Provider> entry = i.next();
6217                PackageParser.Provider p = entry.getValue();
6218                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6219
6220                if (ps != null && p.syncable
6221                        && (!mSafeMode || (p.info.applicationInfo.flags
6222                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6223                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6224                            ps.readUserState(userId), userId);
6225                    if (info != null) {
6226                        outNames.add(entry.getKey());
6227                        outInfo.add(info);
6228                    }
6229                }
6230            }
6231        }
6232    }
6233
6234    @Override
6235    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6236            int uid, int flags) {
6237        final int userId = processName != null ? UserHandle.getUserId(uid)
6238                : UserHandle.getCallingUserId();
6239        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6240        flags = updateFlagsForComponent(flags, userId, processName);
6241
6242        ArrayList<ProviderInfo> finalList = null;
6243        // reader
6244        synchronized (mPackages) {
6245            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6246            while (i.hasNext()) {
6247                final PackageParser.Provider p = i.next();
6248                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6249                if (ps != null && p.info.authority != null
6250                        && (processName == null
6251                                || (p.info.processName.equals(processName)
6252                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6253                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6254                    if (finalList == null) {
6255                        finalList = new ArrayList<ProviderInfo>(3);
6256                    }
6257                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6258                            ps.readUserState(userId), userId);
6259                    if (info != null) {
6260                        finalList.add(info);
6261                    }
6262                }
6263            }
6264        }
6265
6266        if (finalList != null) {
6267            Collections.sort(finalList, mProviderInitOrderSorter);
6268            return new ParceledListSlice<ProviderInfo>(finalList);
6269        }
6270
6271        return ParceledListSlice.emptyList();
6272    }
6273
6274    @Override
6275    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6276        // reader
6277        synchronized (mPackages) {
6278            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6279            return PackageParser.generateInstrumentationInfo(i, flags);
6280        }
6281    }
6282
6283    @Override
6284    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6285            String targetPackage, int flags) {
6286        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6287    }
6288
6289    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6290            int flags) {
6291        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6292
6293        // reader
6294        synchronized (mPackages) {
6295            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6296            while (i.hasNext()) {
6297                final PackageParser.Instrumentation p = i.next();
6298                if (targetPackage == null
6299                        || targetPackage.equals(p.info.targetPackage)) {
6300                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6301                            flags);
6302                    if (ii != null) {
6303                        finalList.add(ii);
6304                    }
6305                }
6306            }
6307        }
6308
6309        return finalList;
6310    }
6311
6312    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6313        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6314        if (overlays == null) {
6315            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6316            return;
6317        }
6318        for (PackageParser.Package opkg : overlays.values()) {
6319            // Not much to do if idmap fails: we already logged the error
6320            // and we certainly don't want to abort installation of pkg simply
6321            // because an overlay didn't fit properly. For these reasons,
6322            // ignore the return value of createIdmapForPackagePairLI.
6323            createIdmapForPackagePairLI(pkg, opkg);
6324        }
6325    }
6326
6327    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6328            PackageParser.Package opkg) {
6329        if (!opkg.mTrustedOverlay) {
6330            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6331                    opkg.baseCodePath + ": overlay not trusted");
6332            return false;
6333        }
6334        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6335        if (overlaySet == null) {
6336            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6337                    opkg.baseCodePath + " but target package has no known overlays");
6338            return false;
6339        }
6340        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6341        // TODO: generate idmap for split APKs
6342        try {
6343            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6344        } catch (InstallerException e) {
6345            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6346                    + opkg.baseCodePath);
6347            return false;
6348        }
6349        PackageParser.Package[] overlayArray =
6350            overlaySet.values().toArray(new PackageParser.Package[0]);
6351        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6352            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6353                return p1.mOverlayPriority - p2.mOverlayPriority;
6354            }
6355        };
6356        Arrays.sort(overlayArray, cmp);
6357
6358        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6359        int i = 0;
6360        for (PackageParser.Package p : overlayArray) {
6361            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6362        }
6363        return true;
6364    }
6365
6366    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6367        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6368        try {
6369            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6370        } finally {
6371            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6372        }
6373    }
6374
6375    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6376        final File[] files = dir.listFiles();
6377        if (ArrayUtils.isEmpty(files)) {
6378            Log.d(TAG, "No files in app dir " + dir);
6379            return;
6380        }
6381
6382        if (DEBUG_PACKAGE_SCANNING) {
6383            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6384                    + " flags=0x" + Integer.toHexString(parseFlags));
6385        }
6386
6387        for (File file : files) {
6388            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6389                    && !PackageInstallerService.isStageName(file.getName());
6390            if (!isPackage) {
6391                // Ignore entries which are not packages
6392                continue;
6393            }
6394            try {
6395                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6396                        scanFlags, currentTime, null);
6397            } catch (PackageManagerException e) {
6398                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6399
6400                // Delete invalid userdata apps
6401                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6402                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6403                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6404                    removeCodePathLI(file);
6405                }
6406            }
6407        }
6408    }
6409
6410    private static File getSettingsProblemFile() {
6411        File dataDir = Environment.getDataDirectory();
6412        File systemDir = new File(dataDir, "system");
6413        File fname = new File(systemDir, "uiderrors.txt");
6414        return fname;
6415    }
6416
6417    static void reportSettingsProblem(int priority, String msg) {
6418        logCriticalInfo(priority, msg);
6419    }
6420
6421    static void logCriticalInfo(int priority, String msg) {
6422        Slog.println(priority, TAG, msg);
6423        EventLogTags.writePmCriticalInfo(msg);
6424        try {
6425            File fname = getSettingsProblemFile();
6426            FileOutputStream out = new FileOutputStream(fname, true);
6427            PrintWriter pw = new FastPrintWriter(out);
6428            SimpleDateFormat formatter = new SimpleDateFormat();
6429            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6430            pw.println(dateString + ": " + msg);
6431            pw.close();
6432            FileUtils.setPermissions(
6433                    fname.toString(),
6434                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6435                    -1, -1);
6436        } catch (java.io.IOException e) {
6437        }
6438    }
6439
6440    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6441            int parseFlags) throws PackageManagerException {
6442        if (ps != null
6443                && ps.codePath.equals(srcFile)
6444                && ps.timeStamp == srcFile.lastModified()
6445                && !isCompatSignatureUpdateNeeded(pkg)
6446                && !isRecoverSignatureUpdateNeeded(pkg)) {
6447            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6448            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6449            ArraySet<PublicKey> signingKs;
6450            synchronized (mPackages) {
6451                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6452            }
6453            if (ps.signatures.mSignatures != null
6454                    && ps.signatures.mSignatures.length != 0
6455                    && signingKs != null) {
6456                // Optimization: reuse the existing cached certificates
6457                // if the package appears to be unchanged.
6458                pkg.mSignatures = ps.signatures.mSignatures;
6459                pkg.mSigningKeys = signingKs;
6460                return;
6461            }
6462
6463            Slog.w(TAG, "PackageSetting for " + ps.name
6464                    + " is missing signatures.  Collecting certs again to recover them.");
6465        } else {
6466            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6467        }
6468
6469        try {
6470            PackageParser.collectCertificates(pkg, parseFlags);
6471        } catch (PackageParserException e) {
6472            throw PackageManagerException.from(e);
6473        }
6474    }
6475
6476    /**
6477     *  Traces a package scan.
6478     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6479     */
6480    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6481            long currentTime, UserHandle user) throws PackageManagerException {
6482        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6483        try {
6484            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6485        } finally {
6486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6487        }
6488    }
6489
6490    /**
6491     *  Scans a package and returns the newly parsed package.
6492     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6493     */
6494    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6495            long currentTime, UserHandle user) throws PackageManagerException {
6496        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6497        parseFlags |= mDefParseFlags;
6498        PackageParser pp = new PackageParser();
6499        pp.setSeparateProcesses(mSeparateProcesses);
6500        pp.setOnlyCoreApps(mOnlyCore);
6501        pp.setDisplayMetrics(mMetrics);
6502
6503        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6504            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6505        }
6506
6507        final PackageParser.Package pkg;
6508        try {
6509            pkg = pp.parsePackage(scanFile, parseFlags);
6510        } catch (PackageParserException e) {
6511            throw PackageManagerException.from(e);
6512        }
6513
6514        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6515    }
6516
6517    /**
6518     *  Scans a package and returns the newly parsed package.
6519     *  @throws PackageManagerException on a parse error.
6520     */
6521    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6522            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6523            throws PackageManagerException {
6524        // If the package has children and this is the first dive in the function
6525        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6526        // packages (parent and children) would be successfully scanned before the
6527        // actual scan since scanning mutates internal state and we want to atomically
6528        // install the package and its children.
6529        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6530            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6531                scanFlags |= SCAN_CHECK_ONLY;
6532            }
6533        } else {
6534            scanFlags &= ~SCAN_CHECK_ONLY;
6535        }
6536
6537        // Scan the parent
6538        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6539                scanFlags, currentTime, user);
6540
6541        // Scan the children
6542        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6543        for (int i = 0; i < childCount; i++) {
6544            PackageParser.Package childPackage = pkg.childPackages.get(i);
6545            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6546                    currentTime, user);
6547        }
6548
6549
6550        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6551            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6552        }
6553
6554        return scannedPkg;
6555    }
6556
6557    /**
6558     *  Scans a package and returns the newly parsed package.
6559     *  @throws PackageManagerException on a parse error.
6560     */
6561    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6562            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6563            throws PackageManagerException {
6564        PackageSetting ps = null;
6565        PackageSetting updatedPkg;
6566        // reader
6567        synchronized (mPackages) {
6568            // Look to see if we already know about this package.
6569            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6570            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6571                // This package has been renamed to its original name.  Let's
6572                // use that.
6573                ps = mSettings.peekPackageLPr(oldName);
6574            }
6575            // If there was no original package, see one for the real package name.
6576            if (ps == null) {
6577                ps = mSettings.peekPackageLPr(pkg.packageName);
6578            }
6579            // Check to see if this package could be hiding/updating a system
6580            // package.  Must look for it either under the original or real
6581            // package name depending on our state.
6582            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6583            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6584
6585            // If this is a package we don't know about on the system partition, we
6586            // may need to remove disabled child packages on the system partition
6587            // or may need to not add child packages if the parent apk is updated
6588            // on the data partition and no longer defines this child package.
6589            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6590                // If this is a parent package for an updated system app and this system
6591                // app got an OTA update which no longer defines some of the child packages
6592                // we have to prune them from the disabled system packages.
6593                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6594                if (disabledPs != null) {
6595                    final int scannedChildCount = (pkg.childPackages != null)
6596                            ? pkg.childPackages.size() : 0;
6597                    final int disabledChildCount = disabledPs.childPackageNames != null
6598                            ? disabledPs.childPackageNames.size() : 0;
6599                    for (int i = 0; i < disabledChildCount; i++) {
6600                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6601                        boolean disabledPackageAvailable = false;
6602                        for (int j = 0; j < scannedChildCount; j++) {
6603                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6604                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6605                                disabledPackageAvailable = true;
6606                                break;
6607                            }
6608                         }
6609                         if (!disabledPackageAvailable) {
6610                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6611                         }
6612                    }
6613                }
6614            }
6615        }
6616
6617        boolean updatedPkgBetter = false;
6618        // First check if this is a system package that may involve an update
6619        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6620            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6621            // it needs to drop FLAG_PRIVILEGED.
6622            if (locationIsPrivileged(scanFile)) {
6623                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6624            } else {
6625                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6626            }
6627
6628            if (ps != null && !ps.codePath.equals(scanFile)) {
6629                // The path has changed from what was last scanned...  check the
6630                // version of the new path against what we have stored to determine
6631                // what to do.
6632                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6633                if (pkg.mVersionCode <= ps.versionCode) {
6634                    // The system package has been updated and the code path does not match
6635                    // Ignore entry. Skip it.
6636                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6637                            + " ignored: updated version " + ps.versionCode
6638                            + " better than this " + pkg.mVersionCode);
6639                    if (!updatedPkg.codePath.equals(scanFile)) {
6640                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6641                                + ps.name + " changing from " + updatedPkg.codePathString
6642                                + " to " + scanFile);
6643                        updatedPkg.codePath = scanFile;
6644                        updatedPkg.codePathString = scanFile.toString();
6645                        updatedPkg.resourcePath = scanFile;
6646                        updatedPkg.resourcePathString = scanFile.toString();
6647                    }
6648                    updatedPkg.pkg = pkg;
6649                    updatedPkg.versionCode = pkg.mVersionCode;
6650
6651                    // Update the disabled system child packages to point to the package too.
6652                    final int childCount = updatedPkg.childPackageNames != null
6653                            ? updatedPkg.childPackageNames.size() : 0;
6654                    for (int i = 0; i < childCount; i++) {
6655                        String childPackageName = updatedPkg.childPackageNames.get(i);
6656                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6657                                childPackageName);
6658                        if (updatedChildPkg != null) {
6659                            updatedChildPkg.pkg = pkg;
6660                            updatedChildPkg.versionCode = pkg.mVersionCode;
6661                        }
6662                    }
6663
6664                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6665                            + scanFile + " ignored: updated version " + ps.versionCode
6666                            + " better than this " + pkg.mVersionCode);
6667                } else {
6668                    // The current app on the system partition is better than
6669                    // what we have updated to on the data partition; switch
6670                    // back to the system partition version.
6671                    // At this point, its safely assumed that package installation for
6672                    // apps in system partition will go through. If not there won't be a working
6673                    // version of the app
6674                    // writer
6675                    synchronized (mPackages) {
6676                        // Just remove the loaded entries from package lists.
6677                        mPackages.remove(ps.name);
6678                    }
6679
6680                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6681                            + " reverting from " + ps.codePathString
6682                            + ": new version " + pkg.mVersionCode
6683                            + " better than installed " + ps.versionCode);
6684
6685                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6686                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6687                    synchronized (mInstallLock) {
6688                        args.cleanUpResourcesLI();
6689                    }
6690                    synchronized (mPackages) {
6691                        mSettings.enableSystemPackageLPw(ps.name);
6692                    }
6693                    updatedPkgBetter = true;
6694                }
6695            }
6696        }
6697
6698        if (updatedPkg != null) {
6699            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6700            // initially
6701            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6702
6703            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6704            // flag set initially
6705            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6706                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6707            }
6708        }
6709
6710        // Verify certificates against what was last scanned
6711        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6712
6713        /*
6714         * A new system app appeared, but we already had a non-system one of the
6715         * same name installed earlier.
6716         */
6717        boolean shouldHideSystemApp = false;
6718        if (updatedPkg == null && ps != null
6719                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6720            /*
6721             * Check to make sure the signatures match first. If they don't,
6722             * wipe the installed application and its data.
6723             */
6724            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6725                    != PackageManager.SIGNATURE_MATCH) {
6726                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6727                        + " signatures don't match existing userdata copy; removing");
6728                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6729                ps = null;
6730            } else {
6731                /*
6732                 * If the newly-added system app is an older version than the
6733                 * already installed version, hide it. It will be scanned later
6734                 * and re-added like an update.
6735                 */
6736                if (pkg.mVersionCode <= ps.versionCode) {
6737                    shouldHideSystemApp = true;
6738                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6739                            + " but new version " + pkg.mVersionCode + " better than installed "
6740                            + ps.versionCode + "; hiding system");
6741                } else {
6742                    /*
6743                     * The newly found system app is a newer version that the
6744                     * one previously installed. Simply remove the
6745                     * already-installed application and replace it with our own
6746                     * while keeping the application data.
6747                     */
6748                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6749                            + " reverting from " + ps.codePathString + ": new version "
6750                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6751                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6752                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6753                    synchronized (mInstallLock) {
6754                        args.cleanUpResourcesLI();
6755                    }
6756                }
6757            }
6758        }
6759
6760        // The apk is forward locked (not public) if its code and resources
6761        // are kept in different files. (except for app in either system or
6762        // vendor path).
6763        // TODO grab this value from PackageSettings
6764        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6765            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6766                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6767            }
6768        }
6769
6770        // TODO: extend to support forward-locked splits
6771        String resourcePath = null;
6772        String baseResourcePath = null;
6773        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6774            if (ps != null && ps.resourcePathString != null) {
6775                resourcePath = ps.resourcePathString;
6776                baseResourcePath = ps.resourcePathString;
6777            } else {
6778                // Should not happen at all. Just log an error.
6779                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6780            }
6781        } else {
6782            resourcePath = pkg.codePath;
6783            baseResourcePath = pkg.baseCodePath;
6784        }
6785
6786        // Set application objects path explicitly.
6787        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6788        pkg.setApplicationInfoCodePath(pkg.codePath);
6789        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6790        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6791        pkg.setApplicationInfoResourcePath(resourcePath);
6792        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6793        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6794
6795        // Note that we invoke the following method only if we are about to unpack an application
6796        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6797                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6798
6799        /*
6800         * If the system app should be overridden by a previously installed
6801         * data, hide the system app now and let the /data/app scan pick it up
6802         * again.
6803         */
6804        if (shouldHideSystemApp) {
6805            synchronized (mPackages) {
6806                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6807            }
6808        }
6809
6810        return scannedPkg;
6811    }
6812
6813    private static String fixProcessName(String defProcessName,
6814            String processName, int uid) {
6815        if (processName == null) {
6816            return defProcessName;
6817        }
6818        return processName;
6819    }
6820
6821    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6822            throws PackageManagerException {
6823        if (pkgSetting.signatures.mSignatures != null) {
6824            // Already existing package. Make sure signatures match
6825            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6826                    == PackageManager.SIGNATURE_MATCH;
6827            if (!match) {
6828                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6829                        == PackageManager.SIGNATURE_MATCH;
6830            }
6831            if (!match) {
6832                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6833                        == PackageManager.SIGNATURE_MATCH;
6834            }
6835            if (!match) {
6836                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6837                        + pkg.packageName + " signatures do not match the "
6838                        + "previously installed version; ignoring!");
6839            }
6840        }
6841
6842        // Check for shared user signatures
6843        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6844            // Already existing package. Make sure signatures match
6845            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6846                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6847            if (!match) {
6848                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6849                        == PackageManager.SIGNATURE_MATCH;
6850            }
6851            if (!match) {
6852                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6853                        == PackageManager.SIGNATURE_MATCH;
6854            }
6855            if (!match) {
6856                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6857                        "Package " + pkg.packageName
6858                        + " has no signatures that match those in shared user "
6859                        + pkgSetting.sharedUser.name + "; ignoring!");
6860            }
6861        }
6862    }
6863
6864    /**
6865     * Enforces that only the system UID or root's UID can call a method exposed
6866     * via Binder.
6867     *
6868     * @param message used as message if SecurityException is thrown
6869     * @throws SecurityException if the caller is not system or root
6870     */
6871    private static final void enforceSystemOrRoot(String message) {
6872        final int uid = Binder.getCallingUid();
6873        if (uid != Process.SYSTEM_UID && uid != 0) {
6874            throw new SecurityException(message);
6875        }
6876    }
6877
6878    @Override
6879    public void performFstrimIfNeeded() {
6880        enforceSystemOrRoot("Only the system can request fstrim");
6881
6882        // Before everything else, see whether we need to fstrim.
6883        try {
6884            IMountService ms = PackageHelper.getMountService();
6885            if (ms != null) {
6886                final boolean isUpgrade = isUpgrade();
6887                boolean doTrim = isUpgrade;
6888                if (doTrim) {
6889                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6890                } else {
6891                    final long interval = android.provider.Settings.Global.getLong(
6892                            mContext.getContentResolver(),
6893                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6894                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6895                    if (interval > 0) {
6896                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6897                        if (timeSinceLast > interval) {
6898                            doTrim = true;
6899                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6900                                    + "; running immediately");
6901                        }
6902                    }
6903                }
6904                if (doTrim) {
6905                    if (!isFirstBoot()) {
6906                        try {
6907                            ActivityManagerNative.getDefault().showBootMessage(
6908                                    mContext.getResources().getString(
6909                                            R.string.android_upgrading_fstrim), true);
6910                        } catch (RemoteException e) {
6911                        }
6912                    }
6913                    ms.runMaintenance();
6914                }
6915            } else {
6916                Slog.e(TAG, "Mount service unavailable!");
6917            }
6918        } catch (RemoteException e) {
6919            // Can't happen; MountService is local
6920        }
6921    }
6922
6923    @Override
6924    public void updatePackagesIfNeeded() {
6925        enforceSystemOrRoot("Only the system can request package update");
6926
6927        // We need to re-extract after an OTA.
6928        boolean causeUpgrade = isUpgrade();
6929
6930        // First boot or factory reset.
6931        // Note: we also handle devices that are upgrading to N right now as if it is their
6932        //       first boot, as they do not have profile data.
6933        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
6934
6935        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
6936        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
6937
6938        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
6939            return;
6940        }
6941
6942        List<PackageParser.Package> pkgs;
6943        synchronized (mPackages) {
6944            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6945        }
6946
6947        int curr = 0;
6948        int total = pkgs.size();
6949        for (PackageParser.Package pkg : pkgs) {
6950            curr++;
6951
6952            if (DEBUG_DEXOPT) {
6953                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6954            }
6955
6956            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6957                // If the cache was pruned, any compiled odex files will likely be out of date
6958                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
6959                // Instead, force the extraction in this case.
6960                performDexOpt(pkg.packageName,
6961                        null /* instructionSet */,
6962                        false /* checkProfiles */,
6963                        causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
6964                        false /* force */);
6965            }
6966        }
6967    }
6968
6969    @Override
6970    public void notifyPackageUse(String packageName) {
6971        synchronized (mPackages) {
6972            PackageParser.Package p = mPackages.get(packageName);
6973            if (p == null) {
6974                return;
6975            }
6976            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6977        }
6978    }
6979
6980    // TODO: this is not used nor needed. Delete it.
6981    @Override
6982    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6983        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
6984                getFullCompilerFilter(), false /* force */);
6985    }
6986
6987    @Override
6988    public boolean performDexOpt(String packageName, String instructionSet,
6989            boolean checkProfiles, int compileReason, boolean force) {
6990        return performDexOptTraced(packageName, instructionSet, checkProfiles,
6991                getCompilerFilterForReason(compileReason), force);
6992    }
6993
6994    @Override
6995    public boolean performDexOptMode(String packageName, String instructionSet,
6996            boolean checkProfiles, String targetCompilerFilter, boolean force) {
6997        return performDexOptTraced(packageName, instructionSet, checkProfiles,
6998                targetCompilerFilter, force);
6999    }
7000
7001    private boolean performDexOptTraced(String packageName, String instructionSet,
7002                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7004        try {
7005            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7006                    targetCompilerFilter, force);
7007        } finally {
7008            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7009        }
7010    }
7011
7012    private boolean performDexOptInternal(String packageName, String instructionSet,
7013                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7014        PackageParser.Package p;
7015        final String targetInstructionSet;
7016        synchronized (mPackages) {
7017            p = mPackages.get(packageName);
7018            if (p == null) {
7019                return false;
7020            }
7021            mPackageUsage.write(false);
7022
7023            targetInstructionSet = instructionSet != null ? instructionSet :
7024                    getPrimaryInstructionSet(p.applicationInfo);
7025        }
7026        long callingId = Binder.clearCallingIdentity();
7027        try {
7028            synchronized (mInstallLock) {
7029                final String[] instructionSets = new String[] { targetInstructionSet };
7030                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7031                        checkProfiles, targetCompilerFilter, force);
7032                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7033            }
7034        } finally {
7035            Binder.restoreCallingIdentity(callingId);
7036        }
7037    }
7038
7039    public ArraySet<String> getOptimizablePackages() {
7040        ArraySet<String> pkgs = new ArraySet<String>();
7041        synchronized (mPackages) {
7042            for (PackageParser.Package p : mPackages.values()) {
7043                if (PackageDexOptimizer.canOptimizePackage(p)) {
7044                    pkgs.add(p.packageName);
7045                }
7046            }
7047        }
7048        return pkgs;
7049    }
7050
7051    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7052            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7053            boolean force) {
7054        // Select the dex optimizer based on the force parameter.
7055        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7056        //       allocate an object here.
7057        PackageDexOptimizer pdo = force
7058                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7059                : mPackageDexOptimizer;
7060
7061        // Optimize all dependencies first. Note: we ignore the return value and march on
7062        // on errors.
7063        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7064        if (!deps.isEmpty()) {
7065            for (PackageParser.Package depPackage : deps) {
7066                // TODO: Analyze and investigate if we (should) profile libraries.
7067                // Currently this will do a full compilation of the library by default.
7068                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7069                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7070            }
7071        }
7072
7073        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7074    }
7075
7076    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7077        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7078            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7079            Set<String> collectedNames = new HashSet<>();
7080            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7081
7082            retValue.remove(p);
7083
7084            return retValue;
7085        } else {
7086            return Collections.emptyList();
7087        }
7088    }
7089
7090    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7091            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7092        if (!collectedNames.contains(p.packageName)) {
7093            collectedNames.add(p.packageName);
7094            collected.add(p);
7095
7096            if (p.usesLibraries != null) {
7097                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7098            }
7099            if (p.usesOptionalLibraries != null) {
7100                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7101                        collectedNames);
7102            }
7103        }
7104    }
7105
7106    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7107            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7108        for (String libName : libs) {
7109            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7110            if (libPkg != null) {
7111                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7112            }
7113        }
7114    }
7115
7116    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7117        synchronized (mPackages) {
7118            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7119            if (lib != null && lib.apk != null) {
7120                return mPackages.get(lib.apk);
7121            }
7122        }
7123        return null;
7124    }
7125
7126    public void shutdown() {
7127        mPackageUsage.write(true);
7128    }
7129
7130    @Override
7131    public void forceDexOpt(String packageName) {
7132        enforceSystemOrRoot("forceDexOpt");
7133
7134        PackageParser.Package pkg;
7135        synchronized (mPackages) {
7136            pkg = mPackages.get(packageName);
7137            if (pkg == null) {
7138                throw new IllegalArgumentException("Unknown package: " + packageName);
7139            }
7140        }
7141
7142        synchronized (mInstallLock) {
7143            final String[] instructionSets = new String[] {
7144                    getPrimaryInstructionSet(pkg.applicationInfo) };
7145
7146            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7147
7148            // Whoever is calling forceDexOpt wants a fully compiled package.
7149            // Don't use profiles since that may cause compilation to be skipped.
7150            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7151                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7152                    true /* force */);
7153
7154            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7155            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7156                throw new IllegalStateException("Failed to dexopt: " + res);
7157            }
7158        }
7159    }
7160
7161    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7162        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7163            Slog.w(TAG, "Unable to update from " + oldPkg.name
7164                    + " to " + newPkg.packageName
7165                    + ": old package not in system partition");
7166            return false;
7167        } else if (mPackages.get(oldPkg.name) != null) {
7168            Slog.w(TAG, "Unable to update from " + oldPkg.name
7169                    + " to " + newPkg.packageName
7170                    + ": old package still exists");
7171            return false;
7172        }
7173        return true;
7174    }
7175
7176    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7177        // TODO: triage flags as part of 26466827
7178        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7179
7180        boolean res = true;
7181        final int[] users = sUserManager.getUserIds();
7182        for (int user : users) {
7183            try {
7184                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7185            } catch (InstallerException e) {
7186                Slog.w(TAG, "Failed to delete data directory", e);
7187                res = false;
7188            }
7189        }
7190        return res;
7191    }
7192
7193    void removeCodePathLI(File codePath) {
7194        if (codePath.isDirectory()) {
7195            try {
7196                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7197            } catch (InstallerException e) {
7198                Slog.w(TAG, "Failed to remove code path", e);
7199            }
7200        } else {
7201            codePath.delete();
7202        }
7203    }
7204
7205    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7206        try {
7207            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7208        } catch (InstallerException e) {
7209            Slog.w(TAG, "Failed to destroy app data", e);
7210        }
7211    }
7212
7213    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7214            int appId, String seinfo) {
7215        try {
7216            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7217        } catch (InstallerException e) {
7218            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7219        }
7220    }
7221
7222    private void deleteProfilesLI(String packageName, boolean destroy) {
7223        final PackageParser.Package pkg;
7224        synchronized (mPackages) {
7225            pkg = mPackages.get(packageName);
7226        }
7227        if (pkg == null) {
7228            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7229            return;
7230        }
7231        deleteProfilesLI(pkg, destroy);
7232    }
7233
7234    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7235        try {
7236            if (destroy) {
7237                mInstaller.destroyAppProfiles(pkg.packageName);
7238            } else {
7239                mInstaller.clearAppProfiles(pkg.packageName);
7240            }
7241        } catch (InstallerException ex) {
7242            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7243        }
7244    }
7245
7246    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7247        final PackageParser.Package pkg;
7248        synchronized (mPackages) {
7249            pkg = mPackages.get(packageName);
7250        }
7251        if (pkg == null) {
7252            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7253            return;
7254        }
7255        deleteCodeCacheDirsLI(pkg);
7256    }
7257
7258    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7259        // TODO: triage flags as part of 26466827
7260        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7261
7262        int[] users = sUserManager.getUserIds();
7263        int res = 0;
7264        for (int user : users) {
7265            // Remove the parent code cache
7266            try {
7267                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7268                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7269            } catch (InstallerException e) {
7270                Slog.w(TAG, "Failed to delete code cache directory", e);
7271            }
7272            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7273            for (int i = 0; i < childCount; i++) {
7274                PackageParser.Package childPkg = pkg.childPackages.get(i);
7275                // Remove the child code cache
7276                try {
7277                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7278                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7279                } catch (InstallerException e) {
7280                    Slog.w(TAG, "Failed to delete code cache directory", e);
7281                }
7282            }
7283        }
7284    }
7285
7286    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7287            long lastUpdateTime) {
7288        // Set parent install/update time
7289        PackageSetting ps = (PackageSetting) pkg.mExtras;
7290        if (ps != null) {
7291            ps.firstInstallTime = firstInstallTime;
7292            ps.lastUpdateTime = lastUpdateTime;
7293        }
7294        // Set children install/update time
7295        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7296        for (int i = 0; i < childCount; i++) {
7297            PackageParser.Package childPkg = pkg.childPackages.get(i);
7298            ps = (PackageSetting) childPkg.mExtras;
7299            if (ps != null) {
7300                ps.firstInstallTime = firstInstallTime;
7301                ps.lastUpdateTime = lastUpdateTime;
7302            }
7303        }
7304    }
7305
7306    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7307            PackageParser.Package changingLib) {
7308        if (file.path != null) {
7309            usesLibraryFiles.add(file.path);
7310            return;
7311        }
7312        PackageParser.Package p = mPackages.get(file.apk);
7313        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7314            // If we are doing this while in the middle of updating a library apk,
7315            // then we need to make sure to use that new apk for determining the
7316            // dependencies here.  (We haven't yet finished committing the new apk
7317            // to the package manager state.)
7318            if (p == null || p.packageName.equals(changingLib.packageName)) {
7319                p = changingLib;
7320            }
7321        }
7322        if (p != null) {
7323            usesLibraryFiles.addAll(p.getAllCodePaths());
7324        }
7325    }
7326
7327    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7328            PackageParser.Package changingLib) throws PackageManagerException {
7329        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7330            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7331            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7332            for (int i=0; i<N; i++) {
7333                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7334                if (file == null) {
7335                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7336                            "Package " + pkg.packageName + " requires unavailable shared library "
7337                            + pkg.usesLibraries.get(i) + "; failing!");
7338                }
7339                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7340            }
7341            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7342            for (int i=0; i<N; i++) {
7343                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7344                if (file == null) {
7345                    Slog.w(TAG, "Package " + pkg.packageName
7346                            + " desires unavailable shared library "
7347                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7348                } else {
7349                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7350                }
7351            }
7352            N = usesLibraryFiles.size();
7353            if (N > 0) {
7354                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7355            } else {
7356                pkg.usesLibraryFiles = null;
7357            }
7358        }
7359    }
7360
7361    private static boolean hasString(List<String> list, List<String> which) {
7362        if (list == null) {
7363            return false;
7364        }
7365        for (int i=list.size()-1; i>=0; i--) {
7366            for (int j=which.size()-1; j>=0; j--) {
7367                if (which.get(j).equals(list.get(i))) {
7368                    return true;
7369                }
7370            }
7371        }
7372        return false;
7373    }
7374
7375    private void updateAllSharedLibrariesLPw() {
7376        for (PackageParser.Package pkg : mPackages.values()) {
7377            try {
7378                updateSharedLibrariesLPw(pkg, null);
7379            } catch (PackageManagerException e) {
7380                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7381            }
7382        }
7383    }
7384
7385    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7386            PackageParser.Package changingPkg) {
7387        ArrayList<PackageParser.Package> res = null;
7388        for (PackageParser.Package pkg : mPackages.values()) {
7389            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7390                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7391                if (res == null) {
7392                    res = new ArrayList<PackageParser.Package>();
7393                }
7394                res.add(pkg);
7395                try {
7396                    updateSharedLibrariesLPw(pkg, changingPkg);
7397                } catch (PackageManagerException e) {
7398                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7399                }
7400            }
7401        }
7402        return res;
7403    }
7404
7405    /**
7406     * Derive the value of the {@code cpuAbiOverride} based on the provided
7407     * value and an optional stored value from the package settings.
7408     */
7409    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7410        String cpuAbiOverride = null;
7411
7412        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7413            cpuAbiOverride = null;
7414        } else if (abiOverride != null) {
7415            cpuAbiOverride = abiOverride;
7416        } else if (settings != null) {
7417            cpuAbiOverride = settings.cpuAbiOverrideString;
7418        }
7419
7420        return cpuAbiOverride;
7421    }
7422
7423    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7424            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7425        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7426        // If the package has children and this is the first dive in the function
7427        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7428        // whether all packages (parent and children) would be successfully scanned
7429        // before the actual scan since scanning mutates internal state and we want
7430        // to atomically install the package and its children.
7431        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7432            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7433                scanFlags |= SCAN_CHECK_ONLY;
7434            }
7435        } else {
7436            scanFlags &= ~SCAN_CHECK_ONLY;
7437        }
7438
7439        final PackageParser.Package scannedPkg;
7440        try {
7441            // Scan the parent
7442            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7443            // Scan the children
7444            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7445            for (int i = 0; i < childCount; i++) {
7446                PackageParser.Package childPkg = pkg.childPackages.get(i);
7447                scanPackageLI(childPkg, parseFlags,
7448                        scanFlags, currentTime, user);
7449            }
7450        } finally {
7451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7452        }
7453
7454        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7455            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7456        }
7457
7458        return scannedPkg;
7459    }
7460
7461    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7462            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7463        boolean success = false;
7464        try {
7465            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7466                    currentTime, user);
7467            success = true;
7468            return res;
7469        } finally {
7470            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7471                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7472            }
7473        }
7474    }
7475
7476    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7477            int scanFlags, long currentTime, UserHandle user)
7478            throws PackageManagerException {
7479        final File scanFile = new File(pkg.codePath);
7480        if (pkg.applicationInfo.getCodePath() == null ||
7481                pkg.applicationInfo.getResourcePath() == null) {
7482            // Bail out. The resource and code paths haven't been set.
7483            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7484                    "Code and resource paths haven't been set correctly");
7485        }
7486
7487        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7488            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7489        } else {
7490            // Only allow system apps to be flagged as core apps.
7491            pkg.coreApp = false;
7492        }
7493
7494        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7495            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7496        }
7497
7498        if (mCustomResolverComponentName != null &&
7499                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7500            setUpCustomResolverActivity(pkg);
7501        }
7502
7503        if (pkg.packageName.equals("android")) {
7504            synchronized (mPackages) {
7505                if (mAndroidApplication != null) {
7506                    Slog.w(TAG, "*************************************************");
7507                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7508                    Slog.w(TAG, " file=" + scanFile);
7509                    Slog.w(TAG, "*************************************************");
7510                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7511                            "Core android package being redefined.  Skipping.");
7512                }
7513
7514                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7515                    // Set up information for our fall-back user intent resolution activity.
7516                    mPlatformPackage = pkg;
7517                    pkg.mVersionCode = mSdkVersion;
7518                    mAndroidApplication = pkg.applicationInfo;
7519
7520                    if (!mResolverReplaced) {
7521                        mResolveActivity.applicationInfo = mAndroidApplication;
7522                        mResolveActivity.name = ResolverActivity.class.getName();
7523                        mResolveActivity.packageName = mAndroidApplication.packageName;
7524                        mResolveActivity.processName = "system:ui";
7525                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7526                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7527                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7528                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7529                        mResolveActivity.exported = true;
7530                        mResolveActivity.enabled = true;
7531                        mResolveInfo.activityInfo = mResolveActivity;
7532                        mResolveInfo.priority = 0;
7533                        mResolveInfo.preferredOrder = 0;
7534                        mResolveInfo.match = 0;
7535                        mResolveComponentName = new ComponentName(
7536                                mAndroidApplication.packageName, mResolveActivity.name);
7537                    }
7538                }
7539            }
7540        }
7541
7542        if (DEBUG_PACKAGE_SCANNING) {
7543            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7544                Log.d(TAG, "Scanning package " + pkg.packageName);
7545        }
7546
7547        synchronized (mPackages) {
7548            if (mPackages.containsKey(pkg.packageName)
7549                    || mSharedLibraries.containsKey(pkg.packageName)) {
7550                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7551                        "Application package " + pkg.packageName
7552                                + " already installed.  Skipping duplicate.");
7553            }
7554
7555            // If we're only installing presumed-existing packages, require that the
7556            // scanned APK is both already known and at the path previously established
7557            // for it.  Previously unknown packages we pick up normally, but if we have an
7558            // a priori expectation about this package's install presence, enforce it.
7559            // With a singular exception for new system packages. When an OTA contains
7560            // a new system package, we allow the codepath to change from a system location
7561            // to the user-installed location. If we don't allow this change, any newer,
7562            // user-installed version of the application will be ignored.
7563            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7564                if (mExpectingBetter.containsKey(pkg.packageName)) {
7565                    logCriticalInfo(Log.WARN,
7566                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7567                } else {
7568                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7569                    if (known != null) {
7570                        if (DEBUG_PACKAGE_SCANNING) {
7571                            Log.d(TAG, "Examining " + pkg.codePath
7572                                    + " and requiring known paths " + known.codePathString
7573                                    + " & " + known.resourcePathString);
7574                        }
7575                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7576                                || !pkg.applicationInfo.getResourcePath().equals(
7577                                known.resourcePathString)) {
7578                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7579                                    "Application package " + pkg.packageName
7580                                            + " found at " + pkg.applicationInfo.getCodePath()
7581                                            + " but expected at " + known.codePathString
7582                                            + "; ignoring.");
7583                        }
7584                    }
7585                }
7586            }
7587        }
7588
7589        // Initialize package source and resource directories
7590        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7591        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7592
7593        SharedUserSetting suid = null;
7594        PackageSetting pkgSetting = null;
7595
7596        if (!isSystemApp(pkg)) {
7597            // Only system apps can use these features.
7598            pkg.mOriginalPackages = null;
7599            pkg.mRealPackage = null;
7600            pkg.mAdoptPermissions = null;
7601        }
7602
7603        // Getting the package setting may have a side-effect, so if we
7604        // are only checking if scan would succeed, stash a copy of the
7605        // old setting to restore at the end.
7606        PackageSetting nonMutatedPs = null;
7607
7608        // writer
7609        synchronized (mPackages) {
7610            if (pkg.mSharedUserId != null) {
7611                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7612                if (suid == null) {
7613                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7614                            "Creating application package " + pkg.packageName
7615                            + " for shared user failed");
7616                }
7617                if (DEBUG_PACKAGE_SCANNING) {
7618                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7619                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7620                                + "): packages=" + suid.packages);
7621                }
7622            }
7623
7624            // Check if we are renaming from an original package name.
7625            PackageSetting origPackage = null;
7626            String realName = null;
7627            if (pkg.mOriginalPackages != null) {
7628                // This package may need to be renamed to a previously
7629                // installed name.  Let's check on that...
7630                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7631                if (pkg.mOriginalPackages.contains(renamed)) {
7632                    // This package had originally been installed as the
7633                    // original name, and we have already taken care of
7634                    // transitioning to the new one.  Just update the new
7635                    // one to continue using the old name.
7636                    realName = pkg.mRealPackage;
7637                    if (!pkg.packageName.equals(renamed)) {
7638                        // Callers into this function may have already taken
7639                        // care of renaming the package; only do it here if
7640                        // it is not already done.
7641                        pkg.setPackageName(renamed);
7642                    }
7643
7644                } else {
7645                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7646                        if ((origPackage = mSettings.peekPackageLPr(
7647                                pkg.mOriginalPackages.get(i))) != null) {
7648                            // We do have the package already installed under its
7649                            // original name...  should we use it?
7650                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7651                                // New package is not compatible with original.
7652                                origPackage = null;
7653                                continue;
7654                            } else if (origPackage.sharedUser != null) {
7655                                // Make sure uid is compatible between packages.
7656                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7657                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7658                                            + " to " + pkg.packageName + ": old uid "
7659                                            + origPackage.sharedUser.name
7660                                            + " differs from " + pkg.mSharedUserId);
7661                                    origPackage = null;
7662                                    continue;
7663                                }
7664                            } else {
7665                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7666                                        + pkg.packageName + " to old name " + origPackage.name);
7667                            }
7668                            break;
7669                        }
7670                    }
7671                }
7672            }
7673
7674            if (mTransferedPackages.contains(pkg.packageName)) {
7675                Slog.w(TAG, "Package " + pkg.packageName
7676                        + " was transferred to another, but its .apk remains");
7677            }
7678
7679            // See comments in nonMutatedPs declaration
7680            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7681                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7682                if (foundPs != null) {
7683                    nonMutatedPs = new PackageSetting(foundPs);
7684                }
7685            }
7686
7687            // Just create the setting, don't add it yet. For already existing packages
7688            // the PkgSetting exists already and doesn't have to be created.
7689            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7690                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7691                    pkg.applicationInfo.primaryCpuAbi,
7692                    pkg.applicationInfo.secondaryCpuAbi,
7693                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7694                    user, false);
7695            if (pkgSetting == null) {
7696                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7697                        "Creating application package " + pkg.packageName + " failed");
7698            }
7699
7700            if (pkgSetting.origPackage != null) {
7701                // If we are first transitioning from an original package,
7702                // fix up the new package's name now.  We need to do this after
7703                // looking up the package under its new name, so getPackageLP
7704                // can take care of fiddling things correctly.
7705                pkg.setPackageName(origPackage.name);
7706
7707                // File a report about this.
7708                String msg = "New package " + pkgSetting.realName
7709                        + " renamed to replace old package " + pkgSetting.name;
7710                reportSettingsProblem(Log.WARN, msg);
7711
7712                // Make a note of it.
7713                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7714                    mTransferedPackages.add(origPackage.name);
7715                }
7716
7717                // No longer need to retain this.
7718                pkgSetting.origPackage = null;
7719            }
7720
7721            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7722                // Make a note of it.
7723                mTransferedPackages.add(pkg.packageName);
7724            }
7725
7726            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7727                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7728            }
7729
7730            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7731                // Check all shared libraries and map to their actual file path.
7732                // We only do this here for apps not on a system dir, because those
7733                // are the only ones that can fail an install due to this.  We
7734                // will take care of the system apps by updating all of their
7735                // library paths after the scan is done.
7736                updateSharedLibrariesLPw(pkg, null);
7737            }
7738
7739            if (mFoundPolicyFile) {
7740                SELinuxMMAC.assignSeinfoValue(pkg);
7741            }
7742
7743            pkg.applicationInfo.uid = pkgSetting.appId;
7744            pkg.mExtras = pkgSetting;
7745            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7746                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7747                    // We just determined the app is signed correctly, so bring
7748                    // over the latest parsed certs.
7749                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7750                } else {
7751                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7752                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7753                                "Package " + pkg.packageName + " upgrade keys do not match the "
7754                                + "previously installed version");
7755                    } else {
7756                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7757                        String msg = "System package " + pkg.packageName
7758                            + " signature changed; retaining data.";
7759                        reportSettingsProblem(Log.WARN, msg);
7760                    }
7761                }
7762            } else {
7763                try {
7764                    verifySignaturesLP(pkgSetting, pkg);
7765                    // We just determined the app is signed correctly, so bring
7766                    // over the latest parsed certs.
7767                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7768                } catch (PackageManagerException e) {
7769                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7770                        throw e;
7771                    }
7772                    // The signature has changed, but this package is in the system
7773                    // image...  let's recover!
7774                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7775                    // However...  if this package is part of a shared user, but it
7776                    // doesn't match the signature of the shared user, let's fail.
7777                    // What this means is that you can't change the signatures
7778                    // associated with an overall shared user, which doesn't seem all
7779                    // that unreasonable.
7780                    if (pkgSetting.sharedUser != null) {
7781                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7782                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7783                            throw new PackageManagerException(
7784                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7785                                            "Signature mismatch for shared user: "
7786                                            + pkgSetting.sharedUser);
7787                        }
7788                    }
7789                    // File a report about this.
7790                    String msg = "System package " + pkg.packageName
7791                        + " signature changed; retaining data.";
7792                    reportSettingsProblem(Log.WARN, msg);
7793                }
7794            }
7795            // Verify that this new package doesn't have any content providers
7796            // that conflict with existing packages.  Only do this if the
7797            // package isn't already installed, since we don't want to break
7798            // things that are installed.
7799            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7800                final int N = pkg.providers.size();
7801                int i;
7802                for (i=0; i<N; i++) {
7803                    PackageParser.Provider p = pkg.providers.get(i);
7804                    if (p.info.authority != null) {
7805                        String names[] = p.info.authority.split(";");
7806                        for (int j = 0; j < names.length; j++) {
7807                            if (mProvidersByAuthority.containsKey(names[j])) {
7808                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7809                                final String otherPackageName =
7810                                        ((other != null && other.getComponentName() != null) ?
7811                                                other.getComponentName().getPackageName() : "?");
7812                                throw new PackageManagerException(
7813                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7814                                                "Can't install because provider name " + names[j]
7815                                                + " (in package " + pkg.applicationInfo.packageName
7816                                                + ") is already used by " + otherPackageName);
7817                            }
7818                        }
7819                    }
7820                }
7821            }
7822
7823            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7824                // This package wants to adopt ownership of permissions from
7825                // another package.
7826                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7827                    final String origName = pkg.mAdoptPermissions.get(i);
7828                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7829                    if (orig != null) {
7830                        if (verifyPackageUpdateLPr(orig, pkg)) {
7831                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7832                                    + pkg.packageName);
7833                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7834                        }
7835                    }
7836                }
7837            }
7838        }
7839
7840        final String pkgName = pkg.packageName;
7841
7842        final long scanFileTime = scanFile.lastModified();
7843        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7844        pkg.applicationInfo.processName = fixProcessName(
7845                pkg.applicationInfo.packageName,
7846                pkg.applicationInfo.processName,
7847                pkg.applicationInfo.uid);
7848
7849        if (pkg != mPlatformPackage) {
7850            // Get all of our default paths setup
7851            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7852        }
7853
7854        final String path = scanFile.getPath();
7855        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7856
7857        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7858            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7859
7860            // Some system apps still use directory structure for native libraries
7861            // in which case we might end up not detecting abi solely based on apk
7862            // structure. Try to detect abi based on directory structure.
7863            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7864                    pkg.applicationInfo.primaryCpuAbi == null) {
7865                setBundledAppAbisAndRoots(pkg, pkgSetting);
7866                setNativeLibraryPaths(pkg);
7867            }
7868
7869        } else {
7870            if ((scanFlags & SCAN_MOVE) != 0) {
7871                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7872                // but we already have this packages package info in the PackageSetting. We just
7873                // use that and derive the native library path based on the new codepath.
7874                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7875                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7876            }
7877
7878            // Set native library paths again. For moves, the path will be updated based on the
7879            // ABIs we've determined above. For non-moves, the path will be updated based on the
7880            // ABIs we determined during compilation, but the path will depend on the final
7881            // package path (after the rename away from the stage path).
7882            setNativeLibraryPaths(pkg);
7883        }
7884
7885        // This is a special case for the "system" package, where the ABI is
7886        // dictated by the zygote configuration (and init.rc). We should keep track
7887        // of this ABI so that we can deal with "normal" applications that run under
7888        // the same UID correctly.
7889        if (mPlatformPackage == pkg) {
7890            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7891                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7892        }
7893
7894        // If there's a mismatch between the abi-override in the package setting
7895        // and the abiOverride specified for the install. Warn about this because we
7896        // would've already compiled the app without taking the package setting into
7897        // account.
7898        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7899            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7900                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7901                        " for package " + pkg.packageName);
7902            }
7903        }
7904
7905        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7906        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7907        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7908
7909        // Copy the derived override back to the parsed package, so that we can
7910        // update the package settings accordingly.
7911        pkg.cpuAbiOverride = cpuAbiOverride;
7912
7913        if (DEBUG_ABI_SELECTION) {
7914            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7915                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7916                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7917        }
7918
7919        // Push the derived path down into PackageSettings so we know what to
7920        // clean up at uninstall time.
7921        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7922
7923        if (DEBUG_ABI_SELECTION) {
7924            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7925                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7926                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7927        }
7928
7929        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7930            // We don't do this here during boot because we can do it all
7931            // at once after scanning all existing packages.
7932            //
7933            // We also do this *before* we perform dexopt on this package, so that
7934            // we can avoid redundant dexopts, and also to make sure we've got the
7935            // code and package path correct.
7936            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7937                    pkg, true /* boot complete */);
7938        }
7939
7940        if (mFactoryTest && pkg.requestedPermissions.contains(
7941                android.Manifest.permission.FACTORY_TEST)) {
7942            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7943        }
7944
7945        ArrayList<PackageParser.Package> clientLibPkgs = null;
7946
7947        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7948            if (nonMutatedPs != null) {
7949                synchronized (mPackages) {
7950                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7951                }
7952            }
7953            return pkg;
7954        }
7955
7956        // Only privileged apps and updated privileged apps can add child packages.
7957        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7958            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7959                throw new PackageManagerException("Only privileged apps and updated "
7960                        + "privileged apps can add child packages. Ignoring package "
7961                        + pkg.packageName);
7962            }
7963            final int childCount = pkg.childPackages.size();
7964            for (int i = 0; i < childCount; i++) {
7965                PackageParser.Package childPkg = pkg.childPackages.get(i);
7966                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7967                        childPkg.packageName)) {
7968                    throw new PackageManagerException("Cannot override a child package of "
7969                            + "another disabled system app. Ignoring package " + pkg.packageName);
7970                }
7971            }
7972        }
7973
7974        // writer
7975        synchronized (mPackages) {
7976            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7977                // Only system apps can add new shared libraries.
7978                if (pkg.libraryNames != null) {
7979                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7980                        String name = pkg.libraryNames.get(i);
7981                        boolean allowed = false;
7982                        if (pkg.isUpdatedSystemApp()) {
7983                            // New library entries can only be added through the
7984                            // system image.  This is important to get rid of a lot
7985                            // of nasty edge cases: for example if we allowed a non-
7986                            // system update of the app to add a library, then uninstalling
7987                            // the update would make the library go away, and assumptions
7988                            // we made such as through app install filtering would now
7989                            // have allowed apps on the device which aren't compatible
7990                            // with it.  Better to just have the restriction here, be
7991                            // conservative, and create many fewer cases that can negatively
7992                            // impact the user experience.
7993                            final PackageSetting sysPs = mSettings
7994                                    .getDisabledSystemPkgLPr(pkg.packageName);
7995                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7996                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7997                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7998                                        allowed = true;
7999                                        break;
8000                                    }
8001                                }
8002                            }
8003                        } else {
8004                            allowed = true;
8005                        }
8006                        if (allowed) {
8007                            if (!mSharedLibraries.containsKey(name)) {
8008                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8009                            } else if (!name.equals(pkg.packageName)) {
8010                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8011                                        + name + " already exists; skipping");
8012                            }
8013                        } else {
8014                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8015                                    + name + " that is not declared on system image; skipping");
8016                        }
8017                    }
8018                    if ((scanFlags & SCAN_BOOTING) == 0) {
8019                        // If we are not booting, we need to update any applications
8020                        // that are clients of our shared library.  If we are booting,
8021                        // this will all be done once the scan is complete.
8022                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8023                    }
8024                }
8025            }
8026        }
8027
8028        // Request the ActivityManager to kill the process(only for existing packages)
8029        // so that we do not end up in a confused state while the user is still using the older
8030        // version of the application while the new one gets installed.
8031        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8032        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8033        if (killApp) {
8034            if (isReplacing) {
8035                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8036
8037                killApplication(pkg.applicationInfo.packageName,
8038                            pkg.applicationInfo.uid, "replace pkg");
8039
8040                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8041            }
8042        }
8043
8044        // Also need to kill any apps that are dependent on the library.
8045        if (clientLibPkgs != null) {
8046            for (int i=0; i<clientLibPkgs.size(); i++) {
8047                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8048                killApplication(clientPkg.applicationInfo.packageName,
8049                        clientPkg.applicationInfo.uid, "update lib");
8050            }
8051        }
8052
8053        // Make sure we're not adding any bogus keyset info
8054        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8055        ksms.assertScannedPackageValid(pkg);
8056
8057        // writer
8058        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8059
8060        boolean createIdmapFailed = false;
8061        synchronized (mPackages) {
8062            // We don't expect installation to fail beyond this point
8063
8064            // Add the new setting to mSettings
8065            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8066            // Add the new setting to mPackages
8067            mPackages.put(pkg.applicationInfo.packageName, pkg);
8068            // Make sure we don't accidentally delete its data.
8069            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8070            while (iter.hasNext()) {
8071                PackageCleanItem item = iter.next();
8072                if (pkgName.equals(item.packageName)) {
8073                    iter.remove();
8074                }
8075            }
8076
8077            // Take care of first install / last update times.
8078            if (currentTime != 0) {
8079                if (pkgSetting.firstInstallTime == 0) {
8080                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8081                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8082                    pkgSetting.lastUpdateTime = currentTime;
8083                }
8084            } else if (pkgSetting.firstInstallTime == 0) {
8085                // We need *something*.  Take time time stamp of the file.
8086                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8087            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8088                if (scanFileTime != pkgSetting.timeStamp) {
8089                    // A package on the system image has changed; consider this
8090                    // to be an update.
8091                    pkgSetting.lastUpdateTime = scanFileTime;
8092                }
8093            }
8094
8095            // Add the package's KeySets to the global KeySetManagerService
8096            ksms.addScannedPackageLPw(pkg);
8097
8098            int N = pkg.providers.size();
8099            StringBuilder r = null;
8100            int i;
8101            for (i=0; i<N; i++) {
8102                PackageParser.Provider p = pkg.providers.get(i);
8103                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8104                        p.info.processName, pkg.applicationInfo.uid);
8105                mProviders.addProvider(p);
8106                p.syncable = p.info.isSyncable;
8107                if (p.info.authority != null) {
8108                    String names[] = p.info.authority.split(";");
8109                    p.info.authority = null;
8110                    for (int j = 0; j < names.length; j++) {
8111                        if (j == 1 && p.syncable) {
8112                            // We only want the first authority for a provider to possibly be
8113                            // syncable, so if we already added this provider using a different
8114                            // authority clear the syncable flag. We copy the provider before
8115                            // changing it because the mProviders object contains a reference
8116                            // to a provider that we don't want to change.
8117                            // Only do this for the second authority since the resulting provider
8118                            // object can be the same for all future authorities for this provider.
8119                            p = new PackageParser.Provider(p);
8120                            p.syncable = false;
8121                        }
8122                        if (!mProvidersByAuthority.containsKey(names[j])) {
8123                            mProvidersByAuthority.put(names[j], p);
8124                            if (p.info.authority == null) {
8125                                p.info.authority = names[j];
8126                            } else {
8127                                p.info.authority = p.info.authority + ";" + names[j];
8128                            }
8129                            if (DEBUG_PACKAGE_SCANNING) {
8130                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8131                                    Log.d(TAG, "Registered content provider: " + names[j]
8132                                            + ", className = " + p.info.name + ", isSyncable = "
8133                                            + p.info.isSyncable);
8134                            }
8135                        } else {
8136                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8137                            Slog.w(TAG, "Skipping provider name " + names[j] +
8138                                    " (in package " + pkg.applicationInfo.packageName +
8139                                    "): name already used by "
8140                                    + ((other != null && other.getComponentName() != null)
8141                                            ? other.getComponentName().getPackageName() : "?"));
8142                        }
8143                    }
8144                }
8145                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8146                    if (r == null) {
8147                        r = new StringBuilder(256);
8148                    } else {
8149                        r.append(' ');
8150                    }
8151                    r.append(p.info.name);
8152                }
8153            }
8154            if (r != null) {
8155                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8156            }
8157
8158            N = pkg.services.size();
8159            r = null;
8160            for (i=0; i<N; i++) {
8161                PackageParser.Service s = pkg.services.get(i);
8162                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8163                        s.info.processName, pkg.applicationInfo.uid);
8164                mServices.addService(s);
8165                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8166                    if (r == null) {
8167                        r = new StringBuilder(256);
8168                    } else {
8169                        r.append(' ');
8170                    }
8171                    r.append(s.info.name);
8172                }
8173            }
8174            if (r != null) {
8175                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8176            }
8177
8178            N = pkg.receivers.size();
8179            r = null;
8180            for (i=0; i<N; i++) {
8181                PackageParser.Activity a = pkg.receivers.get(i);
8182                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8183                        a.info.processName, pkg.applicationInfo.uid);
8184                mReceivers.addActivity(a, "receiver");
8185                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8186                    if (r == null) {
8187                        r = new StringBuilder(256);
8188                    } else {
8189                        r.append(' ');
8190                    }
8191                    r.append(a.info.name);
8192                }
8193            }
8194            if (r != null) {
8195                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8196            }
8197
8198            N = pkg.activities.size();
8199            r = null;
8200            for (i=0; i<N; i++) {
8201                PackageParser.Activity a = pkg.activities.get(i);
8202                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8203                        a.info.processName, pkg.applicationInfo.uid);
8204                mActivities.addActivity(a, "activity");
8205                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8206                    if (r == null) {
8207                        r = new StringBuilder(256);
8208                    } else {
8209                        r.append(' ');
8210                    }
8211                    r.append(a.info.name);
8212                }
8213            }
8214            if (r != null) {
8215                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8216            }
8217
8218            N = pkg.permissionGroups.size();
8219            r = null;
8220            for (i=0; i<N; i++) {
8221                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8222                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8223                if (cur == null) {
8224                    mPermissionGroups.put(pg.info.name, pg);
8225                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8226                        if (r == null) {
8227                            r = new StringBuilder(256);
8228                        } else {
8229                            r.append(' ');
8230                        }
8231                        r.append(pg.info.name);
8232                    }
8233                } else {
8234                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8235                            + pg.info.packageName + " ignored: original from "
8236                            + cur.info.packageName);
8237                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8238                        if (r == null) {
8239                            r = new StringBuilder(256);
8240                        } else {
8241                            r.append(' ');
8242                        }
8243                        r.append("DUP:");
8244                        r.append(pg.info.name);
8245                    }
8246                }
8247            }
8248            if (r != null) {
8249                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8250            }
8251
8252            N = pkg.permissions.size();
8253            r = null;
8254            for (i=0; i<N; i++) {
8255                PackageParser.Permission p = pkg.permissions.get(i);
8256
8257                // Assume by default that we did not install this permission into the system.
8258                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8259
8260                // Now that permission groups have a special meaning, we ignore permission
8261                // groups for legacy apps to prevent unexpected behavior. In particular,
8262                // permissions for one app being granted to someone just becase they happen
8263                // to be in a group defined by another app (before this had no implications).
8264                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8265                    p.group = mPermissionGroups.get(p.info.group);
8266                    // Warn for a permission in an unknown group.
8267                    if (p.info.group != null && p.group == null) {
8268                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8269                                + p.info.packageName + " in an unknown group " + p.info.group);
8270                    }
8271                }
8272
8273                ArrayMap<String, BasePermission> permissionMap =
8274                        p.tree ? mSettings.mPermissionTrees
8275                                : mSettings.mPermissions;
8276                BasePermission bp = permissionMap.get(p.info.name);
8277
8278                // Allow system apps to redefine non-system permissions
8279                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8280                    final boolean currentOwnerIsSystem = (bp.perm != null
8281                            && isSystemApp(bp.perm.owner));
8282                    if (isSystemApp(p.owner)) {
8283                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8284                            // It's a built-in permission and no owner, take ownership now
8285                            bp.packageSetting = pkgSetting;
8286                            bp.perm = p;
8287                            bp.uid = pkg.applicationInfo.uid;
8288                            bp.sourcePackage = p.info.packageName;
8289                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8290                        } else if (!currentOwnerIsSystem) {
8291                            String msg = "New decl " + p.owner + " of permission  "
8292                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8293                            reportSettingsProblem(Log.WARN, msg);
8294                            bp = null;
8295                        }
8296                    }
8297                }
8298
8299                if (bp == null) {
8300                    bp = new BasePermission(p.info.name, p.info.packageName,
8301                            BasePermission.TYPE_NORMAL);
8302                    permissionMap.put(p.info.name, bp);
8303                }
8304
8305                if (bp.perm == null) {
8306                    if (bp.sourcePackage == null
8307                            || bp.sourcePackage.equals(p.info.packageName)) {
8308                        BasePermission tree = findPermissionTreeLP(p.info.name);
8309                        if (tree == null
8310                                || tree.sourcePackage.equals(p.info.packageName)) {
8311                            bp.packageSetting = pkgSetting;
8312                            bp.perm = p;
8313                            bp.uid = pkg.applicationInfo.uid;
8314                            bp.sourcePackage = p.info.packageName;
8315                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8316                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8317                                if (r == null) {
8318                                    r = new StringBuilder(256);
8319                                } else {
8320                                    r.append(' ');
8321                                }
8322                                r.append(p.info.name);
8323                            }
8324                        } else {
8325                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8326                                    + p.info.packageName + " ignored: base tree "
8327                                    + tree.name + " is from package "
8328                                    + tree.sourcePackage);
8329                        }
8330                    } else {
8331                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8332                                + p.info.packageName + " ignored: original from "
8333                                + bp.sourcePackage);
8334                    }
8335                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8336                    if (r == null) {
8337                        r = new StringBuilder(256);
8338                    } else {
8339                        r.append(' ');
8340                    }
8341                    r.append("DUP:");
8342                    r.append(p.info.name);
8343                }
8344                if (bp.perm == p) {
8345                    bp.protectionLevel = p.info.protectionLevel;
8346                }
8347            }
8348
8349            if (r != null) {
8350                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8351            }
8352
8353            N = pkg.instrumentation.size();
8354            r = null;
8355            for (i=0; i<N; i++) {
8356                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8357                a.info.packageName = pkg.applicationInfo.packageName;
8358                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8359                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8360                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8361                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8362                a.info.dataDir = pkg.applicationInfo.dataDir;
8363                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8364                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8365
8366                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8367                // need other information about the application, like the ABI and what not ?
8368                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8369                mInstrumentation.put(a.getComponentName(), a);
8370                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8371                    if (r == null) {
8372                        r = new StringBuilder(256);
8373                    } else {
8374                        r.append(' ');
8375                    }
8376                    r.append(a.info.name);
8377                }
8378            }
8379            if (r != null) {
8380                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8381            }
8382
8383            if (pkg.protectedBroadcasts != null) {
8384                N = pkg.protectedBroadcasts.size();
8385                for (i=0; i<N; i++) {
8386                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8387                }
8388            }
8389
8390            pkgSetting.setTimeStamp(scanFileTime);
8391
8392            // Create idmap files for pairs of (packages, overlay packages).
8393            // Note: "android", ie framework-res.apk, is handled by native layers.
8394            if (pkg.mOverlayTarget != null) {
8395                // This is an overlay package.
8396                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8397                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8398                        mOverlays.put(pkg.mOverlayTarget,
8399                                new ArrayMap<String, PackageParser.Package>());
8400                    }
8401                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8402                    map.put(pkg.packageName, pkg);
8403                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8404                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8405                        createIdmapFailed = true;
8406                    }
8407                }
8408            } else if (mOverlays.containsKey(pkg.packageName) &&
8409                    !pkg.packageName.equals("android")) {
8410                // This is a regular package, with one or more known overlay packages.
8411                createIdmapsForPackageLI(pkg);
8412            }
8413        }
8414
8415        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8416
8417        if (createIdmapFailed) {
8418            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8419                    "scanPackageLI failed to createIdmap");
8420        }
8421        return pkg;
8422    }
8423
8424    /**
8425     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8426     * is derived purely on the basis of the contents of {@code scanFile} and
8427     * {@code cpuAbiOverride}.
8428     *
8429     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8430     */
8431    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8432                                 String cpuAbiOverride, boolean extractLibs)
8433            throws PackageManagerException {
8434        // TODO: We can probably be smarter about this stuff. For installed apps,
8435        // we can calculate this information at install time once and for all. For
8436        // system apps, we can probably assume that this information doesn't change
8437        // after the first boot scan. As things stand, we do lots of unnecessary work.
8438
8439        // Give ourselves some initial paths; we'll come back for another
8440        // pass once we've determined ABI below.
8441        setNativeLibraryPaths(pkg);
8442
8443        // We would never need to extract libs for forward-locked and external packages,
8444        // since the container service will do it for us. We shouldn't attempt to
8445        // extract libs from system app when it was not updated.
8446        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8447                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8448            extractLibs = false;
8449        }
8450
8451        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8452        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8453
8454        NativeLibraryHelper.Handle handle = null;
8455        try {
8456            handle = NativeLibraryHelper.Handle.create(pkg);
8457            // TODO(multiArch): This can be null for apps that didn't go through the
8458            // usual installation process. We can calculate it again, like we
8459            // do during install time.
8460            //
8461            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8462            // unnecessary.
8463            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8464
8465            // Null out the abis so that they can be recalculated.
8466            pkg.applicationInfo.primaryCpuAbi = null;
8467            pkg.applicationInfo.secondaryCpuAbi = null;
8468            if (isMultiArch(pkg.applicationInfo)) {
8469                // Warn if we've set an abiOverride for multi-lib packages..
8470                // By definition, we need to copy both 32 and 64 bit libraries for
8471                // such packages.
8472                if (pkg.cpuAbiOverride != null
8473                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8474                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8475                }
8476
8477                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8478                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8479                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8480                    if (extractLibs) {
8481                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8482                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8483                                useIsaSpecificSubdirs);
8484                    } else {
8485                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8486                    }
8487                }
8488
8489                maybeThrowExceptionForMultiArchCopy(
8490                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8491
8492                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8493                    if (extractLibs) {
8494                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8495                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8496                                useIsaSpecificSubdirs);
8497                    } else {
8498                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8499                    }
8500                }
8501
8502                maybeThrowExceptionForMultiArchCopy(
8503                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8504
8505                if (abi64 >= 0) {
8506                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8507                }
8508
8509                if (abi32 >= 0) {
8510                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8511                    if (abi64 >= 0) {
8512                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8513                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8514                            pkg.applicationInfo.primaryCpuAbi = abi;
8515                        } else {
8516                            pkg.applicationInfo.secondaryCpuAbi = abi;
8517                        }
8518                    } else {
8519                        pkg.applicationInfo.primaryCpuAbi = abi;
8520                    }
8521                }
8522
8523            } else {
8524                String[] abiList = (cpuAbiOverride != null) ?
8525                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8526
8527                // Enable gross and lame hacks for apps that are built with old
8528                // SDK tools. We must scan their APKs for renderscript bitcode and
8529                // not launch them if it's present. Don't bother checking on devices
8530                // that don't have 64 bit support.
8531                boolean needsRenderScriptOverride = false;
8532                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8533                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8534                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8535                    needsRenderScriptOverride = true;
8536                }
8537
8538                final int copyRet;
8539                if (extractLibs) {
8540                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8541                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8542                } else {
8543                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8544                }
8545
8546                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8547                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8548                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8549                }
8550
8551                if (copyRet >= 0) {
8552                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8553                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8554                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8555                } else if (needsRenderScriptOverride) {
8556                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8557                }
8558            }
8559        } catch (IOException ioe) {
8560            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8561        } finally {
8562            IoUtils.closeQuietly(handle);
8563        }
8564
8565        // Now that we've calculated the ABIs and determined if it's an internal app,
8566        // we will go ahead and populate the nativeLibraryPath.
8567        setNativeLibraryPaths(pkg);
8568    }
8569
8570    /**
8571     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8572     * i.e, so that all packages can be run inside a single process if required.
8573     *
8574     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8575     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8576     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8577     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8578     * updating a package that belongs to a shared user.
8579     *
8580     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8581     * adds unnecessary complexity.
8582     */
8583    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8584            PackageParser.Package scannedPackage, boolean bootComplete) {
8585        String requiredInstructionSet = null;
8586        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8587            requiredInstructionSet = VMRuntime.getInstructionSet(
8588                     scannedPackage.applicationInfo.primaryCpuAbi);
8589        }
8590
8591        PackageSetting requirer = null;
8592        for (PackageSetting ps : packagesForUser) {
8593            // If packagesForUser contains scannedPackage, we skip it. This will happen
8594            // when scannedPackage is an update of an existing package. Without this check,
8595            // we will never be able to change the ABI of any package belonging to a shared
8596            // user, even if it's compatible with other packages.
8597            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8598                if (ps.primaryCpuAbiString == null) {
8599                    continue;
8600                }
8601
8602                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8603                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8604                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8605                    // this but there's not much we can do.
8606                    String errorMessage = "Instruction set mismatch, "
8607                            + ((requirer == null) ? "[caller]" : requirer)
8608                            + " requires " + requiredInstructionSet + " whereas " + ps
8609                            + " requires " + instructionSet;
8610                    Slog.w(TAG, errorMessage);
8611                }
8612
8613                if (requiredInstructionSet == null) {
8614                    requiredInstructionSet = instructionSet;
8615                    requirer = ps;
8616                }
8617            }
8618        }
8619
8620        if (requiredInstructionSet != null) {
8621            String adjustedAbi;
8622            if (requirer != null) {
8623                // requirer != null implies that either scannedPackage was null or that scannedPackage
8624                // did not require an ABI, in which case we have to adjust scannedPackage to match
8625                // the ABI of the set (which is the same as requirer's ABI)
8626                adjustedAbi = requirer.primaryCpuAbiString;
8627                if (scannedPackage != null) {
8628                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8629                }
8630            } else {
8631                // requirer == null implies that we're updating all ABIs in the set to
8632                // match scannedPackage.
8633                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8634            }
8635
8636            for (PackageSetting ps : packagesForUser) {
8637                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8638                    if (ps.primaryCpuAbiString != null) {
8639                        continue;
8640                    }
8641
8642                    ps.primaryCpuAbiString = adjustedAbi;
8643                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8644                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8645                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8646                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8647                                + " (requirer="
8648                                + (requirer == null ? "null" : requirer.pkg.packageName)
8649                                + ", scannedPackage="
8650                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8651                                + ")");
8652                        try {
8653                            mInstaller.rmdex(ps.codePathString,
8654                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8655                        } catch (InstallerException ignored) {
8656                        }
8657                    }
8658                }
8659            }
8660        }
8661    }
8662
8663    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8664        synchronized (mPackages) {
8665            mResolverReplaced = true;
8666            // Set up information for custom user intent resolution activity.
8667            mResolveActivity.applicationInfo = pkg.applicationInfo;
8668            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8669            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8670            mResolveActivity.processName = pkg.applicationInfo.packageName;
8671            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8672            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8673                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8674            mResolveActivity.theme = 0;
8675            mResolveActivity.exported = true;
8676            mResolveActivity.enabled = true;
8677            mResolveInfo.activityInfo = mResolveActivity;
8678            mResolveInfo.priority = 0;
8679            mResolveInfo.preferredOrder = 0;
8680            mResolveInfo.match = 0;
8681            mResolveComponentName = mCustomResolverComponentName;
8682            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8683                    mResolveComponentName);
8684        }
8685    }
8686
8687    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8688        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8689
8690        // Set up information for ephemeral installer activity
8691        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8692        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8693        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8694        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8695        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8696        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8697                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8698        mEphemeralInstallerActivity.theme = 0;
8699        mEphemeralInstallerActivity.exported = true;
8700        mEphemeralInstallerActivity.enabled = true;
8701        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8702        mEphemeralInstallerInfo.priority = 0;
8703        mEphemeralInstallerInfo.preferredOrder = 0;
8704        mEphemeralInstallerInfo.match = 0;
8705
8706        if (DEBUG_EPHEMERAL) {
8707            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8708        }
8709    }
8710
8711    private static String calculateBundledApkRoot(final String codePathString) {
8712        final File codePath = new File(codePathString);
8713        final File codeRoot;
8714        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8715            codeRoot = Environment.getRootDirectory();
8716        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8717            codeRoot = Environment.getOemDirectory();
8718        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8719            codeRoot = Environment.getVendorDirectory();
8720        } else {
8721            // Unrecognized code path; take its top real segment as the apk root:
8722            // e.g. /something/app/blah.apk => /something
8723            try {
8724                File f = codePath.getCanonicalFile();
8725                File parent = f.getParentFile();    // non-null because codePath is a file
8726                File tmp;
8727                while ((tmp = parent.getParentFile()) != null) {
8728                    f = parent;
8729                    parent = tmp;
8730                }
8731                codeRoot = f;
8732                Slog.w(TAG, "Unrecognized code path "
8733                        + codePath + " - using " + codeRoot);
8734            } catch (IOException e) {
8735                // Can't canonicalize the code path -- shenanigans?
8736                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8737                return Environment.getRootDirectory().getPath();
8738            }
8739        }
8740        return codeRoot.getPath();
8741    }
8742
8743    /**
8744     * Derive and set the location of native libraries for the given package,
8745     * which varies depending on where and how the package was installed.
8746     */
8747    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8748        final ApplicationInfo info = pkg.applicationInfo;
8749        final String codePath = pkg.codePath;
8750        final File codeFile = new File(codePath);
8751        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8752        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8753
8754        info.nativeLibraryRootDir = null;
8755        info.nativeLibraryRootRequiresIsa = false;
8756        info.nativeLibraryDir = null;
8757        info.secondaryNativeLibraryDir = null;
8758
8759        if (isApkFile(codeFile)) {
8760            // Monolithic install
8761            if (bundledApp) {
8762                // If "/system/lib64/apkname" exists, assume that is the per-package
8763                // native library directory to use; otherwise use "/system/lib/apkname".
8764                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8765                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8766                        getPrimaryInstructionSet(info));
8767
8768                // This is a bundled system app so choose the path based on the ABI.
8769                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8770                // is just the default path.
8771                final String apkName = deriveCodePathName(codePath);
8772                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8773                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8774                        apkName).getAbsolutePath();
8775
8776                if (info.secondaryCpuAbi != null) {
8777                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8778                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8779                            secondaryLibDir, apkName).getAbsolutePath();
8780                }
8781            } else if (asecApp) {
8782                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8783                        .getAbsolutePath();
8784            } else {
8785                final String apkName = deriveCodePathName(codePath);
8786                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8787                        .getAbsolutePath();
8788            }
8789
8790            info.nativeLibraryRootRequiresIsa = false;
8791            info.nativeLibraryDir = info.nativeLibraryRootDir;
8792        } else {
8793            // Cluster install
8794            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8795            info.nativeLibraryRootRequiresIsa = true;
8796
8797            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8798                    getPrimaryInstructionSet(info)).getAbsolutePath();
8799
8800            if (info.secondaryCpuAbi != null) {
8801                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8802                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8803            }
8804        }
8805    }
8806
8807    /**
8808     * Calculate the abis and roots for a bundled app. These can uniquely
8809     * be determined from the contents of the system partition, i.e whether
8810     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8811     * of this information, and instead assume that the system was built
8812     * sensibly.
8813     */
8814    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8815                                           PackageSetting pkgSetting) {
8816        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8817
8818        // If "/system/lib64/apkname" exists, assume that is the per-package
8819        // native library directory to use; otherwise use "/system/lib/apkname".
8820        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8821        setBundledAppAbi(pkg, apkRoot, apkName);
8822        // pkgSetting might be null during rescan following uninstall of updates
8823        // to a bundled app, so accommodate that possibility.  The settings in
8824        // that case will be established later from the parsed package.
8825        //
8826        // If the settings aren't null, sync them up with what we've just derived.
8827        // note that apkRoot isn't stored in the package settings.
8828        if (pkgSetting != null) {
8829            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8830            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8831        }
8832    }
8833
8834    /**
8835     * Deduces the ABI of a bundled app and sets the relevant fields on the
8836     * parsed pkg object.
8837     *
8838     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8839     *        under which system libraries are installed.
8840     * @param apkName the name of the installed package.
8841     */
8842    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8843        final File codeFile = new File(pkg.codePath);
8844
8845        final boolean has64BitLibs;
8846        final boolean has32BitLibs;
8847        if (isApkFile(codeFile)) {
8848            // Monolithic install
8849            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8850            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8851        } else {
8852            // Cluster install
8853            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8854            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8855                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8856                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8857                has64BitLibs = (new File(rootDir, isa)).exists();
8858            } else {
8859                has64BitLibs = false;
8860            }
8861            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8862                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8863                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8864                has32BitLibs = (new File(rootDir, isa)).exists();
8865            } else {
8866                has32BitLibs = false;
8867            }
8868        }
8869
8870        if (has64BitLibs && !has32BitLibs) {
8871            // The package has 64 bit libs, but not 32 bit libs. Its primary
8872            // ABI should be 64 bit. We can safely assume here that the bundled
8873            // native libraries correspond to the most preferred ABI in the list.
8874
8875            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8876            pkg.applicationInfo.secondaryCpuAbi = null;
8877        } else if (has32BitLibs && !has64BitLibs) {
8878            // The package has 32 bit libs but not 64 bit libs. Its primary
8879            // ABI should be 32 bit.
8880
8881            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8882            pkg.applicationInfo.secondaryCpuAbi = null;
8883        } else if (has32BitLibs && has64BitLibs) {
8884            // The application has both 64 and 32 bit bundled libraries. We check
8885            // here that the app declares multiArch support, and warn if it doesn't.
8886            //
8887            // We will be lenient here and record both ABIs. The primary will be the
8888            // ABI that's higher on the list, i.e, a device that's configured to prefer
8889            // 64 bit apps will see a 64 bit primary ABI,
8890
8891            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8892                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8893            }
8894
8895            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8896                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8897                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8898            } else {
8899                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8900                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8901            }
8902        } else {
8903            pkg.applicationInfo.primaryCpuAbi = null;
8904            pkg.applicationInfo.secondaryCpuAbi = null;
8905        }
8906    }
8907
8908    private void killPackage(PackageParser.Package pkg, String reason) {
8909        // Kill the parent package
8910        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8911        // Kill the child packages
8912        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8913        for (int i = 0; i < childCount; i++) {
8914            PackageParser.Package childPkg = pkg.childPackages.get(i);
8915            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8916        }
8917    }
8918
8919    private void killApplication(String pkgName, int appId, String reason) {
8920        // Request the ActivityManager to kill the process(only for existing packages)
8921        // so that we do not end up in a confused state while the user is still using the older
8922        // version of the application while the new one gets installed.
8923        IActivityManager am = ActivityManagerNative.getDefault();
8924        if (am != null) {
8925            try {
8926                am.killApplicationWithAppId(pkgName, appId, reason);
8927            } catch (RemoteException e) {
8928            }
8929        }
8930    }
8931
8932    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8933        // Remove the parent package setting
8934        PackageSetting ps = (PackageSetting) pkg.mExtras;
8935        if (ps != null) {
8936            removePackageLI(ps, chatty);
8937        }
8938        // Remove the child package setting
8939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8940        for (int i = 0; i < childCount; i++) {
8941            PackageParser.Package childPkg = pkg.childPackages.get(i);
8942            ps = (PackageSetting) childPkg.mExtras;
8943            if (ps != null) {
8944                removePackageLI(ps, chatty);
8945            }
8946        }
8947    }
8948
8949    void removePackageLI(PackageSetting ps, boolean chatty) {
8950        if (DEBUG_INSTALL) {
8951            if (chatty)
8952                Log.d(TAG, "Removing package " + ps.name);
8953        }
8954
8955        // writer
8956        synchronized (mPackages) {
8957            mPackages.remove(ps.name);
8958            final PackageParser.Package pkg = ps.pkg;
8959            if (pkg != null) {
8960                cleanPackageDataStructuresLILPw(pkg, chatty);
8961            }
8962        }
8963    }
8964
8965    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8966        if (DEBUG_INSTALL) {
8967            if (chatty)
8968                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8969        }
8970
8971        // writer
8972        synchronized (mPackages) {
8973            // Remove the parent package
8974            mPackages.remove(pkg.applicationInfo.packageName);
8975            cleanPackageDataStructuresLILPw(pkg, chatty);
8976
8977            // Remove the child packages
8978            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8979            for (int i = 0; i < childCount; i++) {
8980                PackageParser.Package childPkg = pkg.childPackages.get(i);
8981                mPackages.remove(childPkg.applicationInfo.packageName);
8982                cleanPackageDataStructuresLILPw(childPkg, chatty);
8983            }
8984        }
8985    }
8986
8987    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8988        int N = pkg.providers.size();
8989        StringBuilder r = null;
8990        int i;
8991        for (i=0; i<N; i++) {
8992            PackageParser.Provider p = pkg.providers.get(i);
8993            mProviders.removeProvider(p);
8994            if (p.info.authority == null) {
8995
8996                /* There was another ContentProvider with this authority when
8997                 * this app was installed so this authority is null,
8998                 * Ignore it as we don't have to unregister the provider.
8999                 */
9000                continue;
9001            }
9002            String names[] = p.info.authority.split(";");
9003            for (int j = 0; j < names.length; j++) {
9004                if (mProvidersByAuthority.get(names[j]) == p) {
9005                    mProvidersByAuthority.remove(names[j]);
9006                    if (DEBUG_REMOVE) {
9007                        if (chatty)
9008                            Log.d(TAG, "Unregistered content provider: " + names[j]
9009                                    + ", className = " + p.info.name + ", isSyncable = "
9010                                    + p.info.isSyncable);
9011                    }
9012                }
9013            }
9014            if (DEBUG_REMOVE && chatty) {
9015                if (r == null) {
9016                    r = new StringBuilder(256);
9017                } else {
9018                    r.append(' ');
9019                }
9020                r.append(p.info.name);
9021            }
9022        }
9023        if (r != null) {
9024            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9025        }
9026
9027        N = pkg.services.size();
9028        r = null;
9029        for (i=0; i<N; i++) {
9030            PackageParser.Service s = pkg.services.get(i);
9031            mServices.removeService(s);
9032            if (chatty) {
9033                if (r == null) {
9034                    r = new StringBuilder(256);
9035                } else {
9036                    r.append(' ');
9037                }
9038                r.append(s.info.name);
9039            }
9040        }
9041        if (r != null) {
9042            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9043        }
9044
9045        N = pkg.receivers.size();
9046        r = null;
9047        for (i=0; i<N; i++) {
9048            PackageParser.Activity a = pkg.receivers.get(i);
9049            mReceivers.removeActivity(a, "receiver");
9050            if (DEBUG_REMOVE && chatty) {
9051                if (r == null) {
9052                    r = new StringBuilder(256);
9053                } else {
9054                    r.append(' ');
9055                }
9056                r.append(a.info.name);
9057            }
9058        }
9059        if (r != null) {
9060            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9061        }
9062
9063        N = pkg.activities.size();
9064        r = null;
9065        for (i=0; i<N; i++) {
9066            PackageParser.Activity a = pkg.activities.get(i);
9067            mActivities.removeActivity(a, "activity");
9068            if (DEBUG_REMOVE && chatty) {
9069                if (r == null) {
9070                    r = new StringBuilder(256);
9071                } else {
9072                    r.append(' ');
9073                }
9074                r.append(a.info.name);
9075            }
9076        }
9077        if (r != null) {
9078            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9079        }
9080
9081        N = pkg.permissions.size();
9082        r = null;
9083        for (i=0; i<N; i++) {
9084            PackageParser.Permission p = pkg.permissions.get(i);
9085            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9086            if (bp == null) {
9087                bp = mSettings.mPermissionTrees.get(p.info.name);
9088            }
9089            if (bp != null && bp.perm == p) {
9090                bp.perm = null;
9091                if (DEBUG_REMOVE && chatty) {
9092                    if (r == null) {
9093                        r = new StringBuilder(256);
9094                    } else {
9095                        r.append(' ');
9096                    }
9097                    r.append(p.info.name);
9098                }
9099            }
9100            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9101                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9102                if (appOpPkgs != null) {
9103                    appOpPkgs.remove(pkg.packageName);
9104                }
9105            }
9106        }
9107        if (r != null) {
9108            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9109        }
9110
9111        N = pkg.requestedPermissions.size();
9112        r = null;
9113        for (i=0; i<N; i++) {
9114            String perm = pkg.requestedPermissions.get(i);
9115            BasePermission bp = mSettings.mPermissions.get(perm);
9116            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9117                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9118                if (appOpPkgs != null) {
9119                    appOpPkgs.remove(pkg.packageName);
9120                    if (appOpPkgs.isEmpty()) {
9121                        mAppOpPermissionPackages.remove(perm);
9122                    }
9123                }
9124            }
9125        }
9126        if (r != null) {
9127            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9128        }
9129
9130        N = pkg.instrumentation.size();
9131        r = null;
9132        for (i=0; i<N; i++) {
9133            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9134            mInstrumentation.remove(a.getComponentName());
9135            if (DEBUG_REMOVE && chatty) {
9136                if (r == null) {
9137                    r = new StringBuilder(256);
9138                } else {
9139                    r.append(' ');
9140                }
9141                r.append(a.info.name);
9142            }
9143        }
9144        if (r != null) {
9145            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9146        }
9147
9148        r = null;
9149        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9150            // Only system apps can hold shared libraries.
9151            if (pkg.libraryNames != null) {
9152                for (i=0; i<pkg.libraryNames.size(); i++) {
9153                    String name = pkg.libraryNames.get(i);
9154                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9155                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9156                        mSharedLibraries.remove(name);
9157                        if (DEBUG_REMOVE && chatty) {
9158                            if (r == null) {
9159                                r = new StringBuilder(256);
9160                            } else {
9161                                r.append(' ');
9162                            }
9163                            r.append(name);
9164                        }
9165                    }
9166                }
9167            }
9168        }
9169        if (r != null) {
9170            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9171        }
9172    }
9173
9174    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9175        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9176            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9177                return true;
9178            }
9179        }
9180        return false;
9181    }
9182
9183    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9184    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9185    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9186
9187    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9188        // Update the parent permissions
9189        updatePermissionsLPw(pkg.packageName, pkg, flags);
9190        // Update the child permissions
9191        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9192        for (int i = 0; i < childCount; i++) {
9193            PackageParser.Package childPkg = pkg.childPackages.get(i);
9194            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9195        }
9196    }
9197
9198    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9199            int flags) {
9200        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9201        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9202    }
9203
9204    private void updatePermissionsLPw(String changingPkg,
9205            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9206        // Make sure there are no dangling permission trees.
9207        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9208        while (it.hasNext()) {
9209            final BasePermission bp = it.next();
9210            if (bp.packageSetting == null) {
9211                // We may not yet have parsed the package, so just see if
9212                // we still know about its settings.
9213                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9214            }
9215            if (bp.packageSetting == null) {
9216                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9217                        + " from package " + bp.sourcePackage);
9218                it.remove();
9219            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9220                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9221                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9222                            + " from package " + bp.sourcePackage);
9223                    flags |= UPDATE_PERMISSIONS_ALL;
9224                    it.remove();
9225                }
9226            }
9227        }
9228
9229        // Make sure all dynamic permissions have been assigned to a package,
9230        // and make sure there are no dangling permissions.
9231        it = mSettings.mPermissions.values().iterator();
9232        while (it.hasNext()) {
9233            final BasePermission bp = it.next();
9234            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9235                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9236                        + bp.name + " pkg=" + bp.sourcePackage
9237                        + " info=" + bp.pendingInfo);
9238                if (bp.packageSetting == null && bp.pendingInfo != null) {
9239                    final BasePermission tree = findPermissionTreeLP(bp.name);
9240                    if (tree != null && tree.perm != null) {
9241                        bp.packageSetting = tree.packageSetting;
9242                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9243                                new PermissionInfo(bp.pendingInfo));
9244                        bp.perm.info.packageName = tree.perm.info.packageName;
9245                        bp.perm.info.name = bp.name;
9246                        bp.uid = tree.uid;
9247                    }
9248                }
9249            }
9250            if (bp.packageSetting == null) {
9251                // We may not yet have parsed the package, so just see if
9252                // we still know about its settings.
9253                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9254            }
9255            if (bp.packageSetting == null) {
9256                Slog.w(TAG, "Removing dangling permission: " + bp.name
9257                        + " from package " + bp.sourcePackage);
9258                it.remove();
9259            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9260                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9261                    Slog.i(TAG, "Removing old permission: " + bp.name
9262                            + " from package " + bp.sourcePackage);
9263                    flags |= UPDATE_PERMISSIONS_ALL;
9264                    it.remove();
9265                }
9266            }
9267        }
9268
9269        // Now update the permissions for all packages, in particular
9270        // replace the granted permissions of the system packages.
9271        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9272            for (PackageParser.Package pkg : mPackages.values()) {
9273                if (pkg != pkgInfo) {
9274                    // Only replace for packages on requested volume
9275                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9276                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9277                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9278                    grantPermissionsLPw(pkg, replace, changingPkg);
9279                }
9280            }
9281        }
9282
9283        if (pkgInfo != null) {
9284            // Only replace for packages on requested volume
9285            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9286            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9287                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9288            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9289        }
9290    }
9291
9292    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9293            String packageOfInterest) {
9294        // IMPORTANT: There are two types of permissions: install and runtime.
9295        // Install time permissions are granted when the app is installed to
9296        // all device users and users added in the future. Runtime permissions
9297        // are granted at runtime explicitly to specific users. Normal and signature
9298        // protected permissions are install time permissions. Dangerous permissions
9299        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9300        // otherwise they are runtime permissions. This function does not manage
9301        // runtime permissions except for the case an app targeting Lollipop MR1
9302        // being upgraded to target a newer SDK, in which case dangerous permissions
9303        // are transformed from install time to runtime ones.
9304
9305        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9306        if (ps == null) {
9307            return;
9308        }
9309
9310        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9311
9312        PermissionsState permissionsState = ps.getPermissionsState();
9313        PermissionsState origPermissions = permissionsState;
9314
9315        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9316
9317        boolean runtimePermissionsRevoked = false;
9318        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9319
9320        boolean changedInstallPermission = false;
9321
9322        if (replace) {
9323            ps.installPermissionsFixed = false;
9324            if (!ps.isSharedUser()) {
9325                origPermissions = new PermissionsState(permissionsState);
9326                permissionsState.reset();
9327            } else {
9328                // We need to know only about runtime permission changes since the
9329                // calling code always writes the install permissions state but
9330                // the runtime ones are written only if changed. The only cases of
9331                // changed runtime permissions here are promotion of an install to
9332                // runtime and revocation of a runtime from a shared user.
9333                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9334                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9335                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9336                    runtimePermissionsRevoked = true;
9337                }
9338            }
9339        }
9340
9341        permissionsState.setGlobalGids(mGlobalGids);
9342
9343        final int N = pkg.requestedPermissions.size();
9344        for (int i=0; i<N; i++) {
9345            final String name = pkg.requestedPermissions.get(i);
9346            final BasePermission bp = mSettings.mPermissions.get(name);
9347
9348            if (DEBUG_INSTALL) {
9349                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9350            }
9351
9352            if (bp == null || bp.packageSetting == null) {
9353                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9354                    Slog.w(TAG, "Unknown permission " + name
9355                            + " in package " + pkg.packageName);
9356                }
9357                continue;
9358            }
9359
9360            final String perm = bp.name;
9361            boolean allowedSig = false;
9362            int grant = GRANT_DENIED;
9363
9364            // Keep track of app op permissions.
9365            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9366                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9367                if (pkgs == null) {
9368                    pkgs = new ArraySet<>();
9369                    mAppOpPermissionPackages.put(bp.name, pkgs);
9370                }
9371                pkgs.add(pkg.packageName);
9372            }
9373
9374            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9375            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9376                    >= Build.VERSION_CODES.M;
9377            switch (level) {
9378                case PermissionInfo.PROTECTION_NORMAL: {
9379                    // For all apps normal permissions are install time ones.
9380                    grant = GRANT_INSTALL;
9381                } break;
9382
9383                case PermissionInfo.PROTECTION_DANGEROUS: {
9384                    // If a permission review is required for legacy apps we represent
9385                    // their permissions as always granted runtime ones since we need
9386                    // to keep the review required permission flag per user while an
9387                    // install permission's state is shared across all users.
9388                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9389                        // For legacy apps dangerous permissions are install time ones.
9390                        grant = GRANT_INSTALL;
9391                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9392                        // For legacy apps that became modern, install becomes runtime.
9393                        grant = GRANT_UPGRADE;
9394                    } else if (mPromoteSystemApps
9395                            && isSystemApp(ps)
9396                            && mExistingSystemPackages.contains(ps.name)) {
9397                        // For legacy system apps, install becomes runtime.
9398                        // We cannot check hasInstallPermission() for system apps since those
9399                        // permissions were granted implicitly and not persisted pre-M.
9400                        grant = GRANT_UPGRADE;
9401                    } else {
9402                        // For modern apps keep runtime permissions unchanged.
9403                        grant = GRANT_RUNTIME;
9404                    }
9405                } break;
9406
9407                case PermissionInfo.PROTECTION_SIGNATURE: {
9408                    // For all apps signature permissions are install time ones.
9409                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9410                    if (allowedSig) {
9411                        grant = GRANT_INSTALL;
9412                    }
9413                } break;
9414            }
9415
9416            if (DEBUG_INSTALL) {
9417                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9418            }
9419
9420            if (grant != GRANT_DENIED) {
9421                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9422                    // If this is an existing, non-system package, then
9423                    // we can't add any new permissions to it.
9424                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9425                        // Except...  if this is a permission that was added
9426                        // to the platform (note: need to only do this when
9427                        // updating the platform).
9428                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9429                            grant = GRANT_DENIED;
9430                        }
9431                    }
9432                }
9433
9434                switch (grant) {
9435                    case GRANT_INSTALL: {
9436                        // Revoke this as runtime permission to handle the case of
9437                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9438                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9439                            if (origPermissions.getRuntimePermissionState(
9440                                    bp.name, userId) != null) {
9441                                // Revoke the runtime permission and clear the flags.
9442                                origPermissions.revokeRuntimePermission(bp, userId);
9443                                origPermissions.updatePermissionFlags(bp, userId,
9444                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9445                                // If we revoked a permission permission, we have to write.
9446                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9447                                        changedRuntimePermissionUserIds, userId);
9448                            }
9449                        }
9450                        // Grant an install permission.
9451                        if (permissionsState.grantInstallPermission(bp) !=
9452                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9453                            changedInstallPermission = true;
9454                        }
9455                    } break;
9456
9457                    case GRANT_RUNTIME: {
9458                        // Grant previously granted runtime permissions.
9459                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9460                            PermissionState permissionState = origPermissions
9461                                    .getRuntimePermissionState(bp.name, userId);
9462                            int flags = permissionState != null
9463                                    ? permissionState.getFlags() : 0;
9464                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9465                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9466                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9467                                    // If we cannot put the permission as it was, we have to write.
9468                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9469                                            changedRuntimePermissionUserIds, userId);
9470                                }
9471                                // If the app supports runtime permissions no need for a review.
9472                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9473                                        && appSupportsRuntimePermissions
9474                                        && (flags & PackageManager
9475                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9476                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9477                                    // Since we changed the flags, we have to write.
9478                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9479                                            changedRuntimePermissionUserIds, userId);
9480                                }
9481                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9482                                    && !appSupportsRuntimePermissions) {
9483                                // For legacy apps that need a permission review, every new
9484                                // runtime permission is granted but it is pending a review.
9485                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9486                                    permissionsState.grantRuntimePermission(bp, userId);
9487                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9488                                    // We changed the permission and flags, hence have to write.
9489                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9490                                            changedRuntimePermissionUserIds, userId);
9491                                }
9492                            }
9493                            // Propagate the permission flags.
9494                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9495                        }
9496                    } break;
9497
9498                    case GRANT_UPGRADE: {
9499                        // Grant runtime permissions for a previously held install permission.
9500                        PermissionState permissionState = origPermissions
9501                                .getInstallPermissionState(bp.name);
9502                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9503
9504                        if (origPermissions.revokeInstallPermission(bp)
9505                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9506                            // We will be transferring the permission flags, so clear them.
9507                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9508                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9509                            changedInstallPermission = true;
9510                        }
9511
9512                        // If the permission is not to be promoted to runtime we ignore it and
9513                        // also its other flags as they are not applicable to install permissions.
9514                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9515                            for (int userId : currentUserIds) {
9516                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9517                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9518                                    // Transfer the permission flags.
9519                                    permissionsState.updatePermissionFlags(bp, userId,
9520                                            flags, flags);
9521                                    // If we granted the permission, we have to write.
9522                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9523                                            changedRuntimePermissionUserIds, userId);
9524                                }
9525                            }
9526                        }
9527                    } break;
9528
9529                    default: {
9530                        if (packageOfInterest == null
9531                                || packageOfInterest.equals(pkg.packageName)) {
9532                            Slog.w(TAG, "Not granting permission " + perm
9533                                    + " to package " + pkg.packageName
9534                                    + " because it was previously installed without");
9535                        }
9536                    } break;
9537                }
9538            } else {
9539                if (permissionsState.revokeInstallPermission(bp) !=
9540                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9541                    // Also drop the permission flags.
9542                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9543                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9544                    changedInstallPermission = true;
9545                    Slog.i(TAG, "Un-granting permission " + perm
9546                            + " from package " + pkg.packageName
9547                            + " (protectionLevel=" + bp.protectionLevel
9548                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9549                            + ")");
9550                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9551                    // Don't print warning for app op permissions, since it is fine for them
9552                    // not to be granted, there is a UI for the user to decide.
9553                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9554                        Slog.w(TAG, "Not granting permission " + perm
9555                                + " to package " + pkg.packageName
9556                                + " (protectionLevel=" + bp.protectionLevel
9557                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9558                                + ")");
9559                    }
9560                }
9561            }
9562        }
9563
9564        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9565                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9566            // This is the first that we have heard about this package, so the
9567            // permissions we have now selected are fixed until explicitly
9568            // changed.
9569            ps.installPermissionsFixed = true;
9570        }
9571
9572        // Persist the runtime permissions state for users with changes. If permissions
9573        // were revoked because no app in the shared user declares them we have to
9574        // write synchronously to avoid losing runtime permissions state.
9575        for (int userId : changedRuntimePermissionUserIds) {
9576            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9577        }
9578
9579        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9580    }
9581
9582    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9583        boolean allowed = false;
9584        final int NP = PackageParser.NEW_PERMISSIONS.length;
9585        for (int ip=0; ip<NP; ip++) {
9586            final PackageParser.NewPermissionInfo npi
9587                    = PackageParser.NEW_PERMISSIONS[ip];
9588            if (npi.name.equals(perm)
9589                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9590                allowed = true;
9591                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9592                        + pkg.packageName);
9593                break;
9594            }
9595        }
9596        return allowed;
9597    }
9598
9599    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9600            BasePermission bp, PermissionsState origPermissions) {
9601        boolean allowed;
9602        allowed = (compareSignatures(
9603                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9604                        == PackageManager.SIGNATURE_MATCH)
9605                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9606                        == PackageManager.SIGNATURE_MATCH);
9607        if (!allowed && (bp.protectionLevel
9608                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9609            if (isSystemApp(pkg)) {
9610                // For updated system applications, a system permission
9611                // is granted only if it had been defined by the original application.
9612                if (pkg.isUpdatedSystemApp()) {
9613                    final PackageSetting sysPs = mSettings
9614                            .getDisabledSystemPkgLPr(pkg.packageName);
9615                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9616                        // If the original was granted this permission, we take
9617                        // that grant decision as read and propagate it to the
9618                        // update.
9619                        if (sysPs.isPrivileged()) {
9620                            allowed = true;
9621                        }
9622                    } else {
9623                        // The system apk may have been updated with an older
9624                        // version of the one on the data partition, but which
9625                        // granted a new system permission that it didn't have
9626                        // before.  In this case we do want to allow the app to
9627                        // now get the new permission if the ancestral apk is
9628                        // privileged to get it.
9629                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9630                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9631                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9632                                    allowed = true;
9633                                    break;
9634                                }
9635                            }
9636                        }
9637                        // Also if a privileged parent package on the system image or any of
9638                        // its children requested a privileged permission, the updated child
9639                        // packages can also get the permission.
9640                        if (pkg.parentPackage != null) {
9641                            final PackageSetting disabledSysParentPs = mSettings
9642                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9643                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9644                                    && disabledSysParentPs.isPrivileged()) {
9645                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9646                                    allowed = true;
9647                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9648                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9649                                    for (int i = 0; i < count; i++) {
9650                                        PackageParser.Package disabledSysChildPkg =
9651                                                disabledSysParentPs.pkg.childPackages.get(i);
9652                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9653                                                perm)) {
9654                                            allowed = true;
9655                                            break;
9656                                        }
9657                                    }
9658                                }
9659                            }
9660                        }
9661                    }
9662                } else {
9663                    allowed = isPrivilegedApp(pkg);
9664                }
9665            }
9666        }
9667        if (!allowed) {
9668            if (!allowed && (bp.protectionLevel
9669                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9670                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9671                // If this was a previously normal/dangerous permission that got moved
9672                // to a system permission as part of the runtime permission redesign, then
9673                // we still want to blindly grant it to old apps.
9674                allowed = true;
9675            }
9676            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9677                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9678                // If this permission is to be granted to the system installer and
9679                // this app is an installer, then it gets the permission.
9680                allowed = true;
9681            }
9682            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9683                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9684                // If this permission is to be granted to the system verifier and
9685                // this app is a verifier, then it gets the permission.
9686                allowed = true;
9687            }
9688            if (!allowed && (bp.protectionLevel
9689                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9690                    && isSystemApp(pkg)) {
9691                // Any pre-installed system app is allowed to get this permission.
9692                allowed = true;
9693            }
9694            if (!allowed && (bp.protectionLevel
9695                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9696                // For development permissions, a development permission
9697                // is granted only if it was already granted.
9698                allowed = origPermissions.hasInstallPermission(perm);
9699            }
9700        }
9701        return allowed;
9702    }
9703
9704    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9705        final int permCount = pkg.requestedPermissions.size();
9706        for (int j = 0; j < permCount; j++) {
9707            String requestedPermission = pkg.requestedPermissions.get(j);
9708            if (permission.equals(requestedPermission)) {
9709                return true;
9710            }
9711        }
9712        return false;
9713    }
9714
9715    final class ActivityIntentResolver
9716            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9717        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9718                boolean defaultOnly, int userId) {
9719            if (!sUserManager.exists(userId)) return null;
9720            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9721            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9722        }
9723
9724        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9725                int userId) {
9726            if (!sUserManager.exists(userId)) return null;
9727            mFlags = flags;
9728            return super.queryIntent(intent, resolvedType,
9729                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9730        }
9731
9732        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9733                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9734            if (!sUserManager.exists(userId)) return null;
9735            if (packageActivities == null) {
9736                return null;
9737            }
9738            mFlags = flags;
9739            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9740            final int N = packageActivities.size();
9741            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9742                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9743
9744            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9745            for (int i = 0; i < N; ++i) {
9746                intentFilters = packageActivities.get(i).intents;
9747                if (intentFilters != null && intentFilters.size() > 0) {
9748                    PackageParser.ActivityIntentInfo[] array =
9749                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9750                    intentFilters.toArray(array);
9751                    listCut.add(array);
9752                }
9753            }
9754            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9755        }
9756
9757        public final void addActivity(PackageParser.Activity a, String type) {
9758            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9759            mActivities.put(a.getComponentName(), a);
9760            if (DEBUG_SHOW_INFO)
9761                Log.v(
9762                TAG, "  " + type + " " +
9763                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9764            if (DEBUG_SHOW_INFO)
9765                Log.v(TAG, "    Class=" + a.info.name);
9766            final int NI = a.intents.size();
9767            for (int j=0; j<NI; j++) {
9768                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9769                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9770                    intent.setPriority(0);
9771                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9772                            + a.className + " with priority > 0, forcing to 0");
9773                }
9774                if (DEBUG_SHOW_INFO) {
9775                    Log.v(TAG, "    IntentFilter:");
9776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9777                }
9778                if (!intent.debugCheck()) {
9779                    Log.w(TAG, "==> For Activity " + a.info.name);
9780                }
9781                addFilter(intent);
9782            }
9783        }
9784
9785        public final void removeActivity(PackageParser.Activity a, String type) {
9786            mActivities.remove(a.getComponentName());
9787            if (DEBUG_SHOW_INFO) {
9788                Log.v(TAG, "  " + type + " "
9789                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9790                                : a.info.name) + ":");
9791                Log.v(TAG, "    Class=" + a.info.name);
9792            }
9793            final int NI = a.intents.size();
9794            for (int j=0; j<NI; j++) {
9795                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9796                if (DEBUG_SHOW_INFO) {
9797                    Log.v(TAG, "    IntentFilter:");
9798                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9799                }
9800                removeFilter(intent);
9801            }
9802        }
9803
9804        @Override
9805        protected boolean allowFilterResult(
9806                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9807            ActivityInfo filterAi = filter.activity.info;
9808            for (int i=dest.size()-1; i>=0; i--) {
9809                ActivityInfo destAi = dest.get(i).activityInfo;
9810                if (destAi.name == filterAi.name
9811                        && destAi.packageName == filterAi.packageName) {
9812                    return false;
9813                }
9814            }
9815            return true;
9816        }
9817
9818        @Override
9819        protected ActivityIntentInfo[] newArray(int size) {
9820            return new ActivityIntentInfo[size];
9821        }
9822
9823        @Override
9824        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9825            if (!sUserManager.exists(userId)) return true;
9826            PackageParser.Package p = filter.activity.owner;
9827            if (p != null) {
9828                PackageSetting ps = (PackageSetting)p.mExtras;
9829                if (ps != null) {
9830                    // System apps are never considered stopped for purposes of
9831                    // filtering, because there may be no way for the user to
9832                    // actually re-launch them.
9833                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9834                            && ps.getStopped(userId);
9835                }
9836            }
9837            return false;
9838        }
9839
9840        @Override
9841        protected boolean isPackageForFilter(String packageName,
9842                PackageParser.ActivityIntentInfo info) {
9843            return packageName.equals(info.activity.owner.packageName);
9844        }
9845
9846        @Override
9847        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9848                int match, int userId) {
9849            if (!sUserManager.exists(userId)) return null;
9850            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9851                return null;
9852            }
9853            final PackageParser.Activity activity = info.activity;
9854            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9855            if (ps == null) {
9856                return null;
9857            }
9858            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9859                    ps.readUserState(userId), userId);
9860            if (ai == null) {
9861                return null;
9862            }
9863            final ResolveInfo res = new ResolveInfo();
9864            res.activityInfo = ai;
9865            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9866                res.filter = info;
9867            }
9868            if (info != null) {
9869                res.handleAllWebDataURI = info.handleAllWebDataURI();
9870            }
9871            res.priority = info.getPriority();
9872            res.preferredOrder = activity.owner.mPreferredOrder;
9873            //System.out.println("Result: " + res.activityInfo.className +
9874            //                   " = " + res.priority);
9875            res.match = match;
9876            res.isDefault = info.hasDefault;
9877            res.labelRes = info.labelRes;
9878            res.nonLocalizedLabel = info.nonLocalizedLabel;
9879            if (userNeedsBadging(userId)) {
9880                res.noResourceId = true;
9881            } else {
9882                res.icon = info.icon;
9883            }
9884            res.iconResourceId = info.icon;
9885            res.system = res.activityInfo.applicationInfo.isSystemApp();
9886            return res;
9887        }
9888
9889        @Override
9890        protected void sortResults(List<ResolveInfo> results) {
9891            Collections.sort(results, mResolvePrioritySorter);
9892        }
9893
9894        @Override
9895        protected void dumpFilter(PrintWriter out, String prefix,
9896                PackageParser.ActivityIntentInfo filter) {
9897            out.print(prefix); out.print(
9898                    Integer.toHexString(System.identityHashCode(filter.activity)));
9899                    out.print(' ');
9900                    filter.activity.printComponentShortName(out);
9901                    out.print(" filter ");
9902                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9903        }
9904
9905        @Override
9906        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9907            return filter.activity;
9908        }
9909
9910        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9911            PackageParser.Activity activity = (PackageParser.Activity)label;
9912            out.print(prefix); out.print(
9913                    Integer.toHexString(System.identityHashCode(activity)));
9914                    out.print(' ');
9915                    activity.printComponentShortName(out);
9916            if (count > 1) {
9917                out.print(" ("); out.print(count); out.print(" filters)");
9918            }
9919            out.println();
9920        }
9921
9922//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9923//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9924//            final List<ResolveInfo> retList = Lists.newArrayList();
9925//            while (i.hasNext()) {
9926//                final ResolveInfo resolveInfo = i.next();
9927//                if (isEnabledLP(resolveInfo.activityInfo)) {
9928//                    retList.add(resolveInfo);
9929//                }
9930//            }
9931//            return retList;
9932//        }
9933
9934        // Keys are String (activity class name), values are Activity.
9935        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9936                = new ArrayMap<ComponentName, PackageParser.Activity>();
9937        private int mFlags;
9938    }
9939
9940    private final class ServiceIntentResolver
9941            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9942        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9943                boolean defaultOnly, int userId) {
9944            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9945            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9946        }
9947
9948        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9949                int userId) {
9950            if (!sUserManager.exists(userId)) return null;
9951            mFlags = flags;
9952            return super.queryIntent(intent, resolvedType,
9953                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9954        }
9955
9956        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9957                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9958            if (!sUserManager.exists(userId)) return null;
9959            if (packageServices == null) {
9960                return null;
9961            }
9962            mFlags = flags;
9963            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9964            final int N = packageServices.size();
9965            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9966                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9967
9968            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9969            for (int i = 0; i < N; ++i) {
9970                intentFilters = packageServices.get(i).intents;
9971                if (intentFilters != null && intentFilters.size() > 0) {
9972                    PackageParser.ServiceIntentInfo[] array =
9973                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9974                    intentFilters.toArray(array);
9975                    listCut.add(array);
9976                }
9977            }
9978            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9979        }
9980
9981        public final void addService(PackageParser.Service s) {
9982            mServices.put(s.getComponentName(), s);
9983            if (DEBUG_SHOW_INFO) {
9984                Log.v(TAG, "  "
9985                        + (s.info.nonLocalizedLabel != null
9986                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9987                Log.v(TAG, "    Class=" + s.info.name);
9988            }
9989            final int NI = s.intents.size();
9990            int j;
9991            for (j=0; j<NI; j++) {
9992                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9993                if (DEBUG_SHOW_INFO) {
9994                    Log.v(TAG, "    IntentFilter:");
9995                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9996                }
9997                if (!intent.debugCheck()) {
9998                    Log.w(TAG, "==> For Service " + s.info.name);
9999                }
10000                addFilter(intent);
10001            }
10002        }
10003
10004        public final void removeService(PackageParser.Service s) {
10005            mServices.remove(s.getComponentName());
10006            if (DEBUG_SHOW_INFO) {
10007                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10008                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10009                Log.v(TAG, "    Class=" + s.info.name);
10010            }
10011            final int NI = s.intents.size();
10012            int j;
10013            for (j=0; j<NI; j++) {
10014                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10015                if (DEBUG_SHOW_INFO) {
10016                    Log.v(TAG, "    IntentFilter:");
10017                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10018                }
10019                removeFilter(intent);
10020            }
10021        }
10022
10023        @Override
10024        protected boolean allowFilterResult(
10025                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10026            ServiceInfo filterSi = filter.service.info;
10027            for (int i=dest.size()-1; i>=0; i--) {
10028                ServiceInfo destAi = dest.get(i).serviceInfo;
10029                if (destAi.name == filterSi.name
10030                        && destAi.packageName == filterSi.packageName) {
10031                    return false;
10032                }
10033            }
10034            return true;
10035        }
10036
10037        @Override
10038        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10039            return new PackageParser.ServiceIntentInfo[size];
10040        }
10041
10042        @Override
10043        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10044            if (!sUserManager.exists(userId)) return true;
10045            PackageParser.Package p = filter.service.owner;
10046            if (p != null) {
10047                PackageSetting ps = (PackageSetting)p.mExtras;
10048                if (ps != null) {
10049                    // System apps are never considered stopped for purposes of
10050                    // filtering, because there may be no way for the user to
10051                    // actually re-launch them.
10052                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10053                            && ps.getStopped(userId);
10054                }
10055            }
10056            return false;
10057        }
10058
10059        @Override
10060        protected boolean isPackageForFilter(String packageName,
10061                PackageParser.ServiceIntentInfo info) {
10062            return packageName.equals(info.service.owner.packageName);
10063        }
10064
10065        @Override
10066        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10067                int match, int userId) {
10068            if (!sUserManager.exists(userId)) return null;
10069            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10070            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10071                return null;
10072            }
10073            final PackageParser.Service service = info.service;
10074            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10075            if (ps == null) {
10076                return null;
10077            }
10078            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10079                    ps.readUserState(userId), userId);
10080            if (si == null) {
10081                return null;
10082            }
10083            final ResolveInfo res = new ResolveInfo();
10084            res.serviceInfo = si;
10085            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10086                res.filter = filter;
10087            }
10088            res.priority = info.getPriority();
10089            res.preferredOrder = service.owner.mPreferredOrder;
10090            res.match = match;
10091            res.isDefault = info.hasDefault;
10092            res.labelRes = info.labelRes;
10093            res.nonLocalizedLabel = info.nonLocalizedLabel;
10094            res.icon = info.icon;
10095            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10096            return res;
10097        }
10098
10099        @Override
10100        protected void sortResults(List<ResolveInfo> results) {
10101            Collections.sort(results, mResolvePrioritySorter);
10102        }
10103
10104        @Override
10105        protected void dumpFilter(PrintWriter out, String prefix,
10106                PackageParser.ServiceIntentInfo filter) {
10107            out.print(prefix); out.print(
10108                    Integer.toHexString(System.identityHashCode(filter.service)));
10109                    out.print(' ');
10110                    filter.service.printComponentShortName(out);
10111                    out.print(" filter ");
10112                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10113        }
10114
10115        @Override
10116        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10117            return filter.service;
10118        }
10119
10120        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10121            PackageParser.Service service = (PackageParser.Service)label;
10122            out.print(prefix); out.print(
10123                    Integer.toHexString(System.identityHashCode(service)));
10124                    out.print(' ');
10125                    service.printComponentShortName(out);
10126            if (count > 1) {
10127                out.print(" ("); out.print(count); out.print(" filters)");
10128            }
10129            out.println();
10130        }
10131
10132//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10133//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10134//            final List<ResolveInfo> retList = Lists.newArrayList();
10135//            while (i.hasNext()) {
10136//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10137//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10138//                    retList.add(resolveInfo);
10139//                }
10140//            }
10141//            return retList;
10142//        }
10143
10144        // Keys are String (activity class name), values are Activity.
10145        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10146                = new ArrayMap<ComponentName, PackageParser.Service>();
10147        private int mFlags;
10148    };
10149
10150    private final class ProviderIntentResolver
10151            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10152        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10153                boolean defaultOnly, int userId) {
10154            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10155            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10156        }
10157
10158        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10159                int userId) {
10160            if (!sUserManager.exists(userId))
10161                return null;
10162            mFlags = flags;
10163            return super.queryIntent(intent, resolvedType,
10164                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10165        }
10166
10167        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10168                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10169            if (!sUserManager.exists(userId))
10170                return null;
10171            if (packageProviders == null) {
10172                return null;
10173            }
10174            mFlags = flags;
10175            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10176            final int N = packageProviders.size();
10177            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10178                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10179
10180            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10181            for (int i = 0; i < N; ++i) {
10182                intentFilters = packageProviders.get(i).intents;
10183                if (intentFilters != null && intentFilters.size() > 0) {
10184                    PackageParser.ProviderIntentInfo[] array =
10185                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10186                    intentFilters.toArray(array);
10187                    listCut.add(array);
10188                }
10189            }
10190            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10191        }
10192
10193        public final void addProvider(PackageParser.Provider p) {
10194            if (mProviders.containsKey(p.getComponentName())) {
10195                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10196                return;
10197            }
10198
10199            mProviders.put(p.getComponentName(), p);
10200            if (DEBUG_SHOW_INFO) {
10201                Log.v(TAG, "  "
10202                        + (p.info.nonLocalizedLabel != null
10203                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10204                Log.v(TAG, "    Class=" + p.info.name);
10205            }
10206            final int NI = p.intents.size();
10207            int j;
10208            for (j = 0; j < NI; j++) {
10209                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10210                if (DEBUG_SHOW_INFO) {
10211                    Log.v(TAG, "    IntentFilter:");
10212                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10213                }
10214                if (!intent.debugCheck()) {
10215                    Log.w(TAG, "==> For Provider " + p.info.name);
10216                }
10217                addFilter(intent);
10218            }
10219        }
10220
10221        public final void removeProvider(PackageParser.Provider p) {
10222            mProviders.remove(p.getComponentName());
10223            if (DEBUG_SHOW_INFO) {
10224                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10225                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10226                Log.v(TAG, "    Class=" + p.info.name);
10227            }
10228            final int NI = p.intents.size();
10229            int j;
10230            for (j = 0; j < NI; j++) {
10231                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10232                if (DEBUG_SHOW_INFO) {
10233                    Log.v(TAG, "    IntentFilter:");
10234                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10235                }
10236                removeFilter(intent);
10237            }
10238        }
10239
10240        @Override
10241        protected boolean allowFilterResult(
10242                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10243            ProviderInfo filterPi = filter.provider.info;
10244            for (int i = dest.size() - 1; i >= 0; i--) {
10245                ProviderInfo destPi = dest.get(i).providerInfo;
10246                if (destPi.name == filterPi.name
10247                        && destPi.packageName == filterPi.packageName) {
10248                    return false;
10249                }
10250            }
10251            return true;
10252        }
10253
10254        @Override
10255        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10256            return new PackageParser.ProviderIntentInfo[size];
10257        }
10258
10259        @Override
10260        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10261            if (!sUserManager.exists(userId))
10262                return true;
10263            PackageParser.Package p = filter.provider.owner;
10264            if (p != null) {
10265                PackageSetting ps = (PackageSetting) p.mExtras;
10266                if (ps != null) {
10267                    // System apps are never considered stopped for purposes of
10268                    // filtering, because there may be no way for the user to
10269                    // actually re-launch them.
10270                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10271                            && ps.getStopped(userId);
10272                }
10273            }
10274            return false;
10275        }
10276
10277        @Override
10278        protected boolean isPackageForFilter(String packageName,
10279                PackageParser.ProviderIntentInfo info) {
10280            return packageName.equals(info.provider.owner.packageName);
10281        }
10282
10283        @Override
10284        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10285                int match, int userId) {
10286            if (!sUserManager.exists(userId))
10287                return null;
10288            final PackageParser.ProviderIntentInfo info = filter;
10289            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10290                return null;
10291            }
10292            final PackageParser.Provider provider = info.provider;
10293            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10294            if (ps == null) {
10295                return null;
10296            }
10297            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10298                    ps.readUserState(userId), userId);
10299            if (pi == null) {
10300                return null;
10301            }
10302            final ResolveInfo res = new ResolveInfo();
10303            res.providerInfo = pi;
10304            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10305                res.filter = filter;
10306            }
10307            res.priority = info.getPriority();
10308            res.preferredOrder = provider.owner.mPreferredOrder;
10309            res.match = match;
10310            res.isDefault = info.hasDefault;
10311            res.labelRes = info.labelRes;
10312            res.nonLocalizedLabel = info.nonLocalizedLabel;
10313            res.icon = info.icon;
10314            res.system = res.providerInfo.applicationInfo.isSystemApp();
10315            return res;
10316        }
10317
10318        @Override
10319        protected void sortResults(List<ResolveInfo> results) {
10320            Collections.sort(results, mResolvePrioritySorter);
10321        }
10322
10323        @Override
10324        protected void dumpFilter(PrintWriter out, String prefix,
10325                PackageParser.ProviderIntentInfo filter) {
10326            out.print(prefix);
10327            out.print(
10328                    Integer.toHexString(System.identityHashCode(filter.provider)));
10329            out.print(' ');
10330            filter.provider.printComponentShortName(out);
10331            out.print(" filter ");
10332            out.println(Integer.toHexString(System.identityHashCode(filter)));
10333        }
10334
10335        @Override
10336        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10337            return filter.provider;
10338        }
10339
10340        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10341            PackageParser.Provider provider = (PackageParser.Provider)label;
10342            out.print(prefix); out.print(
10343                    Integer.toHexString(System.identityHashCode(provider)));
10344                    out.print(' ');
10345                    provider.printComponentShortName(out);
10346            if (count > 1) {
10347                out.print(" ("); out.print(count); out.print(" filters)");
10348            }
10349            out.println();
10350        }
10351
10352        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10353                = new ArrayMap<ComponentName, PackageParser.Provider>();
10354        private int mFlags;
10355    }
10356
10357    private static final class EphemeralIntentResolver
10358            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10359        @Override
10360        protected EphemeralResolveIntentInfo[] newArray(int size) {
10361            return new EphemeralResolveIntentInfo[size];
10362        }
10363
10364        @Override
10365        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10366            return true;
10367        }
10368
10369        @Override
10370        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10371                int userId) {
10372            if (!sUserManager.exists(userId)) {
10373                return null;
10374            }
10375            return info.getEphemeralResolveInfo();
10376        }
10377    }
10378
10379    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10380            new Comparator<ResolveInfo>() {
10381        public int compare(ResolveInfo r1, ResolveInfo r2) {
10382            int v1 = r1.priority;
10383            int v2 = r2.priority;
10384            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10385            if (v1 != v2) {
10386                return (v1 > v2) ? -1 : 1;
10387            }
10388            v1 = r1.preferredOrder;
10389            v2 = r2.preferredOrder;
10390            if (v1 != v2) {
10391                return (v1 > v2) ? -1 : 1;
10392            }
10393            if (r1.isDefault != r2.isDefault) {
10394                return r1.isDefault ? -1 : 1;
10395            }
10396            v1 = r1.match;
10397            v2 = r2.match;
10398            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10399            if (v1 != v2) {
10400                return (v1 > v2) ? -1 : 1;
10401            }
10402            if (r1.system != r2.system) {
10403                return r1.system ? -1 : 1;
10404            }
10405            if (r1.activityInfo != null) {
10406                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10407            }
10408            if (r1.serviceInfo != null) {
10409                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10410            }
10411            if (r1.providerInfo != null) {
10412                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10413            }
10414            return 0;
10415        }
10416    };
10417
10418    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10419            new Comparator<ProviderInfo>() {
10420        public int compare(ProviderInfo p1, ProviderInfo p2) {
10421            final int v1 = p1.initOrder;
10422            final int v2 = p2.initOrder;
10423            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10424        }
10425    };
10426
10427    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10428            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10429            final int[] userIds) {
10430        mHandler.post(new Runnable() {
10431            @Override
10432            public void run() {
10433                try {
10434                    final IActivityManager am = ActivityManagerNative.getDefault();
10435                    if (am == null) return;
10436                    final int[] resolvedUserIds;
10437                    if (userIds == null) {
10438                        resolvedUserIds = am.getRunningUserIds();
10439                    } else {
10440                        resolvedUserIds = userIds;
10441                    }
10442                    for (int id : resolvedUserIds) {
10443                        final Intent intent = new Intent(action,
10444                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10445                        if (extras != null) {
10446                            intent.putExtras(extras);
10447                        }
10448                        if (targetPkg != null) {
10449                            intent.setPackage(targetPkg);
10450                        }
10451                        // Modify the UID when posting to other users
10452                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10453                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10454                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10455                            intent.putExtra(Intent.EXTRA_UID, uid);
10456                        }
10457                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10458                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10459                        if (DEBUG_BROADCASTS) {
10460                            RuntimeException here = new RuntimeException("here");
10461                            here.fillInStackTrace();
10462                            Slog.d(TAG, "Sending to user " + id + ": "
10463                                    + intent.toShortString(false, true, false, false)
10464                                    + " " + intent.getExtras(), here);
10465                        }
10466                        am.broadcastIntent(null, intent, null, finishedReceiver,
10467                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10468                                null, finishedReceiver != null, false, id);
10469                    }
10470                } catch (RemoteException ex) {
10471                }
10472            }
10473        });
10474    }
10475
10476    /**
10477     * Check if the external storage media is available. This is true if there
10478     * is a mounted external storage medium or if the external storage is
10479     * emulated.
10480     */
10481    private boolean isExternalMediaAvailable() {
10482        return mMediaMounted || Environment.isExternalStorageEmulated();
10483    }
10484
10485    @Override
10486    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10487        // writer
10488        synchronized (mPackages) {
10489            if (!isExternalMediaAvailable()) {
10490                // If the external storage is no longer mounted at this point,
10491                // the caller may not have been able to delete all of this
10492                // packages files and can not delete any more.  Bail.
10493                return null;
10494            }
10495            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10496            if (lastPackage != null) {
10497                pkgs.remove(lastPackage);
10498            }
10499            if (pkgs.size() > 0) {
10500                return pkgs.get(0);
10501            }
10502        }
10503        return null;
10504    }
10505
10506    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10507        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10508                userId, andCode ? 1 : 0, packageName);
10509        if (mSystemReady) {
10510            msg.sendToTarget();
10511        } else {
10512            if (mPostSystemReadyMessages == null) {
10513                mPostSystemReadyMessages = new ArrayList<>();
10514            }
10515            mPostSystemReadyMessages.add(msg);
10516        }
10517    }
10518
10519    void startCleaningPackages() {
10520        // reader
10521        if (!isExternalMediaAvailable()) {
10522            return;
10523        }
10524        synchronized (mPackages) {
10525            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10526                return;
10527            }
10528        }
10529        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10530        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10531        IActivityManager am = ActivityManagerNative.getDefault();
10532        if (am != null) {
10533            try {
10534                am.startService(null, intent, null, mContext.getOpPackageName(),
10535                        UserHandle.USER_SYSTEM);
10536            } catch (RemoteException e) {
10537            }
10538        }
10539    }
10540
10541    @Override
10542    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10543            int installFlags, String installerPackageName, int userId) {
10544        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10545
10546        final int callingUid = Binder.getCallingUid();
10547        enforceCrossUserPermission(callingUid, userId,
10548                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10549
10550        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10551            try {
10552                if (observer != null) {
10553                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10554                }
10555            } catch (RemoteException re) {
10556            }
10557            return;
10558        }
10559
10560        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10561            installFlags |= PackageManager.INSTALL_FROM_ADB;
10562
10563        } else {
10564            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10565            // about installerPackageName.
10566
10567            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10568            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10569        }
10570
10571        UserHandle user;
10572        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10573            user = UserHandle.ALL;
10574        } else {
10575            user = new UserHandle(userId);
10576        }
10577
10578        // Only system components can circumvent runtime permissions when installing.
10579        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10580                && mContext.checkCallingOrSelfPermission(Manifest.permission
10581                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10582            throw new SecurityException("You need the "
10583                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10584                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10585        }
10586
10587        final File originFile = new File(originPath);
10588        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10589
10590        final Message msg = mHandler.obtainMessage(INIT_COPY);
10591        final VerificationInfo verificationInfo = new VerificationInfo(
10592                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10593        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10594                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10595                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10596        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10597        msg.obj = params;
10598
10599        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10600                System.identityHashCode(msg.obj));
10601        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10602                System.identityHashCode(msg.obj));
10603
10604        mHandler.sendMessage(msg);
10605    }
10606
10607    void installStage(String packageName, File stagedDir, String stagedCid,
10608            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10609            String installerPackageName, int installerUid, UserHandle user) {
10610        if (DEBUG_EPHEMERAL) {
10611            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10612                Slog.d(TAG, "Ephemeral install of " + packageName);
10613            }
10614        }
10615        final VerificationInfo verificationInfo = new VerificationInfo(
10616                sessionParams.originatingUri, sessionParams.referrerUri,
10617                sessionParams.originatingUid, installerUid);
10618
10619        final OriginInfo origin;
10620        if (stagedDir != null) {
10621            origin = OriginInfo.fromStagedFile(stagedDir);
10622        } else {
10623            origin = OriginInfo.fromStagedContainer(stagedCid);
10624        }
10625
10626        final Message msg = mHandler.obtainMessage(INIT_COPY);
10627        final InstallParams params = new InstallParams(origin, null, observer,
10628                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10629                verificationInfo, user, sessionParams.abiOverride,
10630                sessionParams.grantedRuntimePermissions);
10631        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10632        msg.obj = params;
10633
10634        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10635                System.identityHashCode(msg.obj));
10636        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10637                System.identityHashCode(msg.obj));
10638
10639        mHandler.sendMessage(msg);
10640    }
10641
10642    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10643            int userId) {
10644        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10645        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10646    }
10647
10648    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10649            int appId, int userId) {
10650        Bundle extras = new Bundle(1);
10651        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10652
10653        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10654                packageName, extras, 0, null, null, new int[] {userId});
10655        try {
10656            IActivityManager am = ActivityManagerNative.getDefault();
10657            if (isSystem && am.isUserRunning(userId, 0)) {
10658                // The just-installed/enabled app is bundled on the system, so presumed
10659                // to be able to run automatically without needing an explicit launch.
10660                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10661                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10662                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10663                        .setPackage(packageName);
10664                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10665                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10666            }
10667        } catch (RemoteException e) {
10668            // shouldn't happen
10669            Slog.w(TAG, "Unable to bootstrap installed package", e);
10670        }
10671    }
10672
10673    @Override
10674    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10675            int userId) {
10676        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10677        PackageSetting pkgSetting;
10678        final int uid = Binder.getCallingUid();
10679        enforceCrossUserPermission(uid, userId,
10680                true /* requireFullPermission */, true /* checkShell */,
10681                "setApplicationHiddenSetting for user " + userId);
10682
10683        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10684            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10685            return false;
10686        }
10687
10688        long callingId = Binder.clearCallingIdentity();
10689        try {
10690            boolean sendAdded = false;
10691            boolean sendRemoved = false;
10692            // writer
10693            synchronized (mPackages) {
10694                pkgSetting = mSettings.mPackages.get(packageName);
10695                if (pkgSetting == null) {
10696                    return false;
10697                }
10698                if (pkgSetting.getHidden(userId) != hidden) {
10699                    pkgSetting.setHidden(hidden, userId);
10700                    mSettings.writePackageRestrictionsLPr(userId);
10701                    if (hidden) {
10702                        sendRemoved = true;
10703                    } else {
10704                        sendAdded = true;
10705                    }
10706                }
10707            }
10708            if (sendAdded) {
10709                sendPackageAddedForUser(packageName, pkgSetting, userId);
10710                return true;
10711            }
10712            if (sendRemoved) {
10713                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10714                        "hiding pkg");
10715                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10716                return true;
10717            }
10718        } finally {
10719            Binder.restoreCallingIdentity(callingId);
10720        }
10721        return false;
10722    }
10723
10724    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10725            int userId) {
10726        final PackageRemovedInfo info = new PackageRemovedInfo();
10727        info.removedPackage = packageName;
10728        info.removedUsers = new int[] {userId};
10729        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10730        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10731    }
10732
10733    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10734        if (pkgList.length > 0) {
10735            Bundle extras = new Bundle(1);
10736            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10737
10738            sendPackageBroadcast(
10739                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10740                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10741                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10742                    new int[] {userId});
10743        }
10744    }
10745
10746    /**
10747     * Returns true if application is not found or there was an error. Otherwise it returns
10748     * the hidden state of the package for the given user.
10749     */
10750    @Override
10751    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10752        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10753        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10754                true /* requireFullPermission */, false /* checkShell */,
10755                "getApplicationHidden for user " + userId);
10756        PackageSetting pkgSetting;
10757        long callingId = Binder.clearCallingIdentity();
10758        try {
10759            // writer
10760            synchronized (mPackages) {
10761                pkgSetting = mSettings.mPackages.get(packageName);
10762                if (pkgSetting == null) {
10763                    return true;
10764                }
10765                return pkgSetting.getHidden(userId);
10766            }
10767        } finally {
10768            Binder.restoreCallingIdentity(callingId);
10769        }
10770    }
10771
10772    /**
10773     * @hide
10774     */
10775    @Override
10776    public int installExistingPackageAsUser(String packageName, int userId) {
10777        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10778                null);
10779        PackageSetting pkgSetting;
10780        final int uid = Binder.getCallingUid();
10781        enforceCrossUserPermission(uid, userId,
10782                true /* requireFullPermission */, true /* checkShell */,
10783                "installExistingPackage for user " + userId);
10784        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10785            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10786        }
10787
10788        long callingId = Binder.clearCallingIdentity();
10789        try {
10790            boolean installed = false;
10791
10792            // writer
10793            synchronized (mPackages) {
10794                pkgSetting = mSettings.mPackages.get(packageName);
10795                if (pkgSetting == null) {
10796                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10797                }
10798                if (!pkgSetting.getInstalled(userId)) {
10799                    pkgSetting.setInstalled(true, userId);
10800                    pkgSetting.setHidden(false, userId);
10801                    mSettings.writePackageRestrictionsLPr(userId);
10802                    installed = true;
10803                }
10804            }
10805
10806            if (installed) {
10807                if (pkgSetting.pkg != null) {
10808                    prepareAppDataAfterInstall(pkgSetting.pkg);
10809                }
10810                sendPackageAddedForUser(packageName, pkgSetting, userId);
10811            }
10812        } finally {
10813            Binder.restoreCallingIdentity(callingId);
10814        }
10815
10816        return PackageManager.INSTALL_SUCCEEDED;
10817    }
10818
10819    boolean isUserRestricted(int userId, String restrictionKey) {
10820        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10821        if (restrictions.getBoolean(restrictionKey, false)) {
10822            Log.w(TAG, "User is restricted: " + restrictionKey);
10823            return true;
10824        }
10825        return false;
10826    }
10827
10828    @Override
10829    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10830            int userId) {
10831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10832        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10833                true /* requireFullPermission */, true /* checkShell */,
10834                "setPackagesSuspended for user " + userId);
10835
10836        if (ArrayUtils.isEmpty(packageNames)) {
10837            return packageNames;
10838        }
10839
10840        // List of package names for whom the suspended state has changed.
10841        List<String> changedPackages = new ArrayList<>(packageNames.length);
10842        // List of package names for whom the suspended state is not set as requested in this
10843        // method.
10844        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10845        for (int i = 0; i < packageNames.length; i++) {
10846            String packageName = packageNames[i];
10847            long callingId = Binder.clearCallingIdentity();
10848            try {
10849                boolean changed = false;
10850                final int appId;
10851                synchronized (mPackages) {
10852                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10853                    if (pkgSetting == null) {
10854                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10855                                + "\". Skipping suspending/un-suspending.");
10856                        unactionedPackages.add(packageName);
10857                        continue;
10858                    }
10859                    appId = pkgSetting.appId;
10860                    if (pkgSetting.getSuspended(userId) != suspended) {
10861                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10862                            unactionedPackages.add(packageName);
10863                            continue;
10864                        }
10865                        pkgSetting.setSuspended(suspended, userId);
10866                        mSettings.writePackageRestrictionsLPr(userId);
10867                        changed = true;
10868                        changedPackages.add(packageName);
10869                    }
10870                }
10871
10872                if (changed && suspended) {
10873                    killApplication(packageName, UserHandle.getUid(userId, appId),
10874                            "suspending package");
10875                }
10876            } finally {
10877                Binder.restoreCallingIdentity(callingId);
10878            }
10879        }
10880
10881        if (!changedPackages.isEmpty()) {
10882            sendPackagesSuspendedForUser(changedPackages.toArray(
10883                    new String[changedPackages.size()]), userId, suspended);
10884        }
10885
10886        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10887    }
10888
10889    @Override
10890    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10891        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10892                true /* requireFullPermission */, false /* checkShell */,
10893                "isPackageSuspendedForUser for user " + userId);
10894        synchronized (mPackages) {
10895            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10896            if (pkgSetting == null) {
10897                throw new IllegalArgumentException("Unknown target package: " + packageName);
10898            }
10899            return pkgSetting.getSuspended(userId);
10900        }
10901    }
10902
10903    /**
10904     * TODO: cache and disallow blocking the active dialer.
10905     *
10906     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
10907     */
10908    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10909        if (isPackageDeviceAdmin(packageName, userId)) {
10910            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10911                    + "\": has an active device admin");
10912            return false;
10913        }
10914
10915        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10916        if (packageName.equals(activeLauncherPackageName)) {
10917            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10918                    + "\": contains the active launcher");
10919            return false;
10920        }
10921
10922        if (packageName.equals(mRequiredInstallerPackage)) {
10923            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10924                    + "\": required for package installation");
10925            return false;
10926        }
10927
10928        if (packageName.equals(mRequiredVerifierPackage)) {
10929            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10930                    + "\": required for package verification");
10931            return false;
10932        }
10933
10934        final PackageParser.Package pkg = mPackages.get(packageName);
10935        if (pkg != null && isPrivilegedApp(pkg)) {
10936            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10937                    + "\": is a privileged app");
10938            return false;
10939        }
10940
10941        return true;
10942    }
10943
10944    private String getActiveLauncherPackageName(int userId) {
10945        Intent intent = new Intent(Intent.ACTION_MAIN);
10946        intent.addCategory(Intent.CATEGORY_HOME);
10947        ResolveInfo resolveInfo = resolveIntent(
10948                intent,
10949                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10950                PackageManager.MATCH_DEFAULT_ONLY,
10951                userId);
10952
10953        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10954    }
10955
10956    @Override
10957    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10958        mContext.enforceCallingOrSelfPermission(
10959                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10960                "Only package verification agents can verify applications");
10961
10962        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10963        final PackageVerificationResponse response = new PackageVerificationResponse(
10964                verificationCode, Binder.getCallingUid());
10965        msg.arg1 = id;
10966        msg.obj = response;
10967        mHandler.sendMessage(msg);
10968    }
10969
10970    @Override
10971    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10972            long millisecondsToDelay) {
10973        mContext.enforceCallingOrSelfPermission(
10974                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10975                "Only package verification agents can extend verification timeouts");
10976
10977        final PackageVerificationState state = mPendingVerification.get(id);
10978        final PackageVerificationResponse response = new PackageVerificationResponse(
10979                verificationCodeAtTimeout, Binder.getCallingUid());
10980
10981        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10982            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10983        }
10984        if (millisecondsToDelay < 0) {
10985            millisecondsToDelay = 0;
10986        }
10987        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10988                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10989            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10990        }
10991
10992        if ((state != null) && !state.timeoutExtended()) {
10993            state.extendTimeout();
10994
10995            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10996            msg.arg1 = id;
10997            msg.obj = response;
10998            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10999        }
11000    }
11001
11002    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11003            int verificationCode, UserHandle user) {
11004        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11005        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11006        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11007        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11008        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11009
11010        mContext.sendBroadcastAsUser(intent, user,
11011                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11012    }
11013
11014    private ComponentName matchComponentForVerifier(String packageName,
11015            List<ResolveInfo> receivers) {
11016        ActivityInfo targetReceiver = null;
11017
11018        final int NR = receivers.size();
11019        for (int i = 0; i < NR; i++) {
11020            final ResolveInfo info = receivers.get(i);
11021            if (info.activityInfo == null) {
11022                continue;
11023            }
11024
11025            if (packageName.equals(info.activityInfo.packageName)) {
11026                targetReceiver = info.activityInfo;
11027                break;
11028            }
11029        }
11030
11031        if (targetReceiver == null) {
11032            return null;
11033        }
11034
11035        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11036    }
11037
11038    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11039            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11040        if (pkgInfo.verifiers.length == 0) {
11041            return null;
11042        }
11043
11044        final int N = pkgInfo.verifiers.length;
11045        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11046        for (int i = 0; i < N; i++) {
11047            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11048
11049            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11050                    receivers);
11051            if (comp == null) {
11052                continue;
11053            }
11054
11055            final int verifierUid = getUidForVerifier(verifierInfo);
11056            if (verifierUid == -1) {
11057                continue;
11058            }
11059
11060            if (DEBUG_VERIFY) {
11061                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11062                        + " with the correct signature");
11063            }
11064            sufficientVerifiers.add(comp);
11065            verificationState.addSufficientVerifier(verifierUid);
11066        }
11067
11068        return sufficientVerifiers;
11069    }
11070
11071    private int getUidForVerifier(VerifierInfo verifierInfo) {
11072        synchronized (mPackages) {
11073            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11074            if (pkg == null) {
11075                return -1;
11076            } else if (pkg.mSignatures.length != 1) {
11077                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11078                        + " has more than one signature; ignoring");
11079                return -1;
11080            }
11081
11082            /*
11083             * If the public key of the package's signature does not match
11084             * our expected public key, then this is a different package and
11085             * we should skip.
11086             */
11087
11088            final byte[] expectedPublicKey;
11089            try {
11090                final Signature verifierSig = pkg.mSignatures[0];
11091                final PublicKey publicKey = verifierSig.getPublicKey();
11092                expectedPublicKey = publicKey.getEncoded();
11093            } catch (CertificateException e) {
11094                return -1;
11095            }
11096
11097            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11098
11099            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11100                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11101                        + " does not have the expected public key; ignoring");
11102                return -1;
11103            }
11104
11105            return pkg.applicationInfo.uid;
11106        }
11107    }
11108
11109    @Override
11110    public void finishPackageInstall(int token) {
11111        enforceSystemOrRoot("Only the system is allowed to finish installs");
11112
11113        if (DEBUG_INSTALL) {
11114            Slog.v(TAG, "BM finishing package install for " + token);
11115        }
11116        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11117
11118        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11119        mHandler.sendMessage(msg);
11120    }
11121
11122    /**
11123     * Get the verification agent timeout.
11124     *
11125     * @return verification timeout in milliseconds
11126     */
11127    private long getVerificationTimeout() {
11128        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11129                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11130                DEFAULT_VERIFICATION_TIMEOUT);
11131    }
11132
11133    /**
11134     * Get the default verification agent response code.
11135     *
11136     * @return default verification response code
11137     */
11138    private int getDefaultVerificationResponse() {
11139        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11140                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11141                DEFAULT_VERIFICATION_RESPONSE);
11142    }
11143
11144    /**
11145     * Check whether or not package verification has been enabled.
11146     *
11147     * @return true if verification should be performed
11148     */
11149    private boolean isVerificationEnabled(int userId, int installFlags) {
11150        if (!DEFAULT_VERIFY_ENABLE) {
11151            return false;
11152        }
11153        // Ephemeral apps don't get the full verification treatment
11154        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11155            if (DEBUG_EPHEMERAL) {
11156                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11157            }
11158            return false;
11159        }
11160
11161        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11162
11163        // Check if installing from ADB
11164        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11165            // Do not run verification in a test harness environment
11166            if (ActivityManager.isRunningInTestHarness()) {
11167                return false;
11168            }
11169            if (ensureVerifyAppsEnabled) {
11170                return true;
11171            }
11172            // Check if the developer does not want package verification for ADB installs
11173            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11174                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11175                return false;
11176            }
11177        }
11178
11179        if (ensureVerifyAppsEnabled) {
11180            return true;
11181        }
11182
11183        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11184                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11185    }
11186
11187    @Override
11188    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11189            throws RemoteException {
11190        mContext.enforceCallingOrSelfPermission(
11191                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11192                "Only intentfilter verification agents can verify applications");
11193
11194        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11195        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11196                Binder.getCallingUid(), verificationCode, failedDomains);
11197        msg.arg1 = id;
11198        msg.obj = response;
11199        mHandler.sendMessage(msg);
11200    }
11201
11202    @Override
11203    public int getIntentVerificationStatus(String packageName, int userId) {
11204        synchronized (mPackages) {
11205            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11206        }
11207    }
11208
11209    @Override
11210    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11211        mContext.enforceCallingOrSelfPermission(
11212                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11213
11214        boolean result = false;
11215        synchronized (mPackages) {
11216            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11217        }
11218        if (result) {
11219            scheduleWritePackageRestrictionsLocked(userId);
11220        }
11221        return result;
11222    }
11223
11224    @Override
11225    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11226            String packageName) {
11227        synchronized (mPackages) {
11228            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11229        }
11230    }
11231
11232    @Override
11233    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11234        if (TextUtils.isEmpty(packageName)) {
11235            return ParceledListSlice.emptyList();
11236        }
11237        synchronized (mPackages) {
11238            PackageParser.Package pkg = mPackages.get(packageName);
11239            if (pkg == null || pkg.activities == null) {
11240                return ParceledListSlice.emptyList();
11241            }
11242            final int count = pkg.activities.size();
11243            ArrayList<IntentFilter> result = new ArrayList<>();
11244            for (int n=0; n<count; n++) {
11245                PackageParser.Activity activity = pkg.activities.get(n);
11246                if (activity.intents != null && activity.intents.size() > 0) {
11247                    result.addAll(activity.intents);
11248                }
11249            }
11250            return new ParceledListSlice<>(result);
11251        }
11252    }
11253
11254    @Override
11255    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11256        mContext.enforceCallingOrSelfPermission(
11257                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11258
11259        synchronized (mPackages) {
11260            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11261            if (packageName != null) {
11262                result |= updateIntentVerificationStatus(packageName,
11263                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11264                        userId);
11265                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11266                        packageName, userId);
11267            }
11268            return result;
11269        }
11270    }
11271
11272    @Override
11273    public String getDefaultBrowserPackageName(int userId) {
11274        synchronized (mPackages) {
11275            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11276        }
11277    }
11278
11279    /**
11280     * Get the "allow unknown sources" setting.
11281     *
11282     * @return the current "allow unknown sources" setting
11283     */
11284    private int getUnknownSourcesSettings() {
11285        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11286                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11287                -1);
11288    }
11289
11290    @Override
11291    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11292        final int uid = Binder.getCallingUid();
11293        // writer
11294        synchronized (mPackages) {
11295            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11296            if (targetPackageSetting == null) {
11297                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11298            }
11299
11300            PackageSetting installerPackageSetting;
11301            if (installerPackageName != null) {
11302                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11303                if (installerPackageSetting == null) {
11304                    throw new IllegalArgumentException("Unknown installer package: "
11305                            + installerPackageName);
11306                }
11307            } else {
11308                installerPackageSetting = null;
11309            }
11310
11311            Signature[] callerSignature;
11312            Object obj = mSettings.getUserIdLPr(uid);
11313            if (obj != null) {
11314                if (obj instanceof SharedUserSetting) {
11315                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11316                } else if (obj instanceof PackageSetting) {
11317                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11318                } else {
11319                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11320                }
11321            } else {
11322                throw new SecurityException("Unknown calling UID: " + uid);
11323            }
11324
11325            // Verify: can't set installerPackageName to a package that is
11326            // not signed with the same cert as the caller.
11327            if (installerPackageSetting != null) {
11328                if (compareSignatures(callerSignature,
11329                        installerPackageSetting.signatures.mSignatures)
11330                        != PackageManager.SIGNATURE_MATCH) {
11331                    throw new SecurityException(
11332                            "Caller does not have same cert as new installer package "
11333                            + installerPackageName);
11334                }
11335            }
11336
11337            // Verify: if target already has an installer package, it must
11338            // be signed with the same cert as the caller.
11339            if (targetPackageSetting.installerPackageName != null) {
11340                PackageSetting setting = mSettings.mPackages.get(
11341                        targetPackageSetting.installerPackageName);
11342                // If the currently set package isn't valid, then it's always
11343                // okay to change it.
11344                if (setting != null) {
11345                    if (compareSignatures(callerSignature,
11346                            setting.signatures.mSignatures)
11347                            != PackageManager.SIGNATURE_MATCH) {
11348                        throw new SecurityException(
11349                                "Caller does not have same cert as old installer package "
11350                                + targetPackageSetting.installerPackageName);
11351                    }
11352                }
11353            }
11354
11355            // Okay!
11356            targetPackageSetting.installerPackageName = installerPackageName;
11357            scheduleWriteSettingsLocked();
11358        }
11359    }
11360
11361    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11362        // Queue up an async operation since the package installation may take a little while.
11363        mHandler.post(new Runnable() {
11364            public void run() {
11365                mHandler.removeCallbacks(this);
11366                 // Result object to be returned
11367                PackageInstalledInfo res = new PackageInstalledInfo();
11368                res.setReturnCode(currentStatus);
11369                res.uid = -1;
11370                res.pkg = null;
11371                res.removedInfo = null;
11372                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11373                    args.doPreInstall(res.returnCode);
11374                    synchronized (mInstallLock) {
11375                        installPackageTracedLI(args, res);
11376                    }
11377                    args.doPostInstall(res.returnCode, res.uid);
11378                }
11379
11380                // A restore should be performed at this point if (a) the install
11381                // succeeded, (b) the operation is not an update, and (c) the new
11382                // package has not opted out of backup participation.
11383                final boolean update = res.removedInfo != null
11384                        && res.removedInfo.removedPackage != null;
11385                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11386                boolean doRestore = !update
11387                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11388
11389                // Set up the post-install work request bookkeeping.  This will be used
11390                // and cleaned up by the post-install event handling regardless of whether
11391                // there's a restore pass performed.  Token values are >= 1.
11392                int token;
11393                if (mNextInstallToken < 0) mNextInstallToken = 1;
11394                token = mNextInstallToken++;
11395
11396                PostInstallData data = new PostInstallData(args, res);
11397                mRunningInstalls.put(token, data);
11398                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11399
11400                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11401                    // Pass responsibility to the Backup Manager.  It will perform a
11402                    // restore if appropriate, then pass responsibility back to the
11403                    // Package Manager to run the post-install observer callbacks
11404                    // and broadcasts.
11405                    IBackupManager bm = IBackupManager.Stub.asInterface(
11406                            ServiceManager.getService(Context.BACKUP_SERVICE));
11407                    if (bm != null) {
11408                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11409                                + " to BM for possible restore");
11410                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11411                        try {
11412                            // TODO: http://b/22388012
11413                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11414                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11415                            } else {
11416                                doRestore = false;
11417                            }
11418                        } catch (RemoteException e) {
11419                            // can't happen; the backup manager is local
11420                        } catch (Exception e) {
11421                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11422                            doRestore = false;
11423                        }
11424                    } else {
11425                        Slog.e(TAG, "Backup Manager not found!");
11426                        doRestore = false;
11427                    }
11428                }
11429
11430                if (!doRestore) {
11431                    // No restore possible, or the Backup Manager was mysteriously not
11432                    // available -- just fire the post-install work request directly.
11433                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11434
11435                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11436
11437                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11438                    mHandler.sendMessage(msg);
11439                }
11440            }
11441        });
11442    }
11443
11444    private abstract class HandlerParams {
11445        private static final int MAX_RETRIES = 4;
11446
11447        /**
11448         * Number of times startCopy() has been attempted and had a non-fatal
11449         * error.
11450         */
11451        private int mRetries = 0;
11452
11453        /** User handle for the user requesting the information or installation. */
11454        private final UserHandle mUser;
11455        String traceMethod;
11456        int traceCookie;
11457
11458        HandlerParams(UserHandle user) {
11459            mUser = user;
11460        }
11461
11462        UserHandle getUser() {
11463            return mUser;
11464        }
11465
11466        HandlerParams setTraceMethod(String traceMethod) {
11467            this.traceMethod = traceMethod;
11468            return this;
11469        }
11470
11471        HandlerParams setTraceCookie(int traceCookie) {
11472            this.traceCookie = traceCookie;
11473            return this;
11474        }
11475
11476        final boolean startCopy() {
11477            boolean res;
11478            try {
11479                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11480
11481                if (++mRetries > MAX_RETRIES) {
11482                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11483                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11484                    handleServiceError();
11485                    return false;
11486                } else {
11487                    handleStartCopy();
11488                    res = true;
11489                }
11490            } catch (RemoteException e) {
11491                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11492                mHandler.sendEmptyMessage(MCS_RECONNECT);
11493                res = false;
11494            }
11495            handleReturnCode();
11496            return res;
11497        }
11498
11499        final void serviceError() {
11500            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11501            handleServiceError();
11502            handleReturnCode();
11503        }
11504
11505        abstract void handleStartCopy() throws RemoteException;
11506        abstract void handleServiceError();
11507        abstract void handleReturnCode();
11508    }
11509
11510    class MeasureParams extends HandlerParams {
11511        private final PackageStats mStats;
11512        private boolean mSuccess;
11513
11514        private final IPackageStatsObserver mObserver;
11515
11516        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11517            super(new UserHandle(stats.userHandle));
11518            mObserver = observer;
11519            mStats = stats;
11520        }
11521
11522        @Override
11523        public String toString() {
11524            return "MeasureParams{"
11525                + Integer.toHexString(System.identityHashCode(this))
11526                + " " + mStats.packageName + "}";
11527        }
11528
11529        @Override
11530        void handleStartCopy() throws RemoteException {
11531            synchronized (mInstallLock) {
11532                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11533            }
11534
11535            if (mSuccess) {
11536                final boolean mounted;
11537                if (Environment.isExternalStorageEmulated()) {
11538                    mounted = true;
11539                } else {
11540                    final String status = Environment.getExternalStorageState();
11541                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11542                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11543                }
11544
11545                if (mounted) {
11546                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11547
11548                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11549                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11550
11551                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11552                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11553
11554                    // Always subtract cache size, since it's a subdirectory
11555                    mStats.externalDataSize -= mStats.externalCacheSize;
11556
11557                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11558                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11559
11560                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11561                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11562                }
11563            }
11564        }
11565
11566        @Override
11567        void handleReturnCode() {
11568            if (mObserver != null) {
11569                try {
11570                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11571                } catch (RemoteException e) {
11572                    Slog.i(TAG, "Observer no longer exists.");
11573                }
11574            }
11575        }
11576
11577        @Override
11578        void handleServiceError() {
11579            Slog.e(TAG, "Could not measure application " + mStats.packageName
11580                            + " external storage");
11581        }
11582    }
11583
11584    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11585            throws RemoteException {
11586        long result = 0;
11587        for (File path : paths) {
11588            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11589        }
11590        return result;
11591    }
11592
11593    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11594        for (File path : paths) {
11595            try {
11596                mcs.clearDirectory(path.getAbsolutePath());
11597            } catch (RemoteException e) {
11598            }
11599        }
11600    }
11601
11602    static class OriginInfo {
11603        /**
11604         * Location where install is coming from, before it has been
11605         * copied/renamed into place. This could be a single monolithic APK
11606         * file, or a cluster directory. This location may be untrusted.
11607         */
11608        final File file;
11609        final String cid;
11610
11611        /**
11612         * Flag indicating that {@link #file} or {@link #cid} has already been
11613         * staged, meaning downstream users don't need to defensively copy the
11614         * contents.
11615         */
11616        final boolean staged;
11617
11618        /**
11619         * Flag indicating that {@link #file} or {@link #cid} is an already
11620         * installed app that is being moved.
11621         */
11622        final boolean existing;
11623
11624        final String resolvedPath;
11625        final File resolvedFile;
11626
11627        static OriginInfo fromNothing() {
11628            return new OriginInfo(null, null, false, false);
11629        }
11630
11631        static OriginInfo fromUntrustedFile(File file) {
11632            return new OriginInfo(file, null, false, false);
11633        }
11634
11635        static OriginInfo fromExistingFile(File file) {
11636            return new OriginInfo(file, null, false, true);
11637        }
11638
11639        static OriginInfo fromStagedFile(File file) {
11640            return new OriginInfo(file, null, true, false);
11641        }
11642
11643        static OriginInfo fromStagedContainer(String cid) {
11644            return new OriginInfo(null, cid, true, false);
11645        }
11646
11647        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11648            this.file = file;
11649            this.cid = cid;
11650            this.staged = staged;
11651            this.existing = existing;
11652
11653            if (cid != null) {
11654                resolvedPath = PackageHelper.getSdDir(cid);
11655                resolvedFile = new File(resolvedPath);
11656            } else if (file != null) {
11657                resolvedPath = file.getAbsolutePath();
11658                resolvedFile = file;
11659            } else {
11660                resolvedPath = null;
11661                resolvedFile = null;
11662            }
11663        }
11664    }
11665
11666    static class MoveInfo {
11667        final int moveId;
11668        final String fromUuid;
11669        final String toUuid;
11670        final String packageName;
11671        final String dataAppName;
11672        final int appId;
11673        final String seinfo;
11674        final int targetSdkVersion;
11675
11676        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11677                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11678            this.moveId = moveId;
11679            this.fromUuid = fromUuid;
11680            this.toUuid = toUuid;
11681            this.packageName = packageName;
11682            this.dataAppName = dataAppName;
11683            this.appId = appId;
11684            this.seinfo = seinfo;
11685            this.targetSdkVersion = targetSdkVersion;
11686        }
11687    }
11688
11689    static class VerificationInfo {
11690        /** A constant used to indicate that a uid value is not present. */
11691        public static final int NO_UID = -1;
11692
11693        /** URI referencing where the package was downloaded from. */
11694        final Uri originatingUri;
11695
11696        /** HTTP referrer URI associated with the originatingURI. */
11697        final Uri referrer;
11698
11699        /** UID of the application that the install request originated from. */
11700        final int originatingUid;
11701
11702        /** UID of application requesting the install */
11703        final int installerUid;
11704
11705        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11706            this.originatingUri = originatingUri;
11707            this.referrer = referrer;
11708            this.originatingUid = originatingUid;
11709            this.installerUid = installerUid;
11710        }
11711    }
11712
11713    class InstallParams extends HandlerParams {
11714        final OriginInfo origin;
11715        final MoveInfo move;
11716        final IPackageInstallObserver2 observer;
11717        int installFlags;
11718        final String installerPackageName;
11719        final String volumeUuid;
11720        private InstallArgs mArgs;
11721        private int mRet;
11722        final String packageAbiOverride;
11723        final String[] grantedRuntimePermissions;
11724        final VerificationInfo verificationInfo;
11725
11726        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11727                int installFlags, String installerPackageName, String volumeUuid,
11728                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11729                String[] grantedPermissions) {
11730            super(user);
11731            this.origin = origin;
11732            this.move = move;
11733            this.observer = observer;
11734            this.installFlags = installFlags;
11735            this.installerPackageName = installerPackageName;
11736            this.volumeUuid = volumeUuid;
11737            this.verificationInfo = verificationInfo;
11738            this.packageAbiOverride = packageAbiOverride;
11739            this.grantedRuntimePermissions = grantedPermissions;
11740        }
11741
11742        @Override
11743        public String toString() {
11744            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11745                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11746        }
11747
11748        private int installLocationPolicy(PackageInfoLite pkgLite) {
11749            String packageName = pkgLite.packageName;
11750            int installLocation = pkgLite.installLocation;
11751            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11752            // reader
11753            synchronized (mPackages) {
11754                // Currently installed package which the new package is attempting to replace or
11755                // null if no such package is installed.
11756                PackageParser.Package installedPkg = mPackages.get(packageName);
11757                // Package which currently owns the data which the new package will own if installed.
11758                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11759                // will be null whereas dataOwnerPkg will contain information about the package
11760                // which was uninstalled while keeping its data.
11761                PackageParser.Package dataOwnerPkg = installedPkg;
11762                if (dataOwnerPkg  == null) {
11763                    PackageSetting ps = mSettings.mPackages.get(packageName);
11764                    if (ps != null) {
11765                        dataOwnerPkg = ps.pkg;
11766                    }
11767                }
11768
11769                if (dataOwnerPkg != null) {
11770                    // If installed, the package will get access to data left on the device by its
11771                    // predecessor. As a security measure, this is permited only if this is not a
11772                    // version downgrade or if the predecessor package is marked as debuggable and
11773                    // a downgrade is explicitly requested.
11774                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11775                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11776                        try {
11777                            checkDowngrade(dataOwnerPkg, pkgLite);
11778                        } catch (PackageManagerException e) {
11779                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11780                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11781                        }
11782                    }
11783                }
11784
11785                if (installedPkg != null) {
11786                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11787                        // Check for updated system application.
11788                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11789                            if (onSd) {
11790                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11791                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11792                            }
11793                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11794                        } else {
11795                            if (onSd) {
11796                                // Install flag overrides everything.
11797                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11798                            }
11799                            // If current upgrade specifies particular preference
11800                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11801                                // Application explicitly specified internal.
11802                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11803                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11804                                // App explictly prefers external. Let policy decide
11805                            } else {
11806                                // Prefer previous location
11807                                if (isExternal(installedPkg)) {
11808                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11809                                }
11810                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11811                            }
11812                        }
11813                    } else {
11814                        // Invalid install. Return error code
11815                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11816                    }
11817                }
11818            }
11819            // All the special cases have been taken care of.
11820            // Return result based on recommended install location.
11821            if (onSd) {
11822                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11823            }
11824            return pkgLite.recommendedInstallLocation;
11825        }
11826
11827        /*
11828         * Invoke remote method to get package information and install
11829         * location values. Override install location based on default
11830         * policy if needed and then create install arguments based
11831         * on the install location.
11832         */
11833        public void handleStartCopy() throws RemoteException {
11834            int ret = PackageManager.INSTALL_SUCCEEDED;
11835
11836            // If we're already staged, we've firmly committed to an install location
11837            if (origin.staged) {
11838                if (origin.file != null) {
11839                    installFlags |= PackageManager.INSTALL_INTERNAL;
11840                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11841                } else if (origin.cid != null) {
11842                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11843                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11844                } else {
11845                    throw new IllegalStateException("Invalid stage location");
11846                }
11847            }
11848
11849            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11850            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11851            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11852            PackageInfoLite pkgLite = null;
11853
11854            if (onInt && onSd) {
11855                // Check if both bits are set.
11856                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11857                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11858            } else if (onSd && ephemeral) {
11859                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11860                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11861            } else {
11862                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11863                        packageAbiOverride);
11864
11865                if (DEBUG_EPHEMERAL && ephemeral) {
11866                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11867                }
11868
11869                /*
11870                 * If we have too little free space, try to free cache
11871                 * before giving up.
11872                 */
11873                if (!origin.staged && pkgLite.recommendedInstallLocation
11874                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11875                    // TODO: focus freeing disk space on the target device
11876                    final StorageManager storage = StorageManager.from(mContext);
11877                    final long lowThreshold = storage.getStorageLowBytes(
11878                            Environment.getDataDirectory());
11879
11880                    final long sizeBytes = mContainerService.calculateInstalledSize(
11881                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11882
11883                    try {
11884                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11885                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11886                                installFlags, packageAbiOverride);
11887                    } catch (InstallerException e) {
11888                        Slog.w(TAG, "Failed to free cache", e);
11889                    }
11890
11891                    /*
11892                     * The cache free must have deleted the file we
11893                     * downloaded to install.
11894                     *
11895                     * TODO: fix the "freeCache" call to not delete
11896                     *       the file we care about.
11897                     */
11898                    if (pkgLite.recommendedInstallLocation
11899                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11900                        pkgLite.recommendedInstallLocation
11901                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11902                    }
11903                }
11904            }
11905
11906            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11907                int loc = pkgLite.recommendedInstallLocation;
11908                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11909                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11910                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11911                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11912                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11913                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11914                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11915                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11916                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11917                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11918                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11919                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11920                } else {
11921                    // Override with defaults if needed.
11922                    loc = installLocationPolicy(pkgLite);
11923                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11924                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11925                    } else if (!onSd && !onInt) {
11926                        // Override install location with flags
11927                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11928                            // Set the flag to install on external media.
11929                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11930                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11931                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11932                            if (DEBUG_EPHEMERAL) {
11933                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11934                            }
11935                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11936                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11937                                    |PackageManager.INSTALL_INTERNAL);
11938                        } else {
11939                            // Make sure the flag for installing on external
11940                            // media is unset
11941                            installFlags |= PackageManager.INSTALL_INTERNAL;
11942                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11943                        }
11944                    }
11945                }
11946            }
11947
11948            final InstallArgs args = createInstallArgs(this);
11949            mArgs = args;
11950
11951            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11952                // TODO: http://b/22976637
11953                // Apps installed for "all" users use the device owner to verify the app
11954                UserHandle verifierUser = getUser();
11955                if (verifierUser == UserHandle.ALL) {
11956                    verifierUser = UserHandle.SYSTEM;
11957                }
11958
11959                /*
11960                 * Determine if we have any installed package verifiers. If we
11961                 * do, then we'll defer to them to verify the packages.
11962                 */
11963                final int requiredUid = mRequiredVerifierPackage == null ? -1
11964                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11965                                verifierUser.getIdentifier());
11966                if (!origin.existing && requiredUid != -1
11967                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11968                    final Intent verification = new Intent(
11969                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11970                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11971                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11972                            PACKAGE_MIME_TYPE);
11973                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11974
11975                    // Query all live verifiers based on current user state
11976                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
11977                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11978
11979                    if (DEBUG_VERIFY) {
11980                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11981                                + verification.toString() + " with " + pkgLite.verifiers.length
11982                                + " optional verifiers");
11983                    }
11984
11985                    final int verificationId = mPendingVerificationToken++;
11986
11987                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11988
11989                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11990                            installerPackageName);
11991
11992                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11993                            installFlags);
11994
11995                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11996                            pkgLite.packageName);
11997
11998                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11999                            pkgLite.versionCode);
12000
12001                    if (verificationInfo != null) {
12002                        if (verificationInfo.originatingUri != null) {
12003                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12004                                    verificationInfo.originatingUri);
12005                        }
12006                        if (verificationInfo.referrer != null) {
12007                            verification.putExtra(Intent.EXTRA_REFERRER,
12008                                    verificationInfo.referrer);
12009                        }
12010                        if (verificationInfo.originatingUid >= 0) {
12011                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12012                                    verificationInfo.originatingUid);
12013                        }
12014                        if (verificationInfo.installerUid >= 0) {
12015                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12016                                    verificationInfo.installerUid);
12017                        }
12018                    }
12019
12020                    final PackageVerificationState verificationState = new PackageVerificationState(
12021                            requiredUid, args);
12022
12023                    mPendingVerification.append(verificationId, verificationState);
12024
12025                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12026                            receivers, verificationState);
12027
12028                    /*
12029                     * If any sufficient verifiers were listed in the package
12030                     * manifest, attempt to ask them.
12031                     */
12032                    if (sufficientVerifiers != null) {
12033                        final int N = sufficientVerifiers.size();
12034                        if (N == 0) {
12035                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12036                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12037                        } else {
12038                            for (int i = 0; i < N; i++) {
12039                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12040
12041                                final Intent sufficientIntent = new Intent(verification);
12042                                sufficientIntent.setComponent(verifierComponent);
12043                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12044                            }
12045                        }
12046                    }
12047
12048                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12049                            mRequiredVerifierPackage, receivers);
12050                    if (ret == PackageManager.INSTALL_SUCCEEDED
12051                            && mRequiredVerifierPackage != null) {
12052                        Trace.asyncTraceBegin(
12053                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12054                        /*
12055                         * Send the intent to the required verification agent,
12056                         * but only start the verification timeout after the
12057                         * target BroadcastReceivers have run.
12058                         */
12059                        verification.setComponent(requiredVerifierComponent);
12060                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12061                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12062                                new BroadcastReceiver() {
12063                                    @Override
12064                                    public void onReceive(Context context, Intent intent) {
12065                                        final Message msg = mHandler
12066                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12067                                        msg.arg1 = verificationId;
12068                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12069                                    }
12070                                }, null, 0, null, null);
12071
12072                        /*
12073                         * We don't want the copy to proceed until verification
12074                         * succeeds, so null out this field.
12075                         */
12076                        mArgs = null;
12077                    }
12078                } else {
12079                    /*
12080                     * No package verification is enabled, so immediately start
12081                     * the remote call to initiate copy using temporary file.
12082                     */
12083                    ret = args.copyApk(mContainerService, true);
12084                }
12085            }
12086
12087            mRet = ret;
12088        }
12089
12090        @Override
12091        void handleReturnCode() {
12092            // If mArgs is null, then MCS couldn't be reached. When it
12093            // reconnects, it will try again to install. At that point, this
12094            // will succeed.
12095            if (mArgs != null) {
12096                processPendingInstall(mArgs, mRet);
12097            }
12098        }
12099
12100        @Override
12101        void handleServiceError() {
12102            mArgs = createInstallArgs(this);
12103            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12104        }
12105
12106        public boolean isForwardLocked() {
12107            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12108        }
12109    }
12110
12111    /**
12112     * Used during creation of InstallArgs
12113     *
12114     * @param installFlags package installation flags
12115     * @return true if should be installed on external storage
12116     */
12117    private static boolean installOnExternalAsec(int installFlags) {
12118        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12119            return false;
12120        }
12121        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12122            return true;
12123        }
12124        return false;
12125    }
12126
12127    /**
12128     * Used during creation of InstallArgs
12129     *
12130     * @param installFlags package installation flags
12131     * @return true if should be installed as forward locked
12132     */
12133    private static boolean installForwardLocked(int installFlags) {
12134        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12135    }
12136
12137    private InstallArgs createInstallArgs(InstallParams params) {
12138        if (params.move != null) {
12139            return new MoveInstallArgs(params);
12140        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12141            return new AsecInstallArgs(params);
12142        } else {
12143            return new FileInstallArgs(params);
12144        }
12145    }
12146
12147    /**
12148     * Create args that describe an existing installed package. Typically used
12149     * when cleaning up old installs, or used as a move source.
12150     */
12151    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12152            String resourcePath, String[] instructionSets) {
12153        final boolean isInAsec;
12154        if (installOnExternalAsec(installFlags)) {
12155            /* Apps on SD card are always in ASEC containers. */
12156            isInAsec = true;
12157        } else if (installForwardLocked(installFlags)
12158                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12159            /*
12160             * Forward-locked apps are only in ASEC containers if they're the
12161             * new style
12162             */
12163            isInAsec = true;
12164        } else {
12165            isInAsec = false;
12166        }
12167
12168        if (isInAsec) {
12169            return new AsecInstallArgs(codePath, instructionSets,
12170                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12171        } else {
12172            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12173        }
12174    }
12175
12176    static abstract class InstallArgs {
12177        /** @see InstallParams#origin */
12178        final OriginInfo origin;
12179        /** @see InstallParams#move */
12180        final MoveInfo move;
12181
12182        final IPackageInstallObserver2 observer;
12183        // Always refers to PackageManager flags only
12184        final int installFlags;
12185        final String installerPackageName;
12186        final String volumeUuid;
12187        final UserHandle user;
12188        final String abiOverride;
12189        final String[] installGrantPermissions;
12190        /** If non-null, drop an async trace when the install completes */
12191        final String traceMethod;
12192        final int traceCookie;
12193
12194        // The list of instruction sets supported by this app. This is currently
12195        // only used during the rmdex() phase to clean up resources. We can get rid of this
12196        // if we move dex files under the common app path.
12197        /* nullable */ String[] instructionSets;
12198
12199        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12200                int installFlags, String installerPackageName, String volumeUuid,
12201                UserHandle user, String[] instructionSets,
12202                String abiOverride, String[] installGrantPermissions,
12203                String traceMethod, int traceCookie) {
12204            this.origin = origin;
12205            this.move = move;
12206            this.installFlags = installFlags;
12207            this.observer = observer;
12208            this.installerPackageName = installerPackageName;
12209            this.volumeUuid = volumeUuid;
12210            this.user = user;
12211            this.instructionSets = instructionSets;
12212            this.abiOverride = abiOverride;
12213            this.installGrantPermissions = installGrantPermissions;
12214            this.traceMethod = traceMethod;
12215            this.traceCookie = traceCookie;
12216        }
12217
12218        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12219        abstract int doPreInstall(int status);
12220
12221        /**
12222         * Rename package into final resting place. All paths on the given
12223         * scanned package should be updated to reflect the rename.
12224         */
12225        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12226        abstract int doPostInstall(int status, int uid);
12227
12228        /** @see PackageSettingBase#codePathString */
12229        abstract String getCodePath();
12230        /** @see PackageSettingBase#resourcePathString */
12231        abstract String getResourcePath();
12232
12233        // Need installer lock especially for dex file removal.
12234        abstract void cleanUpResourcesLI();
12235        abstract boolean doPostDeleteLI(boolean delete);
12236
12237        /**
12238         * Called before the source arguments are copied. This is used mostly
12239         * for MoveParams when it needs to read the source file to put it in the
12240         * destination.
12241         */
12242        int doPreCopy() {
12243            return PackageManager.INSTALL_SUCCEEDED;
12244        }
12245
12246        /**
12247         * Called after the source arguments are copied. This is used mostly for
12248         * MoveParams when it needs to read the source file to put it in the
12249         * destination.
12250         *
12251         * @return
12252         */
12253        int doPostCopy(int uid) {
12254            return PackageManager.INSTALL_SUCCEEDED;
12255        }
12256
12257        protected boolean isFwdLocked() {
12258            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12259        }
12260
12261        protected boolean isExternalAsec() {
12262            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12263        }
12264
12265        protected boolean isEphemeral() {
12266            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12267        }
12268
12269        UserHandle getUser() {
12270            return user;
12271        }
12272    }
12273
12274    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12275        if (!allCodePaths.isEmpty()) {
12276            if (instructionSets == null) {
12277                throw new IllegalStateException("instructionSet == null");
12278            }
12279            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12280            for (String codePath : allCodePaths) {
12281                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12282                    try {
12283                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12284                    } catch (InstallerException ignored) {
12285                    }
12286                }
12287            }
12288        }
12289    }
12290
12291    /**
12292     * Logic to handle installation of non-ASEC applications, including copying
12293     * and renaming logic.
12294     */
12295    class FileInstallArgs extends InstallArgs {
12296        private File codeFile;
12297        private File resourceFile;
12298
12299        // Example topology:
12300        // /data/app/com.example/base.apk
12301        // /data/app/com.example/split_foo.apk
12302        // /data/app/com.example/lib/arm/libfoo.so
12303        // /data/app/com.example/lib/arm64/libfoo.so
12304        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12305
12306        /** New install */
12307        FileInstallArgs(InstallParams params) {
12308            super(params.origin, params.move, params.observer, params.installFlags,
12309                    params.installerPackageName, params.volumeUuid,
12310                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12311                    params.grantedRuntimePermissions,
12312                    params.traceMethod, params.traceCookie);
12313            if (isFwdLocked()) {
12314                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12315            }
12316        }
12317
12318        /** Existing install */
12319        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12320            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12321                    null, null, null, 0);
12322            this.codeFile = (codePath != null) ? new File(codePath) : null;
12323            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12324        }
12325
12326        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12327            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12328            try {
12329                return doCopyApk(imcs, temp);
12330            } finally {
12331                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12332            }
12333        }
12334
12335        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12336            if (origin.staged) {
12337                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12338                codeFile = origin.file;
12339                resourceFile = origin.file;
12340                return PackageManager.INSTALL_SUCCEEDED;
12341            }
12342
12343            try {
12344                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12345                final File tempDir =
12346                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12347                codeFile = tempDir;
12348                resourceFile = tempDir;
12349            } catch (IOException e) {
12350                Slog.w(TAG, "Failed to create copy file: " + e);
12351                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12352            }
12353
12354            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12355                @Override
12356                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12357                    if (!FileUtils.isValidExtFilename(name)) {
12358                        throw new IllegalArgumentException("Invalid filename: " + name);
12359                    }
12360                    try {
12361                        final File file = new File(codeFile, name);
12362                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12363                                O_RDWR | O_CREAT, 0644);
12364                        Os.chmod(file.getAbsolutePath(), 0644);
12365                        return new ParcelFileDescriptor(fd);
12366                    } catch (ErrnoException e) {
12367                        throw new RemoteException("Failed to open: " + e.getMessage());
12368                    }
12369                }
12370            };
12371
12372            int ret = PackageManager.INSTALL_SUCCEEDED;
12373            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12374            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12375                Slog.e(TAG, "Failed to copy package");
12376                return ret;
12377            }
12378
12379            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12380            NativeLibraryHelper.Handle handle = null;
12381            try {
12382                handle = NativeLibraryHelper.Handle.create(codeFile);
12383                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12384                        abiOverride);
12385            } catch (IOException e) {
12386                Slog.e(TAG, "Copying native libraries failed", e);
12387                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12388            } finally {
12389                IoUtils.closeQuietly(handle);
12390            }
12391
12392            return ret;
12393        }
12394
12395        int doPreInstall(int status) {
12396            if (status != PackageManager.INSTALL_SUCCEEDED) {
12397                cleanUp();
12398            }
12399            return status;
12400        }
12401
12402        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12403            if (status != PackageManager.INSTALL_SUCCEEDED) {
12404                cleanUp();
12405                return false;
12406            }
12407
12408            final File targetDir = codeFile.getParentFile();
12409            final File beforeCodeFile = codeFile;
12410            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12411
12412            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12413            try {
12414                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12415            } catch (ErrnoException e) {
12416                Slog.w(TAG, "Failed to rename", e);
12417                return false;
12418            }
12419
12420            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12421                Slog.w(TAG, "Failed to restorecon");
12422                return false;
12423            }
12424
12425            // Reflect the rename internally
12426            codeFile = afterCodeFile;
12427            resourceFile = afterCodeFile;
12428
12429            // Reflect the rename in scanned details
12430            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12431            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12432                    afterCodeFile, pkg.baseCodePath));
12433            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12434                    afterCodeFile, pkg.splitCodePaths));
12435
12436            // Reflect the rename in app info
12437            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12438            pkg.setApplicationInfoCodePath(pkg.codePath);
12439            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12440            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12441            pkg.setApplicationInfoResourcePath(pkg.codePath);
12442            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12443            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12444
12445            return true;
12446        }
12447
12448        int doPostInstall(int status, int uid) {
12449            if (status != PackageManager.INSTALL_SUCCEEDED) {
12450                cleanUp();
12451            }
12452            return status;
12453        }
12454
12455        @Override
12456        String getCodePath() {
12457            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12458        }
12459
12460        @Override
12461        String getResourcePath() {
12462            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12463        }
12464
12465        private boolean cleanUp() {
12466            if (codeFile == null || !codeFile.exists()) {
12467                return false;
12468            }
12469
12470            removeCodePathLI(codeFile);
12471
12472            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12473                resourceFile.delete();
12474            }
12475
12476            return true;
12477        }
12478
12479        void cleanUpResourcesLI() {
12480            // Try enumerating all code paths before deleting
12481            List<String> allCodePaths = Collections.EMPTY_LIST;
12482            if (codeFile != null && codeFile.exists()) {
12483                try {
12484                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12485                    allCodePaths = pkg.getAllCodePaths();
12486                } catch (PackageParserException e) {
12487                    // Ignored; we tried our best
12488                }
12489            }
12490
12491            cleanUp();
12492            removeDexFiles(allCodePaths, instructionSets);
12493        }
12494
12495        boolean doPostDeleteLI(boolean delete) {
12496            // XXX err, shouldn't we respect the delete flag?
12497            cleanUpResourcesLI();
12498            return true;
12499        }
12500    }
12501
12502    private boolean isAsecExternal(String cid) {
12503        final String asecPath = PackageHelper.getSdFilesystem(cid);
12504        return !asecPath.startsWith(mAsecInternalPath);
12505    }
12506
12507    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12508            PackageManagerException {
12509        if (copyRet < 0) {
12510            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12511                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12512                throw new PackageManagerException(copyRet, message);
12513            }
12514        }
12515    }
12516
12517    /**
12518     * Extract the MountService "container ID" from the full code path of an
12519     * .apk.
12520     */
12521    static String cidFromCodePath(String fullCodePath) {
12522        int eidx = fullCodePath.lastIndexOf("/");
12523        String subStr1 = fullCodePath.substring(0, eidx);
12524        int sidx = subStr1.lastIndexOf("/");
12525        return subStr1.substring(sidx+1, eidx);
12526    }
12527
12528    /**
12529     * Logic to handle installation of ASEC applications, including copying and
12530     * renaming logic.
12531     */
12532    class AsecInstallArgs extends InstallArgs {
12533        static final String RES_FILE_NAME = "pkg.apk";
12534        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12535
12536        String cid;
12537        String packagePath;
12538        String resourcePath;
12539
12540        /** New install */
12541        AsecInstallArgs(InstallParams params) {
12542            super(params.origin, params.move, params.observer, params.installFlags,
12543                    params.installerPackageName, params.volumeUuid,
12544                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12545                    params.grantedRuntimePermissions,
12546                    params.traceMethod, params.traceCookie);
12547        }
12548
12549        /** Existing install */
12550        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12551                        boolean isExternal, boolean isForwardLocked) {
12552            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12553                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12554                    instructionSets, null, null, null, 0);
12555            // Hackily pretend we're still looking at a full code path
12556            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12557                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12558            }
12559
12560            // Extract cid from fullCodePath
12561            int eidx = fullCodePath.lastIndexOf("/");
12562            String subStr1 = fullCodePath.substring(0, eidx);
12563            int sidx = subStr1.lastIndexOf("/");
12564            cid = subStr1.substring(sidx+1, eidx);
12565            setMountPath(subStr1);
12566        }
12567
12568        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12569            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12570                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12571                    instructionSets, null, null, null, 0);
12572            this.cid = cid;
12573            setMountPath(PackageHelper.getSdDir(cid));
12574        }
12575
12576        void createCopyFile() {
12577            cid = mInstallerService.allocateExternalStageCidLegacy();
12578        }
12579
12580        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12581            if (origin.staged && origin.cid != null) {
12582                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12583                cid = origin.cid;
12584                setMountPath(PackageHelper.getSdDir(cid));
12585                return PackageManager.INSTALL_SUCCEEDED;
12586            }
12587
12588            if (temp) {
12589                createCopyFile();
12590            } else {
12591                /*
12592                 * Pre-emptively destroy the container since it's destroyed if
12593                 * copying fails due to it existing anyway.
12594                 */
12595                PackageHelper.destroySdDir(cid);
12596            }
12597
12598            final String newMountPath = imcs.copyPackageToContainer(
12599                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12600                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12601
12602            if (newMountPath != null) {
12603                setMountPath(newMountPath);
12604                return PackageManager.INSTALL_SUCCEEDED;
12605            } else {
12606                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12607            }
12608        }
12609
12610        @Override
12611        String getCodePath() {
12612            return packagePath;
12613        }
12614
12615        @Override
12616        String getResourcePath() {
12617            return resourcePath;
12618        }
12619
12620        int doPreInstall(int status) {
12621            if (status != PackageManager.INSTALL_SUCCEEDED) {
12622                // Destroy container
12623                PackageHelper.destroySdDir(cid);
12624            } else {
12625                boolean mounted = PackageHelper.isContainerMounted(cid);
12626                if (!mounted) {
12627                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12628                            Process.SYSTEM_UID);
12629                    if (newMountPath != null) {
12630                        setMountPath(newMountPath);
12631                    } else {
12632                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12633                    }
12634                }
12635            }
12636            return status;
12637        }
12638
12639        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12640            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12641            String newMountPath = null;
12642            if (PackageHelper.isContainerMounted(cid)) {
12643                // Unmount the container
12644                if (!PackageHelper.unMountSdDir(cid)) {
12645                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12646                    return false;
12647                }
12648            }
12649            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12650                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12651                        " which might be stale. Will try to clean up.");
12652                // Clean up the stale container and proceed to recreate.
12653                if (!PackageHelper.destroySdDir(newCacheId)) {
12654                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12655                    return false;
12656                }
12657                // Successfully cleaned up stale container. Try to rename again.
12658                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12659                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12660                            + " inspite of cleaning it up.");
12661                    return false;
12662                }
12663            }
12664            if (!PackageHelper.isContainerMounted(newCacheId)) {
12665                Slog.w(TAG, "Mounting container " + newCacheId);
12666                newMountPath = PackageHelper.mountSdDir(newCacheId,
12667                        getEncryptKey(), Process.SYSTEM_UID);
12668            } else {
12669                newMountPath = PackageHelper.getSdDir(newCacheId);
12670            }
12671            if (newMountPath == null) {
12672                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12673                return false;
12674            }
12675            Log.i(TAG, "Succesfully renamed " + cid +
12676                    " to " + newCacheId +
12677                    " at new path: " + newMountPath);
12678            cid = newCacheId;
12679
12680            final File beforeCodeFile = new File(packagePath);
12681            setMountPath(newMountPath);
12682            final File afterCodeFile = new File(packagePath);
12683
12684            // Reflect the rename in scanned details
12685            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12686            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12687                    afterCodeFile, pkg.baseCodePath));
12688            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12689                    afterCodeFile, pkg.splitCodePaths));
12690
12691            // Reflect the rename in app info
12692            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12693            pkg.setApplicationInfoCodePath(pkg.codePath);
12694            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12695            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12696            pkg.setApplicationInfoResourcePath(pkg.codePath);
12697            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12698            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12699
12700            return true;
12701        }
12702
12703        private void setMountPath(String mountPath) {
12704            final File mountFile = new File(mountPath);
12705
12706            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12707            if (monolithicFile.exists()) {
12708                packagePath = monolithicFile.getAbsolutePath();
12709                if (isFwdLocked()) {
12710                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12711                } else {
12712                    resourcePath = packagePath;
12713                }
12714            } else {
12715                packagePath = mountFile.getAbsolutePath();
12716                resourcePath = packagePath;
12717            }
12718        }
12719
12720        int doPostInstall(int status, int uid) {
12721            if (status != PackageManager.INSTALL_SUCCEEDED) {
12722                cleanUp();
12723            } else {
12724                final int groupOwner;
12725                final String protectedFile;
12726                if (isFwdLocked()) {
12727                    groupOwner = UserHandle.getSharedAppGid(uid);
12728                    protectedFile = RES_FILE_NAME;
12729                } else {
12730                    groupOwner = -1;
12731                    protectedFile = null;
12732                }
12733
12734                if (uid < Process.FIRST_APPLICATION_UID
12735                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12736                    Slog.e(TAG, "Failed to finalize " + cid);
12737                    PackageHelper.destroySdDir(cid);
12738                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12739                }
12740
12741                boolean mounted = PackageHelper.isContainerMounted(cid);
12742                if (!mounted) {
12743                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12744                }
12745            }
12746            return status;
12747        }
12748
12749        private void cleanUp() {
12750            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12751
12752            // Destroy secure container
12753            PackageHelper.destroySdDir(cid);
12754        }
12755
12756        private List<String> getAllCodePaths() {
12757            final File codeFile = new File(getCodePath());
12758            if (codeFile != null && codeFile.exists()) {
12759                try {
12760                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12761                    return pkg.getAllCodePaths();
12762                } catch (PackageParserException e) {
12763                    // Ignored; we tried our best
12764                }
12765            }
12766            return Collections.EMPTY_LIST;
12767        }
12768
12769        void cleanUpResourcesLI() {
12770            // Enumerate all code paths before deleting
12771            cleanUpResourcesLI(getAllCodePaths());
12772        }
12773
12774        private void cleanUpResourcesLI(List<String> allCodePaths) {
12775            cleanUp();
12776            removeDexFiles(allCodePaths, instructionSets);
12777        }
12778
12779        String getPackageName() {
12780            return getAsecPackageName(cid);
12781        }
12782
12783        boolean doPostDeleteLI(boolean delete) {
12784            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12785            final List<String> allCodePaths = getAllCodePaths();
12786            boolean mounted = PackageHelper.isContainerMounted(cid);
12787            if (mounted) {
12788                // Unmount first
12789                if (PackageHelper.unMountSdDir(cid)) {
12790                    mounted = false;
12791                }
12792            }
12793            if (!mounted && delete) {
12794                cleanUpResourcesLI(allCodePaths);
12795            }
12796            return !mounted;
12797        }
12798
12799        @Override
12800        int doPreCopy() {
12801            if (isFwdLocked()) {
12802                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12803                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12804                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12805                }
12806            }
12807
12808            return PackageManager.INSTALL_SUCCEEDED;
12809        }
12810
12811        @Override
12812        int doPostCopy(int uid) {
12813            if (isFwdLocked()) {
12814                if (uid < Process.FIRST_APPLICATION_UID
12815                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12816                                RES_FILE_NAME)) {
12817                    Slog.e(TAG, "Failed to finalize " + cid);
12818                    PackageHelper.destroySdDir(cid);
12819                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12820                }
12821            }
12822
12823            return PackageManager.INSTALL_SUCCEEDED;
12824        }
12825    }
12826
12827    /**
12828     * Logic to handle movement of existing installed applications.
12829     */
12830    class MoveInstallArgs extends InstallArgs {
12831        private File codeFile;
12832        private File resourceFile;
12833
12834        /** New install */
12835        MoveInstallArgs(InstallParams params) {
12836            super(params.origin, params.move, params.observer, params.installFlags,
12837                    params.installerPackageName, params.volumeUuid,
12838                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12839                    params.grantedRuntimePermissions,
12840                    params.traceMethod, params.traceCookie);
12841        }
12842
12843        int copyApk(IMediaContainerService imcs, boolean temp) {
12844            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12845                    + move.fromUuid + " to " + move.toUuid);
12846            synchronized (mInstaller) {
12847                try {
12848                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12849                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12850                } catch (InstallerException e) {
12851                    Slog.w(TAG, "Failed to move app", e);
12852                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12853                }
12854            }
12855
12856            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12857            resourceFile = codeFile;
12858            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12859
12860            return PackageManager.INSTALL_SUCCEEDED;
12861        }
12862
12863        int doPreInstall(int status) {
12864            if (status != PackageManager.INSTALL_SUCCEEDED) {
12865                cleanUp(move.toUuid);
12866            }
12867            return status;
12868        }
12869
12870        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12871            if (status != PackageManager.INSTALL_SUCCEEDED) {
12872                cleanUp(move.toUuid);
12873                return false;
12874            }
12875
12876            // Reflect the move in app info
12877            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12878            pkg.setApplicationInfoCodePath(pkg.codePath);
12879            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12880            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12881            pkg.setApplicationInfoResourcePath(pkg.codePath);
12882            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12883            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12884
12885            return true;
12886        }
12887
12888        int doPostInstall(int status, int uid) {
12889            if (status == PackageManager.INSTALL_SUCCEEDED) {
12890                cleanUp(move.fromUuid);
12891            } else {
12892                cleanUp(move.toUuid);
12893            }
12894            return status;
12895        }
12896
12897        @Override
12898        String getCodePath() {
12899            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12900        }
12901
12902        @Override
12903        String getResourcePath() {
12904            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12905        }
12906
12907        private boolean cleanUp(String volumeUuid) {
12908            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12909                    move.dataAppName);
12910            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12911            synchronized (mInstallLock) {
12912                // Clean up both app data and code
12913                removeDataDirsLI(volumeUuid, move.packageName);
12914                removeCodePathLI(codeFile);
12915            }
12916            return true;
12917        }
12918
12919        void cleanUpResourcesLI() {
12920            throw new UnsupportedOperationException();
12921        }
12922
12923        boolean doPostDeleteLI(boolean delete) {
12924            throw new UnsupportedOperationException();
12925        }
12926    }
12927
12928    static String getAsecPackageName(String packageCid) {
12929        int idx = packageCid.lastIndexOf("-");
12930        if (idx == -1) {
12931            return packageCid;
12932        }
12933        return packageCid.substring(0, idx);
12934    }
12935
12936    // Utility method used to create code paths based on package name and available index.
12937    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12938        String idxStr = "";
12939        int idx = 1;
12940        // Fall back to default value of idx=1 if prefix is not
12941        // part of oldCodePath
12942        if (oldCodePath != null) {
12943            String subStr = oldCodePath;
12944            // Drop the suffix right away
12945            if (suffix != null && subStr.endsWith(suffix)) {
12946                subStr = subStr.substring(0, subStr.length() - suffix.length());
12947            }
12948            // If oldCodePath already contains prefix find out the
12949            // ending index to either increment or decrement.
12950            int sidx = subStr.lastIndexOf(prefix);
12951            if (sidx != -1) {
12952                subStr = subStr.substring(sidx + prefix.length());
12953                if (subStr != null) {
12954                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12955                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12956                    }
12957                    try {
12958                        idx = Integer.parseInt(subStr);
12959                        if (idx <= 1) {
12960                            idx++;
12961                        } else {
12962                            idx--;
12963                        }
12964                    } catch(NumberFormatException e) {
12965                    }
12966                }
12967            }
12968        }
12969        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12970        return prefix + idxStr;
12971    }
12972
12973    private File getNextCodePath(File targetDir, String packageName) {
12974        int suffix = 1;
12975        File result;
12976        do {
12977            result = new File(targetDir, packageName + "-" + suffix);
12978            suffix++;
12979        } while (result.exists());
12980        return result;
12981    }
12982
12983    // Utility method that returns the relative package path with respect
12984    // to the installation directory. Like say for /data/data/com.test-1.apk
12985    // string com.test-1 is returned.
12986    static String deriveCodePathName(String codePath) {
12987        if (codePath == null) {
12988            return null;
12989        }
12990        final File codeFile = new File(codePath);
12991        final String name = codeFile.getName();
12992        if (codeFile.isDirectory()) {
12993            return name;
12994        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12995            final int lastDot = name.lastIndexOf('.');
12996            return name.substring(0, lastDot);
12997        } else {
12998            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12999            return null;
13000        }
13001    }
13002
13003    static class PackageInstalledInfo {
13004        String name;
13005        int uid;
13006        // The set of users that originally had this package installed.
13007        int[] origUsers;
13008        // The set of users that now have this package installed.
13009        int[] newUsers;
13010        PackageParser.Package pkg;
13011        int returnCode;
13012        String returnMsg;
13013        PackageRemovedInfo removedInfo;
13014        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13015
13016        public void setError(int code, String msg) {
13017            setReturnCode(code);
13018            setReturnMessage(msg);
13019            Slog.w(TAG, msg);
13020        }
13021
13022        public void setError(String msg, PackageParserException e) {
13023            setReturnCode(e.error);
13024            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13025            Slog.w(TAG, msg, e);
13026        }
13027
13028        public void setError(String msg, PackageManagerException e) {
13029            returnCode = e.error;
13030            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13031            Slog.w(TAG, msg, e);
13032        }
13033
13034        public void setReturnCode(int returnCode) {
13035            this.returnCode = returnCode;
13036            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13037            for (int i = 0; i < childCount; i++) {
13038                addedChildPackages.valueAt(i).returnCode = returnCode;
13039            }
13040        }
13041
13042        private void setReturnMessage(String returnMsg) {
13043            this.returnMsg = returnMsg;
13044            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13045            for (int i = 0; i < childCount; i++) {
13046                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13047            }
13048        }
13049
13050        // In some error cases we want to convey more info back to the observer
13051        String origPackage;
13052        String origPermission;
13053    }
13054
13055    /*
13056     * Install a non-existing package.
13057     */
13058    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13059            UserHandle user, String installerPackageName, String volumeUuid,
13060            PackageInstalledInfo res) {
13061        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13062
13063        // Remember this for later, in case we need to rollback this install
13064        String pkgName = pkg.packageName;
13065
13066        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13067
13068        synchronized(mPackages) {
13069            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13070                // A package with the same name is already installed, though
13071                // it has been renamed to an older name.  The package we
13072                // are trying to install should be installed as an update to
13073                // the existing one, but that has not been requested, so bail.
13074                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13075                        + " without first uninstalling package running as "
13076                        + mSettings.mRenamedPackages.get(pkgName));
13077                return;
13078            }
13079            if (mPackages.containsKey(pkgName)) {
13080                // Don't allow installation over an existing package with the same name.
13081                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13082                        + " without first uninstalling.");
13083                return;
13084            }
13085        }
13086
13087        try {
13088            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13089                    System.currentTimeMillis(), user);
13090
13091            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13092
13093            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13094                prepareAppDataAfterInstall(newPackage);
13095
13096            } else {
13097                // Remove package from internal structures, but keep around any
13098                // data that might have already existed
13099                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13100                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13101            }
13102        } catch (PackageManagerException e) {
13103            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13104        }
13105
13106        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13107    }
13108
13109    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13110        // Can't rotate keys during boot or if sharedUser.
13111        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13112                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13113            return false;
13114        }
13115        // app is using upgradeKeySets; make sure all are valid
13116        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13117        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13118        for (int i = 0; i < upgradeKeySets.length; i++) {
13119            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13120                Slog.wtf(TAG, "Package "
13121                         + (oldPs.name != null ? oldPs.name : "<null>")
13122                         + " contains upgrade-key-set reference to unknown key-set: "
13123                         + upgradeKeySets[i]
13124                         + " reverting to signatures check.");
13125                return false;
13126            }
13127        }
13128        return true;
13129    }
13130
13131    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13132        // Upgrade keysets are being used.  Determine if new package has a superset of the
13133        // required keys.
13134        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13135        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13136        for (int i = 0; i < upgradeKeySets.length; i++) {
13137            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13138            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13139                return true;
13140            }
13141        }
13142        return false;
13143    }
13144
13145    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13146            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13147        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13148
13149        final PackageParser.Package oldPackage;
13150        final String pkgName = pkg.packageName;
13151        final int[] allUsers;
13152        final boolean weFroze;
13153
13154        // First find the old package info and check signatures
13155        synchronized(mPackages) {
13156            oldPackage = mPackages.get(pkgName);
13157            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13158            if (isEphemeral && !oldIsEphemeral) {
13159                // can't downgrade from full to ephemeral
13160                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13161                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13162                return;
13163            }
13164            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13165            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13166            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13167                if (!checkUpgradeKeySetLP(ps, pkg)) {
13168                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13169                            "New package not signed by keys specified by upgrade-keysets: "
13170                                    + pkgName);
13171                    return;
13172                }
13173            } else {
13174                // default to original signature matching
13175                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13176                        != PackageManager.SIGNATURE_MATCH) {
13177                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13178                            "New package has a different signature: " + pkgName);
13179                    return;
13180                }
13181            }
13182
13183            // In case of rollback, remember per-user/profile install state
13184            allUsers = sUserManager.getUserIds();
13185
13186            // Mark the app as frozen to prevent launching during the upgrade
13187            // process, and then kill all running instances
13188            if (!ps.frozen) {
13189                ps.frozen = true;
13190                weFroze = true;
13191            } else {
13192                weFroze = false;
13193            }
13194        }
13195
13196        try {
13197            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13198                    installerPackageName, res);
13199        } finally {
13200            // Regardless of success or failure of upgrade steps above, always
13201            // unfreeze the package if we froze it
13202            if (weFroze) {
13203                unfreezePackage(pkgName);
13204            }
13205        }
13206    }
13207
13208    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13209            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13210            String installerPackageName, PackageInstalledInfo res) {
13211        // Update what is removed
13212        res.removedInfo = new PackageRemovedInfo();
13213        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13214        res.removedInfo.removedPackage = oldPackage.packageName;
13215        res.removedInfo.isUpdate = true;
13216        final int childCount = (oldPackage.childPackages != null)
13217                ? oldPackage.childPackages.size() : 0;
13218        for (int i = 0; i < childCount; i++) {
13219            boolean childPackageUpdated = false;
13220            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13221            if (res.addedChildPackages != null) {
13222                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13223                if (childRes != null) {
13224                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13225                    childRes.removedInfo.removedPackage = childPkg.packageName;
13226                    childRes.removedInfo.isUpdate = true;
13227                    childPackageUpdated = true;
13228                }
13229            }
13230            if (!childPackageUpdated) {
13231                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13232                childRemovedRes.removedPackage = childPkg.packageName;
13233                childRemovedRes.isUpdate = false;
13234                childRemovedRes.dataRemoved = true;
13235                synchronized (mPackages) {
13236                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13237                    if (childPs != null) {
13238                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13239                    }
13240                }
13241                if (res.removedInfo.removedChildPackages == null) {
13242                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13243                }
13244                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13245            }
13246        }
13247
13248        boolean sysPkg = (isSystemApp(oldPackage));
13249        if (sysPkg) {
13250            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13251                    user, allUsers, installerPackageName, res);
13252        } else {
13253            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13254                    user, allUsers, installerPackageName, res);
13255        }
13256    }
13257
13258    public List<String> getPreviousCodePaths(String packageName) {
13259        final PackageSetting ps = mSettings.mPackages.get(packageName);
13260        final List<String> result = new ArrayList<String>();
13261        if (ps != null && ps.oldCodePaths != null) {
13262            result.addAll(ps.oldCodePaths);
13263        }
13264        return result;
13265    }
13266
13267    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13268            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13269            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13270        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13271                + deletedPackage);
13272
13273        String pkgName = deletedPackage.packageName;
13274        boolean deletedPkg = true;
13275        boolean addedPkg = false;
13276        boolean updatedSettings = false;
13277        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13278        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13279                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13280
13281        final long origUpdateTime = (pkg.mExtras != null)
13282                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13283
13284        // First delete the existing package while retaining the data directory
13285        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13286                res.removedInfo, true, pkg)) {
13287            // If the existing package wasn't successfully deleted
13288            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13289            deletedPkg = false;
13290        } else {
13291            // Successfully deleted the old package; proceed with replace.
13292
13293            // If deleted package lived in a container, give users a chance to
13294            // relinquish resources before killing.
13295            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13296                if (DEBUG_INSTALL) {
13297                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13298                }
13299                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13300                final ArrayList<String> pkgList = new ArrayList<String>(1);
13301                pkgList.add(deletedPackage.applicationInfo.packageName);
13302                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13303            }
13304
13305            deleteCodeCacheDirsLI(pkg);
13306            deleteProfilesLI(pkg, /*destroy*/ false);
13307
13308            try {
13309                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13310                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13311                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13312
13313                // Update the in-memory copy of the previous code paths.
13314                PackageSetting ps = mSettings.mPackages.get(pkgName);
13315                if (!killApp) {
13316                    if (ps.oldCodePaths == null) {
13317                        ps.oldCodePaths = new ArraySet<>();
13318                    }
13319                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13320                    if (deletedPackage.splitCodePaths != null) {
13321                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13322                    }
13323                } else {
13324                    ps.oldCodePaths = null;
13325                }
13326                if (ps.childPackageNames != null) {
13327                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13328                        final String childPkgName = ps.childPackageNames.get(i);
13329                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13330                        childPs.oldCodePaths = ps.oldCodePaths;
13331                    }
13332                }
13333                prepareAppDataAfterInstall(newPackage);
13334                addedPkg = true;
13335            } catch (PackageManagerException e) {
13336                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13337            }
13338        }
13339
13340        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13341            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13342
13343            // Revert all internal state mutations and added folders for the failed install
13344            if (addedPkg) {
13345                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13346                        res.removedInfo, true, null);
13347            }
13348
13349            // Restore the old package
13350            if (deletedPkg) {
13351                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13352                File restoreFile = new File(deletedPackage.codePath);
13353                // Parse old package
13354                boolean oldExternal = isExternal(deletedPackage);
13355                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13356                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13357                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13358                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13359                try {
13360                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13361                            null);
13362                } catch (PackageManagerException e) {
13363                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13364                            + e.getMessage());
13365                    return;
13366                }
13367
13368                synchronized (mPackages) {
13369                    // Ensure the installer package name up to date
13370                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13371
13372                    // Update permissions for restored package
13373                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13374
13375                    mSettings.writeLPr();
13376                }
13377
13378                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13379            }
13380        } else {
13381            synchronized (mPackages) {
13382                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13383                if (ps != null) {
13384                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13385                    if (res.removedInfo.removedChildPackages != null) {
13386                        final int childCount = res.removedInfo.removedChildPackages.size();
13387                        // Iterate in reverse as we may modify the collection
13388                        for (int i = childCount - 1; i >= 0; i--) {
13389                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13390                            if (res.addedChildPackages.containsKey(childPackageName)) {
13391                                res.removedInfo.removedChildPackages.removeAt(i);
13392                            } else {
13393                                PackageRemovedInfo childInfo = res.removedInfo
13394                                        .removedChildPackages.valueAt(i);
13395                                childInfo.removedForAllUsers = mPackages.get(
13396                                        childInfo.removedPackage) == null;
13397                            }
13398                        }
13399                    }
13400                }
13401            }
13402        }
13403    }
13404
13405    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13406            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13407            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13408        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13409                + ", old=" + deletedPackage);
13410
13411        final boolean disabledSystem;
13412
13413        // Set the system/privileged flags as needed
13414        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13415        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13416                != 0) {
13417            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13418        }
13419
13420        // Kill package processes including services, providers, etc.
13421        killPackage(deletedPackage, "replace sys pkg");
13422
13423        // Remove existing system package
13424        removePackageLI(deletedPackage, true);
13425
13426        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13427        if (!disabledSystem) {
13428            // We didn't need to disable the .apk as a current system package,
13429            // which means we are replacing another update that is already
13430            // installed.  We need to make sure to delete the older one's .apk.
13431            res.removedInfo.args = createInstallArgsForExisting(0,
13432                    deletedPackage.applicationInfo.getCodePath(),
13433                    deletedPackage.applicationInfo.getResourcePath(),
13434                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13435        } else {
13436            res.removedInfo.args = null;
13437        }
13438
13439        // Successfully disabled the old package. Now proceed with re-installation
13440        deleteCodeCacheDirsLI(pkg);
13441        deleteProfilesLI(pkg, /*destroy*/ false);
13442
13443        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13444        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13445                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13446
13447        PackageParser.Package newPackage = null;
13448        try {
13449            // Add the package to the internal data structures
13450            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13451
13452            // Set the update and install times
13453            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13454            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13455                    System.currentTimeMillis());
13456
13457            // Check for shared user id changes
13458            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13459                    deletedPackage, newPackage);
13460            if (invalidPackageName != null) {
13461                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13462                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13463                                + " to " + invalidPackageName);
13464            }
13465
13466            // Update the package dynamic state if succeeded
13467            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13468                // Now that the install succeeded make sure we remove data
13469                // directories for any child package the update removed.
13470                final int deletedChildCount = (deletedPackage.childPackages != null)
13471                        ? deletedPackage.childPackages.size() : 0;
13472                final int newChildCount = (newPackage.childPackages != null)
13473                        ? newPackage.childPackages.size() : 0;
13474                for (int i = 0; i < deletedChildCount; i++) {
13475                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13476                    boolean childPackageDeleted = true;
13477                    for (int j = 0; j < newChildCount; j++) {
13478                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13479                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13480                            childPackageDeleted = false;
13481                            break;
13482                        }
13483                    }
13484                    if (childPackageDeleted) {
13485                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13486                                deletedChildPkg.packageName);
13487                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13488                            PackageRemovedInfo removedChildRes = res.removedInfo
13489                                    .removedChildPackages.get(deletedChildPkg.packageName);
13490                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13491                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13492                        }
13493                    }
13494                }
13495
13496                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13497                prepareAppDataAfterInstall(newPackage);
13498            }
13499        } catch (PackageManagerException e) {
13500            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13501            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13502        }
13503
13504        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13505            // Re installation failed. Restore old information
13506            // Remove new pkg information
13507            if (newPackage != null) {
13508                removeInstalledPackageLI(newPackage, true);
13509            }
13510            // Add back the old system package
13511            try {
13512                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13513            } catch (PackageManagerException e) {
13514                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13515            }
13516
13517            synchronized (mPackages) {
13518                if (disabledSystem) {
13519                    enableSystemPackageLPw(deletedPackage);
13520                }
13521
13522                // Ensure the installer package name up to date
13523                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13524
13525                // Update permissions for restored package
13526                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13527
13528                mSettings.writeLPr();
13529            }
13530
13531            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13532                    + " after failed upgrade");
13533        }
13534    }
13535
13536    /**
13537     * Checks whether the parent or any of the child packages have a change shared
13538     * user. For a package to be a valid update the shred users of the parent and
13539     * the children should match. We may later support changing child shared users.
13540     * @param oldPkg The updated package.
13541     * @param newPkg The update package.
13542     * @return The shared user that change between the versions.
13543     */
13544    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13545            PackageParser.Package newPkg) {
13546        // Check parent shared user
13547        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13548            return newPkg.packageName;
13549        }
13550        // Check child shared users
13551        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13552        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13553        for (int i = 0; i < newChildCount; i++) {
13554            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13555            // If this child was present, did it have the same shared user?
13556            for (int j = 0; j < oldChildCount; j++) {
13557                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13558                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13559                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13560                    return newChildPkg.packageName;
13561                }
13562            }
13563        }
13564        return null;
13565    }
13566
13567    private void removeNativeBinariesLI(PackageSetting ps) {
13568        // Remove the lib path for the parent package
13569        if (ps != null) {
13570            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13571            // Remove the lib path for the child packages
13572            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13573            for (int i = 0; i < childCount; i++) {
13574                PackageSetting childPs = null;
13575                synchronized (mPackages) {
13576                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13577                }
13578                if (childPs != null) {
13579                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13580                            .legacyNativeLibraryPathString);
13581                }
13582            }
13583        }
13584    }
13585
13586    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13587        // Enable the parent package
13588        mSettings.enableSystemPackageLPw(pkg.packageName);
13589        // Enable the child packages
13590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13591        for (int i = 0; i < childCount; i++) {
13592            PackageParser.Package childPkg = pkg.childPackages.get(i);
13593            mSettings.enableSystemPackageLPw(childPkg.packageName);
13594        }
13595    }
13596
13597    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13598            PackageParser.Package newPkg) {
13599        // Disable the parent package (parent always replaced)
13600        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13601        // Disable the child packages
13602        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13603        for (int i = 0; i < childCount; i++) {
13604            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13605            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13606            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13607        }
13608        return disabled;
13609    }
13610
13611    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13612            String installerPackageName) {
13613        // Enable the parent package
13614        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13615        // Enable the child packages
13616        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13617        for (int i = 0; i < childCount; i++) {
13618            PackageParser.Package childPkg = pkg.childPackages.get(i);
13619            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13620        }
13621    }
13622
13623    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13624        // Collect all used permissions in the UID
13625        ArraySet<String> usedPermissions = new ArraySet<>();
13626        final int packageCount = su.packages.size();
13627        for (int i = 0; i < packageCount; i++) {
13628            PackageSetting ps = su.packages.valueAt(i);
13629            if (ps.pkg == null) {
13630                continue;
13631            }
13632            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13633            for (int j = 0; j < requestedPermCount; j++) {
13634                String permission = ps.pkg.requestedPermissions.get(j);
13635                BasePermission bp = mSettings.mPermissions.get(permission);
13636                if (bp != null) {
13637                    usedPermissions.add(permission);
13638                }
13639            }
13640        }
13641
13642        PermissionsState permissionsState = su.getPermissionsState();
13643        // Prune install permissions
13644        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13645        final int installPermCount = installPermStates.size();
13646        for (int i = installPermCount - 1; i >= 0;  i--) {
13647            PermissionState permissionState = installPermStates.get(i);
13648            if (!usedPermissions.contains(permissionState.getName())) {
13649                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13650                if (bp != null) {
13651                    permissionsState.revokeInstallPermission(bp);
13652                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13653                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13654                }
13655            }
13656        }
13657
13658        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13659
13660        // Prune runtime permissions
13661        for (int userId : allUserIds) {
13662            List<PermissionState> runtimePermStates = permissionsState
13663                    .getRuntimePermissionStates(userId);
13664            final int runtimePermCount = runtimePermStates.size();
13665            for (int i = runtimePermCount - 1; i >= 0; i--) {
13666                PermissionState permissionState = runtimePermStates.get(i);
13667                if (!usedPermissions.contains(permissionState.getName())) {
13668                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13669                    if (bp != null) {
13670                        permissionsState.revokeRuntimePermission(bp, userId);
13671                        permissionsState.updatePermissionFlags(bp, userId,
13672                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13673                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13674                                runtimePermissionChangedUserIds, userId);
13675                    }
13676                }
13677            }
13678        }
13679
13680        return runtimePermissionChangedUserIds;
13681    }
13682
13683    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13684            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13685        // Update the parent package setting
13686        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13687                res, user);
13688        // Update the child packages setting
13689        final int childCount = (newPackage.childPackages != null)
13690                ? newPackage.childPackages.size() : 0;
13691        for (int i = 0; i < childCount; i++) {
13692            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13693            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13694            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13695                    childRes.origUsers, childRes, user);
13696        }
13697    }
13698
13699    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13700            String installerPackageName, int[] allUsers, int[] installedForUsers,
13701            PackageInstalledInfo res, UserHandle user) {
13702        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13703
13704        String pkgName = newPackage.packageName;
13705        synchronized (mPackages) {
13706            //write settings. the installStatus will be incomplete at this stage.
13707            //note that the new package setting would have already been
13708            //added to mPackages. It hasn't been persisted yet.
13709            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13710            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13711            mSettings.writeLPr();
13712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13713        }
13714
13715        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13716        synchronized (mPackages) {
13717            updatePermissionsLPw(newPackage.packageName, newPackage,
13718                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13719                            ? UPDATE_PERMISSIONS_ALL : 0));
13720            // For system-bundled packages, we assume that installing an upgraded version
13721            // of the package implies that the user actually wants to run that new code,
13722            // so we enable the package.
13723            PackageSetting ps = mSettings.mPackages.get(pkgName);
13724            final int userId = user.getIdentifier();
13725            if (ps != null) {
13726                if (isSystemApp(newPackage)) {
13727                    if (DEBUG_INSTALL) {
13728                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13729                    }
13730                    // Enable system package for requested users
13731                    if (res.origUsers != null) {
13732                        for (int origUserId : res.origUsers) {
13733                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13734                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13735                                        origUserId, installerPackageName);
13736                            }
13737                        }
13738                    }
13739                    // Also convey the prior install/uninstall state
13740                    if (allUsers != null && installedForUsers != null) {
13741                        for (int currentUserId : allUsers) {
13742                            final boolean installed = ArrayUtils.contains(
13743                                    installedForUsers, currentUserId);
13744                            if (DEBUG_INSTALL) {
13745                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13746                            }
13747                            ps.setInstalled(installed, currentUserId);
13748                        }
13749                        // these install state changes will be persisted in the
13750                        // upcoming call to mSettings.writeLPr().
13751                    }
13752                }
13753                // It's implied that when a user requests installation, they want the app to be
13754                // installed and enabled.
13755                if (userId != UserHandle.USER_ALL) {
13756                    ps.setInstalled(true, userId);
13757                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13758                }
13759            }
13760            res.name = pkgName;
13761            res.uid = newPackage.applicationInfo.uid;
13762            res.pkg = newPackage;
13763            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13764            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13765            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13766            //to update install status
13767            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13768            mSettings.writeLPr();
13769            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13770        }
13771
13772        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13773    }
13774
13775    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13776        try {
13777            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13778            installPackageLI(args, res);
13779        } finally {
13780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13781        }
13782    }
13783
13784    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13785        final int installFlags = args.installFlags;
13786        final String installerPackageName = args.installerPackageName;
13787        final String volumeUuid = args.volumeUuid;
13788        final File tmpPackageFile = new File(args.getCodePath());
13789        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13790        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13791                || (args.volumeUuid != null));
13792        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13793        boolean replace = false;
13794        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13795        if (args.move != null) {
13796            // moving a complete application; perform an initial scan on the new install location
13797            scanFlags |= SCAN_INITIAL;
13798        }
13799        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13800            scanFlags |= SCAN_DONT_KILL_APP;
13801        }
13802
13803        // Result object to be returned
13804        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13805
13806        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13807
13808        // Sanity check
13809        if (ephemeral && (forwardLocked || onExternal)) {
13810            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13811                    + " external=" + onExternal);
13812            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13813            return;
13814        }
13815
13816        // Retrieve PackageSettings and parse package
13817        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13818                | PackageParser.PARSE_ENFORCE_CODE
13819                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13820                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13821                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13822        PackageParser pp = new PackageParser();
13823        pp.setSeparateProcesses(mSeparateProcesses);
13824        pp.setDisplayMetrics(mMetrics);
13825
13826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13827        final PackageParser.Package pkg;
13828        try {
13829            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13830        } catch (PackageParserException e) {
13831            res.setError("Failed parse during installPackageLI", e);
13832            return;
13833        } finally {
13834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13835        }
13836
13837        // If we are installing a clustered package add results for the children
13838        if (pkg.childPackages != null) {
13839            synchronized (mPackages) {
13840                final int childCount = pkg.childPackages.size();
13841                for (int i = 0; i < childCount; i++) {
13842                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13843                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13844                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13845                    childRes.pkg = childPkg;
13846                    childRes.name = childPkg.packageName;
13847                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13848                    if (childPs != null) {
13849                        childRes.origUsers = childPs.queryInstalledUsers(
13850                                sUserManager.getUserIds(), true);
13851                    }
13852                    if ((mPackages.containsKey(childPkg.packageName))) {
13853                        childRes.removedInfo = new PackageRemovedInfo();
13854                        childRes.removedInfo.removedPackage = childPkg.packageName;
13855                    }
13856                    if (res.addedChildPackages == null) {
13857                        res.addedChildPackages = new ArrayMap<>();
13858                    }
13859                    res.addedChildPackages.put(childPkg.packageName, childRes);
13860                }
13861            }
13862        }
13863
13864        // If package doesn't declare API override, mark that we have an install
13865        // time CPU ABI override.
13866        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13867            pkg.cpuAbiOverride = args.abiOverride;
13868        }
13869
13870        String pkgName = res.name = pkg.packageName;
13871        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13872            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13873                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13874                return;
13875            }
13876        }
13877
13878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13879        try {
13880            PackageParser.collectCertificates(pkg, parseFlags);
13881        } catch (PackageParserException e) {
13882            res.setError("Failed collect during installPackageLI", e);
13883            return;
13884        } finally {
13885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13886        }
13887
13888        // Get rid of all references to package scan path via parser.
13889        pp = null;
13890        String oldCodePath = null;
13891        boolean systemApp = false;
13892        synchronized (mPackages) {
13893            // Check if installing already existing package
13894            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13895                String oldName = mSettings.mRenamedPackages.get(pkgName);
13896                if (pkg.mOriginalPackages != null
13897                        && pkg.mOriginalPackages.contains(oldName)
13898                        && mPackages.containsKey(oldName)) {
13899                    // This package is derived from an original package,
13900                    // and this device has been updating from that original
13901                    // name.  We must continue using the original name, so
13902                    // rename the new package here.
13903                    pkg.setPackageName(oldName);
13904                    pkgName = pkg.packageName;
13905                    replace = true;
13906                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13907                            + oldName + " pkgName=" + pkgName);
13908                } else if (mPackages.containsKey(pkgName)) {
13909                    // This package, under its official name, already exists
13910                    // on the device; we should replace it.
13911                    replace = true;
13912                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13913                }
13914
13915                // Child packages are installed through the parent package
13916                if (pkg.parentPackage != null) {
13917                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13918                            "Package " + pkg.packageName + " is child of package "
13919                                    + pkg.parentPackage.parentPackage + ". Child packages "
13920                                    + "can be updated only through the parent package.");
13921                    return;
13922                }
13923
13924                if (replace) {
13925                    // Prevent apps opting out from runtime permissions
13926                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13927                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13928                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13929                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13930                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13931                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13932                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13933                                        + " doesn't support runtime permissions but the old"
13934                                        + " target SDK " + oldTargetSdk + " does.");
13935                        return;
13936                    }
13937
13938                    // Prevent installing of child packages
13939                    if (oldPackage.parentPackage != null) {
13940                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13941                                "Package " + pkg.packageName + " is child of package "
13942                                        + oldPackage.parentPackage + ". Child packages "
13943                                        + "can be updated only through the parent package.");
13944                        return;
13945                    }
13946                }
13947            }
13948
13949            PackageSetting ps = mSettings.mPackages.get(pkgName);
13950            if (ps != null) {
13951                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13952
13953                // Quick sanity check that we're signed correctly if updating;
13954                // we'll check this again later when scanning, but we want to
13955                // bail early here before tripping over redefined permissions.
13956                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13957                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13958                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13959                                + pkg.packageName + " upgrade keys do not match the "
13960                                + "previously installed version");
13961                        return;
13962                    }
13963                } else {
13964                    try {
13965                        verifySignaturesLP(ps, pkg);
13966                    } catch (PackageManagerException e) {
13967                        res.setError(e.error, e.getMessage());
13968                        return;
13969                    }
13970                }
13971
13972                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13973                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13974                    systemApp = (ps.pkg.applicationInfo.flags &
13975                            ApplicationInfo.FLAG_SYSTEM) != 0;
13976                }
13977                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13978            }
13979
13980            // Check whether the newly-scanned package wants to define an already-defined perm
13981            int N = pkg.permissions.size();
13982            for (int i = N-1; i >= 0; i--) {
13983                PackageParser.Permission perm = pkg.permissions.get(i);
13984                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13985                if (bp != null) {
13986                    // If the defining package is signed with our cert, it's okay.  This
13987                    // also includes the "updating the same package" case, of course.
13988                    // "updating same package" could also involve key-rotation.
13989                    final boolean sigsOk;
13990                    if (bp.sourcePackage.equals(pkg.packageName)
13991                            && (bp.packageSetting instanceof PackageSetting)
13992                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13993                                    scanFlags))) {
13994                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13995                    } else {
13996                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13997                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13998                    }
13999                    if (!sigsOk) {
14000                        // If the owning package is the system itself, we log but allow
14001                        // install to proceed; we fail the install on all other permission
14002                        // redefinitions.
14003                        if (!bp.sourcePackage.equals("android")) {
14004                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14005                                    + pkg.packageName + " attempting to redeclare permission "
14006                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14007                            res.origPermission = perm.info.name;
14008                            res.origPackage = bp.sourcePackage;
14009                            return;
14010                        } else {
14011                            Slog.w(TAG, "Package " + pkg.packageName
14012                                    + " attempting to redeclare system permission "
14013                                    + perm.info.name + "; ignoring new declaration");
14014                            pkg.permissions.remove(i);
14015                        }
14016                    }
14017                }
14018            }
14019        }
14020
14021        if (systemApp) {
14022            if (onExternal) {
14023                // Abort update; system app can't be replaced with app on sdcard
14024                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14025                        "Cannot install updates to system apps on sdcard");
14026                return;
14027            } else if (ephemeral) {
14028                // Abort update; system app can't be replaced with an ephemeral app
14029                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14030                        "Cannot update a system app with an ephemeral app");
14031                return;
14032            }
14033        }
14034
14035        if (args.move != null) {
14036            // We did an in-place move, so dex is ready to roll
14037            scanFlags |= SCAN_NO_DEX;
14038            scanFlags |= SCAN_MOVE;
14039
14040            synchronized (mPackages) {
14041                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14042                if (ps == null) {
14043                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14044                            "Missing settings for moved package " + pkgName);
14045                }
14046
14047                // We moved the entire application as-is, so bring over the
14048                // previously derived ABI information.
14049                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14050                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14051            }
14052
14053        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14054            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14055            scanFlags |= SCAN_NO_DEX;
14056
14057            try {
14058                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14059                    args.abiOverride : pkg.cpuAbiOverride);
14060                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14061                        true /* extract libs */);
14062            } catch (PackageManagerException pme) {
14063                Slog.e(TAG, "Error deriving application ABI", pme);
14064                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14065                return;
14066            }
14067
14068
14069            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14070            // Do not run PackageDexOptimizer through the local performDexOpt
14071            // method because `pkg` is not in `mPackages` yet.
14072            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14073                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14074            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14075            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14076                String msg = "Extracking package failed for " + pkgName;
14077                res.setError(INSTALL_FAILED_DEXOPT, msg);
14078                return;
14079            }
14080        }
14081
14082        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14083            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14084            return;
14085        }
14086
14087        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14088
14089        if (replace) {
14090            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14091                    installerPackageName, res);
14092        } else {
14093            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14094                    args.user, installerPackageName, volumeUuid, res);
14095        }
14096        synchronized (mPackages) {
14097            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14098            if (ps != null) {
14099                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14100            }
14101
14102            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14103            for (int i = 0; i < childCount; i++) {
14104                PackageParser.Package childPkg = pkg.childPackages.get(i);
14105                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14106                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14107                if (childPs != null) {
14108                    childRes.newUsers = childPs.queryInstalledUsers(
14109                            sUserManager.getUserIds(), true);
14110                }
14111            }
14112        }
14113    }
14114
14115    private void startIntentFilterVerifications(int userId, boolean replacing,
14116            PackageParser.Package pkg) {
14117        if (mIntentFilterVerifierComponent == null) {
14118            Slog.w(TAG, "No IntentFilter verification will not be done as "
14119                    + "there is no IntentFilterVerifier available!");
14120            return;
14121        }
14122
14123        final int verifierUid = getPackageUid(
14124                mIntentFilterVerifierComponent.getPackageName(),
14125                MATCH_DEBUG_TRIAGED_MISSING,
14126                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14127
14128        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14129        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14130        mHandler.sendMessage(msg);
14131
14132        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14133        for (int i = 0; i < childCount; i++) {
14134            PackageParser.Package childPkg = pkg.childPackages.get(i);
14135            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14136            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14137            mHandler.sendMessage(msg);
14138        }
14139    }
14140
14141    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14142            PackageParser.Package pkg) {
14143        int size = pkg.activities.size();
14144        if (size == 0) {
14145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14146                    "No activity, so no need to verify any IntentFilter!");
14147            return;
14148        }
14149
14150        final boolean hasDomainURLs = hasDomainURLs(pkg);
14151        if (!hasDomainURLs) {
14152            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14153                    "No domain URLs, so no need to verify any IntentFilter!");
14154            return;
14155        }
14156
14157        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14158                + " if any IntentFilter from the " + size
14159                + " Activities needs verification ...");
14160
14161        int count = 0;
14162        final String packageName = pkg.packageName;
14163
14164        synchronized (mPackages) {
14165            // If this is a new install and we see that we've already run verification for this
14166            // package, we have nothing to do: it means the state was restored from backup.
14167            if (!replacing) {
14168                IntentFilterVerificationInfo ivi =
14169                        mSettings.getIntentFilterVerificationLPr(packageName);
14170                if (ivi != null) {
14171                    if (DEBUG_DOMAIN_VERIFICATION) {
14172                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14173                                + ivi.getStatusString());
14174                    }
14175                    return;
14176                }
14177            }
14178
14179            // If any filters need to be verified, then all need to be.
14180            boolean needToVerify = false;
14181            for (PackageParser.Activity a : pkg.activities) {
14182                for (ActivityIntentInfo filter : a.intents) {
14183                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14184                        if (DEBUG_DOMAIN_VERIFICATION) {
14185                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14186                        }
14187                        needToVerify = true;
14188                        break;
14189                    }
14190                }
14191            }
14192
14193            if (needToVerify) {
14194                final int verificationId = mIntentFilterVerificationToken++;
14195                for (PackageParser.Activity a : pkg.activities) {
14196                    for (ActivityIntentInfo filter : a.intents) {
14197                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14198                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14199                                    "Verification needed for IntentFilter:" + filter.toString());
14200                            mIntentFilterVerifier.addOneIntentFilterVerification(
14201                                    verifierUid, userId, verificationId, filter, packageName);
14202                            count++;
14203                        }
14204                    }
14205                }
14206            }
14207        }
14208
14209        if (count > 0) {
14210            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14211                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14212                    +  " for userId:" + userId);
14213            mIntentFilterVerifier.startVerifications(userId);
14214        } else {
14215            if (DEBUG_DOMAIN_VERIFICATION) {
14216                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14217            }
14218        }
14219    }
14220
14221    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14222        final ComponentName cn  = filter.activity.getComponentName();
14223        final String packageName = cn.getPackageName();
14224
14225        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14226                packageName);
14227        if (ivi == null) {
14228            return true;
14229        }
14230        int status = ivi.getStatus();
14231        switch (status) {
14232            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14233            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14234                return true;
14235
14236            default:
14237                // Nothing to do
14238                return false;
14239        }
14240    }
14241
14242    private static boolean isMultiArch(ApplicationInfo info) {
14243        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14244    }
14245
14246    private static boolean isExternal(PackageParser.Package pkg) {
14247        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14248    }
14249
14250    private static boolean isExternal(PackageSetting ps) {
14251        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14252    }
14253
14254    private static boolean isEphemeral(PackageParser.Package pkg) {
14255        return pkg.applicationInfo.isEphemeralApp();
14256    }
14257
14258    private static boolean isEphemeral(PackageSetting ps) {
14259        return ps.pkg != null && isEphemeral(ps.pkg);
14260    }
14261
14262    private static boolean isSystemApp(PackageParser.Package pkg) {
14263        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14264    }
14265
14266    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14267        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14268    }
14269
14270    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14271        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14272    }
14273
14274    private static boolean isSystemApp(PackageSetting ps) {
14275        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14276    }
14277
14278    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14279        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14280    }
14281
14282    private int packageFlagsToInstallFlags(PackageSetting ps) {
14283        int installFlags = 0;
14284        if (isEphemeral(ps)) {
14285            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14286        }
14287        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14288            // This existing package was an external ASEC install when we have
14289            // the external flag without a UUID
14290            installFlags |= PackageManager.INSTALL_EXTERNAL;
14291        }
14292        if (ps.isForwardLocked()) {
14293            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14294        }
14295        return installFlags;
14296    }
14297
14298    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14299        if (isExternal(pkg)) {
14300            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14301                return StorageManager.UUID_PRIMARY_PHYSICAL;
14302            } else {
14303                return pkg.volumeUuid;
14304            }
14305        } else {
14306            return StorageManager.UUID_PRIVATE_INTERNAL;
14307        }
14308    }
14309
14310    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14311        if (isExternal(pkg)) {
14312            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14313                return mSettings.getExternalVersion();
14314            } else {
14315                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14316            }
14317        } else {
14318            return mSettings.getInternalVersion();
14319        }
14320    }
14321
14322    private void deleteTempPackageFiles() {
14323        final FilenameFilter filter = new FilenameFilter() {
14324            public boolean accept(File dir, String name) {
14325                return name.startsWith("vmdl") && name.endsWith(".tmp");
14326            }
14327        };
14328        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14329            file.delete();
14330        }
14331    }
14332
14333    @Override
14334    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14335            int flags) {
14336        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14337                flags);
14338    }
14339
14340    @Override
14341    public void deletePackage(final String packageName,
14342            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14343        mContext.enforceCallingOrSelfPermission(
14344                android.Manifest.permission.DELETE_PACKAGES, null);
14345        Preconditions.checkNotNull(packageName);
14346        Preconditions.checkNotNull(observer);
14347        final int uid = Binder.getCallingUid();
14348        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14349        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14350        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14351            mContext.enforceCallingOrSelfPermission(
14352                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14353                    "deletePackage for user " + userId);
14354        }
14355
14356        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14357            try {
14358                observer.onPackageDeleted(packageName,
14359                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14360            } catch (RemoteException re) {
14361            }
14362            return;
14363        }
14364
14365        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14366            try {
14367                observer.onPackageDeleted(packageName,
14368                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14369            } catch (RemoteException re) {
14370            }
14371            return;
14372        }
14373
14374        if (DEBUG_REMOVE) {
14375            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14376                    + " deleteAllUsers: " + deleteAllUsers );
14377        }
14378        // Queue up an async operation since the package deletion may take a little while.
14379        mHandler.post(new Runnable() {
14380            public void run() {
14381                mHandler.removeCallbacks(this);
14382                int returnCode;
14383                if (!deleteAllUsers) {
14384                    returnCode = deletePackageX(packageName, userId, flags);
14385                } else {
14386                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14387                    // If nobody is blocking uninstall, proceed with delete for all users
14388                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14389                        returnCode = deletePackageX(packageName, userId, flags);
14390                    } else {
14391                        // Otherwise uninstall individually for users with blockUninstalls=false
14392                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14393                        for (int userId : users) {
14394                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14395                                returnCode = deletePackageX(packageName, userId, userFlags);
14396                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14397                                    Slog.w(TAG, "Package delete failed for user " + userId
14398                                            + ", returnCode " + returnCode);
14399                                }
14400                            }
14401                        }
14402                        // The app has only been marked uninstalled for certain users.
14403                        // We still need to report that delete was blocked
14404                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14405                    }
14406                }
14407                try {
14408                    observer.onPackageDeleted(packageName, returnCode, null);
14409                } catch (RemoteException e) {
14410                    Log.i(TAG, "Observer no longer exists.");
14411                } //end catch
14412            } //end run
14413        });
14414    }
14415
14416    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14417        int[] result = EMPTY_INT_ARRAY;
14418        for (int userId : userIds) {
14419            if (getBlockUninstallForUser(packageName, userId)) {
14420                result = ArrayUtils.appendInt(result, userId);
14421            }
14422        }
14423        return result;
14424    }
14425
14426    @Override
14427    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14428        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14429    }
14430
14431    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14432        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14433                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14434        try {
14435            if (dpm != null) {
14436                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14437                        /* callingUserOnly =*/ false);
14438                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14439                        : deviceOwnerComponentName.getPackageName();
14440                // Does the package contains the device owner?
14441                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14442                // this check is probably not needed, since DO should be registered as a device
14443                // admin on some user too. (Original bug for this: b/17657954)
14444                if (packageName.equals(deviceOwnerPackageName)) {
14445                    return true;
14446                }
14447                // Does it contain a device admin for any user?
14448                int[] users;
14449                if (userId == UserHandle.USER_ALL) {
14450                    users = sUserManager.getUserIds();
14451                } else {
14452                    users = new int[]{userId};
14453                }
14454                for (int i = 0; i < users.length; ++i) {
14455                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14456                        return true;
14457                    }
14458                }
14459            }
14460        } catch (RemoteException e) {
14461        }
14462        return false;
14463    }
14464
14465    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14466        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14467    }
14468
14469    /**
14470     *  This method is an internal method that could be get invoked either
14471     *  to delete an installed package or to clean up a failed installation.
14472     *  After deleting an installed package, a broadcast is sent to notify any
14473     *  listeners that the package has been installed. For cleaning up a failed
14474     *  installation, the broadcast is not necessary since the package's
14475     *  installation wouldn't have sent the initial broadcast either
14476     *  The key steps in deleting a package are
14477     *  deleting the package information in internal structures like mPackages,
14478     *  deleting the packages base directories through installd
14479     *  updating mSettings to reflect current status
14480     *  persisting settings for later use
14481     *  sending a broadcast if necessary
14482     */
14483    private int deletePackageX(String packageName, int userId, int flags) {
14484        final PackageRemovedInfo info = new PackageRemovedInfo();
14485        final boolean res;
14486
14487        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14488                ? UserHandle.ALL : new UserHandle(userId);
14489
14490        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14491            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14492            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14493        }
14494
14495        PackageSetting uninstalledPs = null;
14496
14497        // for the uninstall-updates case and restricted profiles, remember the per-
14498        // user handle installed state
14499        int[] allUsers;
14500        synchronized (mPackages) {
14501            uninstalledPs = mSettings.mPackages.get(packageName);
14502            if (uninstalledPs == null) {
14503                Slog.w(TAG, "Not removing non-existent package " + packageName);
14504                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14505            }
14506            allUsers = sUserManager.getUserIds();
14507            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14508        }
14509
14510        synchronized (mInstallLock) {
14511            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14512            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14513                    flags | REMOVE_CHATTY, info, true, null);
14514            synchronized (mPackages) {
14515                if (res) {
14516                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14517                }
14518            }
14519        }
14520
14521        if (res) {
14522            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14523            info.sendPackageRemovedBroadcasts(killApp);
14524            info.sendSystemPackageUpdatedBroadcasts();
14525            info.sendSystemPackageAppearedBroadcasts();
14526        }
14527        // Force a gc here.
14528        Runtime.getRuntime().gc();
14529        // Delete the resources here after sending the broadcast to let
14530        // other processes clean up before deleting resources.
14531        if (info.args != null) {
14532            synchronized (mInstallLock) {
14533                info.args.doPostDeleteLI(true);
14534            }
14535        }
14536
14537        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14538    }
14539
14540    class PackageRemovedInfo {
14541        String removedPackage;
14542        int uid = -1;
14543        int removedAppId = -1;
14544        int[] origUsers;
14545        int[] removedUsers = null;
14546        boolean isRemovedPackageSystemUpdate = false;
14547        boolean isUpdate;
14548        boolean dataRemoved;
14549        boolean removedForAllUsers;
14550        // Clean up resources deleted packages.
14551        InstallArgs args = null;
14552        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14553        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14554
14555        void sendPackageRemovedBroadcasts(boolean killApp) {
14556            sendPackageRemovedBroadcastInternal(killApp);
14557            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14558            for (int i = 0; i < childCount; i++) {
14559                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14560                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14561            }
14562        }
14563
14564        void sendSystemPackageUpdatedBroadcasts() {
14565            if (isRemovedPackageSystemUpdate) {
14566                sendSystemPackageUpdatedBroadcastsInternal();
14567                final int childCount = (removedChildPackages != null)
14568                        ? removedChildPackages.size() : 0;
14569                for (int i = 0; i < childCount; i++) {
14570                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14571                    if (childInfo.isRemovedPackageSystemUpdate) {
14572                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14573                    }
14574                }
14575            }
14576        }
14577
14578        void sendSystemPackageAppearedBroadcasts() {
14579            final int packageCount = (appearedChildPackages != null)
14580                    ? appearedChildPackages.size() : 0;
14581            for (int i = 0; i < packageCount; i++) {
14582                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14583                for (int userId : installedInfo.newUsers) {
14584                    sendPackageAddedForUser(installedInfo.name, true,
14585                            UserHandle.getAppId(installedInfo.uid), userId);
14586                }
14587            }
14588        }
14589
14590        private void sendSystemPackageUpdatedBroadcastsInternal() {
14591            Bundle extras = new Bundle(2);
14592            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14593            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14594            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14595                    extras, 0, null, null, null);
14596            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14597                    extras, 0, null, null, null);
14598            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14599                    null, 0, removedPackage, null, null);
14600        }
14601
14602        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14603            Bundle extras = new Bundle(2);
14604            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14605            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14606            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14607            if (isUpdate || isRemovedPackageSystemUpdate) {
14608                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14609            }
14610            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14611            if (removedPackage != null) {
14612                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14613                        extras, 0, null, null, removedUsers);
14614                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14615                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14616                            removedPackage, extras, 0, null, null, removedUsers);
14617                }
14618            }
14619            if (removedAppId >= 0) {
14620                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14621                        removedUsers);
14622            }
14623        }
14624    }
14625
14626    /*
14627     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14628     * flag is not set, the data directory is removed as well.
14629     * make sure this flag is set for partially installed apps. If not its meaningless to
14630     * delete a partially installed application.
14631     */
14632    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14633            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14634        String packageName = ps.name;
14635        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14636        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14637        // Retrieve object to delete permissions for shared user later on
14638        final PackageSetting deletedPs;
14639        // reader
14640        synchronized (mPackages) {
14641            deletedPs = mSettings.mPackages.get(packageName);
14642            if (outInfo != null) {
14643                outInfo.removedPackage = packageName;
14644                outInfo.removedUsers = deletedPs != null
14645                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14646                        : null;
14647            }
14648        }
14649        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14650            removeDataDirsLI(ps.volumeUuid, packageName);
14651            if (outInfo != null) {
14652                outInfo.dataRemoved = true;
14653            }
14654            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14655        }
14656        // writer
14657        synchronized (mPackages) {
14658            if (deletedPs != null) {
14659                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14660                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14661                    clearDefaultBrowserIfNeeded(packageName);
14662                    if (outInfo != null) {
14663                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14664                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14665                    }
14666                    updatePermissionsLPw(deletedPs.name, null, 0);
14667                    if (deletedPs.sharedUser != null) {
14668                        // Remove permissions associated with package. Since runtime
14669                        // permissions are per user we have to kill the removed package
14670                        // or packages running under the shared user of the removed
14671                        // package if revoking the permissions requested only by the removed
14672                        // package is successful and this causes a change in gids.
14673                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14674                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14675                                    userId);
14676                            if (userIdToKill == UserHandle.USER_ALL
14677                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14678                                // If gids changed for this user, kill all affected packages.
14679                                mHandler.post(new Runnable() {
14680                                    @Override
14681                                    public void run() {
14682                                        // This has to happen with no lock held.
14683                                        killApplication(deletedPs.name, deletedPs.appId,
14684                                                KILL_APP_REASON_GIDS_CHANGED);
14685                                    }
14686                                });
14687                                break;
14688                            }
14689                        }
14690                    }
14691                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14692                }
14693                // make sure to preserve per-user disabled state if this removal was just
14694                // a downgrade of a system app to the factory package
14695                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14696                    if (DEBUG_REMOVE) {
14697                        Slog.d(TAG, "Propagating install state across downgrade");
14698                    }
14699                    for (int userId : allUserHandles) {
14700                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14701                        if (DEBUG_REMOVE) {
14702                            Slog.d(TAG, "    user " + userId + " => " + installed);
14703                        }
14704                        ps.setInstalled(installed, userId);
14705                    }
14706                }
14707            }
14708            // can downgrade to reader
14709            if (writeSettings) {
14710                // Save settings now
14711                mSettings.writeLPr();
14712            }
14713        }
14714        if (outInfo != null) {
14715            // A user ID was deleted here. Go through all users and remove it
14716            // from KeyStore.
14717            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14718        }
14719    }
14720
14721    static boolean locationIsPrivileged(File path) {
14722        try {
14723            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14724                    .getCanonicalPath();
14725            return path.getCanonicalPath().startsWith(privilegedAppDir);
14726        } catch (IOException e) {
14727            Slog.e(TAG, "Unable to access code path " + path);
14728        }
14729        return false;
14730    }
14731
14732    /*
14733     * Tries to delete system package.
14734     */
14735    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14736            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14737            boolean writeSettings) {
14738        if (deletedPs.parentPackageName != null) {
14739            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14740            return false;
14741        }
14742
14743        final boolean applyUserRestrictions
14744                = (allUserHandles != null) && (outInfo.origUsers != null);
14745        final PackageSetting disabledPs;
14746        // Confirm if the system package has been updated
14747        // An updated system app can be deleted. This will also have to restore
14748        // the system pkg from system partition
14749        // reader
14750        synchronized (mPackages) {
14751            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14752        }
14753
14754        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14755                + " disabledPs=" + disabledPs);
14756
14757        if (disabledPs == null) {
14758            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14759            return false;
14760        } else if (DEBUG_REMOVE) {
14761            Slog.d(TAG, "Deleting system pkg from data partition");
14762        }
14763
14764        if (DEBUG_REMOVE) {
14765            if (applyUserRestrictions) {
14766                Slog.d(TAG, "Remembering install states:");
14767                for (int userId : allUserHandles) {
14768                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14769                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14770                }
14771            }
14772        }
14773
14774        // Delete the updated package
14775        outInfo.isRemovedPackageSystemUpdate = true;
14776        if (outInfo.removedChildPackages != null) {
14777            final int childCount = (deletedPs.childPackageNames != null)
14778                    ? deletedPs.childPackageNames.size() : 0;
14779            for (int i = 0; i < childCount; i++) {
14780                String childPackageName = deletedPs.childPackageNames.get(i);
14781                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14782                        .contains(childPackageName)) {
14783                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14784                            childPackageName);
14785                    if (childInfo != null) {
14786                        childInfo.isRemovedPackageSystemUpdate = true;
14787                    }
14788                }
14789            }
14790        }
14791
14792        if (disabledPs.versionCode < deletedPs.versionCode) {
14793            // Delete data for downgrades
14794            flags &= ~PackageManager.DELETE_KEEP_DATA;
14795        } else {
14796            // Preserve data by setting flag
14797            flags |= PackageManager.DELETE_KEEP_DATA;
14798        }
14799
14800        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14801                outInfo, writeSettings, disabledPs.pkg);
14802        if (!ret) {
14803            return false;
14804        }
14805
14806        // writer
14807        synchronized (mPackages) {
14808            // Reinstate the old system package
14809            enableSystemPackageLPw(disabledPs.pkg);
14810            // Remove any native libraries from the upgraded package.
14811            removeNativeBinariesLI(deletedPs);
14812        }
14813
14814        // Install the system package
14815        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14816        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14817        if (locationIsPrivileged(disabledPs.codePath)) {
14818            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14819        }
14820
14821        final PackageParser.Package newPkg;
14822        try {
14823            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14824        } catch (PackageManagerException e) {
14825            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14826                    + e.getMessage());
14827            return false;
14828        }
14829
14830        prepareAppDataAfterInstall(newPkg);
14831
14832        // writer
14833        synchronized (mPackages) {
14834            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14835
14836            // Propagate the permissions state as we do not want to drop on the floor
14837            // runtime permissions. The update permissions method below will take
14838            // care of removing obsolete permissions and grant install permissions.
14839            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14840            updatePermissionsLPw(newPkg.packageName, newPkg,
14841                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14842
14843            if (applyUserRestrictions) {
14844                if (DEBUG_REMOVE) {
14845                    Slog.d(TAG, "Propagating install state across reinstall");
14846                }
14847                for (int userId : allUserHandles) {
14848                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14849                    if (DEBUG_REMOVE) {
14850                        Slog.d(TAG, "    user " + userId + " => " + installed);
14851                    }
14852                    ps.setInstalled(installed, userId);
14853
14854                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14855                }
14856                // Regardless of writeSettings we need to ensure that this restriction
14857                // state propagation is persisted
14858                mSettings.writeAllUsersPackageRestrictionsLPr();
14859            }
14860            // can downgrade to reader here
14861            if (writeSettings) {
14862                mSettings.writeLPr();
14863            }
14864        }
14865        return true;
14866    }
14867
14868    private boolean deleteInstalledPackageLI(PackageSetting ps,
14869            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14870            PackageRemovedInfo outInfo, boolean writeSettings,
14871            PackageParser.Package replacingPackage) {
14872        synchronized (mPackages) {
14873            if (outInfo != null) {
14874                outInfo.uid = ps.appId;
14875            }
14876
14877            if (outInfo != null && outInfo.removedChildPackages != null) {
14878                final int childCount = (ps.childPackageNames != null)
14879                        ? ps.childPackageNames.size() : 0;
14880                for (int i = 0; i < childCount; i++) {
14881                    String childPackageName = ps.childPackageNames.get(i);
14882                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14883                    if (childPs == null) {
14884                        return false;
14885                    }
14886                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14887                            childPackageName);
14888                    if (childInfo != null) {
14889                        childInfo.uid = childPs.appId;
14890                    }
14891                }
14892            }
14893        }
14894
14895        // Delete package data from internal structures and also remove data if flag is set
14896        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14897
14898        // Delete the child packages data
14899        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14900        for (int i = 0; i < childCount; i++) {
14901            PackageSetting childPs;
14902            synchronized (mPackages) {
14903                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14904            }
14905            if (childPs != null) {
14906                PackageRemovedInfo childOutInfo = (outInfo != null
14907                        && outInfo.removedChildPackages != null)
14908                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14909                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14910                        && (replacingPackage != null
14911                        && !replacingPackage.hasChildPackage(childPs.name))
14912                        ? flags & ~DELETE_KEEP_DATA : flags;
14913                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14914                        deleteFlags, writeSettings);
14915            }
14916        }
14917
14918        // Delete application code and resources only for parent packages
14919        if (ps.parentPackageName == null) {
14920            if (deleteCodeAndResources && (outInfo != null)) {
14921                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14922                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14923                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14924            }
14925        }
14926
14927        return true;
14928    }
14929
14930    @Override
14931    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14932            int userId) {
14933        mContext.enforceCallingOrSelfPermission(
14934                android.Manifest.permission.DELETE_PACKAGES, null);
14935        synchronized (mPackages) {
14936            PackageSetting ps = mSettings.mPackages.get(packageName);
14937            if (ps == null) {
14938                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14939                return false;
14940            }
14941            if (!ps.getInstalled(userId)) {
14942                // Can't block uninstall for an app that is not installed or enabled.
14943                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14944                return false;
14945            }
14946            ps.setBlockUninstall(blockUninstall, userId);
14947            mSettings.writePackageRestrictionsLPr(userId);
14948        }
14949        return true;
14950    }
14951
14952    @Override
14953    public boolean getBlockUninstallForUser(String packageName, int userId) {
14954        synchronized (mPackages) {
14955            PackageSetting ps = mSettings.mPackages.get(packageName);
14956            if (ps == null) {
14957                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14958                return false;
14959            }
14960            return ps.getBlockUninstall(userId);
14961        }
14962    }
14963
14964    @Override
14965    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14966        int callingUid = Binder.getCallingUid();
14967        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14968            throw new SecurityException(
14969                    "setRequiredForSystemUser can only be run by the system or root");
14970        }
14971        synchronized (mPackages) {
14972            PackageSetting ps = mSettings.mPackages.get(packageName);
14973            if (ps == null) {
14974                Log.w(TAG, "Package doesn't exist: " + packageName);
14975                return false;
14976            }
14977            if (systemUserApp) {
14978                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14979            } else {
14980                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14981            }
14982            mSettings.writeLPr();
14983        }
14984        return true;
14985    }
14986
14987    /*
14988     * This method handles package deletion in general
14989     */
14990    private boolean deletePackageLI(String packageName, UserHandle user,
14991            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14992            PackageRemovedInfo outInfo, boolean writeSettings,
14993            PackageParser.Package replacingPackage) {
14994        if (packageName == null) {
14995            Slog.w(TAG, "Attempt to delete null packageName.");
14996            return false;
14997        }
14998
14999        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15000
15001        PackageSetting ps;
15002
15003        synchronized (mPackages) {
15004            ps = mSettings.mPackages.get(packageName);
15005            if (ps == null) {
15006                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15007                return false;
15008            }
15009
15010            if (ps.parentPackageName != null && (!isSystemApp(ps)
15011                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15012                if (DEBUG_REMOVE) {
15013                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15014                            + ((user == null) ? UserHandle.USER_ALL : user));
15015                }
15016                final int removedUserId = (user != null) ? user.getIdentifier()
15017                        : UserHandle.USER_ALL;
15018                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15019                    return false;
15020                }
15021                markPackageUninstalledForUserLPw(ps, user);
15022                scheduleWritePackageRestrictionsLocked(user);
15023                return true;
15024            }
15025        }
15026
15027        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15028                && user.getIdentifier() != UserHandle.USER_ALL)) {
15029            // The caller is asking that the package only be deleted for a single
15030            // user.  To do this, we just mark its uninstalled state and delete
15031            // its data. If this is a system app, we only allow this to happen if
15032            // they have set the special DELETE_SYSTEM_APP which requests different
15033            // semantics than normal for uninstalling system apps.
15034            markPackageUninstalledForUserLPw(ps, user);
15035
15036            if (!isSystemApp(ps)) {
15037                // Do not uninstall the APK if an app should be cached
15038                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15039                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15040                    // Other user still have this package installed, so all
15041                    // we need to do is clear this user's data and save that
15042                    // it is uninstalled.
15043                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15044                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15045                        return false;
15046                    }
15047                    scheduleWritePackageRestrictionsLocked(user);
15048                    return true;
15049                } else {
15050                    // We need to set it back to 'installed' so the uninstall
15051                    // broadcasts will be sent correctly.
15052                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15053                    ps.setInstalled(true, user.getIdentifier());
15054                }
15055            } else {
15056                // This is a system app, so we assume that the
15057                // other users still have this package installed, so all
15058                // we need to do is clear this user's data and save that
15059                // it is uninstalled.
15060                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15061                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15062                    return false;
15063                }
15064                scheduleWritePackageRestrictionsLocked(user);
15065                return true;
15066            }
15067        }
15068
15069        // If we are deleting a composite package for all users, keep track
15070        // of result for each child.
15071        if (ps.childPackageNames != null && outInfo != null) {
15072            synchronized (mPackages) {
15073                final int childCount = ps.childPackageNames.size();
15074                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15075                for (int i = 0; i < childCount; i++) {
15076                    String childPackageName = ps.childPackageNames.get(i);
15077                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15078                    childInfo.removedPackage = childPackageName;
15079                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15080                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15081                    if (childPs != null) {
15082                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15083                    }
15084                }
15085            }
15086        }
15087
15088        boolean ret = false;
15089        if (isSystemApp(ps)) {
15090            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15091            // When an updated system application is deleted we delete the existing resources
15092            // as well and fall back to existing code in system partition
15093            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15094        } else {
15095            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15096            // Kill application pre-emptively especially for apps on sd.
15097            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15098            if (killApp) {
15099                killApplication(packageName, ps.appId, "uninstall pkg");
15100            }
15101            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15102                    outInfo, writeSettings, replacingPackage);
15103        }
15104
15105        // Take a note whether we deleted the package for all users
15106        if (outInfo != null) {
15107            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15108            if (outInfo.removedChildPackages != null) {
15109                synchronized (mPackages) {
15110                    final int childCount = outInfo.removedChildPackages.size();
15111                    for (int i = 0; i < childCount; i++) {
15112                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15113                        if (childInfo != null) {
15114                            childInfo.removedForAllUsers = mPackages.get(
15115                                    childInfo.removedPackage) == null;
15116                        }
15117                    }
15118                }
15119            }
15120            // If we uninstalled an update to a system app there may be some
15121            // child packages that appeared as they are declared in the system
15122            // app but were not declared in the update.
15123            if (isSystemApp(ps)) {
15124                synchronized (mPackages) {
15125                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15126                    final int childCount = (updatedPs.childPackageNames != null)
15127                            ? updatedPs.childPackageNames.size() : 0;
15128                    for (int i = 0; i < childCount; i++) {
15129                        String childPackageName = updatedPs.childPackageNames.get(i);
15130                        if (outInfo.removedChildPackages == null
15131                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15132                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15133                            if (childPs == null) {
15134                                continue;
15135                            }
15136                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15137                            installRes.name = childPackageName;
15138                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15139                            installRes.pkg = mPackages.get(childPackageName);
15140                            installRes.uid = childPs.pkg.applicationInfo.uid;
15141                            if (outInfo.appearedChildPackages == null) {
15142                                outInfo.appearedChildPackages = new ArrayMap<>();
15143                            }
15144                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15145                        }
15146                    }
15147                }
15148            }
15149        }
15150
15151        return ret;
15152    }
15153
15154    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15155        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15156                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15157        for (int nextUserId : userIds) {
15158            if (DEBUG_REMOVE) {
15159                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15160            }
15161            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15162                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15163                    false /*hidden*/, false /*suspended*/, null, null, null,
15164                    false /*blockUninstall*/,
15165                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15166        }
15167    }
15168
15169    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15170            PackageRemovedInfo outInfo) {
15171        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15172                : new int[] {userId};
15173        for (int nextUserId : userIds) {
15174            if (DEBUG_REMOVE) {
15175                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15176                        + nextUserId);
15177            }
15178            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15179            try {
15180                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15181            } catch (InstallerException e) {
15182                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15183                return false;
15184            }
15185            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15186            schedulePackageCleaning(ps.name, nextUserId, false);
15187            synchronized (mPackages) {
15188                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15189                    scheduleWritePackageRestrictionsLocked(nextUserId);
15190                }
15191                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15192            }
15193        }
15194
15195        if (outInfo != null) {
15196            outInfo.removedPackage = ps.name;
15197            outInfo.removedAppId = ps.appId;
15198            outInfo.removedUsers = userIds;
15199        }
15200
15201        return true;
15202    }
15203
15204    private final class ClearStorageConnection implements ServiceConnection {
15205        IMediaContainerService mContainerService;
15206
15207        @Override
15208        public void onServiceConnected(ComponentName name, IBinder service) {
15209            synchronized (this) {
15210                mContainerService = IMediaContainerService.Stub.asInterface(service);
15211                notifyAll();
15212            }
15213        }
15214
15215        @Override
15216        public void onServiceDisconnected(ComponentName name) {
15217        }
15218    }
15219
15220    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15221        final boolean mounted;
15222        if (Environment.isExternalStorageEmulated()) {
15223            mounted = true;
15224        } else {
15225            final String status = Environment.getExternalStorageState();
15226
15227            mounted = status.equals(Environment.MEDIA_MOUNTED)
15228                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15229        }
15230
15231        if (!mounted) {
15232            return;
15233        }
15234
15235        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15236        int[] users;
15237        if (userId == UserHandle.USER_ALL) {
15238            users = sUserManager.getUserIds();
15239        } else {
15240            users = new int[] { userId };
15241        }
15242        final ClearStorageConnection conn = new ClearStorageConnection();
15243        if (mContext.bindServiceAsUser(
15244                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15245            try {
15246                for (int curUser : users) {
15247                    long timeout = SystemClock.uptimeMillis() + 5000;
15248                    synchronized (conn) {
15249                        long now = SystemClock.uptimeMillis();
15250                        while (conn.mContainerService == null && now < timeout) {
15251                            try {
15252                                conn.wait(timeout - now);
15253                            } catch (InterruptedException e) {
15254                            }
15255                        }
15256                    }
15257                    if (conn.mContainerService == null) {
15258                        return;
15259                    }
15260
15261                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15262                    clearDirectory(conn.mContainerService,
15263                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15264                    if (allData) {
15265                        clearDirectory(conn.mContainerService,
15266                                userEnv.buildExternalStorageAppDataDirs(packageName));
15267                        clearDirectory(conn.mContainerService,
15268                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15269                    }
15270                }
15271            } finally {
15272                mContext.unbindService(conn);
15273            }
15274        }
15275    }
15276
15277    @Override
15278    public void clearApplicationProfileData(String packageName) {
15279        enforceSystemOrRoot("Only the system can clear all profile data");
15280        try {
15281            mInstaller.clearAppProfiles(packageName);
15282        } catch (InstallerException ex) {
15283            Log.e(TAG, "Could not clear profile data of package " + packageName);
15284        }
15285    }
15286
15287    @Override
15288    public void clearApplicationUserData(final String packageName,
15289            final IPackageDataObserver observer, final int userId) {
15290        mContext.enforceCallingOrSelfPermission(
15291                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15292
15293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15294                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15295
15296        final DevicePolicyManagerInternal dpmi = LocalServices
15297                .getService(DevicePolicyManagerInternal.class);
15298        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15299            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15300        }
15301        // Queue up an async operation since the package deletion may take a little while.
15302        mHandler.post(new Runnable() {
15303            public void run() {
15304                mHandler.removeCallbacks(this);
15305                final boolean succeeded;
15306                synchronized (mInstallLock) {
15307                    succeeded = clearApplicationUserDataLI(packageName, userId);
15308                }
15309                clearExternalStorageDataSync(packageName, userId, true);
15310                if (succeeded) {
15311                    // invoke DeviceStorageMonitor's update method to clear any notifications
15312                    DeviceStorageMonitorInternal dsm = LocalServices
15313                            .getService(DeviceStorageMonitorInternal.class);
15314                    if (dsm != null) {
15315                        dsm.checkMemory();
15316                    }
15317                }
15318                if(observer != null) {
15319                    try {
15320                        observer.onRemoveCompleted(packageName, succeeded);
15321                    } catch (RemoteException e) {
15322                        Log.i(TAG, "Observer no longer exists.");
15323                    }
15324                } //end if observer
15325            } //end run
15326        });
15327    }
15328
15329    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15330        if (packageName == null) {
15331            Slog.w(TAG, "Attempt to delete null packageName.");
15332            return false;
15333        }
15334
15335        // Try finding details about the requested package
15336        PackageParser.Package pkg;
15337        synchronized (mPackages) {
15338            pkg = mPackages.get(packageName);
15339            if (pkg == null) {
15340                final PackageSetting ps = mSettings.mPackages.get(packageName);
15341                if (ps != null) {
15342                    pkg = ps.pkg;
15343                }
15344            }
15345
15346            if (pkg == null) {
15347                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15348                return false;
15349            }
15350
15351            PackageSetting ps = (PackageSetting) pkg.mExtras;
15352            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15353        }
15354
15355        // Always delete data directories for package, even if we found no other
15356        // record of app. This helps users recover from UID mismatches without
15357        // resorting to a full data wipe.
15358        // TODO: triage flags as part of 26466827
15359        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15360        try {
15361            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15362        } catch (InstallerException e) {
15363            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15364            return false;
15365        }
15366
15367        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15368        removeKeystoreDataIfNeeded(userId, appId);
15369
15370        // Create a native library symlink only if we have native libraries
15371        // and if the native libraries are 32 bit libraries. We do not provide
15372        // this symlink for 64 bit libraries.
15373        if (pkg.applicationInfo.primaryCpuAbi != null &&
15374                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15375            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15376            try {
15377                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15378                        nativeLibPath, userId);
15379            } catch (InstallerException e) {
15380                Slog.w(TAG, "Failed linking native library dir", e);
15381                return false;
15382            }
15383        }
15384
15385        return true;
15386    }
15387
15388    /**
15389     * Reverts user permission state changes (permissions and flags) in
15390     * all packages for a given user.
15391     *
15392     * @param userId The device user for which to do a reset.
15393     */
15394    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15395        final int packageCount = mPackages.size();
15396        for (int i = 0; i < packageCount; i++) {
15397            PackageParser.Package pkg = mPackages.valueAt(i);
15398            PackageSetting ps = (PackageSetting) pkg.mExtras;
15399            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15400        }
15401    }
15402
15403    /**
15404     * Reverts user permission state changes (permissions and flags).
15405     *
15406     * @param ps The package for which to reset.
15407     * @param userId The device user for which to do a reset.
15408     */
15409    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15410            final PackageSetting ps, final int userId) {
15411        if (ps.pkg == null) {
15412            return;
15413        }
15414
15415        // These are flags that can change base on user actions.
15416        final int userSettableMask = FLAG_PERMISSION_USER_SET
15417                | FLAG_PERMISSION_USER_FIXED
15418                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15419                | FLAG_PERMISSION_REVIEW_REQUIRED;
15420
15421        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15422                | FLAG_PERMISSION_POLICY_FIXED;
15423
15424        boolean writeInstallPermissions = false;
15425        boolean writeRuntimePermissions = false;
15426
15427        final int permissionCount = ps.pkg.requestedPermissions.size();
15428        for (int i = 0; i < permissionCount; i++) {
15429            String permission = ps.pkg.requestedPermissions.get(i);
15430
15431            BasePermission bp = mSettings.mPermissions.get(permission);
15432            if (bp == null) {
15433                continue;
15434            }
15435
15436            // If shared user we just reset the state to which only this app contributed.
15437            if (ps.sharedUser != null) {
15438                boolean used = false;
15439                final int packageCount = ps.sharedUser.packages.size();
15440                for (int j = 0; j < packageCount; j++) {
15441                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15442                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15443                            && pkg.pkg.requestedPermissions.contains(permission)) {
15444                        used = true;
15445                        break;
15446                    }
15447                }
15448                if (used) {
15449                    continue;
15450                }
15451            }
15452
15453            PermissionsState permissionsState = ps.getPermissionsState();
15454
15455            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15456
15457            // Always clear the user settable flags.
15458            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15459                    bp.name) != null;
15460            // If permission review is enabled and this is a legacy app, mark the
15461            // permission as requiring a review as this is the initial state.
15462            int flags = 0;
15463            if (Build.PERMISSIONS_REVIEW_REQUIRED
15464                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15465                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15466            }
15467            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15468                if (hasInstallState) {
15469                    writeInstallPermissions = true;
15470                } else {
15471                    writeRuntimePermissions = true;
15472                }
15473            }
15474
15475            // Below is only runtime permission handling.
15476            if (!bp.isRuntime()) {
15477                continue;
15478            }
15479
15480            // Never clobber system or policy.
15481            if ((oldFlags & policyOrSystemFlags) != 0) {
15482                continue;
15483            }
15484
15485            // If this permission was granted by default, make sure it is.
15486            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15487                if (permissionsState.grantRuntimePermission(bp, userId)
15488                        != PERMISSION_OPERATION_FAILURE) {
15489                    writeRuntimePermissions = true;
15490                }
15491            // If permission review is enabled the permissions for a legacy apps
15492            // are represented as constantly granted runtime ones, so don't revoke.
15493            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15494                // Otherwise, reset the permission.
15495                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15496                switch (revokeResult) {
15497                    case PERMISSION_OPERATION_SUCCESS: {
15498                        writeRuntimePermissions = true;
15499                    } break;
15500
15501                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15502                        writeRuntimePermissions = true;
15503                        final int appId = ps.appId;
15504                        mHandler.post(new Runnable() {
15505                            @Override
15506                            public void run() {
15507                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15508                            }
15509                        });
15510                    } break;
15511                }
15512            }
15513        }
15514
15515        // Synchronously write as we are taking permissions away.
15516        if (writeRuntimePermissions) {
15517            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15518        }
15519
15520        // Synchronously write as we are taking permissions away.
15521        if (writeInstallPermissions) {
15522            mSettings.writeLPr();
15523        }
15524    }
15525
15526    /**
15527     * Remove entries from the keystore daemon. Will only remove it if the
15528     * {@code appId} is valid.
15529     */
15530    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15531        if (appId < 0) {
15532            return;
15533        }
15534
15535        final KeyStore keyStore = KeyStore.getInstance();
15536        if (keyStore != null) {
15537            if (userId == UserHandle.USER_ALL) {
15538                for (final int individual : sUserManager.getUserIds()) {
15539                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15540                }
15541            } else {
15542                keyStore.clearUid(UserHandle.getUid(userId, appId));
15543            }
15544        } else {
15545            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15546        }
15547    }
15548
15549    @Override
15550    public void deleteApplicationCacheFiles(final String packageName,
15551            final IPackageDataObserver observer) {
15552        mContext.enforceCallingOrSelfPermission(
15553                android.Manifest.permission.DELETE_CACHE_FILES, null);
15554        // Queue up an async operation since the package deletion may take a little while.
15555        final int userId = UserHandle.getCallingUserId();
15556        mHandler.post(new Runnable() {
15557            public void run() {
15558                mHandler.removeCallbacks(this);
15559                final boolean succeded;
15560                synchronized (mInstallLock) {
15561                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15562                }
15563                clearExternalStorageDataSync(packageName, userId, false);
15564                if (observer != null) {
15565                    try {
15566                        observer.onRemoveCompleted(packageName, succeded);
15567                    } catch (RemoteException e) {
15568                        Log.i(TAG, "Observer no longer exists.");
15569                    }
15570                } //end if observer
15571            } //end run
15572        });
15573    }
15574
15575    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15576        if (packageName == null) {
15577            Slog.w(TAG, "Attempt to delete null packageName.");
15578            return false;
15579        }
15580        PackageParser.Package p;
15581        synchronized (mPackages) {
15582            p = mPackages.get(packageName);
15583        }
15584        if (p == null) {
15585            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15586            return false;
15587        }
15588        final ApplicationInfo applicationInfo = p.applicationInfo;
15589        if (applicationInfo == null) {
15590            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15591            return false;
15592        }
15593        // TODO: triage flags as part of 26466827
15594        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15595        try {
15596            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15597                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15598        } catch (InstallerException e) {
15599            Slog.w(TAG, "Couldn't remove cache files for package "
15600                    + packageName + " u" + userId, e);
15601            return false;
15602        }
15603        return true;
15604    }
15605
15606    @Override
15607    public void getPackageSizeInfo(final String packageName, int userHandle,
15608            final IPackageStatsObserver observer) {
15609        mContext.enforceCallingOrSelfPermission(
15610                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15611        if (packageName == null) {
15612            throw new IllegalArgumentException("Attempt to get size of null packageName");
15613        }
15614
15615        PackageStats stats = new PackageStats(packageName, userHandle);
15616
15617        /*
15618         * Queue up an async operation since the package measurement may take a
15619         * little while.
15620         */
15621        Message msg = mHandler.obtainMessage(INIT_COPY);
15622        msg.obj = new MeasureParams(stats, observer);
15623        mHandler.sendMessage(msg);
15624    }
15625
15626    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15627            PackageStats pStats) {
15628        if (packageName == null) {
15629            Slog.w(TAG, "Attempt to get size of null packageName.");
15630            return false;
15631        }
15632        PackageParser.Package p;
15633        boolean dataOnly = false;
15634        String libDirRoot = null;
15635        String asecPath = null;
15636        PackageSetting ps = null;
15637        synchronized (mPackages) {
15638            p = mPackages.get(packageName);
15639            ps = mSettings.mPackages.get(packageName);
15640            if(p == null) {
15641                dataOnly = true;
15642                if((ps == null) || (ps.pkg == null)) {
15643                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15644                    return false;
15645                }
15646                p = ps.pkg;
15647            }
15648            if (ps != null) {
15649                libDirRoot = ps.legacyNativeLibraryPathString;
15650            }
15651            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15652                final long token = Binder.clearCallingIdentity();
15653                try {
15654                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15655                    if (secureContainerId != null) {
15656                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15657                    }
15658                } finally {
15659                    Binder.restoreCallingIdentity(token);
15660                }
15661            }
15662        }
15663        String publicSrcDir = null;
15664        if(!dataOnly) {
15665            final ApplicationInfo applicationInfo = p.applicationInfo;
15666            if (applicationInfo == null) {
15667                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15668                return false;
15669            }
15670            if (p.isForwardLocked()) {
15671                publicSrcDir = applicationInfo.getBaseResourcePath();
15672            }
15673        }
15674        // TODO: extend to measure size of split APKs
15675        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15676        // not just the first level.
15677        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15678        // just the primary.
15679        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15680
15681        String apkPath;
15682        File packageDir = new File(p.codePath);
15683
15684        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15685            apkPath = packageDir.getAbsolutePath();
15686            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15687            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15688                libDirRoot = null;
15689            }
15690        } else {
15691            apkPath = p.baseCodePath;
15692        }
15693
15694        // TODO: triage flags as part of 26466827
15695        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15696        try {
15697            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15698                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15699        } catch (InstallerException e) {
15700            return false;
15701        }
15702
15703        // Fix-up for forward-locked applications in ASEC containers.
15704        if (!isExternal(p)) {
15705            pStats.codeSize += pStats.externalCodeSize;
15706            pStats.externalCodeSize = 0L;
15707        }
15708
15709        return true;
15710    }
15711
15712    private int getUidTargetSdkVersionLockedLPr(int uid) {
15713        Object obj = mSettings.getUserIdLPr(uid);
15714        if (obj instanceof SharedUserSetting) {
15715            final SharedUserSetting sus = (SharedUserSetting) obj;
15716            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15717            final Iterator<PackageSetting> it = sus.packages.iterator();
15718            while (it.hasNext()) {
15719                final PackageSetting ps = it.next();
15720                if (ps.pkg != null) {
15721                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15722                    if (v < vers) vers = v;
15723                }
15724            }
15725            return vers;
15726        } else if (obj instanceof PackageSetting) {
15727            final PackageSetting ps = (PackageSetting) obj;
15728            if (ps.pkg != null) {
15729                return ps.pkg.applicationInfo.targetSdkVersion;
15730            }
15731        }
15732        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15733    }
15734
15735    @Override
15736    public void addPreferredActivity(IntentFilter filter, int match,
15737            ComponentName[] set, ComponentName activity, int userId) {
15738        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15739                "Adding preferred");
15740    }
15741
15742    private void addPreferredActivityInternal(IntentFilter filter, int match,
15743            ComponentName[] set, ComponentName activity, boolean always, int userId,
15744            String opname) {
15745        // writer
15746        int callingUid = Binder.getCallingUid();
15747        enforceCrossUserPermission(callingUid, userId,
15748                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15749        if (filter.countActions() == 0) {
15750            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15751            return;
15752        }
15753        synchronized (mPackages) {
15754            if (mContext.checkCallingOrSelfPermission(
15755                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15756                    != PackageManager.PERMISSION_GRANTED) {
15757                if (getUidTargetSdkVersionLockedLPr(callingUid)
15758                        < Build.VERSION_CODES.FROYO) {
15759                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15760                            + callingUid);
15761                    return;
15762                }
15763                mContext.enforceCallingOrSelfPermission(
15764                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15765            }
15766
15767            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15768            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15769                    + userId + ":");
15770            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15771            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15772            scheduleWritePackageRestrictionsLocked(userId);
15773        }
15774    }
15775
15776    @Override
15777    public void replacePreferredActivity(IntentFilter filter, int match,
15778            ComponentName[] set, ComponentName activity, int userId) {
15779        if (filter.countActions() != 1) {
15780            throw new IllegalArgumentException(
15781                    "replacePreferredActivity expects filter to have only 1 action.");
15782        }
15783        if (filter.countDataAuthorities() != 0
15784                || filter.countDataPaths() != 0
15785                || filter.countDataSchemes() > 1
15786                || filter.countDataTypes() != 0) {
15787            throw new IllegalArgumentException(
15788                    "replacePreferredActivity expects filter to have no data authorities, " +
15789                    "paths, or types; and at most one scheme.");
15790        }
15791
15792        final int callingUid = Binder.getCallingUid();
15793        enforceCrossUserPermission(callingUid, userId,
15794                true /* requireFullPermission */, false /* checkShell */,
15795                "replace preferred activity");
15796        synchronized (mPackages) {
15797            if (mContext.checkCallingOrSelfPermission(
15798                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15799                    != PackageManager.PERMISSION_GRANTED) {
15800                if (getUidTargetSdkVersionLockedLPr(callingUid)
15801                        < Build.VERSION_CODES.FROYO) {
15802                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15803                            + Binder.getCallingUid());
15804                    return;
15805                }
15806                mContext.enforceCallingOrSelfPermission(
15807                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15808            }
15809
15810            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15811            if (pir != null) {
15812                // Get all of the existing entries that exactly match this filter.
15813                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15814                if (existing != null && existing.size() == 1) {
15815                    PreferredActivity cur = existing.get(0);
15816                    if (DEBUG_PREFERRED) {
15817                        Slog.i(TAG, "Checking replace of preferred:");
15818                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15819                        if (!cur.mPref.mAlways) {
15820                            Slog.i(TAG, "  -- CUR; not mAlways!");
15821                        } else {
15822                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15823                            Slog.i(TAG, "  -- CUR: mSet="
15824                                    + Arrays.toString(cur.mPref.mSetComponents));
15825                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15826                            Slog.i(TAG, "  -- NEW: mMatch="
15827                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15828                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15829                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15830                        }
15831                    }
15832                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15833                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15834                            && cur.mPref.sameSet(set)) {
15835                        // Setting the preferred activity to what it happens to be already
15836                        if (DEBUG_PREFERRED) {
15837                            Slog.i(TAG, "Replacing with same preferred activity "
15838                                    + cur.mPref.mShortComponent + " for user "
15839                                    + userId + ":");
15840                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15841                        }
15842                        return;
15843                    }
15844                }
15845
15846                if (existing != null) {
15847                    if (DEBUG_PREFERRED) {
15848                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15849                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15850                    }
15851                    for (int i = 0; i < existing.size(); i++) {
15852                        PreferredActivity pa = existing.get(i);
15853                        if (DEBUG_PREFERRED) {
15854                            Slog.i(TAG, "Removing existing preferred activity "
15855                                    + pa.mPref.mComponent + ":");
15856                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15857                        }
15858                        pir.removeFilter(pa);
15859                    }
15860                }
15861            }
15862            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15863                    "Replacing preferred");
15864        }
15865    }
15866
15867    @Override
15868    public void clearPackagePreferredActivities(String packageName) {
15869        final int uid = Binder.getCallingUid();
15870        // writer
15871        synchronized (mPackages) {
15872            PackageParser.Package pkg = mPackages.get(packageName);
15873            if (pkg == null || pkg.applicationInfo.uid != uid) {
15874                if (mContext.checkCallingOrSelfPermission(
15875                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15876                        != PackageManager.PERMISSION_GRANTED) {
15877                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15878                            < Build.VERSION_CODES.FROYO) {
15879                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15880                                + Binder.getCallingUid());
15881                        return;
15882                    }
15883                    mContext.enforceCallingOrSelfPermission(
15884                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15885                }
15886            }
15887
15888            int user = UserHandle.getCallingUserId();
15889            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15890                scheduleWritePackageRestrictionsLocked(user);
15891            }
15892        }
15893    }
15894
15895    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15896    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15897        ArrayList<PreferredActivity> removed = null;
15898        boolean changed = false;
15899        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15900            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15901            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15902            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15903                continue;
15904            }
15905            Iterator<PreferredActivity> it = pir.filterIterator();
15906            while (it.hasNext()) {
15907                PreferredActivity pa = it.next();
15908                // Mark entry for removal only if it matches the package name
15909                // and the entry is of type "always".
15910                if (packageName == null ||
15911                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15912                                && pa.mPref.mAlways)) {
15913                    if (removed == null) {
15914                        removed = new ArrayList<PreferredActivity>();
15915                    }
15916                    removed.add(pa);
15917                }
15918            }
15919            if (removed != null) {
15920                for (int j=0; j<removed.size(); j++) {
15921                    PreferredActivity pa = removed.get(j);
15922                    pir.removeFilter(pa);
15923                }
15924                changed = true;
15925            }
15926        }
15927        return changed;
15928    }
15929
15930    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15931    private void clearIntentFilterVerificationsLPw(int userId) {
15932        final int packageCount = mPackages.size();
15933        for (int i = 0; i < packageCount; i++) {
15934            PackageParser.Package pkg = mPackages.valueAt(i);
15935            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15936        }
15937    }
15938
15939    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15940    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15941        if (userId == UserHandle.USER_ALL) {
15942            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15943                    sUserManager.getUserIds())) {
15944                for (int oneUserId : sUserManager.getUserIds()) {
15945                    scheduleWritePackageRestrictionsLocked(oneUserId);
15946                }
15947            }
15948        } else {
15949            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15950                scheduleWritePackageRestrictionsLocked(userId);
15951            }
15952        }
15953    }
15954
15955    void clearDefaultBrowserIfNeeded(String packageName) {
15956        for (int oneUserId : sUserManager.getUserIds()) {
15957            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15958            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15959            if (packageName.equals(defaultBrowserPackageName)) {
15960                setDefaultBrowserPackageName(null, oneUserId);
15961            }
15962        }
15963    }
15964
15965    @Override
15966    public void resetApplicationPreferences(int userId) {
15967        mContext.enforceCallingOrSelfPermission(
15968                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15969        // writer
15970        synchronized (mPackages) {
15971            final long identity = Binder.clearCallingIdentity();
15972            try {
15973                clearPackagePreferredActivitiesLPw(null, userId);
15974                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15975                // TODO: We have to reset the default SMS and Phone. This requires
15976                // significant refactoring to keep all default apps in the package
15977                // manager (cleaner but more work) or have the services provide
15978                // callbacks to the package manager to request a default app reset.
15979                applyFactoryDefaultBrowserLPw(userId);
15980                clearIntentFilterVerificationsLPw(userId);
15981                primeDomainVerificationsLPw(userId);
15982                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15983                scheduleWritePackageRestrictionsLocked(userId);
15984            } finally {
15985                Binder.restoreCallingIdentity(identity);
15986            }
15987        }
15988    }
15989
15990    @Override
15991    public int getPreferredActivities(List<IntentFilter> outFilters,
15992            List<ComponentName> outActivities, String packageName) {
15993
15994        int num = 0;
15995        final int userId = UserHandle.getCallingUserId();
15996        // reader
15997        synchronized (mPackages) {
15998            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15999            if (pir != null) {
16000                final Iterator<PreferredActivity> it = pir.filterIterator();
16001                while (it.hasNext()) {
16002                    final PreferredActivity pa = it.next();
16003                    if (packageName == null
16004                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16005                                    && pa.mPref.mAlways)) {
16006                        if (outFilters != null) {
16007                            outFilters.add(new IntentFilter(pa));
16008                        }
16009                        if (outActivities != null) {
16010                            outActivities.add(pa.mPref.mComponent);
16011                        }
16012                    }
16013                }
16014            }
16015        }
16016
16017        return num;
16018    }
16019
16020    @Override
16021    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16022            int userId) {
16023        int callingUid = Binder.getCallingUid();
16024        if (callingUid != Process.SYSTEM_UID) {
16025            throw new SecurityException(
16026                    "addPersistentPreferredActivity can only be run by the system");
16027        }
16028        if (filter.countActions() == 0) {
16029            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16030            return;
16031        }
16032        synchronized (mPackages) {
16033            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16034                    ":");
16035            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16036            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16037                    new PersistentPreferredActivity(filter, activity));
16038            scheduleWritePackageRestrictionsLocked(userId);
16039        }
16040    }
16041
16042    @Override
16043    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16044        int callingUid = Binder.getCallingUid();
16045        if (callingUid != Process.SYSTEM_UID) {
16046            throw new SecurityException(
16047                    "clearPackagePersistentPreferredActivities can only be run by the system");
16048        }
16049        ArrayList<PersistentPreferredActivity> removed = null;
16050        boolean changed = false;
16051        synchronized (mPackages) {
16052            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16053                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16054                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16055                        .valueAt(i);
16056                if (userId != thisUserId) {
16057                    continue;
16058                }
16059                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16060                while (it.hasNext()) {
16061                    PersistentPreferredActivity ppa = it.next();
16062                    // Mark entry for removal only if it matches the package name.
16063                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16064                        if (removed == null) {
16065                            removed = new ArrayList<PersistentPreferredActivity>();
16066                        }
16067                        removed.add(ppa);
16068                    }
16069                }
16070                if (removed != null) {
16071                    for (int j=0; j<removed.size(); j++) {
16072                        PersistentPreferredActivity ppa = removed.get(j);
16073                        ppir.removeFilter(ppa);
16074                    }
16075                    changed = true;
16076                }
16077            }
16078
16079            if (changed) {
16080                scheduleWritePackageRestrictionsLocked(userId);
16081            }
16082        }
16083    }
16084
16085    /**
16086     * Common machinery for picking apart a restored XML blob and passing
16087     * it to a caller-supplied functor to be applied to the running system.
16088     */
16089    private void restoreFromXml(XmlPullParser parser, int userId,
16090            String expectedStartTag, BlobXmlRestorer functor)
16091            throws IOException, XmlPullParserException {
16092        int type;
16093        while ((type = parser.next()) != XmlPullParser.START_TAG
16094                && type != XmlPullParser.END_DOCUMENT) {
16095        }
16096        if (type != XmlPullParser.START_TAG) {
16097            // oops didn't find a start tag?!
16098            if (DEBUG_BACKUP) {
16099                Slog.e(TAG, "Didn't find start tag during restore");
16100            }
16101            return;
16102        }
16103Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16104        // this is supposed to be TAG_PREFERRED_BACKUP
16105        if (!expectedStartTag.equals(parser.getName())) {
16106            if (DEBUG_BACKUP) {
16107                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16108            }
16109            return;
16110        }
16111
16112        // skip interfering stuff, then we're aligned with the backing implementation
16113        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16114Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16115        functor.apply(parser, userId);
16116    }
16117
16118    private interface BlobXmlRestorer {
16119        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16120    }
16121
16122    /**
16123     * Non-Binder method, support for the backup/restore mechanism: write the
16124     * full set of preferred activities in its canonical XML format.  Returns the
16125     * XML output as a byte array, or null if there is none.
16126     */
16127    @Override
16128    public byte[] getPreferredActivityBackup(int userId) {
16129        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16130            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16131        }
16132
16133        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16134        try {
16135            final XmlSerializer serializer = new FastXmlSerializer();
16136            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16137            serializer.startDocument(null, true);
16138            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16139
16140            synchronized (mPackages) {
16141                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16142            }
16143
16144            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16145            serializer.endDocument();
16146            serializer.flush();
16147        } catch (Exception e) {
16148            if (DEBUG_BACKUP) {
16149                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16150            }
16151            return null;
16152        }
16153
16154        return dataStream.toByteArray();
16155    }
16156
16157    @Override
16158    public void restorePreferredActivities(byte[] backup, int userId) {
16159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16160            throw new SecurityException("Only the system may call restorePreferredActivities()");
16161        }
16162
16163        try {
16164            final XmlPullParser parser = Xml.newPullParser();
16165            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16166            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16167                    new BlobXmlRestorer() {
16168                        @Override
16169                        public void apply(XmlPullParser parser, int userId)
16170                                throws XmlPullParserException, IOException {
16171                            synchronized (mPackages) {
16172                                mSettings.readPreferredActivitiesLPw(parser, userId);
16173                            }
16174                        }
16175                    } );
16176        } catch (Exception e) {
16177            if (DEBUG_BACKUP) {
16178                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16179            }
16180        }
16181    }
16182
16183    /**
16184     * Non-Binder method, support for the backup/restore mechanism: write the
16185     * default browser (etc) settings in its canonical XML format.  Returns the default
16186     * browser XML representation as a byte array, or null if there is none.
16187     */
16188    @Override
16189    public byte[] getDefaultAppsBackup(int userId) {
16190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16191            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16192        }
16193
16194        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16195        try {
16196            final XmlSerializer serializer = new FastXmlSerializer();
16197            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16198            serializer.startDocument(null, true);
16199            serializer.startTag(null, TAG_DEFAULT_APPS);
16200
16201            synchronized (mPackages) {
16202                mSettings.writeDefaultAppsLPr(serializer, userId);
16203            }
16204
16205            serializer.endTag(null, TAG_DEFAULT_APPS);
16206            serializer.endDocument();
16207            serializer.flush();
16208        } catch (Exception e) {
16209            if (DEBUG_BACKUP) {
16210                Slog.e(TAG, "Unable to write default apps for backup", e);
16211            }
16212            return null;
16213        }
16214
16215        return dataStream.toByteArray();
16216    }
16217
16218    @Override
16219    public void restoreDefaultApps(byte[] backup, int userId) {
16220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16221            throw new SecurityException("Only the system may call restoreDefaultApps()");
16222        }
16223
16224        try {
16225            final XmlPullParser parser = Xml.newPullParser();
16226            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16227            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16228                    new BlobXmlRestorer() {
16229                        @Override
16230                        public void apply(XmlPullParser parser, int userId)
16231                                throws XmlPullParserException, IOException {
16232                            synchronized (mPackages) {
16233                                mSettings.readDefaultAppsLPw(parser, userId);
16234                            }
16235                        }
16236                    } );
16237        } catch (Exception e) {
16238            if (DEBUG_BACKUP) {
16239                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16240            }
16241        }
16242    }
16243
16244    @Override
16245    public byte[] getIntentFilterVerificationBackup(int userId) {
16246        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16247            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16248        }
16249
16250        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16251        try {
16252            final XmlSerializer serializer = new FastXmlSerializer();
16253            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16254            serializer.startDocument(null, true);
16255            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16256
16257            synchronized (mPackages) {
16258                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16259            }
16260
16261            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16262            serializer.endDocument();
16263            serializer.flush();
16264        } catch (Exception e) {
16265            if (DEBUG_BACKUP) {
16266                Slog.e(TAG, "Unable to write default apps for backup", e);
16267            }
16268            return null;
16269        }
16270
16271        return dataStream.toByteArray();
16272    }
16273
16274    @Override
16275    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16276        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16277            throw new SecurityException("Only the system may call restorePreferredActivities()");
16278        }
16279
16280        try {
16281            final XmlPullParser parser = Xml.newPullParser();
16282            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16283            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16284                    new BlobXmlRestorer() {
16285                        @Override
16286                        public void apply(XmlPullParser parser, int userId)
16287                                throws XmlPullParserException, IOException {
16288                            synchronized (mPackages) {
16289                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16290                                mSettings.writeLPr();
16291                            }
16292                        }
16293                    } );
16294        } catch (Exception e) {
16295            if (DEBUG_BACKUP) {
16296                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16297            }
16298        }
16299    }
16300
16301    @Override
16302    public byte[] getPermissionGrantBackup(int userId) {
16303        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16304            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16305        }
16306
16307        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16308        try {
16309            final XmlSerializer serializer = new FastXmlSerializer();
16310            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16311            serializer.startDocument(null, true);
16312            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16313
16314            synchronized (mPackages) {
16315                serializeRuntimePermissionGrantsLPr(serializer, userId);
16316            }
16317
16318            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16319            serializer.endDocument();
16320            serializer.flush();
16321        } catch (Exception e) {
16322            if (DEBUG_BACKUP) {
16323                Slog.e(TAG, "Unable to write default apps for backup", e);
16324            }
16325            return null;
16326        }
16327
16328        return dataStream.toByteArray();
16329    }
16330
16331    @Override
16332    public void restorePermissionGrants(byte[] backup, int userId) {
16333        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16334            throw new SecurityException("Only the system may call restorePermissionGrants()");
16335        }
16336
16337        try {
16338            final XmlPullParser parser = Xml.newPullParser();
16339            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16340            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16341                    new BlobXmlRestorer() {
16342                        @Override
16343                        public void apply(XmlPullParser parser, int userId)
16344                                throws XmlPullParserException, IOException {
16345                            synchronized (mPackages) {
16346                                processRestoredPermissionGrantsLPr(parser, userId);
16347                            }
16348                        }
16349                    } );
16350        } catch (Exception e) {
16351            if (DEBUG_BACKUP) {
16352                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16353            }
16354        }
16355    }
16356
16357    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16358            throws IOException {
16359        serializer.startTag(null, TAG_ALL_GRANTS);
16360
16361        final int N = mSettings.mPackages.size();
16362        for (int i = 0; i < N; i++) {
16363            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16364            boolean pkgGrantsKnown = false;
16365
16366            PermissionsState packagePerms = ps.getPermissionsState();
16367
16368            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16369                final int grantFlags = state.getFlags();
16370                // only look at grants that are not system/policy fixed
16371                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16372                    final boolean isGranted = state.isGranted();
16373                    // And only back up the user-twiddled state bits
16374                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16375                        final String packageName = mSettings.mPackages.keyAt(i);
16376                        if (!pkgGrantsKnown) {
16377                            serializer.startTag(null, TAG_GRANT);
16378                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16379                            pkgGrantsKnown = true;
16380                        }
16381
16382                        final boolean userSet =
16383                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16384                        final boolean userFixed =
16385                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16386                        final boolean revoke =
16387                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16388
16389                        serializer.startTag(null, TAG_PERMISSION);
16390                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16391                        if (isGranted) {
16392                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16393                        }
16394                        if (userSet) {
16395                            serializer.attribute(null, ATTR_USER_SET, "true");
16396                        }
16397                        if (userFixed) {
16398                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16399                        }
16400                        if (revoke) {
16401                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16402                        }
16403                        serializer.endTag(null, TAG_PERMISSION);
16404                    }
16405                }
16406            }
16407
16408            if (pkgGrantsKnown) {
16409                serializer.endTag(null, TAG_GRANT);
16410            }
16411        }
16412
16413        serializer.endTag(null, TAG_ALL_GRANTS);
16414    }
16415
16416    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16417            throws XmlPullParserException, IOException {
16418        String pkgName = null;
16419        int outerDepth = parser.getDepth();
16420        int type;
16421        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16422                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16423            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16424                continue;
16425            }
16426
16427            final String tagName = parser.getName();
16428            if (tagName.equals(TAG_GRANT)) {
16429                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16430                if (DEBUG_BACKUP) {
16431                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16432                }
16433            } else if (tagName.equals(TAG_PERMISSION)) {
16434
16435                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16436                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16437
16438                int newFlagSet = 0;
16439                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16440                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16441                }
16442                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16443                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16444                }
16445                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16446                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16447                }
16448                if (DEBUG_BACKUP) {
16449                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16450                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16451                }
16452                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16453                if (ps != null) {
16454                    // Already installed so we apply the grant immediately
16455                    if (DEBUG_BACKUP) {
16456                        Slog.v(TAG, "        + already installed; applying");
16457                    }
16458                    PermissionsState perms = ps.getPermissionsState();
16459                    BasePermission bp = mSettings.mPermissions.get(permName);
16460                    if (bp != null) {
16461                        if (isGranted) {
16462                            perms.grantRuntimePermission(bp, userId);
16463                        }
16464                        if (newFlagSet != 0) {
16465                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16466                        }
16467                    }
16468                } else {
16469                    // Need to wait for post-restore install to apply the grant
16470                    if (DEBUG_BACKUP) {
16471                        Slog.v(TAG, "        - not yet installed; saving for later");
16472                    }
16473                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16474                            isGranted, newFlagSet, userId);
16475                }
16476            } else {
16477                PackageManagerService.reportSettingsProblem(Log.WARN,
16478                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16479                XmlUtils.skipCurrentTag(parser);
16480            }
16481        }
16482
16483        scheduleWriteSettingsLocked();
16484        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16485    }
16486
16487    @Override
16488    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16489            int sourceUserId, int targetUserId, int flags) {
16490        mContext.enforceCallingOrSelfPermission(
16491                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16492        int callingUid = Binder.getCallingUid();
16493        enforceOwnerRights(ownerPackage, callingUid);
16494        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16495        if (intentFilter.countActions() == 0) {
16496            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16497            return;
16498        }
16499        synchronized (mPackages) {
16500            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16501                    ownerPackage, targetUserId, flags);
16502            CrossProfileIntentResolver resolver =
16503                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16504            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16505            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16506            if (existing != null) {
16507                int size = existing.size();
16508                for (int i = 0; i < size; i++) {
16509                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16510                        return;
16511                    }
16512                }
16513            }
16514            resolver.addFilter(newFilter);
16515            scheduleWritePackageRestrictionsLocked(sourceUserId);
16516        }
16517    }
16518
16519    @Override
16520    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16521        mContext.enforceCallingOrSelfPermission(
16522                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16523        int callingUid = Binder.getCallingUid();
16524        enforceOwnerRights(ownerPackage, callingUid);
16525        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16526        synchronized (mPackages) {
16527            CrossProfileIntentResolver resolver =
16528                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16529            ArraySet<CrossProfileIntentFilter> set =
16530                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16531            for (CrossProfileIntentFilter filter : set) {
16532                if (filter.getOwnerPackage().equals(ownerPackage)) {
16533                    resolver.removeFilter(filter);
16534                }
16535            }
16536            scheduleWritePackageRestrictionsLocked(sourceUserId);
16537        }
16538    }
16539
16540    // Enforcing that callingUid is owning pkg on userId
16541    private void enforceOwnerRights(String pkg, int callingUid) {
16542        // The system owns everything.
16543        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16544            return;
16545        }
16546        int callingUserId = UserHandle.getUserId(callingUid);
16547        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16548        if (pi == null) {
16549            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16550                    + callingUserId);
16551        }
16552        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16553            throw new SecurityException("Calling uid " + callingUid
16554                    + " does not own package " + pkg);
16555        }
16556    }
16557
16558    @Override
16559    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16560        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16561    }
16562
16563    private Intent getHomeIntent() {
16564        Intent intent = new Intent(Intent.ACTION_MAIN);
16565        intent.addCategory(Intent.CATEGORY_HOME);
16566        return intent;
16567    }
16568
16569    private IntentFilter getHomeFilter() {
16570        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16571        filter.addCategory(Intent.CATEGORY_HOME);
16572        filter.addCategory(Intent.CATEGORY_DEFAULT);
16573        return filter;
16574    }
16575
16576    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16577            int userId) {
16578        Intent intent  = getHomeIntent();
16579        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16580                PackageManager.GET_META_DATA, userId);
16581        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16582                true, false, false, userId);
16583
16584        allHomeCandidates.clear();
16585        if (list != null) {
16586            for (ResolveInfo ri : list) {
16587                allHomeCandidates.add(ri);
16588            }
16589        }
16590        return (preferred == null || preferred.activityInfo == null)
16591                ? null
16592                : new ComponentName(preferred.activityInfo.packageName,
16593                        preferred.activityInfo.name);
16594    }
16595
16596    @Override
16597    public void setHomeActivity(ComponentName comp, int userId) {
16598        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16599        getHomeActivitiesAsUser(homeActivities, userId);
16600
16601        boolean found = false;
16602
16603        final int size = homeActivities.size();
16604        final ComponentName[] set = new ComponentName[size];
16605        for (int i = 0; i < size; i++) {
16606            final ResolveInfo candidate = homeActivities.get(i);
16607            final ActivityInfo info = candidate.activityInfo;
16608            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16609            set[i] = activityName;
16610            if (!found && activityName.equals(comp)) {
16611                found = true;
16612            }
16613        }
16614        if (!found) {
16615            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16616                    + userId);
16617        }
16618        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16619                set, comp, userId);
16620    }
16621
16622    @Override
16623    public void setApplicationEnabledSetting(String appPackageName,
16624            int newState, int flags, int userId, String callingPackage) {
16625        if (!sUserManager.exists(userId)) return;
16626        if (callingPackage == null) {
16627            callingPackage = Integer.toString(Binder.getCallingUid());
16628        }
16629        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16630    }
16631
16632    @Override
16633    public void setComponentEnabledSetting(ComponentName componentName,
16634            int newState, int flags, int userId) {
16635        if (!sUserManager.exists(userId)) return;
16636        setEnabledSetting(componentName.getPackageName(),
16637                componentName.getClassName(), newState, flags, userId, null);
16638    }
16639
16640    private void setEnabledSetting(final String packageName, String className, int newState,
16641            final int flags, int userId, String callingPackage) {
16642        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16643              || newState == COMPONENT_ENABLED_STATE_ENABLED
16644              || newState == COMPONENT_ENABLED_STATE_DISABLED
16645              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16646              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16647            throw new IllegalArgumentException("Invalid new component state: "
16648                    + newState);
16649        }
16650        PackageSetting pkgSetting;
16651        final int uid = Binder.getCallingUid();
16652        final int permission = mContext.checkCallingOrSelfPermission(
16653                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16654        enforceCrossUserPermission(uid, userId,
16655                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16656        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16657        boolean sendNow = false;
16658        boolean isApp = (className == null);
16659        String componentName = isApp ? packageName : className;
16660        int packageUid = -1;
16661        ArrayList<String> components;
16662
16663        // writer
16664        synchronized (mPackages) {
16665            pkgSetting = mSettings.mPackages.get(packageName);
16666            if (pkgSetting == null) {
16667                if (className == null) {
16668                    throw new IllegalArgumentException("Unknown package: " + packageName);
16669                }
16670                throw new IllegalArgumentException(
16671                        "Unknown component: " + packageName + "/" + className);
16672            }
16673            // Allow root and verify that userId is not being specified by a different user
16674            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16675                throw new SecurityException(
16676                        "Permission Denial: attempt to change component state from pid="
16677                        + Binder.getCallingPid()
16678                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16679            }
16680            if (className == null) {
16681                // We're dealing with an application/package level state change
16682                if (pkgSetting.getEnabled(userId) == newState) {
16683                    // Nothing to do
16684                    return;
16685                }
16686                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16687                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16688                    // Don't care about who enables an app.
16689                    callingPackage = null;
16690                }
16691                pkgSetting.setEnabled(newState, userId, callingPackage);
16692                // pkgSetting.pkg.mSetEnabled = newState;
16693            } else {
16694                // We're dealing with a component level state change
16695                // First, verify that this is a valid class name.
16696                PackageParser.Package pkg = pkgSetting.pkg;
16697                if (pkg == null || !pkg.hasComponentClassName(className)) {
16698                    if (pkg != null &&
16699                            pkg.applicationInfo.targetSdkVersion >=
16700                                    Build.VERSION_CODES.JELLY_BEAN) {
16701                        throw new IllegalArgumentException("Component class " + className
16702                                + " does not exist in " + packageName);
16703                    } else {
16704                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16705                                + className + " does not exist in " + packageName);
16706                    }
16707                }
16708                switch (newState) {
16709                case COMPONENT_ENABLED_STATE_ENABLED:
16710                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16711                        return;
16712                    }
16713                    break;
16714                case COMPONENT_ENABLED_STATE_DISABLED:
16715                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16716                        return;
16717                    }
16718                    break;
16719                case COMPONENT_ENABLED_STATE_DEFAULT:
16720                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16721                        return;
16722                    }
16723                    break;
16724                default:
16725                    Slog.e(TAG, "Invalid new component state: " + newState);
16726                    return;
16727                }
16728            }
16729            scheduleWritePackageRestrictionsLocked(userId);
16730            components = mPendingBroadcasts.get(userId, packageName);
16731            final boolean newPackage = components == null;
16732            if (newPackage) {
16733                components = new ArrayList<String>();
16734            }
16735            if (!components.contains(componentName)) {
16736                components.add(componentName);
16737            }
16738            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16739                sendNow = true;
16740                // Purge entry from pending broadcast list if another one exists already
16741                // since we are sending one right away.
16742                mPendingBroadcasts.remove(userId, packageName);
16743            } else {
16744                if (newPackage) {
16745                    mPendingBroadcasts.put(userId, packageName, components);
16746                }
16747                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16748                    // Schedule a message
16749                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16750                }
16751            }
16752        }
16753
16754        long callingId = Binder.clearCallingIdentity();
16755        try {
16756            if (sendNow) {
16757                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16758                sendPackageChangedBroadcast(packageName,
16759                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16760            }
16761        } finally {
16762            Binder.restoreCallingIdentity(callingId);
16763        }
16764    }
16765
16766    @Override
16767    public void flushPackageRestrictionsAsUser(int userId) {
16768        if (!sUserManager.exists(userId)) {
16769            return;
16770        }
16771        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
16772                false /* checkShell */, "flushPackageRestrictions");
16773        synchronized (mPackages) {
16774            mSettings.writePackageRestrictionsLPr(userId);
16775            mDirtyUsers.remove(userId);
16776            if (mDirtyUsers.isEmpty()) {
16777                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
16778            }
16779        }
16780    }
16781
16782    private void sendPackageChangedBroadcast(String packageName,
16783            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16784        if (DEBUG_INSTALL)
16785            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16786                    + componentNames);
16787        Bundle extras = new Bundle(4);
16788        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16789        String nameList[] = new String[componentNames.size()];
16790        componentNames.toArray(nameList);
16791        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16792        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16793        extras.putInt(Intent.EXTRA_UID, packageUid);
16794        // If this is not reporting a change of the overall package, then only send it
16795        // to registered receivers.  We don't want to launch a swath of apps for every
16796        // little component state change.
16797        final int flags = !componentNames.contains(packageName)
16798                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16799        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16800                new int[] {UserHandle.getUserId(packageUid)});
16801    }
16802
16803    @Override
16804    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16805        if (!sUserManager.exists(userId)) return;
16806        final int uid = Binder.getCallingUid();
16807        final int permission = mContext.checkCallingOrSelfPermission(
16808                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16809        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16810        enforceCrossUserPermission(uid, userId,
16811                true /* requireFullPermission */, true /* checkShell */, "stop package");
16812        // writer
16813        synchronized (mPackages) {
16814            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16815                    allowedByPermission, uid, userId)) {
16816                scheduleWritePackageRestrictionsLocked(userId);
16817            }
16818        }
16819    }
16820
16821    @Override
16822    public String getInstallerPackageName(String packageName) {
16823        // reader
16824        synchronized (mPackages) {
16825            return mSettings.getInstallerPackageNameLPr(packageName);
16826        }
16827    }
16828
16829    @Override
16830    public int getApplicationEnabledSetting(String packageName, int userId) {
16831        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16832        int uid = Binder.getCallingUid();
16833        enforceCrossUserPermission(uid, userId,
16834                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16835        // reader
16836        synchronized (mPackages) {
16837            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16838        }
16839    }
16840
16841    @Override
16842    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16843        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16844        int uid = Binder.getCallingUid();
16845        enforceCrossUserPermission(uid, userId,
16846                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16847        // reader
16848        synchronized (mPackages) {
16849            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16850        }
16851    }
16852
16853    @Override
16854    public void enterSafeMode() {
16855        enforceSystemOrRoot("Only the system can request entering safe mode");
16856
16857        if (!mSystemReady) {
16858            mSafeMode = true;
16859        }
16860    }
16861
16862    @Override
16863    public void systemReady() {
16864        mSystemReady = true;
16865
16866        // Read the compatibilty setting when the system is ready.
16867        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16868                mContext.getContentResolver(),
16869                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16870        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16871        if (DEBUG_SETTINGS) {
16872            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16873        }
16874
16875        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16876
16877        synchronized (mPackages) {
16878            // Verify that all of the preferred activity components actually
16879            // exist.  It is possible for applications to be updated and at
16880            // that point remove a previously declared activity component that
16881            // had been set as a preferred activity.  We try to clean this up
16882            // the next time we encounter that preferred activity, but it is
16883            // possible for the user flow to never be able to return to that
16884            // situation so here we do a sanity check to make sure we haven't
16885            // left any junk around.
16886            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16887            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16888                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16889                removed.clear();
16890                for (PreferredActivity pa : pir.filterSet()) {
16891                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16892                        removed.add(pa);
16893                    }
16894                }
16895                if (removed.size() > 0) {
16896                    for (int r=0; r<removed.size(); r++) {
16897                        PreferredActivity pa = removed.get(r);
16898                        Slog.w(TAG, "Removing dangling preferred activity: "
16899                                + pa.mPref.mComponent);
16900                        pir.removeFilter(pa);
16901                    }
16902                    mSettings.writePackageRestrictionsLPr(
16903                            mSettings.mPreferredActivities.keyAt(i));
16904                }
16905            }
16906
16907            for (int userId : UserManagerService.getInstance().getUserIds()) {
16908                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16909                    grantPermissionsUserIds = ArrayUtils.appendInt(
16910                            grantPermissionsUserIds, userId);
16911                }
16912            }
16913        }
16914        sUserManager.systemReady();
16915
16916        // If we upgraded grant all default permissions before kicking off.
16917        for (int userId : grantPermissionsUserIds) {
16918            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16919        }
16920
16921        // Kick off any messages waiting for system ready
16922        if (mPostSystemReadyMessages != null) {
16923            for (Message msg : mPostSystemReadyMessages) {
16924                msg.sendToTarget();
16925            }
16926            mPostSystemReadyMessages = null;
16927        }
16928
16929        // Watch for external volumes that come and go over time
16930        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16931        storage.registerListener(mStorageListener);
16932
16933        mInstallerService.systemReady();
16934        mPackageDexOptimizer.systemReady();
16935
16936        MountServiceInternal mountServiceInternal = LocalServices.getService(
16937                MountServiceInternal.class);
16938        mountServiceInternal.addExternalStoragePolicy(
16939                new MountServiceInternal.ExternalStorageMountPolicy() {
16940            @Override
16941            public int getMountMode(int uid, String packageName) {
16942                if (Process.isIsolated(uid)) {
16943                    return Zygote.MOUNT_EXTERNAL_NONE;
16944                }
16945                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16946                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16947                }
16948                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16949                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16950                }
16951                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16952                    return Zygote.MOUNT_EXTERNAL_READ;
16953                }
16954                return Zygote.MOUNT_EXTERNAL_WRITE;
16955            }
16956
16957            @Override
16958            public boolean hasExternalStorage(int uid, String packageName) {
16959                return true;
16960            }
16961        });
16962    }
16963
16964    @Override
16965    public boolean isSafeMode() {
16966        return mSafeMode;
16967    }
16968
16969    @Override
16970    public boolean hasSystemUidErrors() {
16971        return mHasSystemUidErrors;
16972    }
16973
16974    static String arrayToString(int[] array) {
16975        StringBuffer buf = new StringBuffer(128);
16976        buf.append('[');
16977        if (array != null) {
16978            for (int i=0; i<array.length; i++) {
16979                if (i > 0) buf.append(", ");
16980                buf.append(array[i]);
16981            }
16982        }
16983        buf.append(']');
16984        return buf.toString();
16985    }
16986
16987    static class DumpState {
16988        public static final int DUMP_LIBS = 1 << 0;
16989        public static final int DUMP_FEATURES = 1 << 1;
16990        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16991        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16992        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16993        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16994        public static final int DUMP_PERMISSIONS = 1 << 6;
16995        public static final int DUMP_PACKAGES = 1 << 7;
16996        public static final int DUMP_SHARED_USERS = 1 << 8;
16997        public static final int DUMP_MESSAGES = 1 << 9;
16998        public static final int DUMP_PROVIDERS = 1 << 10;
16999        public static final int DUMP_VERIFIERS = 1 << 11;
17000        public static final int DUMP_PREFERRED = 1 << 12;
17001        public static final int DUMP_PREFERRED_XML = 1 << 13;
17002        public static final int DUMP_KEYSETS = 1 << 14;
17003        public static final int DUMP_VERSION = 1 << 15;
17004        public static final int DUMP_INSTALLS = 1 << 16;
17005        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17006        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17007
17008        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17009
17010        private int mTypes;
17011
17012        private int mOptions;
17013
17014        private boolean mTitlePrinted;
17015
17016        private SharedUserSetting mSharedUser;
17017
17018        public boolean isDumping(int type) {
17019            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17020                return true;
17021            }
17022
17023            return (mTypes & type) != 0;
17024        }
17025
17026        public void setDump(int type) {
17027            mTypes |= type;
17028        }
17029
17030        public boolean isOptionEnabled(int option) {
17031            return (mOptions & option) != 0;
17032        }
17033
17034        public void setOptionEnabled(int option) {
17035            mOptions |= option;
17036        }
17037
17038        public boolean onTitlePrinted() {
17039            final boolean printed = mTitlePrinted;
17040            mTitlePrinted = true;
17041            return printed;
17042        }
17043
17044        public boolean getTitlePrinted() {
17045            return mTitlePrinted;
17046        }
17047
17048        public void setTitlePrinted(boolean enabled) {
17049            mTitlePrinted = enabled;
17050        }
17051
17052        public SharedUserSetting getSharedUser() {
17053            return mSharedUser;
17054        }
17055
17056        public void setSharedUser(SharedUserSetting user) {
17057            mSharedUser = user;
17058        }
17059    }
17060
17061    @Override
17062    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17063            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17064        (new PackageManagerShellCommand(this)).exec(
17065                this, in, out, err, args, resultReceiver);
17066    }
17067
17068    @Override
17069    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17070        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17071                != PackageManager.PERMISSION_GRANTED) {
17072            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17073                    + Binder.getCallingPid()
17074                    + ", uid=" + Binder.getCallingUid()
17075                    + " without permission "
17076                    + android.Manifest.permission.DUMP);
17077            return;
17078        }
17079
17080        DumpState dumpState = new DumpState();
17081        boolean fullPreferred = false;
17082        boolean checkin = false;
17083
17084        String packageName = null;
17085        ArraySet<String> permissionNames = null;
17086
17087        int opti = 0;
17088        while (opti < args.length) {
17089            String opt = args[opti];
17090            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17091                break;
17092            }
17093            opti++;
17094
17095            if ("-a".equals(opt)) {
17096                // Right now we only know how to print all.
17097            } else if ("-h".equals(opt)) {
17098                pw.println("Package manager dump options:");
17099                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17100                pw.println("    --checkin: dump for a checkin");
17101                pw.println("    -f: print details of intent filters");
17102                pw.println("    -h: print this help");
17103                pw.println("  cmd may be one of:");
17104                pw.println("    l[ibraries]: list known shared libraries");
17105                pw.println("    f[eatures]: list device features");
17106                pw.println("    k[eysets]: print known keysets");
17107                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17108                pw.println("    perm[issions]: dump permissions");
17109                pw.println("    permission [name ...]: dump declaration and use of given permission");
17110                pw.println("    pref[erred]: print preferred package settings");
17111                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17112                pw.println("    prov[iders]: dump content providers");
17113                pw.println("    p[ackages]: dump installed packages");
17114                pw.println("    s[hared-users]: dump shared user IDs");
17115                pw.println("    m[essages]: print collected runtime messages");
17116                pw.println("    v[erifiers]: print package verifier info");
17117                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17118                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17119                pw.println("    version: print database version info");
17120                pw.println("    write: write current settings now");
17121                pw.println("    installs: details about install sessions");
17122                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17123                pw.println("    <package.name>: info about given package");
17124                return;
17125            } else if ("--checkin".equals(opt)) {
17126                checkin = true;
17127            } else if ("-f".equals(opt)) {
17128                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17129            } else {
17130                pw.println("Unknown argument: " + opt + "; use -h for help");
17131            }
17132        }
17133
17134        // Is the caller requesting to dump a particular piece of data?
17135        if (opti < args.length) {
17136            String cmd = args[opti];
17137            opti++;
17138            // Is this a package name?
17139            if ("android".equals(cmd) || cmd.contains(".")) {
17140                packageName = cmd;
17141                // When dumping a single package, we always dump all of its
17142                // filter information since the amount of data will be reasonable.
17143                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17144            } else if ("check-permission".equals(cmd)) {
17145                if (opti >= args.length) {
17146                    pw.println("Error: check-permission missing permission argument");
17147                    return;
17148                }
17149                String perm = args[opti];
17150                opti++;
17151                if (opti >= args.length) {
17152                    pw.println("Error: check-permission missing package argument");
17153                    return;
17154                }
17155                String pkg = args[opti];
17156                opti++;
17157                int user = UserHandle.getUserId(Binder.getCallingUid());
17158                if (opti < args.length) {
17159                    try {
17160                        user = Integer.parseInt(args[opti]);
17161                    } catch (NumberFormatException e) {
17162                        pw.println("Error: check-permission user argument is not a number: "
17163                                + args[opti]);
17164                        return;
17165                    }
17166                }
17167                pw.println(checkPermission(perm, pkg, user));
17168                return;
17169            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17170                dumpState.setDump(DumpState.DUMP_LIBS);
17171            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17172                dumpState.setDump(DumpState.DUMP_FEATURES);
17173            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17174                if (opti >= args.length) {
17175                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17176                            | DumpState.DUMP_SERVICE_RESOLVERS
17177                            | DumpState.DUMP_RECEIVER_RESOLVERS
17178                            | DumpState.DUMP_CONTENT_RESOLVERS);
17179                } else {
17180                    while (opti < args.length) {
17181                        String name = args[opti];
17182                        if ("a".equals(name) || "activity".equals(name)) {
17183                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17184                        } else if ("s".equals(name) || "service".equals(name)) {
17185                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17186                        } else if ("r".equals(name) || "receiver".equals(name)) {
17187                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17188                        } else if ("c".equals(name) || "content".equals(name)) {
17189                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17190                        } else {
17191                            pw.println("Error: unknown resolver table type: " + name);
17192                            return;
17193                        }
17194                        opti++;
17195                    }
17196                }
17197            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17198                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17199            } else if ("permission".equals(cmd)) {
17200                if (opti >= args.length) {
17201                    pw.println("Error: permission requires permission name");
17202                    return;
17203                }
17204                permissionNames = new ArraySet<>();
17205                while (opti < args.length) {
17206                    permissionNames.add(args[opti]);
17207                    opti++;
17208                }
17209                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17210                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17211            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17212                dumpState.setDump(DumpState.DUMP_PREFERRED);
17213            } else if ("preferred-xml".equals(cmd)) {
17214                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17215                if (opti < args.length && "--full".equals(args[opti])) {
17216                    fullPreferred = true;
17217                    opti++;
17218                }
17219            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17220                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17221            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17222                dumpState.setDump(DumpState.DUMP_PACKAGES);
17223            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17224                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17225            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17226                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17227            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17228                dumpState.setDump(DumpState.DUMP_MESSAGES);
17229            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17230                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17231            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17232                    || "intent-filter-verifiers".equals(cmd)) {
17233                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17234            } else if ("version".equals(cmd)) {
17235                dumpState.setDump(DumpState.DUMP_VERSION);
17236            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17237                dumpState.setDump(DumpState.DUMP_KEYSETS);
17238            } else if ("installs".equals(cmd)) {
17239                dumpState.setDump(DumpState.DUMP_INSTALLS);
17240            } else if ("write".equals(cmd)) {
17241                synchronized (mPackages) {
17242                    mSettings.writeLPr();
17243                    pw.println("Settings written.");
17244                    return;
17245                }
17246            }
17247        }
17248
17249        if (checkin) {
17250            pw.println("vers,1");
17251        }
17252
17253        // reader
17254        synchronized (mPackages) {
17255            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17256                if (!checkin) {
17257                    if (dumpState.onTitlePrinted())
17258                        pw.println();
17259                    pw.println("Database versions:");
17260                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17261                }
17262            }
17263
17264            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17265                if (!checkin) {
17266                    if (dumpState.onTitlePrinted())
17267                        pw.println();
17268                    pw.println("Verifiers:");
17269                    pw.print("  Required: ");
17270                    pw.print(mRequiredVerifierPackage);
17271                    pw.print(" (uid=");
17272                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17273                            UserHandle.USER_SYSTEM));
17274                    pw.println(")");
17275                } else if (mRequiredVerifierPackage != null) {
17276                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17277                    pw.print(",");
17278                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17279                            UserHandle.USER_SYSTEM));
17280                }
17281            }
17282
17283            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17284                    packageName == null) {
17285                if (mIntentFilterVerifierComponent != null) {
17286                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17287                    if (!checkin) {
17288                        if (dumpState.onTitlePrinted())
17289                            pw.println();
17290                        pw.println("Intent Filter Verifier:");
17291                        pw.print("  Using: ");
17292                        pw.print(verifierPackageName);
17293                        pw.print(" (uid=");
17294                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17295                                UserHandle.USER_SYSTEM));
17296                        pw.println(")");
17297                    } else if (verifierPackageName != null) {
17298                        pw.print("ifv,"); pw.print(verifierPackageName);
17299                        pw.print(",");
17300                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17301                                UserHandle.USER_SYSTEM));
17302                    }
17303                } else {
17304                    pw.println();
17305                    pw.println("No Intent Filter Verifier available!");
17306                }
17307            }
17308
17309            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17310                boolean printedHeader = false;
17311                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17312                while (it.hasNext()) {
17313                    String name = it.next();
17314                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17315                    if (!checkin) {
17316                        if (!printedHeader) {
17317                            if (dumpState.onTitlePrinted())
17318                                pw.println();
17319                            pw.println("Libraries:");
17320                            printedHeader = true;
17321                        }
17322                        pw.print("  ");
17323                    } else {
17324                        pw.print("lib,");
17325                    }
17326                    pw.print(name);
17327                    if (!checkin) {
17328                        pw.print(" -> ");
17329                    }
17330                    if (ent.path != null) {
17331                        if (!checkin) {
17332                            pw.print("(jar) ");
17333                            pw.print(ent.path);
17334                        } else {
17335                            pw.print(",jar,");
17336                            pw.print(ent.path);
17337                        }
17338                    } else {
17339                        if (!checkin) {
17340                            pw.print("(apk) ");
17341                            pw.print(ent.apk);
17342                        } else {
17343                            pw.print(",apk,");
17344                            pw.print(ent.apk);
17345                        }
17346                    }
17347                    pw.println();
17348                }
17349            }
17350
17351            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17352                if (dumpState.onTitlePrinted())
17353                    pw.println();
17354                if (!checkin) {
17355                    pw.println("Features:");
17356                }
17357
17358                for (FeatureInfo feat : mAvailableFeatures.values()) {
17359                    if (checkin) {
17360                        pw.print("feat,");
17361                        pw.print(feat.name);
17362                        pw.print(",");
17363                        pw.println(feat.version);
17364                    } else {
17365                        pw.print("  ");
17366                        pw.print(feat.name);
17367                        if (feat.version > 0) {
17368                            pw.print(" version=");
17369                            pw.print(feat.version);
17370                        }
17371                        pw.println();
17372                    }
17373                }
17374            }
17375
17376            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17377                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17378                        : "Activity Resolver Table:", "  ", packageName,
17379                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17380                    dumpState.setTitlePrinted(true);
17381                }
17382            }
17383            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17384                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17385                        : "Receiver Resolver Table:", "  ", packageName,
17386                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17387                    dumpState.setTitlePrinted(true);
17388                }
17389            }
17390            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17391                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17392                        : "Service Resolver Table:", "  ", packageName,
17393                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17394                    dumpState.setTitlePrinted(true);
17395                }
17396            }
17397            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17398                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17399                        : "Provider Resolver Table:", "  ", packageName,
17400                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17401                    dumpState.setTitlePrinted(true);
17402                }
17403            }
17404
17405            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17406                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17407                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17408                    int user = mSettings.mPreferredActivities.keyAt(i);
17409                    if (pir.dump(pw,
17410                            dumpState.getTitlePrinted()
17411                                ? "\nPreferred Activities User " + user + ":"
17412                                : "Preferred Activities User " + user + ":", "  ",
17413                            packageName, true, false)) {
17414                        dumpState.setTitlePrinted(true);
17415                    }
17416                }
17417            }
17418
17419            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17420                pw.flush();
17421                FileOutputStream fout = new FileOutputStream(fd);
17422                BufferedOutputStream str = new BufferedOutputStream(fout);
17423                XmlSerializer serializer = new FastXmlSerializer();
17424                try {
17425                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17426                    serializer.startDocument(null, true);
17427                    serializer.setFeature(
17428                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17429                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17430                    serializer.endDocument();
17431                    serializer.flush();
17432                } catch (IllegalArgumentException e) {
17433                    pw.println("Failed writing: " + e);
17434                } catch (IllegalStateException e) {
17435                    pw.println("Failed writing: " + e);
17436                } catch (IOException e) {
17437                    pw.println("Failed writing: " + e);
17438                }
17439            }
17440
17441            if (!checkin
17442                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17443                    && packageName == null) {
17444                pw.println();
17445                int count = mSettings.mPackages.size();
17446                if (count == 0) {
17447                    pw.println("No applications!");
17448                    pw.println();
17449                } else {
17450                    final String prefix = "  ";
17451                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17452                    if (allPackageSettings.size() == 0) {
17453                        pw.println("No domain preferred apps!");
17454                        pw.println();
17455                    } else {
17456                        pw.println("App verification status:");
17457                        pw.println();
17458                        count = 0;
17459                        for (PackageSetting ps : allPackageSettings) {
17460                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17461                            if (ivi == null || ivi.getPackageName() == null) continue;
17462                            pw.println(prefix + "Package: " + ivi.getPackageName());
17463                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17464                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17465                            pw.println();
17466                            count++;
17467                        }
17468                        if (count == 0) {
17469                            pw.println(prefix + "No app verification established.");
17470                            pw.println();
17471                        }
17472                        for (int userId : sUserManager.getUserIds()) {
17473                            pw.println("App linkages for user " + userId + ":");
17474                            pw.println();
17475                            count = 0;
17476                            for (PackageSetting ps : allPackageSettings) {
17477                                final long status = ps.getDomainVerificationStatusForUser(userId);
17478                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17479                                    continue;
17480                                }
17481                                pw.println(prefix + "Package: " + ps.name);
17482                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17483                                String statusStr = IntentFilterVerificationInfo.
17484                                        getStatusStringFromValue(status);
17485                                pw.println(prefix + "Status:  " + statusStr);
17486                                pw.println();
17487                                count++;
17488                            }
17489                            if (count == 0) {
17490                                pw.println(prefix + "No configured app linkages.");
17491                                pw.println();
17492                            }
17493                        }
17494                    }
17495                }
17496            }
17497
17498            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17499                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17500                if (packageName == null && permissionNames == null) {
17501                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17502                        if (iperm == 0) {
17503                            if (dumpState.onTitlePrinted())
17504                                pw.println();
17505                            pw.println("AppOp Permissions:");
17506                        }
17507                        pw.print("  AppOp Permission ");
17508                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17509                        pw.println(":");
17510                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17511                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17512                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17513                        }
17514                    }
17515                }
17516            }
17517
17518            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17519                boolean printedSomething = false;
17520                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17521                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17522                        continue;
17523                    }
17524                    if (!printedSomething) {
17525                        if (dumpState.onTitlePrinted())
17526                            pw.println();
17527                        pw.println("Registered ContentProviders:");
17528                        printedSomething = true;
17529                    }
17530                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17531                    pw.print("    "); pw.println(p.toString());
17532                }
17533                printedSomething = false;
17534                for (Map.Entry<String, PackageParser.Provider> entry :
17535                        mProvidersByAuthority.entrySet()) {
17536                    PackageParser.Provider p = entry.getValue();
17537                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17538                        continue;
17539                    }
17540                    if (!printedSomething) {
17541                        if (dumpState.onTitlePrinted())
17542                            pw.println();
17543                        pw.println("ContentProvider Authorities:");
17544                        printedSomething = true;
17545                    }
17546                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17547                    pw.print("    "); pw.println(p.toString());
17548                    if (p.info != null && p.info.applicationInfo != null) {
17549                        final String appInfo = p.info.applicationInfo.toString();
17550                        pw.print("      applicationInfo="); pw.println(appInfo);
17551                    }
17552                }
17553            }
17554
17555            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17556                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17557            }
17558
17559            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17560                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17561            }
17562
17563            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17564                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17565            }
17566
17567            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17568                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17569            }
17570
17571            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17572                // XXX should handle packageName != null by dumping only install data that
17573                // the given package is involved with.
17574                if (dumpState.onTitlePrinted()) pw.println();
17575                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17576            }
17577
17578            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17579                if (dumpState.onTitlePrinted()) pw.println();
17580                mSettings.dumpReadMessagesLPr(pw, dumpState);
17581
17582                pw.println();
17583                pw.println("Package warning messages:");
17584                BufferedReader in = null;
17585                String line = null;
17586                try {
17587                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17588                    while ((line = in.readLine()) != null) {
17589                        if (line.contains("ignored: updated version")) continue;
17590                        pw.println(line);
17591                    }
17592                } catch (IOException ignored) {
17593                } finally {
17594                    IoUtils.closeQuietly(in);
17595                }
17596            }
17597
17598            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17599                BufferedReader in = null;
17600                String line = null;
17601                try {
17602                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17603                    while ((line = in.readLine()) != null) {
17604                        if (line.contains("ignored: updated version")) continue;
17605                        pw.print("msg,");
17606                        pw.println(line);
17607                    }
17608                } catch (IOException ignored) {
17609                } finally {
17610                    IoUtils.closeQuietly(in);
17611                }
17612            }
17613        }
17614    }
17615
17616    private String dumpDomainString(String packageName) {
17617        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
17618                .getList();
17619        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
17620
17621        ArraySet<String> result = new ArraySet<>();
17622        if (iviList.size() > 0) {
17623            for (IntentFilterVerificationInfo ivi : iviList) {
17624                for (String host : ivi.getDomains()) {
17625                    result.add(host);
17626                }
17627            }
17628        }
17629        if (filters != null && filters.size() > 0) {
17630            for (IntentFilter filter : filters) {
17631                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17632                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17633                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17634                    result.addAll(filter.getHostsList());
17635                }
17636            }
17637        }
17638
17639        StringBuilder sb = new StringBuilder(result.size() * 16);
17640        for (String domain : result) {
17641            if (sb.length() > 0) sb.append(" ");
17642            sb.append(domain);
17643        }
17644        return sb.toString();
17645    }
17646
17647    // ------- apps on sdcard specific code -------
17648    static final boolean DEBUG_SD_INSTALL = false;
17649
17650    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17651
17652    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17653
17654    private boolean mMediaMounted = false;
17655
17656    static String getEncryptKey() {
17657        try {
17658            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17659                    SD_ENCRYPTION_KEYSTORE_NAME);
17660            if (sdEncKey == null) {
17661                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17662                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17663                if (sdEncKey == null) {
17664                    Slog.e(TAG, "Failed to create encryption keys");
17665                    return null;
17666                }
17667            }
17668            return sdEncKey;
17669        } catch (NoSuchAlgorithmException nsae) {
17670            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17671            return null;
17672        } catch (IOException ioe) {
17673            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17674            return null;
17675        }
17676    }
17677
17678    /*
17679     * Update media status on PackageManager.
17680     */
17681    @Override
17682    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17683        int callingUid = Binder.getCallingUid();
17684        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17685            throw new SecurityException("Media status can only be updated by the system");
17686        }
17687        // reader; this apparently protects mMediaMounted, but should probably
17688        // be a different lock in that case.
17689        synchronized (mPackages) {
17690            Log.i(TAG, "Updating external media status from "
17691                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17692                    + (mediaStatus ? "mounted" : "unmounted"));
17693            if (DEBUG_SD_INSTALL)
17694                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17695                        + ", mMediaMounted=" + mMediaMounted);
17696            if (mediaStatus == mMediaMounted) {
17697                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17698                        : 0, -1);
17699                mHandler.sendMessage(msg);
17700                return;
17701            }
17702            mMediaMounted = mediaStatus;
17703        }
17704        // Queue up an async operation since the package installation may take a
17705        // little while.
17706        mHandler.post(new Runnable() {
17707            public void run() {
17708                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17709            }
17710        });
17711    }
17712
17713    /**
17714     * Called by MountService when the initial ASECs to scan are available.
17715     * Should block until all the ASEC containers are finished being scanned.
17716     */
17717    public void scanAvailableAsecs() {
17718        updateExternalMediaStatusInner(true, false, false);
17719    }
17720
17721    /*
17722     * Collect information of applications on external media, map them against
17723     * existing containers and update information based on current mount status.
17724     * Please note that we always have to report status if reportStatus has been
17725     * set to true especially when unloading packages.
17726     */
17727    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17728            boolean externalStorage) {
17729        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17730        int[] uidArr = EmptyArray.INT;
17731
17732        final String[] list = PackageHelper.getSecureContainerList();
17733        if (ArrayUtils.isEmpty(list)) {
17734            Log.i(TAG, "No secure containers found");
17735        } else {
17736            // Process list of secure containers and categorize them
17737            // as active or stale based on their package internal state.
17738
17739            // reader
17740            synchronized (mPackages) {
17741                for (String cid : list) {
17742                    // Leave stages untouched for now; installer service owns them
17743                    if (PackageInstallerService.isStageName(cid)) continue;
17744
17745                    if (DEBUG_SD_INSTALL)
17746                        Log.i(TAG, "Processing container " + cid);
17747                    String pkgName = getAsecPackageName(cid);
17748                    if (pkgName == null) {
17749                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17750                        continue;
17751                    }
17752                    if (DEBUG_SD_INSTALL)
17753                        Log.i(TAG, "Looking for pkg : " + pkgName);
17754
17755                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17756                    if (ps == null) {
17757                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17758                        continue;
17759                    }
17760
17761                    /*
17762                     * Skip packages that are not external if we're unmounting
17763                     * external storage.
17764                     */
17765                    if (externalStorage && !isMounted && !isExternal(ps)) {
17766                        continue;
17767                    }
17768
17769                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17770                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17771                    // The package status is changed only if the code path
17772                    // matches between settings and the container id.
17773                    if (ps.codePathString != null
17774                            && ps.codePathString.startsWith(args.getCodePath())) {
17775                        if (DEBUG_SD_INSTALL) {
17776                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17777                                    + " at code path: " + ps.codePathString);
17778                        }
17779
17780                        // We do have a valid package installed on sdcard
17781                        processCids.put(args, ps.codePathString);
17782                        final int uid = ps.appId;
17783                        if (uid != -1) {
17784                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17785                        }
17786                    } else {
17787                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17788                                + ps.codePathString);
17789                    }
17790                }
17791            }
17792
17793            Arrays.sort(uidArr);
17794        }
17795
17796        // Process packages with valid entries.
17797        if (isMounted) {
17798            if (DEBUG_SD_INSTALL)
17799                Log.i(TAG, "Loading packages");
17800            loadMediaPackages(processCids, uidArr, externalStorage);
17801            startCleaningPackages();
17802            mInstallerService.onSecureContainersAvailable();
17803        } else {
17804            if (DEBUG_SD_INSTALL)
17805                Log.i(TAG, "Unloading packages");
17806            unloadMediaPackages(processCids, uidArr, reportStatus);
17807        }
17808    }
17809
17810    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17811            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17812        final int size = infos.size();
17813        final String[] packageNames = new String[size];
17814        final int[] packageUids = new int[size];
17815        for (int i = 0; i < size; i++) {
17816            final ApplicationInfo info = infos.get(i);
17817            packageNames[i] = info.packageName;
17818            packageUids[i] = info.uid;
17819        }
17820        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17821                finishedReceiver);
17822    }
17823
17824    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17825            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17826        sendResourcesChangedBroadcast(mediaStatus, replacing,
17827                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17828    }
17829
17830    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17831            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17832        int size = pkgList.length;
17833        if (size > 0) {
17834            // Send broadcasts here
17835            Bundle extras = new Bundle();
17836            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17837            if (uidArr != null) {
17838                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17839            }
17840            if (replacing) {
17841                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17842            }
17843            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17844                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17845            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17846        }
17847    }
17848
17849   /*
17850     * Look at potentially valid container ids from processCids If package
17851     * information doesn't match the one on record or package scanning fails,
17852     * the cid is added to list of removeCids. We currently don't delete stale
17853     * containers.
17854     */
17855    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17856            boolean externalStorage) {
17857        ArrayList<String> pkgList = new ArrayList<String>();
17858        Set<AsecInstallArgs> keys = processCids.keySet();
17859
17860        for (AsecInstallArgs args : keys) {
17861            String codePath = processCids.get(args);
17862            if (DEBUG_SD_INSTALL)
17863                Log.i(TAG, "Loading container : " + args.cid);
17864            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17865            try {
17866                // Make sure there are no container errors first.
17867                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17868                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17869                            + " when installing from sdcard");
17870                    continue;
17871                }
17872                // Check code path here.
17873                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17874                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17875                            + " does not match one in settings " + codePath);
17876                    continue;
17877                }
17878                // Parse package
17879                int parseFlags = mDefParseFlags;
17880                if (args.isExternalAsec()) {
17881                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17882                }
17883                if (args.isFwdLocked()) {
17884                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17885                }
17886
17887                synchronized (mInstallLock) {
17888                    PackageParser.Package pkg = null;
17889                    try {
17890                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17891                    } catch (PackageManagerException e) {
17892                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17893                    }
17894                    // Scan the package
17895                    if (pkg != null) {
17896                        /*
17897                         * TODO why is the lock being held? doPostInstall is
17898                         * called in other places without the lock. This needs
17899                         * to be straightened out.
17900                         */
17901                        // writer
17902                        synchronized (mPackages) {
17903                            retCode = PackageManager.INSTALL_SUCCEEDED;
17904                            pkgList.add(pkg.packageName);
17905                            // Post process args
17906                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17907                                    pkg.applicationInfo.uid);
17908                        }
17909                    } else {
17910                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17911                    }
17912                }
17913
17914            } finally {
17915                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17916                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17917                }
17918            }
17919        }
17920        // writer
17921        synchronized (mPackages) {
17922            // If the platform SDK has changed since the last time we booted,
17923            // we need to re-grant app permission to catch any new ones that
17924            // appear. This is really a hack, and means that apps can in some
17925            // cases get permissions that the user didn't initially explicitly
17926            // allow... it would be nice to have some better way to handle
17927            // this situation.
17928            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17929                    : mSettings.getInternalVersion();
17930            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17931                    : StorageManager.UUID_PRIVATE_INTERNAL;
17932
17933            int updateFlags = UPDATE_PERMISSIONS_ALL;
17934            if (ver.sdkVersion != mSdkVersion) {
17935                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17936                        + mSdkVersion + "; regranting permissions for external");
17937                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17938            }
17939            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17940
17941            // Yay, everything is now upgraded
17942            ver.forceCurrent();
17943
17944            // can downgrade to reader
17945            // Persist settings
17946            mSettings.writeLPr();
17947        }
17948        // Send a broadcast to let everyone know we are done processing
17949        if (pkgList.size() > 0) {
17950            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17951        }
17952    }
17953
17954   /*
17955     * Utility method to unload a list of specified containers
17956     */
17957    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17958        // Just unmount all valid containers.
17959        for (AsecInstallArgs arg : cidArgs) {
17960            synchronized (mInstallLock) {
17961                arg.doPostDeleteLI(false);
17962           }
17963       }
17964   }
17965
17966    /*
17967     * Unload packages mounted on external media. This involves deleting package
17968     * data from internal structures, sending broadcasts about disabled packages,
17969     * gc'ing to free up references, unmounting all secure containers
17970     * corresponding to packages on external media, and posting a
17971     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17972     * that we always have to post this message if status has been requested no
17973     * matter what.
17974     */
17975    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17976            final boolean reportStatus) {
17977        if (DEBUG_SD_INSTALL)
17978            Log.i(TAG, "unloading media packages");
17979        ArrayList<String> pkgList = new ArrayList<String>();
17980        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17981        final Set<AsecInstallArgs> keys = processCids.keySet();
17982        for (AsecInstallArgs args : keys) {
17983            String pkgName = args.getPackageName();
17984            if (DEBUG_SD_INSTALL)
17985                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17986            // Delete package internally
17987            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17988            synchronized (mInstallLock) {
17989                boolean res = deletePackageLI(pkgName, null, false, null,
17990                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17991                if (res) {
17992                    pkgList.add(pkgName);
17993                } else {
17994                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17995                    failedList.add(args);
17996                }
17997            }
17998        }
17999
18000        // reader
18001        synchronized (mPackages) {
18002            // We didn't update the settings after removing each package;
18003            // write them now for all packages.
18004            mSettings.writeLPr();
18005        }
18006
18007        // We have to absolutely send UPDATED_MEDIA_STATUS only
18008        // after confirming that all the receivers processed the ordered
18009        // broadcast when packages get disabled, force a gc to clean things up.
18010        // and unload all the containers.
18011        if (pkgList.size() > 0) {
18012            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18013                    new IIntentReceiver.Stub() {
18014                public void performReceive(Intent intent, int resultCode, String data,
18015                        Bundle extras, boolean ordered, boolean sticky,
18016                        int sendingUser) throws RemoteException {
18017                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18018                            reportStatus ? 1 : 0, 1, keys);
18019                    mHandler.sendMessage(msg);
18020                }
18021            });
18022        } else {
18023            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18024                    keys);
18025            mHandler.sendMessage(msg);
18026        }
18027    }
18028
18029    private void loadPrivatePackages(final VolumeInfo vol) {
18030        mHandler.post(new Runnable() {
18031            @Override
18032            public void run() {
18033                loadPrivatePackagesInner(vol);
18034            }
18035        });
18036    }
18037
18038    private void loadPrivatePackagesInner(VolumeInfo vol) {
18039        final String volumeUuid = vol.fsUuid;
18040        if (TextUtils.isEmpty(volumeUuid)) {
18041            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18042            return;
18043        }
18044
18045        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18046        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18047
18048        final VersionInfo ver;
18049        final List<PackageSetting> packages;
18050        synchronized (mPackages) {
18051            ver = mSettings.findOrCreateVersion(volumeUuid);
18052            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18053        }
18054
18055        // TODO: introduce a new concept similar to "frozen" to prevent these
18056        // apps from being launched until after data has been fully reconciled
18057        for (PackageSetting ps : packages) {
18058            synchronized (mInstallLock) {
18059                final PackageParser.Package pkg;
18060                try {
18061                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18062                    loaded.add(pkg.applicationInfo);
18063
18064                } catch (PackageManagerException e) {
18065                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18066                }
18067
18068                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18069                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18070                }
18071            }
18072        }
18073
18074        // Reconcile app data for all started/unlocked users
18075        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18076        final UserManager um = mContext.getSystemService(UserManager.class);
18077        for (UserInfo user : um.getUsers()) {
18078            final int flags;
18079            if (um.isUserUnlocked(user.id)) {
18080                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18081            } else if (um.isUserRunning(user.id)) {
18082                flags = StorageManager.FLAG_STORAGE_DE;
18083            } else {
18084                continue;
18085            }
18086
18087            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18088            reconcileAppsData(volumeUuid, user.id, flags);
18089        }
18090
18091        synchronized (mPackages) {
18092            int updateFlags = UPDATE_PERMISSIONS_ALL;
18093            if (ver.sdkVersion != mSdkVersion) {
18094                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18095                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18096                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18097            }
18098            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18099
18100            // Yay, everything is now upgraded
18101            ver.forceCurrent();
18102
18103            mSettings.writeLPr();
18104        }
18105
18106        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18107        sendResourcesChangedBroadcast(true, false, loaded, null);
18108    }
18109
18110    private void unloadPrivatePackages(final VolumeInfo vol) {
18111        mHandler.post(new Runnable() {
18112            @Override
18113            public void run() {
18114                unloadPrivatePackagesInner(vol);
18115            }
18116        });
18117    }
18118
18119    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18120        final String volumeUuid = vol.fsUuid;
18121        if (TextUtils.isEmpty(volumeUuid)) {
18122            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18123            return;
18124        }
18125
18126        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18127        synchronized (mInstallLock) {
18128        synchronized (mPackages) {
18129            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18130            for (PackageSetting ps : packages) {
18131                if (ps.pkg == null) continue;
18132
18133                final ApplicationInfo info = ps.pkg.applicationInfo;
18134                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18135                if (deletePackageLI(ps.name, null, false, null,
18136                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18137                    unloaded.add(info);
18138                } else {
18139                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18140                }
18141            }
18142
18143            mSettings.writeLPr();
18144        }
18145        }
18146
18147        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18148        sendResourcesChangedBroadcast(false, false, unloaded, null);
18149    }
18150
18151    /**
18152     * Examine all users present on given mounted volume, and destroy data
18153     * belonging to users that are no longer valid, or whose user ID has been
18154     * recycled.
18155     */
18156    private void reconcileUsers(String volumeUuid) {
18157        // TODO: also reconcile DE directories
18158        final File[] files = FileUtils
18159                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18160        for (File file : files) {
18161            if (!file.isDirectory()) continue;
18162
18163            final int userId;
18164            final UserInfo info;
18165            try {
18166                userId = Integer.parseInt(file.getName());
18167                info = sUserManager.getUserInfo(userId);
18168            } catch (NumberFormatException e) {
18169                Slog.w(TAG, "Invalid user directory " + file);
18170                continue;
18171            }
18172
18173            boolean destroyUser = false;
18174            if (info == null) {
18175                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18176                        + " because no matching user was found");
18177                destroyUser = true;
18178            } else {
18179                try {
18180                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18181                } catch (IOException e) {
18182                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18183                            + " because we failed to enforce serial number: " + e);
18184                    destroyUser = true;
18185                }
18186            }
18187
18188            if (destroyUser) {
18189                synchronized (mInstallLock) {
18190                    try {
18191                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18192                    } catch (InstallerException e) {
18193                        Slog.w(TAG, "Failed to clean up user dirs", e);
18194                    }
18195                }
18196            }
18197        }
18198    }
18199
18200    private void assertPackageKnown(String volumeUuid, String packageName)
18201            throws PackageManagerException {
18202        synchronized (mPackages) {
18203            final PackageSetting ps = mSettings.mPackages.get(packageName);
18204            if (ps == null) {
18205                throw new PackageManagerException("Package " + packageName + " is unknown");
18206            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18207                throw new PackageManagerException(
18208                        "Package " + packageName + " found on unknown volume " + volumeUuid
18209                                + "; expected volume " + ps.volumeUuid);
18210            }
18211        }
18212    }
18213
18214    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18215            throws PackageManagerException {
18216        synchronized (mPackages) {
18217            final PackageSetting ps = mSettings.mPackages.get(packageName);
18218            if (ps == null) {
18219                throw new PackageManagerException("Package " + packageName + " is unknown");
18220            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18221                throw new PackageManagerException(
18222                        "Package " + packageName + " found on unknown volume " + volumeUuid
18223                                + "; expected volume " + ps.volumeUuid);
18224            } else if (!ps.getInstalled(userId)) {
18225                throw new PackageManagerException(
18226                        "Package " + packageName + " not installed for user " + userId);
18227            }
18228        }
18229    }
18230
18231    /**
18232     * Examine all apps present on given mounted volume, and destroy apps that
18233     * aren't expected, either due to uninstallation or reinstallation on
18234     * another volume.
18235     */
18236    private void reconcileApps(String volumeUuid) {
18237        final File[] files = FileUtils
18238                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18239        for (File file : files) {
18240            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18241                    && !PackageInstallerService.isStageName(file.getName());
18242            if (!isPackage) {
18243                // Ignore entries which are not packages
18244                continue;
18245            }
18246
18247            try {
18248                final PackageLite pkg = PackageParser.parsePackageLite(file,
18249                        PackageParser.PARSE_MUST_BE_APK);
18250                assertPackageKnown(volumeUuid, pkg.packageName);
18251
18252            } catch (PackageParserException | PackageManagerException e) {
18253                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18254                synchronized (mInstallLock) {
18255                    removeCodePathLI(file);
18256                }
18257            }
18258        }
18259    }
18260
18261    /**
18262     * Reconcile all app data for the given user.
18263     * <p>
18264     * Verifies that directories exist and that ownership and labeling is
18265     * correct for all installed apps on all mounted volumes.
18266     */
18267    void reconcileAppsData(int userId, int flags) {
18268        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18269        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18270            final String volumeUuid = vol.getFsUuid();
18271            reconcileAppsData(volumeUuid, userId, flags);
18272        }
18273    }
18274
18275    /**
18276     * Reconcile all app data on given mounted volume.
18277     * <p>
18278     * Destroys app data that isn't expected, either due to uninstallation or
18279     * reinstallation on another volume.
18280     * <p>
18281     * Verifies that directories exist and that ownership and labeling is
18282     * correct for all installed apps.
18283     */
18284    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18285        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18286                + Integer.toHexString(flags));
18287
18288        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18289        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18290
18291        boolean restoreconNeeded = false;
18292
18293        // First look for stale data that doesn't belong, and check if things
18294        // have changed since we did our last restorecon
18295        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18296            if (!isUserKeyUnlocked(userId)) {
18297                throw new RuntimeException(
18298                        "Yikes, someone asked us to reconcile CE storage while " + userId
18299                                + " was still locked; this would have caused massive data loss!");
18300            }
18301
18302            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18303
18304            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18305            for (File file : files) {
18306                final String packageName = file.getName();
18307                try {
18308                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18309                } catch (PackageManagerException e) {
18310                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18311                    synchronized (mInstallLock) {
18312                        destroyAppDataLI(volumeUuid, packageName, userId,
18313                                StorageManager.FLAG_STORAGE_CE);
18314                    }
18315                }
18316            }
18317        }
18318        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18319            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18320
18321            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18322            for (File file : files) {
18323                final String packageName = file.getName();
18324                try {
18325                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18326                } catch (PackageManagerException e) {
18327                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18328                    synchronized (mInstallLock) {
18329                        destroyAppDataLI(volumeUuid, packageName, userId,
18330                                StorageManager.FLAG_STORAGE_DE);
18331                    }
18332                }
18333            }
18334        }
18335
18336        // Ensure that data directories are ready to roll for all packages
18337        // installed for this volume and user
18338        final List<PackageSetting> packages;
18339        synchronized (mPackages) {
18340            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18341        }
18342        int preparedCount = 0;
18343        for (PackageSetting ps : packages) {
18344            final String packageName = ps.name;
18345            if (ps.pkg == null) {
18346                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18347                // TODO: might be due to legacy ASEC apps; we should circle back
18348                // and reconcile again once they're scanned
18349                continue;
18350            }
18351
18352            if (ps.getInstalled(userId)) {
18353                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18354
18355                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18356                    // We may have just shuffled around app data directories, so
18357                    // prepare them one more time
18358                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18359                }
18360
18361                preparedCount++;
18362            }
18363        }
18364
18365        if (restoreconNeeded) {
18366            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18367                SELinuxMMAC.setRestoreconDone(ceDir);
18368            }
18369            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18370                SELinuxMMAC.setRestoreconDone(deDir);
18371            }
18372        }
18373
18374        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18375                + " packages; restoreconNeeded was " + restoreconNeeded);
18376    }
18377
18378    /**
18379     * Prepare app data for the given app just after it was installed or
18380     * upgraded. This method carefully only touches users that it's installed
18381     * for, and it forces a restorecon to handle any seinfo changes.
18382     * <p>
18383     * Verifies that directories exist and that ownership and labeling is
18384     * correct for all installed apps. If there is an ownership mismatch, it
18385     * will try recovering system apps by wiping data; third-party app data is
18386     * left intact.
18387     * <p>
18388     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18389     */
18390    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18391        prepareAppDataAfterInstallInternal(pkg);
18392        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18393        for (int i = 0; i < childCount; i++) {
18394            PackageParser.Package childPackage = pkg.childPackages.get(i);
18395            prepareAppDataAfterInstallInternal(childPackage);
18396        }
18397    }
18398
18399    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18400        final PackageSetting ps;
18401        synchronized (mPackages) {
18402            ps = mSettings.mPackages.get(pkg.packageName);
18403            mSettings.writeKernelMappingLPr(ps);
18404        }
18405
18406        final UserManager um = mContext.getSystemService(UserManager.class);
18407        for (UserInfo user : um.getUsers()) {
18408            final int flags;
18409            if (um.isUserUnlocked(user.id)) {
18410                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18411            } else if (um.isUserRunning(user.id)) {
18412                flags = StorageManager.FLAG_STORAGE_DE;
18413            } else {
18414                continue;
18415            }
18416
18417            if (ps.getInstalled(user.id)) {
18418                // Whenever an app changes, force a restorecon of its data
18419                // TODO: when user data is locked, mark that we're still dirty
18420                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18421            }
18422        }
18423    }
18424
18425    /**
18426     * Prepare app data for the given app.
18427     * <p>
18428     * Verifies that directories exist and that ownership and labeling is
18429     * correct for all installed apps. If there is an ownership mismatch, this
18430     * will try recovering system apps by wiping data; third-party app data is
18431     * left intact.
18432     */
18433    private void prepareAppData(String volumeUuid, int userId, int flags,
18434            PackageParser.Package pkg, boolean restoreconNeeded) {
18435        if (DEBUG_APP_DATA) {
18436            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18437                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18438        }
18439
18440        final String packageName = pkg.packageName;
18441        final ApplicationInfo app = pkg.applicationInfo;
18442        final int appId = UserHandle.getAppId(app.uid);
18443
18444        Preconditions.checkNotNull(app.seinfo);
18445
18446        synchronized (mInstallLock) {
18447            try {
18448                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18449                        appId, app.seinfo, app.targetSdkVersion);
18450            } catch (InstallerException e) {
18451                if (app.isSystemApp()) {
18452                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18453                            + ", but trying to recover: " + e);
18454                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18455                    try {
18456                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18457                                appId, app.seinfo, app.targetSdkVersion);
18458                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18459                    } catch (InstallerException e2) {
18460                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18461                    }
18462                } else {
18463                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18464                }
18465            }
18466
18467            if (restoreconNeeded) {
18468                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18469            }
18470
18471            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18472                // Create a native library symlink only if we have native libraries
18473                // and if the native libraries are 32 bit libraries. We do not provide
18474                // this symlink for 64 bit libraries.
18475                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18476                    final String nativeLibPath = app.nativeLibraryDir;
18477                    try {
18478                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18479                                nativeLibPath, userId);
18480                    } catch (InstallerException e) {
18481                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18482                    }
18483                }
18484            }
18485        }
18486    }
18487
18488    /**
18489     * For system apps on non-FBE devices, this method migrates any existing
18490     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18491     * requested by the app.
18492     */
18493    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18494        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18495                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18496            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18497                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18498            synchronized (mInstallLock) {
18499                try {
18500                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18501                } catch (InstallerException e) {
18502                    logCriticalInfo(Log.WARN,
18503                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18504                }
18505            }
18506            return true;
18507        } else {
18508            return false;
18509        }
18510    }
18511
18512    private void unfreezePackage(String packageName) {
18513        synchronized (mPackages) {
18514            final PackageSetting ps = mSettings.mPackages.get(packageName);
18515            if (ps != null) {
18516                ps.frozen = false;
18517            }
18518        }
18519    }
18520
18521    @Override
18522    public int movePackage(final String packageName, final String volumeUuid) {
18523        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18524
18525        final int moveId = mNextMoveId.getAndIncrement();
18526        mHandler.post(new Runnable() {
18527            @Override
18528            public void run() {
18529                try {
18530                    movePackageInternal(packageName, volumeUuid, moveId);
18531                } catch (PackageManagerException e) {
18532                    Slog.w(TAG, "Failed to move " + packageName, e);
18533                    mMoveCallbacks.notifyStatusChanged(moveId,
18534                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18535                }
18536            }
18537        });
18538        return moveId;
18539    }
18540
18541    private void movePackageInternal(final String packageName, final String volumeUuid,
18542            final int moveId) throws PackageManagerException {
18543        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18545        final PackageManager pm = mContext.getPackageManager();
18546
18547        final boolean currentAsec;
18548        final String currentVolumeUuid;
18549        final File codeFile;
18550        final String installerPackageName;
18551        final String packageAbiOverride;
18552        final int appId;
18553        final String seinfo;
18554        final String label;
18555        final int targetSdkVersion;
18556
18557        // reader
18558        synchronized (mPackages) {
18559            final PackageParser.Package pkg = mPackages.get(packageName);
18560            final PackageSetting ps = mSettings.mPackages.get(packageName);
18561            if (pkg == null || ps == null) {
18562                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18563            }
18564
18565            if (pkg.applicationInfo.isSystemApp()) {
18566                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18567                        "Cannot move system application");
18568            }
18569
18570            if (pkg.applicationInfo.isExternalAsec()) {
18571                currentAsec = true;
18572                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18573            } else if (pkg.applicationInfo.isForwardLocked()) {
18574                currentAsec = true;
18575                currentVolumeUuid = "forward_locked";
18576            } else {
18577                currentAsec = false;
18578                currentVolumeUuid = ps.volumeUuid;
18579
18580                final File probe = new File(pkg.codePath);
18581                final File probeOat = new File(probe, "oat");
18582                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18583                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18584                            "Move only supported for modern cluster style installs");
18585                }
18586            }
18587
18588            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18589                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18590                        "Package already moved to " + volumeUuid);
18591            }
18592            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18593                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18594                        "Device admin cannot be moved");
18595            }
18596
18597            if (ps.frozen) {
18598                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18599                        "Failed to move already frozen package");
18600            }
18601            ps.frozen = true;
18602
18603            codeFile = new File(pkg.codePath);
18604            installerPackageName = ps.installerPackageName;
18605            packageAbiOverride = ps.cpuAbiOverrideString;
18606            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18607            seinfo = pkg.applicationInfo.seinfo;
18608            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18609            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18610        }
18611
18612        // Now that we're guarded by frozen state, kill app during move
18613        final long token = Binder.clearCallingIdentity();
18614        try {
18615            killApplication(packageName, appId, "move pkg");
18616        } finally {
18617            Binder.restoreCallingIdentity(token);
18618        }
18619
18620        final Bundle extras = new Bundle();
18621        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18622        extras.putString(Intent.EXTRA_TITLE, label);
18623        mMoveCallbacks.notifyCreated(moveId, extras);
18624
18625        int installFlags;
18626        final boolean moveCompleteApp;
18627        final File measurePath;
18628
18629        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18630            installFlags = INSTALL_INTERNAL;
18631            moveCompleteApp = !currentAsec;
18632            measurePath = Environment.getDataAppDirectory(volumeUuid);
18633        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18634            installFlags = INSTALL_EXTERNAL;
18635            moveCompleteApp = false;
18636            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18637        } else {
18638            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18639            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18640                    || !volume.isMountedWritable()) {
18641                unfreezePackage(packageName);
18642                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18643                        "Move location not mounted private volume");
18644            }
18645
18646            Preconditions.checkState(!currentAsec);
18647
18648            installFlags = INSTALL_INTERNAL;
18649            moveCompleteApp = true;
18650            measurePath = Environment.getDataAppDirectory(volumeUuid);
18651        }
18652
18653        final PackageStats stats = new PackageStats(null, -1);
18654        synchronized (mInstaller) {
18655            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18656                unfreezePackage(packageName);
18657                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18658                        "Failed to measure package size");
18659            }
18660        }
18661
18662        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18663                + stats.dataSize);
18664
18665        final long startFreeBytes = measurePath.getFreeSpace();
18666        final long sizeBytes;
18667        if (moveCompleteApp) {
18668            sizeBytes = stats.codeSize + stats.dataSize;
18669        } else {
18670            sizeBytes = stats.codeSize;
18671        }
18672
18673        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18674            unfreezePackage(packageName);
18675            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18676                    "Not enough free space to move");
18677        }
18678
18679        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18680
18681        final CountDownLatch installedLatch = new CountDownLatch(1);
18682        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18683            @Override
18684            public void onUserActionRequired(Intent intent) throws RemoteException {
18685                throw new IllegalStateException();
18686            }
18687
18688            @Override
18689            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18690                    Bundle extras) throws RemoteException {
18691                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18692                        + PackageManager.installStatusToString(returnCode, msg));
18693
18694                installedLatch.countDown();
18695
18696                // Regardless of success or failure of the move operation,
18697                // always unfreeze the package
18698                unfreezePackage(packageName);
18699
18700                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18701                switch (status) {
18702                    case PackageInstaller.STATUS_SUCCESS:
18703                        mMoveCallbacks.notifyStatusChanged(moveId,
18704                                PackageManager.MOVE_SUCCEEDED);
18705                        break;
18706                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18707                        mMoveCallbacks.notifyStatusChanged(moveId,
18708                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18709                        break;
18710                    default:
18711                        mMoveCallbacks.notifyStatusChanged(moveId,
18712                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18713                        break;
18714                }
18715            }
18716        };
18717
18718        final MoveInfo move;
18719        if (moveCompleteApp) {
18720            // Kick off a thread to report progress estimates
18721            new Thread() {
18722                @Override
18723                public void run() {
18724                    while (true) {
18725                        try {
18726                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18727                                break;
18728                            }
18729                        } catch (InterruptedException ignored) {
18730                        }
18731
18732                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18733                        final int progress = 10 + (int) MathUtils.constrain(
18734                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18735                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18736                    }
18737                }
18738            }.start();
18739
18740            final String dataAppName = codeFile.getName();
18741            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18742                    dataAppName, appId, seinfo, targetSdkVersion);
18743        } else {
18744            move = null;
18745        }
18746
18747        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18748
18749        final Message msg = mHandler.obtainMessage(INIT_COPY);
18750        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18751        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18752                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18753                packageAbiOverride, null);
18754        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18755        msg.obj = params;
18756
18757        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18758                System.identityHashCode(msg.obj));
18759        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18760                System.identityHashCode(msg.obj));
18761
18762        mHandler.sendMessage(msg);
18763    }
18764
18765    @Override
18766    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18767        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18768
18769        final int realMoveId = mNextMoveId.getAndIncrement();
18770        final Bundle extras = new Bundle();
18771        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18772        mMoveCallbacks.notifyCreated(realMoveId, extras);
18773
18774        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18775            @Override
18776            public void onCreated(int moveId, Bundle extras) {
18777                // Ignored
18778            }
18779
18780            @Override
18781            public void onStatusChanged(int moveId, int status, long estMillis) {
18782                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18783            }
18784        };
18785
18786        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18787        storage.setPrimaryStorageUuid(volumeUuid, callback);
18788        return realMoveId;
18789    }
18790
18791    @Override
18792    public int getMoveStatus(int moveId) {
18793        mContext.enforceCallingOrSelfPermission(
18794                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18795        return mMoveCallbacks.mLastStatus.get(moveId);
18796    }
18797
18798    @Override
18799    public void registerMoveCallback(IPackageMoveObserver callback) {
18800        mContext.enforceCallingOrSelfPermission(
18801                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18802        mMoveCallbacks.register(callback);
18803    }
18804
18805    @Override
18806    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18807        mContext.enforceCallingOrSelfPermission(
18808                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18809        mMoveCallbacks.unregister(callback);
18810    }
18811
18812    @Override
18813    public boolean setInstallLocation(int loc) {
18814        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18815                null);
18816        if (getInstallLocation() == loc) {
18817            return true;
18818        }
18819        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18820                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18821            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18822                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18823            return true;
18824        }
18825        return false;
18826   }
18827
18828    @Override
18829    public int getInstallLocation() {
18830        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18831                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18832                PackageHelper.APP_INSTALL_AUTO);
18833    }
18834
18835    /** Called by UserManagerService */
18836    void cleanUpUser(UserManagerService userManager, int userHandle) {
18837        synchronized (mPackages) {
18838            mDirtyUsers.remove(userHandle);
18839            mUserNeedsBadging.delete(userHandle);
18840            mSettings.removeUserLPw(userHandle);
18841            mPendingBroadcasts.remove(userHandle);
18842            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18843        }
18844        synchronized (mInstallLock) {
18845            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18846            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18847                final String volumeUuid = vol.getFsUuid();
18848                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18849                try {
18850                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18851                } catch (InstallerException e) {
18852                    Slog.w(TAG, "Failed to remove user data", e);
18853                }
18854            }
18855            synchronized (mPackages) {
18856                removeUnusedPackagesLILPw(userManager, userHandle);
18857            }
18858        }
18859    }
18860
18861    /**
18862     * We're removing userHandle and would like to remove any downloaded packages
18863     * that are no longer in use by any other user.
18864     * @param userHandle the user being removed
18865     */
18866    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18867        final boolean DEBUG_CLEAN_APKS = false;
18868        int [] users = userManager.getUserIds();
18869        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18870        while (psit.hasNext()) {
18871            PackageSetting ps = psit.next();
18872            if (ps.pkg == null) {
18873                continue;
18874            }
18875            final String packageName = ps.pkg.packageName;
18876            // Skip over if system app
18877            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18878                continue;
18879            }
18880            if (DEBUG_CLEAN_APKS) {
18881                Slog.i(TAG, "Checking package " + packageName);
18882            }
18883            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18884            if (keep) {
18885                if (DEBUG_CLEAN_APKS) {
18886                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18887                }
18888            } else {
18889                for (int i = 0; i < users.length; i++) {
18890                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18891                        keep = true;
18892                        if (DEBUG_CLEAN_APKS) {
18893                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18894                                    + users[i]);
18895                        }
18896                        break;
18897                    }
18898                }
18899            }
18900            if (!keep) {
18901                if (DEBUG_CLEAN_APKS) {
18902                    Slog.i(TAG, "  Removing package " + packageName);
18903                }
18904                mHandler.post(new Runnable() {
18905                    public void run() {
18906                        deletePackageX(packageName, userHandle, 0);
18907                    } //end run
18908                });
18909            }
18910        }
18911    }
18912
18913    /** Called by UserManagerService */
18914    void createNewUser(int userHandle) {
18915        synchronized (mInstallLock) {
18916            try {
18917                mInstaller.createUserConfig(userHandle);
18918            } catch (InstallerException e) {
18919                Slog.w(TAG, "Failed to create user config", e);
18920            }
18921            mSettings.createNewUserLI(this, mInstaller, userHandle);
18922        }
18923        synchronized (mPackages) {
18924            applyFactoryDefaultBrowserLPw(userHandle);
18925            primeDomainVerificationsLPw(userHandle);
18926        }
18927    }
18928
18929    void newUserCreated(final int userHandle) {
18930        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18931        // If permission review for legacy apps is required, we represent
18932        // dagerous permissions for such apps as always granted runtime
18933        // permissions to keep per user flag state whether review is needed.
18934        // Hence, if a new user is added we have to propagate dangerous
18935        // permission grants for these legacy apps.
18936        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18937            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18938                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18939        }
18940    }
18941
18942    @Override
18943    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18944        mContext.enforceCallingOrSelfPermission(
18945                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18946                "Only package verification agents can read the verifier device identity");
18947
18948        synchronized (mPackages) {
18949            return mSettings.getVerifierDeviceIdentityLPw();
18950        }
18951    }
18952
18953    @Override
18954    public void setPermissionEnforced(String permission, boolean enforced) {
18955        // TODO: Now that we no longer change GID for storage, this should to away.
18956        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18957                "setPermissionEnforced");
18958        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18959            synchronized (mPackages) {
18960                if (mSettings.mReadExternalStorageEnforced == null
18961                        || mSettings.mReadExternalStorageEnforced != enforced) {
18962                    mSettings.mReadExternalStorageEnforced = enforced;
18963                    mSettings.writeLPr();
18964                }
18965            }
18966            // kill any non-foreground processes so we restart them and
18967            // grant/revoke the GID.
18968            final IActivityManager am = ActivityManagerNative.getDefault();
18969            if (am != null) {
18970                final long token = Binder.clearCallingIdentity();
18971                try {
18972                    am.killProcessesBelowForeground("setPermissionEnforcement");
18973                } catch (RemoteException e) {
18974                } finally {
18975                    Binder.restoreCallingIdentity(token);
18976                }
18977            }
18978        } else {
18979            throw new IllegalArgumentException("No selective enforcement for " + permission);
18980        }
18981    }
18982
18983    @Override
18984    @Deprecated
18985    public boolean isPermissionEnforced(String permission) {
18986        return true;
18987    }
18988
18989    @Override
18990    public boolean isStorageLow() {
18991        final long token = Binder.clearCallingIdentity();
18992        try {
18993            final DeviceStorageMonitorInternal
18994                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18995            if (dsm != null) {
18996                return dsm.isMemoryLow();
18997            } else {
18998                return false;
18999            }
19000        } finally {
19001            Binder.restoreCallingIdentity(token);
19002        }
19003    }
19004
19005    @Override
19006    public IPackageInstaller getPackageInstaller() {
19007        return mInstallerService;
19008    }
19009
19010    private boolean userNeedsBadging(int userId) {
19011        int index = mUserNeedsBadging.indexOfKey(userId);
19012        if (index < 0) {
19013            final UserInfo userInfo;
19014            final long token = Binder.clearCallingIdentity();
19015            try {
19016                userInfo = sUserManager.getUserInfo(userId);
19017            } finally {
19018                Binder.restoreCallingIdentity(token);
19019            }
19020            final boolean b;
19021            if (userInfo != null && userInfo.isManagedProfile()) {
19022                b = true;
19023            } else {
19024                b = false;
19025            }
19026            mUserNeedsBadging.put(userId, b);
19027            return b;
19028        }
19029        return mUserNeedsBadging.valueAt(index);
19030    }
19031
19032    @Override
19033    public KeySet getKeySetByAlias(String packageName, String alias) {
19034        if (packageName == null || alias == null) {
19035            return null;
19036        }
19037        synchronized(mPackages) {
19038            final PackageParser.Package pkg = mPackages.get(packageName);
19039            if (pkg == null) {
19040                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19041                throw new IllegalArgumentException("Unknown package: " + packageName);
19042            }
19043            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19044            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19045        }
19046    }
19047
19048    @Override
19049    public KeySet getSigningKeySet(String packageName) {
19050        if (packageName == null) {
19051            return null;
19052        }
19053        synchronized(mPackages) {
19054            final PackageParser.Package pkg = mPackages.get(packageName);
19055            if (pkg == null) {
19056                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19057                throw new IllegalArgumentException("Unknown package: " + packageName);
19058            }
19059            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19060                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19061                throw new SecurityException("May not access signing KeySet of other apps.");
19062            }
19063            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19064            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19065        }
19066    }
19067
19068    @Override
19069    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19070        if (packageName == null || ks == null) {
19071            return false;
19072        }
19073        synchronized(mPackages) {
19074            final PackageParser.Package pkg = mPackages.get(packageName);
19075            if (pkg == null) {
19076                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19077                throw new IllegalArgumentException("Unknown package: " + packageName);
19078            }
19079            IBinder ksh = ks.getToken();
19080            if (ksh instanceof KeySetHandle) {
19081                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19082                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19083            }
19084            return false;
19085        }
19086    }
19087
19088    @Override
19089    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19090        if (packageName == null || ks == null) {
19091            return false;
19092        }
19093        synchronized(mPackages) {
19094            final PackageParser.Package pkg = mPackages.get(packageName);
19095            if (pkg == null) {
19096                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19097                throw new IllegalArgumentException("Unknown package: " + packageName);
19098            }
19099            IBinder ksh = ks.getToken();
19100            if (ksh instanceof KeySetHandle) {
19101                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19102                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19103            }
19104            return false;
19105        }
19106    }
19107
19108    private void deletePackageIfUnusedLPr(final String packageName) {
19109        PackageSetting ps = mSettings.mPackages.get(packageName);
19110        if (ps == null) {
19111            return;
19112        }
19113        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19114            // TODO Implement atomic delete if package is unused
19115            // It is currently possible that the package will be deleted even if it is installed
19116            // after this method returns.
19117            mHandler.post(new Runnable() {
19118                public void run() {
19119                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19120                }
19121            });
19122        }
19123    }
19124
19125    /**
19126     * Check and throw if the given before/after packages would be considered a
19127     * downgrade.
19128     */
19129    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19130            throws PackageManagerException {
19131        if (after.versionCode < before.mVersionCode) {
19132            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19133                    "Update version code " + after.versionCode + " is older than current "
19134                    + before.mVersionCode);
19135        } else if (after.versionCode == before.mVersionCode) {
19136            if (after.baseRevisionCode < before.baseRevisionCode) {
19137                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19138                        "Update base revision code " + after.baseRevisionCode
19139                        + " is older than current " + before.baseRevisionCode);
19140            }
19141
19142            if (!ArrayUtils.isEmpty(after.splitNames)) {
19143                for (int i = 0; i < after.splitNames.length; i++) {
19144                    final String splitName = after.splitNames[i];
19145                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19146                    if (j != -1) {
19147                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19148                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19149                                    "Update split " + splitName + " revision code "
19150                                    + after.splitRevisionCodes[i] + " is older than current "
19151                                    + before.splitRevisionCodes[j]);
19152                        }
19153                    }
19154                }
19155            }
19156        }
19157    }
19158
19159    private static class MoveCallbacks extends Handler {
19160        private static final int MSG_CREATED = 1;
19161        private static final int MSG_STATUS_CHANGED = 2;
19162
19163        private final RemoteCallbackList<IPackageMoveObserver>
19164                mCallbacks = new RemoteCallbackList<>();
19165
19166        private final SparseIntArray mLastStatus = new SparseIntArray();
19167
19168        public MoveCallbacks(Looper looper) {
19169            super(looper);
19170        }
19171
19172        public void register(IPackageMoveObserver callback) {
19173            mCallbacks.register(callback);
19174        }
19175
19176        public void unregister(IPackageMoveObserver callback) {
19177            mCallbacks.unregister(callback);
19178        }
19179
19180        @Override
19181        public void handleMessage(Message msg) {
19182            final SomeArgs args = (SomeArgs) msg.obj;
19183            final int n = mCallbacks.beginBroadcast();
19184            for (int i = 0; i < n; i++) {
19185                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19186                try {
19187                    invokeCallback(callback, msg.what, args);
19188                } catch (RemoteException ignored) {
19189                }
19190            }
19191            mCallbacks.finishBroadcast();
19192            args.recycle();
19193        }
19194
19195        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19196                throws RemoteException {
19197            switch (what) {
19198                case MSG_CREATED: {
19199                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19200                    break;
19201                }
19202                case MSG_STATUS_CHANGED: {
19203                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19204                    break;
19205                }
19206            }
19207        }
19208
19209        private void notifyCreated(int moveId, Bundle extras) {
19210            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19211
19212            final SomeArgs args = SomeArgs.obtain();
19213            args.argi1 = moveId;
19214            args.arg2 = extras;
19215            obtainMessage(MSG_CREATED, args).sendToTarget();
19216        }
19217
19218        private void notifyStatusChanged(int moveId, int status) {
19219            notifyStatusChanged(moveId, status, -1);
19220        }
19221
19222        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19223            Slog.v(TAG, "Move " + moveId + " status " + status);
19224
19225            final SomeArgs args = SomeArgs.obtain();
19226            args.argi1 = moveId;
19227            args.argi2 = status;
19228            args.arg3 = estMillis;
19229            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19230
19231            synchronized (mLastStatus) {
19232                mLastStatus.put(moveId, status);
19233            }
19234        }
19235    }
19236
19237    private final static class OnPermissionChangeListeners extends Handler {
19238        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19239
19240        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19241                new RemoteCallbackList<>();
19242
19243        public OnPermissionChangeListeners(Looper looper) {
19244            super(looper);
19245        }
19246
19247        @Override
19248        public void handleMessage(Message msg) {
19249            switch (msg.what) {
19250                case MSG_ON_PERMISSIONS_CHANGED: {
19251                    final int uid = msg.arg1;
19252                    handleOnPermissionsChanged(uid);
19253                } break;
19254            }
19255        }
19256
19257        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19258            mPermissionListeners.register(listener);
19259
19260        }
19261
19262        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19263            mPermissionListeners.unregister(listener);
19264        }
19265
19266        public void onPermissionsChanged(int uid) {
19267            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19268                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19269            }
19270        }
19271
19272        private void handleOnPermissionsChanged(int uid) {
19273            final int count = mPermissionListeners.beginBroadcast();
19274            try {
19275                for (int i = 0; i < count; i++) {
19276                    IOnPermissionsChangeListener callback = mPermissionListeners
19277                            .getBroadcastItem(i);
19278                    try {
19279                        callback.onPermissionsChanged(uid);
19280                    } catch (RemoteException e) {
19281                        Log.e(TAG, "Permission listener is dead", e);
19282                    }
19283                }
19284            } finally {
19285                mPermissionListeners.finishBroadcast();
19286            }
19287        }
19288    }
19289
19290    private class PackageManagerInternalImpl extends PackageManagerInternal {
19291        @Override
19292        public void setLocationPackagesProvider(PackagesProvider provider) {
19293            synchronized (mPackages) {
19294                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19295            }
19296        }
19297
19298        @Override
19299        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19300            synchronized (mPackages) {
19301                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19302            }
19303        }
19304
19305        @Override
19306        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19307            synchronized (mPackages) {
19308                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19309            }
19310        }
19311
19312        @Override
19313        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19314            synchronized (mPackages) {
19315                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19316            }
19317        }
19318
19319        @Override
19320        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19321            synchronized (mPackages) {
19322                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19323            }
19324        }
19325
19326        @Override
19327        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19328            synchronized (mPackages) {
19329                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19330            }
19331        }
19332
19333        @Override
19334        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19335            synchronized (mPackages) {
19336                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19337                        packageName, userId);
19338            }
19339        }
19340
19341        @Override
19342        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19343            synchronized (mPackages) {
19344                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19345                        packageName, userId);
19346            }
19347        }
19348
19349        @Override
19350        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19351            synchronized (mPackages) {
19352                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19353                        packageName, userId);
19354            }
19355        }
19356
19357        @Override
19358        public void setKeepUninstalledPackages(final List<String> packageList) {
19359            Preconditions.checkNotNull(packageList);
19360            List<String> removedFromList = null;
19361            synchronized (mPackages) {
19362                if (mKeepUninstalledPackages != null) {
19363                    final int packagesCount = mKeepUninstalledPackages.size();
19364                    for (int i = 0; i < packagesCount; i++) {
19365                        String oldPackage = mKeepUninstalledPackages.get(i);
19366                        if (packageList != null && packageList.contains(oldPackage)) {
19367                            continue;
19368                        }
19369                        if (removedFromList == null) {
19370                            removedFromList = new ArrayList<>();
19371                        }
19372                        removedFromList.add(oldPackage);
19373                    }
19374                }
19375                mKeepUninstalledPackages = new ArrayList<>(packageList);
19376                if (removedFromList != null) {
19377                    final int removedCount = removedFromList.size();
19378                    for (int i = 0; i < removedCount; i++) {
19379                        deletePackageIfUnusedLPr(removedFromList.get(i));
19380                    }
19381                }
19382            }
19383        }
19384
19385        @Override
19386        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19387            synchronized (mPackages) {
19388                // If we do not support permission review, done.
19389                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19390                    return false;
19391                }
19392
19393                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19394                if (packageSetting == null) {
19395                    return false;
19396                }
19397
19398                // Permission review applies only to apps not supporting the new permission model.
19399                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19400                    return false;
19401                }
19402
19403                // Legacy apps have the permission and get user consent on launch.
19404                PermissionsState permissionsState = packageSetting.getPermissionsState();
19405                return permissionsState.isPermissionReviewRequired(userId);
19406            }
19407        }
19408
19409        @Override
19410        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19411            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19412        }
19413
19414        @Override
19415        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19416                int userId) {
19417            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19418        }
19419    }
19420
19421    @Override
19422    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19423        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19424        synchronized (mPackages) {
19425            final long identity = Binder.clearCallingIdentity();
19426            try {
19427                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19428                        packageNames, userId);
19429            } finally {
19430                Binder.restoreCallingIdentity(identity);
19431            }
19432        }
19433    }
19434
19435    private static void enforceSystemOrPhoneCaller(String tag) {
19436        int callingUid = Binder.getCallingUid();
19437        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19438            throw new SecurityException(
19439                    "Cannot call " + tag + " from UID " + callingUid);
19440        }
19441    }
19442
19443    boolean isHistoricalPackageUsageAvailable() {
19444        return mPackageUsage.isHistoricalPackageUsageAvailable();
19445    }
19446
19447    /**
19448     * Return a <b>copy</b> of the collection of packages known to the package manager.
19449     * @return A copy of the values of mPackages.
19450     */
19451    Collection<PackageParser.Package> getPackages() {
19452        synchronized (mPackages) {
19453            return new ArrayList<>(mPackages.values());
19454        }
19455    }
19456
19457    /**
19458     * Logs process start information (including base APK hash) to the security log.
19459     * @hide
19460     */
19461    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
19462            String apkFile, int pid) {
19463        if (!SecurityLog.isLoggingEnabled()) {
19464            return;
19465        }
19466        Bundle data = new Bundle();
19467        data.putLong("startTimestamp", System.currentTimeMillis());
19468        data.putString("processName", processName);
19469        data.putInt("uid", uid);
19470        data.putString("seinfo", seinfo);
19471        data.putString("apkFile", apkFile);
19472        data.putInt("pid", pid);
19473        Message msg = mProcessLoggingHandler.obtainMessage(
19474                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
19475        msg.setData(data);
19476        mProcessLoggingHandler.sendMessage(msg);
19477    }
19478}
19479