PackageManagerService.java revision 5217cacbd9f382068bb9e176cd5a0b15388a335c
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
79import static com.android.internal.util.ArrayUtils.appendInt;
80import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
89
90import android.Manifest;
91import android.app.ActivityManager;
92import android.app.ActivityManagerNative;
93import android.app.AppGlobals;
94import android.app.IActivityManager;
95import android.app.admin.IDevicePolicyManager;
96import android.app.backup.IBackupManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.AppsQueryHelper;
109import android.content.pm.EphemeralApplicationInfo;
110import android.content.pm.EphemeralResolveInfo;
111import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
112import android.content.pm.FeatureInfo;
113import android.content.pm.IOnPermissionsChangeListener;
114import android.content.pm.IPackageDataObserver;
115import android.content.pm.IPackageDeleteObserver;
116import android.content.pm.IPackageDeleteObserver2;
117import android.content.pm.IPackageInstallObserver2;
118import android.content.pm.IPackageInstaller;
119import android.content.pm.IPackageManager;
120import android.content.pm.IPackageMoveObserver;
121import android.content.pm.IPackageStatsObserver;
122import android.content.pm.InstrumentationInfo;
123import android.content.pm.IntentFilterVerificationInfo;
124import android.content.pm.KeySet;
125import android.content.pm.ManifestDigest;
126import android.content.pm.PackageCleanItem;
127import android.content.pm.PackageInfo;
128import android.content.pm.PackageInfoLite;
129import android.content.pm.PackageInstaller;
130import android.content.pm.PackageManager;
131import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
132import android.content.pm.PackageManagerInternal;
133import android.content.pm.PackageParser;
134import android.content.pm.PackageParser.ActivityIntentInfo;
135import android.content.pm.PackageParser.PackageLite;
136import android.content.pm.PackageParser.PackageParserException;
137import android.content.pm.PackageStats;
138import android.content.pm.PackageUserState;
139import android.content.pm.ParceledListSlice;
140import android.content.pm.PermissionGroupInfo;
141import android.content.pm.PermissionInfo;
142import android.content.pm.ProviderInfo;
143import android.content.pm.ResolveInfo;
144import android.content.pm.ServiceInfo;
145import android.content.pm.Signature;
146import android.content.pm.UserInfo;
147import android.content.pm.VerificationParams;
148import android.content.pm.VerifierDeviceIdentity;
149import android.content.pm.VerifierInfo;
150import android.content.res.Resources;
151import android.graphics.Bitmap;
152import android.hardware.display.DisplayManager;
153import android.net.Uri;
154import android.os.Binder;
155import android.os.Build;
156import android.os.Bundle;
157import android.os.Debug;
158import android.os.Environment;
159import android.os.Environment.UserEnvironment;
160import android.os.FileUtils;
161import android.os.Handler;
162import android.os.IBinder;
163import android.os.Looper;
164import android.os.Message;
165import android.os.Parcel;
166import android.os.ParcelFileDescriptor;
167import android.os.Process;
168import android.os.RemoteCallbackList;
169import android.os.RemoteException;
170import android.os.ResultReceiver;
171import android.os.SELinux;
172import android.os.ServiceManager;
173import android.os.SystemClock;
174import android.os.SystemProperties;
175import android.os.Trace;
176import android.os.UserHandle;
177import android.os.UserManager;
178import android.os.storage.IMountService;
179import android.os.storage.MountServiceInternal;
180import android.os.storage.StorageEventListener;
181import android.os.storage.StorageManager;
182import android.os.storage.VolumeInfo;
183import android.os.storage.VolumeRecord;
184import android.security.KeyStore;
185import android.security.SystemKeyStore;
186import android.system.ErrnoException;
187import android.system.Os;
188import android.system.StructStat;
189import android.text.TextUtils;
190import android.text.format.DateUtils;
191import android.util.ArrayMap;
192import android.util.ArraySet;
193import android.util.AtomicFile;
194import android.util.DisplayMetrics;
195import android.util.EventLog;
196import android.util.ExceptionUtils;
197import android.util.Log;
198import android.util.LogPrinter;
199import android.util.MathUtils;
200import android.util.PrintStreamPrinter;
201import android.util.Slog;
202import android.util.SparseArray;
203import android.util.SparseBooleanArray;
204import android.util.SparseIntArray;
205import android.util.Xml;
206import android.view.Display;
207
208import com.android.internal.R;
209import com.android.internal.annotations.GuardedBy;
210import com.android.internal.annotations.GuardedBy;
211import com.android.internal.app.IMediaContainerService;
212import com.android.internal.app.ResolverActivity;
213import com.android.internal.content.NativeLibraryHelper;
214import com.android.internal.content.PackageHelper;
215import com.android.internal.os.IParcelFileDescriptorFactory;
216import com.android.internal.os.SomeArgs;
217import com.android.internal.os.Zygote;
218import com.android.internal.util.ArrayUtils;
219import com.android.internal.util.FastPrintWriter;
220import com.android.internal.util.FastXmlSerializer;
221import com.android.internal.util.IndentingPrintWriter;
222import com.android.internal.util.Preconditions;
223import com.android.server.EventLogTags;
224import com.android.server.FgThread;
225import com.android.server.IntentResolver;
226import com.android.server.LocalServices;
227import com.android.server.ServiceThread;
228import com.android.server.SystemConfig;
229import com.android.server.Watchdog;
230import com.android.server.pm.PermissionsState.PermissionState;
231import com.android.server.pm.Settings.DatabaseVersion;
232import com.android.server.pm.Settings.VersionInfo;
233import com.android.server.storage.DeviceStorageMonitorInternal;
234
235import dalvik.system.DexFile;
236import dalvik.system.VMRuntime;
237
238import libcore.io.IoUtils;
239import libcore.util.EmptyArray;
240
241import org.xmlpull.v1.XmlPullParser;
242import org.xmlpull.v1.XmlPullParserException;
243import org.xmlpull.v1.XmlSerializer;
244
245import java.io.BufferedInputStream;
246import java.io.BufferedOutputStream;
247import java.io.BufferedReader;
248import java.io.ByteArrayInputStream;
249import java.io.ByteArrayOutputStream;
250import java.io.File;
251import java.io.FileDescriptor;
252import java.io.FileNotFoundException;
253import java.io.FileOutputStream;
254import java.io.FileReader;
255import java.io.FilenameFilter;
256import java.io.IOException;
257import java.io.InputStream;
258import java.io.PrintWriter;
259import java.nio.charset.StandardCharsets;
260import java.security.MessageDigest;
261import java.security.NoSuchAlgorithmException;
262import java.security.PublicKey;
263import java.security.cert.CertificateEncodingException;
264import java.security.cert.CertificateException;
265import java.text.SimpleDateFormat;
266import java.util.ArrayList;
267import java.util.Arrays;
268import java.util.Collection;
269import java.util.Collections;
270import java.util.Comparator;
271import java.util.Date;
272import java.util.Iterator;
273import java.util.List;
274import java.util.Map;
275import java.util.Objects;
276import java.util.Set;
277import java.util.concurrent.CountDownLatch;
278import java.util.concurrent.TimeUnit;
279import java.util.concurrent.atomic.AtomicBoolean;
280import java.util.concurrent.atomic.AtomicInteger;
281import java.util.concurrent.atomic.AtomicLong;
282
283/**
284 * Keep track of all those .apks everywhere.
285 *
286 * This is very central to the platform's security; please run the unit
287 * tests whenever making modifications here:
288 *
289runtest -c android.content.pm.PackageManagerTests frameworks-core
290 *
291 * {@hide}
292 */
293public class PackageManagerService extends IPackageManager.Stub {
294    static final String TAG = "PackageManager";
295    static final boolean DEBUG_SETTINGS = false;
296    static final boolean DEBUG_PREFERRED = false;
297    static final boolean DEBUG_UPGRADE = false;
298    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
299    private static final boolean DEBUG_BACKUP = false;
300    private static final boolean DEBUG_INSTALL = false;
301    private static final boolean DEBUG_REMOVE = false;
302    private static final boolean DEBUG_BROADCASTS = false;
303    private static final boolean DEBUG_SHOW_INFO = false;
304    private static final boolean DEBUG_PACKAGE_INFO = false;
305    private static final boolean DEBUG_INTENT_MATCHING = false;
306    private static final boolean DEBUG_PACKAGE_SCANNING = false;
307    private static final boolean DEBUG_VERIFY = false;
308    private static final boolean DEBUG_DEXOPT = false;
309    private static final boolean DEBUG_ABI_SELECTION = false;
310    private static final boolean DEBUG_EPHEMERAL = false;
311    private static final boolean DEBUG_ENCRYPTION_AWARE = false;
312
313    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
314
315    private static final int RADIO_UID = Process.PHONE_UID;
316    private static final int LOG_UID = Process.LOG_UID;
317    private static final int NFC_UID = Process.NFC_UID;
318    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
319    private static final int SHELL_UID = Process.SHELL_UID;
320
321    // Cap the size of permission trees that 3rd party apps can define
322    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
323
324    // Suffix used during package installation when copying/moving
325    // package apks to install directory.
326    private static final String INSTALL_PACKAGE_SUFFIX = "-";
327
328    static final int SCAN_NO_DEX = 1<<1;
329    static final int SCAN_FORCE_DEX = 1<<2;
330    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
331    static final int SCAN_NEW_INSTALL = 1<<4;
332    static final int SCAN_NO_PATHS = 1<<5;
333    static final int SCAN_UPDATE_TIME = 1<<6;
334    static final int SCAN_DEFER_DEX = 1<<7;
335    static final int SCAN_BOOTING = 1<<8;
336    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
337    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
338    static final int SCAN_REPLACING = 1<<11;
339    static final int SCAN_REQUIRE_KNOWN = 1<<12;
340    static final int SCAN_MOVE = 1<<13;
341    static final int SCAN_INITIAL = 1<<14;
342
343    static final int REMOVE_CHATTY = 1<<16;
344
345    private static final int[] EMPTY_INT_ARRAY = new int[0];
346
347    /**
348     * Timeout (in milliseconds) after which the watchdog should declare that
349     * our handler thread is wedged.  The usual default for such things is one
350     * minute but we sometimes do very lengthy I/O operations on this thread,
351     * such as installing multi-gigabyte applications, so ours needs to be longer.
352     */
353    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
354
355    /**
356     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
357     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
358     * settings entry if available, otherwise we use the hardcoded default.  If it's been
359     * more than this long since the last fstrim, we force one during the boot sequence.
360     *
361     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
362     * one gets run at the next available charging+idle time.  This final mandatory
363     * no-fstrim check kicks in only of the other scheduling criteria is never met.
364     */
365    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
366
367    /**
368     * Whether verification is enabled by default.
369     */
370    private static final boolean DEFAULT_VERIFY_ENABLE = true;
371
372    /**
373     * The default maximum time to wait for the verification agent to return in
374     * milliseconds.
375     */
376    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
377
378    /**
379     * The default response for package verification timeout.
380     *
381     * This can be either PackageManager.VERIFICATION_ALLOW or
382     * PackageManager.VERIFICATION_REJECT.
383     */
384    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
385
386    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
387
388    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
389            DEFAULT_CONTAINER_PACKAGE,
390            "com.android.defcontainer.DefaultContainerService");
391
392    private static final String KILL_APP_REASON_GIDS_CHANGED =
393            "permission grant or revoke changed gids";
394
395    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
396            "permissions revoked";
397
398    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
399
400    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
401
402    /** Permission grant: not grant the permission. */
403    private static final int GRANT_DENIED = 1;
404
405    /** Permission grant: grant the permission as an install permission. */
406    private static final int GRANT_INSTALL = 2;
407
408    /** Permission grant: grant the permission as a runtime one. */
409    private static final int GRANT_RUNTIME = 3;
410
411    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
412    private static final int GRANT_UPGRADE = 4;
413
414    /** Canonical intent used to identify what counts as a "web browser" app */
415    private static final Intent sBrowserIntent;
416    static {
417        sBrowserIntent = new Intent();
418        sBrowserIntent.setAction(Intent.ACTION_VIEW);
419        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
420        sBrowserIntent.setData(Uri.parse("http:"));
421    }
422
423    final ServiceThread mHandlerThread;
424
425    final PackageHandler mHandler;
426
427    /**
428     * Messages for {@link #mHandler} that need to wait for system ready before
429     * being dispatched.
430     */
431    private ArrayList<Message> mPostSystemReadyMessages;
432
433    final int mSdkVersion = Build.VERSION.SDK_INT;
434
435    final Context mContext;
436    final boolean mFactoryTest;
437    final boolean mOnlyCore;
438    final DisplayMetrics mMetrics;
439    final int mDefParseFlags;
440    final String[] mSeparateProcesses;
441    final boolean mIsUpgrade;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453    final File mEphemeralInstallDir;
454
455    /**
456     * Directory to which applications installed internally have their
457     * 32 bit native libraries copied.
458     */
459    private File mAppLib32InstallDir;
460
461    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462    // apps.
463    final File mDrmAppPrivateInstallDir;
464
465    // ----------------------------------------------------------------
466
467    // Lock for state used when installing and doing other long running
468    // operations.  Methods that must be called with this lock held have
469    // the suffix "LI".
470    final Object mInstallLock = new Object();
471
472    // ----------------------------------------------------------------
473
474    // Keys are String (package name), values are Package.  This also serves
475    // as the lock for the global state.  Methods that must be called with
476    // this lock held have the prefix "LP".
477    @GuardedBy("mPackages")
478    final ArrayMap<String, PackageParser.Package> mPackages =
479            new ArrayMap<String, PackageParser.Package>();
480
481    // Tracks available target package names -> overlay package paths.
482    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485    /**
486     * Tracks new system packages [received in an OTA] that we expect to
487     * find updated user-installed versions. Keys are package name, values
488     * are package location.
489     */
490    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492    /**
493     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494     */
495    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496    /**
497     * Whether or not system app permissions should be promoted from install to runtime.
498     */
499    boolean mPromoteSystemApps;
500
501    final Settings mSettings;
502    boolean mRestoredSettings;
503
504    // System configuration read by SystemConfig.
505    final int[] mGlobalGids;
506    final SparseArray<ArraySet<String>> mSystemPermissions;
507    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509    // If mac_permissions.xml was found for seinfo labeling.
510    boolean mFoundPolicyFile;
511
512    // If a recursive restorecon of /data/data/<pkg> is needed.
513    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
516
517    public static final class SharedLibraryEntry {
518        public final String path;
519        public final String apk;
520
521        SharedLibraryEntry(String _path, String _apk) {
522            path = _path;
523            apk = _apk;
524        }
525    }
526
527    // Currently known shared libraries.
528    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
529            new ArrayMap<String, SharedLibraryEntry>();
530
531    // All available activities, for your resolving pleasure.
532    final ActivityIntentResolver mActivities =
533            new ActivityIntentResolver();
534
535    // All available receivers, for your resolving pleasure.
536    final ActivityIntentResolver mReceivers =
537            new ActivityIntentResolver();
538
539    // All available services, for your resolving pleasure.
540    final ServiceIntentResolver mServices = new ServiceIntentResolver();
541
542    // All available providers, for your resolving pleasure.
543    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
544
545    // Mapping from provider base names (first directory in content URI codePath)
546    // to the provider information.
547    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
548            new ArrayMap<String, PackageParser.Provider>();
549
550    // Mapping from instrumentation class names to info about them.
551    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
552            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
553
554    // Mapping from permission names to info about them.
555    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
556            new ArrayMap<String, PackageParser.PermissionGroup>();
557
558    // Packages whose data we have transfered into another package, thus
559    // should no longer exist.
560    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
561
562    // Broadcast actions that are only available to the system.
563    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
564
565    /** List of packages waiting for verification. */
566    final SparseArray<PackageVerificationState> mPendingVerification
567            = new SparseArray<PackageVerificationState>();
568
569    /** Set of packages associated with each app op permission. */
570    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
571
572    final PackageInstallerService mInstallerService;
573
574    private final PackageDexOptimizer mPackageDexOptimizer;
575
576    private AtomicInteger mNextMoveId = new AtomicInteger();
577    private final MoveCallbacks mMoveCallbacks;
578
579    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
580
581    // Cache of users who need badging.
582    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
583
584    /** Token for keys in mPendingVerification. */
585    private int mPendingVerificationToken = 0;
586
587    volatile boolean mSystemReady;
588    volatile boolean mSafeMode;
589    volatile boolean mHasSystemUidErrors;
590
591    ApplicationInfo mAndroidApplication;
592    final ActivityInfo mResolveActivity = new ActivityInfo();
593    final ResolveInfo mResolveInfo = new ResolveInfo();
594    ComponentName mResolveComponentName;
595    PackageParser.Package mPlatformPackage;
596    ComponentName mCustomResolverComponentName;
597
598    boolean mResolverReplaced = false;
599
600    private final ComponentName mIntentFilterVerifierComponent;
601    private int mIntentFilterVerificationToken = 0;
602
603    /** Component that knows whether or not an ephemeral application exists */
604    final ComponentName mEphemeralResolverComponent;
605    /** The service connection to the ephemeral resolver */
606    final EphemeralResolverConnection mEphemeralResolverConnection;
607
608    /** Component used to install ephemeral applications */
609    final ComponentName mEphemeralInstallerComponent;
610    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
611    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
612
613    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
614            = new SparseArray<IntentFilterVerificationState>();
615
616    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
617            new DefaultPermissionGrantPolicy(this);
618
619    // List of packages names to keep cached, even if they are uninstalled for all users
620    private List<String> mKeepUninstalledPackages;
621
622    private static class IFVerificationParams {
623        PackageParser.Package pkg;
624        boolean replacing;
625        int userId;
626        int verifierUid;
627
628        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
629                int _userId, int _verifierUid) {
630            pkg = _pkg;
631            replacing = _replacing;
632            userId = _userId;
633            replacing = _replacing;
634            verifierUid = _verifierUid;
635        }
636    }
637
638    private interface IntentFilterVerifier<T extends IntentFilter> {
639        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
640                                               T filter, String packageName);
641        void startVerifications(int userId);
642        void receiveVerificationResponse(int verificationId);
643    }
644
645    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
646        private Context mContext;
647        private ComponentName mIntentFilterVerifierComponent;
648        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
649
650        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
651            mContext = context;
652            mIntentFilterVerifierComponent = verifierComponent;
653        }
654
655        private String getDefaultScheme() {
656            return IntentFilter.SCHEME_HTTPS;
657        }
658
659        @Override
660        public void startVerifications(int userId) {
661            // Launch verifications requests
662            int count = mCurrentIntentFilterVerifications.size();
663            for (int n=0; n<count; n++) {
664                int verificationId = mCurrentIntentFilterVerifications.get(n);
665                final IntentFilterVerificationState ivs =
666                        mIntentFilterVerificationStates.get(verificationId);
667
668                String packageName = ivs.getPackageName();
669
670                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
671                final int filterCount = filters.size();
672                ArraySet<String> domainsSet = new ArraySet<>();
673                for (int m=0; m<filterCount; m++) {
674                    PackageParser.ActivityIntentInfo filter = filters.get(m);
675                    domainsSet.addAll(filter.getHostsList());
676                }
677                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
678                synchronized (mPackages) {
679                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
680                            packageName, domainsList) != null) {
681                        scheduleWriteSettingsLocked();
682                    }
683                }
684                sendVerificationRequest(userId, verificationId, ivs);
685            }
686            mCurrentIntentFilterVerifications.clear();
687        }
688
689        private void sendVerificationRequest(int userId, int verificationId,
690                IntentFilterVerificationState ivs) {
691
692            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
693            verificationIntent.putExtra(
694                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
695                    verificationId);
696            verificationIntent.putExtra(
697                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
698                    getDefaultScheme());
699            verificationIntent.putExtra(
700                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
701                    ivs.getHostsString());
702            verificationIntent.putExtra(
703                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
704                    ivs.getPackageName());
705            verificationIntent.setComponent(mIntentFilterVerifierComponent);
706            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
707
708            UserHandle user = new UserHandle(userId);
709            mContext.sendBroadcastAsUser(verificationIntent, user);
710            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
711                    "Sending IntentFilter verification broadcast");
712        }
713
714        public void receiveVerificationResponse(int verificationId) {
715            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
716
717            final boolean verified = ivs.isVerified();
718
719            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
720            final int count = filters.size();
721            if (DEBUG_DOMAIN_VERIFICATION) {
722                Slog.i(TAG, "Received verification response " + verificationId
723                        + " for " + count + " filters, verified=" + verified);
724            }
725            for (int n=0; n<count; n++) {
726                PackageParser.ActivityIntentInfo filter = filters.get(n);
727                filter.setVerified(verified);
728
729                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
730                        + " verified with result:" + verified + " and hosts:"
731                        + ivs.getHostsString());
732            }
733
734            mIntentFilterVerificationStates.remove(verificationId);
735
736            final String packageName = ivs.getPackageName();
737            IntentFilterVerificationInfo ivi = null;
738
739            synchronized (mPackages) {
740                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
741            }
742            if (ivi == null) {
743                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
744                        + verificationId + " packageName:" + packageName);
745                return;
746            }
747            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
748                    "Updating IntentFilterVerificationInfo for package " + packageName
749                            +" verificationId:" + verificationId);
750
751            synchronized (mPackages) {
752                if (verified) {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
754                } else {
755                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
756                }
757                scheduleWriteSettingsLocked();
758
759                final int userId = ivs.getUserId();
760                if (userId != UserHandle.USER_ALL) {
761                    final int userStatus =
762                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
763
764                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
765                    boolean needUpdate = false;
766
767                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
768                    // already been set by the User thru the Disambiguation dialog
769                    switch (userStatus) {
770                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
771                            if (verified) {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
773                            } else {
774                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
775                            }
776                            needUpdate = true;
777                            break;
778
779                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
780                            if (verified) {
781                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
782                                needUpdate = true;
783                            }
784                            break;
785
786                        default:
787                            // Nothing to do
788                    }
789
790                    if (needUpdate) {
791                        mSettings.updateIntentFilterVerificationStatusLPw(
792                                packageName, updatedStatus, userId);
793                        scheduleWritePackageRestrictionsLocked(userId);
794                    }
795                }
796            }
797        }
798
799        @Override
800        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
801                    ActivityIntentInfo filter, String packageName) {
802            if (!hasValidDomains(filter)) {
803                return false;
804            }
805            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
806            if (ivs == null) {
807                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
808                        packageName);
809            }
810            if (DEBUG_DOMAIN_VERIFICATION) {
811                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
812            }
813            ivs.addFilter(filter);
814            return true;
815        }
816
817        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
818                int userId, int verificationId, String packageName) {
819            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
820                    verifierUid, userId, packageName);
821            ivs.setPendingState();
822            synchronized (mPackages) {
823                mIntentFilterVerificationStates.append(verificationId, ivs);
824                mCurrentIntentFilterVerifications.add(verificationId);
825            }
826            return ivs;
827        }
828    }
829
830    private static boolean hasValidDomains(ActivityIntentInfo filter) {
831        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
832                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
833                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
834    }
835
836    private IntentFilterVerifier mIntentFilterVerifier;
837
838    // Set of pending broadcasts for aggregating enable/disable of components.
839    static class PendingPackageBroadcasts {
840        // for each user id, a map of <package name -> components within that package>
841        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
842
843        public PendingPackageBroadcasts() {
844            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
845        }
846
847        public ArrayList<String> get(int userId, String packageName) {
848            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
849            return packages.get(packageName);
850        }
851
852        public void put(int userId, String packageName, ArrayList<String> components) {
853            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
854            packages.put(packageName, components);
855        }
856
857        public void remove(int userId, String packageName) {
858            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
859            if (packages != null) {
860                packages.remove(packageName);
861            }
862        }
863
864        public void remove(int userId) {
865            mUidMap.remove(userId);
866        }
867
868        public int userIdCount() {
869            return mUidMap.size();
870        }
871
872        public int userIdAt(int n) {
873            return mUidMap.keyAt(n);
874        }
875
876        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
877            return mUidMap.get(userId);
878        }
879
880        public int size() {
881            // total number of pending broadcast entries across all userIds
882            int num = 0;
883            for (int i = 0; i< mUidMap.size(); i++) {
884                num += mUidMap.valueAt(i).size();
885            }
886            return num;
887        }
888
889        public void clear() {
890            mUidMap.clear();
891        }
892
893        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
894            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
895            if (map == null) {
896                map = new ArrayMap<String, ArrayList<String>>();
897                mUidMap.put(userId, map);
898            }
899            return map;
900        }
901    }
902    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
903
904    // Service Connection to remote media container service to copy
905    // package uri's from external media onto secure containers
906    // or internal storage.
907    private IMediaContainerService mContainerService = null;
908
909    static final int SEND_PENDING_BROADCAST = 1;
910    static final int MCS_BOUND = 3;
911    static final int END_COPY = 4;
912    static final int INIT_COPY = 5;
913    static final int MCS_UNBIND = 6;
914    static final int START_CLEANING_PACKAGE = 7;
915    static final int FIND_INSTALL_LOC = 8;
916    static final int POST_INSTALL = 9;
917    static final int MCS_RECONNECT = 10;
918    static final int MCS_GIVE_UP = 11;
919    static final int UPDATED_MEDIA_STATUS = 12;
920    static final int WRITE_SETTINGS = 13;
921    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
922    static final int PACKAGE_VERIFIED = 15;
923    static final int CHECK_PENDING_VERIFICATION = 16;
924    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
925    static final int INTENT_FILTER_VERIFIED = 18;
926
927    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
928
929    // Delay time in millisecs
930    static final int BROADCAST_DELAY = 10 * 1000;
931
932    static UserManagerService sUserManager;
933
934    // Stores a list of users whose package restrictions file needs to be updated
935    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
936
937    final private DefaultContainerConnection mDefContainerConn =
938            new DefaultContainerConnection();
939    class DefaultContainerConnection implements ServiceConnection {
940        public void onServiceConnected(ComponentName name, IBinder service) {
941            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
942            IMediaContainerService imcs =
943                IMediaContainerService.Stub.asInterface(service);
944            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
945        }
946
947        public void onServiceDisconnected(ComponentName name) {
948            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
949        }
950    }
951
952    // Recordkeeping of restore-after-install operations that are currently in flight
953    // between the Package Manager and the Backup Manager
954    static class PostInstallData {
955        public InstallArgs args;
956        public PackageInstalledInfo res;
957
958        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
959            args = _a;
960            res = _r;
961        }
962    }
963
964    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
965    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
966
967    // XML tags for backup/restore of various bits of state
968    private static final String TAG_PREFERRED_BACKUP = "pa";
969    private static final String TAG_DEFAULT_APPS = "da";
970    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
971
972    final String mRequiredVerifierPackage;
973    final String mRequiredInstallerPackage;
974
975    private final PackageUsage mPackageUsage = new PackageUsage();
976
977    private class PackageUsage {
978        private static final int WRITE_INTERVAL
979            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
980
981        private final Object mFileLock = new Object();
982        private final AtomicLong mLastWritten = new AtomicLong(0);
983        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
984
985        private boolean mIsHistoricalPackageUsageAvailable = true;
986
987        boolean isHistoricalPackageUsageAvailable() {
988            return mIsHistoricalPackageUsageAvailable;
989        }
990
991        void write(boolean force) {
992            if (force) {
993                writeInternal();
994                return;
995            }
996            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
997                && !DEBUG_DEXOPT) {
998                return;
999            }
1000            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1001                new Thread("PackageUsage_DiskWriter") {
1002                    @Override
1003                    public void run() {
1004                        try {
1005                            writeInternal();
1006                        } finally {
1007                            mBackgroundWriteRunning.set(false);
1008                        }
1009                    }
1010                }.start();
1011            }
1012        }
1013
1014        private void writeInternal() {
1015            synchronized (mPackages) {
1016                synchronized (mFileLock) {
1017                    AtomicFile file = getFile();
1018                    FileOutputStream f = null;
1019                    try {
1020                        f = file.startWrite();
1021                        BufferedOutputStream out = new BufferedOutputStream(f);
1022                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1023                        StringBuilder sb = new StringBuilder();
1024                        for (PackageParser.Package pkg : mPackages.values()) {
1025                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1026                                continue;
1027                            }
1028                            sb.setLength(0);
1029                            sb.append(pkg.packageName);
1030                            sb.append(' ');
1031                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1032                            sb.append('\n');
1033                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1034                        }
1035                        out.flush();
1036                        file.finishWrite(f);
1037                    } catch (IOException e) {
1038                        if (f != null) {
1039                            file.failWrite(f);
1040                        }
1041                        Log.e(TAG, "Failed to write package usage times", e);
1042                    }
1043                }
1044            }
1045            mLastWritten.set(SystemClock.elapsedRealtime());
1046        }
1047
1048        void readLP() {
1049            synchronized (mFileLock) {
1050                AtomicFile file = getFile();
1051                BufferedInputStream in = null;
1052                try {
1053                    in = new BufferedInputStream(file.openRead());
1054                    StringBuffer sb = new StringBuffer();
1055                    while (true) {
1056                        String packageName = readToken(in, sb, ' ');
1057                        if (packageName == null) {
1058                            break;
1059                        }
1060                        String timeInMillisString = readToken(in, sb, '\n');
1061                        if (timeInMillisString == null) {
1062                            throw new IOException("Failed to find last usage time for package "
1063                                                  + packageName);
1064                        }
1065                        PackageParser.Package pkg = mPackages.get(packageName);
1066                        if (pkg == null) {
1067                            continue;
1068                        }
1069                        long timeInMillis;
1070                        try {
1071                            timeInMillis = Long.parseLong(timeInMillisString);
1072                        } catch (NumberFormatException e) {
1073                            throw new IOException("Failed to parse " + timeInMillisString
1074                                                  + " as a long.", e);
1075                        }
1076                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1077                    }
1078                } catch (FileNotFoundException expected) {
1079                    mIsHistoricalPackageUsageAvailable = false;
1080                } catch (IOException e) {
1081                    Log.w(TAG, "Failed to read package usage times", e);
1082                } finally {
1083                    IoUtils.closeQuietly(in);
1084                }
1085            }
1086            mLastWritten.set(SystemClock.elapsedRealtime());
1087        }
1088
1089        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1090                throws IOException {
1091            sb.setLength(0);
1092            while (true) {
1093                int ch = in.read();
1094                if (ch == -1) {
1095                    if (sb.length() == 0) {
1096                        return null;
1097                    }
1098                    throw new IOException("Unexpected EOF");
1099                }
1100                if (ch == endOfToken) {
1101                    return sb.toString();
1102                }
1103                sb.append((char)ch);
1104            }
1105        }
1106
1107        private AtomicFile getFile() {
1108            File dataDir = Environment.getDataDirectory();
1109            File systemDir = new File(dataDir, "system");
1110            File fname = new File(systemDir, "package-usage.list");
1111            return new AtomicFile(fname);
1112        }
1113    }
1114
1115    class PackageHandler extends Handler {
1116        private boolean mBound = false;
1117        final ArrayList<HandlerParams> mPendingInstalls =
1118            new ArrayList<HandlerParams>();
1119
1120        private boolean connectToService() {
1121            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1122                    " DefaultContainerService");
1123            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1126                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1127                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1128                mBound = true;
1129                return true;
1130            }
1131            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1132            return false;
1133        }
1134
1135        private void disconnectService() {
1136            mContainerService = null;
1137            mBound = false;
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1139            mContext.unbindService(mDefContainerConn);
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1141        }
1142
1143        PackageHandler(Looper looper) {
1144            super(looper);
1145        }
1146
1147        public void handleMessage(Message msg) {
1148            try {
1149                doHandleMessage(msg);
1150            } finally {
1151                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1152            }
1153        }
1154
1155        void doHandleMessage(Message msg) {
1156            switch (msg.what) {
1157                case INIT_COPY: {
1158                    HandlerParams params = (HandlerParams) msg.obj;
1159                    int idx = mPendingInstalls.size();
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1161                    // If a bind was already initiated we dont really
1162                    // need to do anything. The pending install
1163                    // will be processed later on.
1164                    if (!mBound) {
1165                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1166                                System.identityHashCode(mHandler));
1167                        // If this is the only one pending we might
1168                        // have to bind to the service again.
1169                        if (!connectToService()) {
1170                            Slog.e(TAG, "Failed to bind to media container service");
1171                            params.serviceError();
1172                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1173                                    System.identityHashCode(mHandler));
1174                            if (params.traceMethod != null) {
1175                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1176                                        params.traceCookie);
1177                            }
1178                            return;
1179                        } else {
1180                            // Once we bind to the service, the first
1181                            // pending request will be processed.
1182                            mPendingInstalls.add(idx, params);
1183                        }
1184                    } else {
1185                        mPendingInstalls.add(idx, params);
1186                        // Already bound to the service. Just make
1187                        // sure we trigger off processing the first request.
1188                        if (idx == 0) {
1189                            mHandler.sendEmptyMessage(MCS_BOUND);
1190                        }
1191                    }
1192                    break;
1193                }
1194                case MCS_BOUND: {
1195                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1196                    if (msg.obj != null) {
1197                        mContainerService = (IMediaContainerService) msg.obj;
1198                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199                                System.identityHashCode(mHandler));
1200                    }
1201                    if (mContainerService == null) {
1202                        if (!mBound) {
1203                            // Something seriously wrong since we are not bound and we are not
1204                            // waiting for connection. Bail out.
1205                            Slog.e(TAG, "Cannot bind to media container service");
1206                            for (HandlerParams params : mPendingInstalls) {
1207                                // Indicate service bind error
1208                                params.serviceError();
1209                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1210                                        System.identityHashCode(params));
1211                                if (params.traceMethod != null) {
1212                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1213                                            params.traceMethod, params.traceCookie);
1214                                }
1215                                return;
1216                            }
1217                            mPendingInstalls.clear();
1218                        } else {
1219                            Slog.w(TAG, "Waiting to connect to media container service");
1220                        }
1221                    } else if (mPendingInstalls.size() > 0) {
1222                        HandlerParams params = mPendingInstalls.get(0);
1223                        if (params != null) {
1224                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1225                                    System.identityHashCode(params));
1226                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1227                            if (params.startCopy()) {
1228                                // We are done...  look for more work or to
1229                                // go idle.
1230                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1231                                        "Checking for more work or unbind...");
1232                                // Delete pending install
1233                                if (mPendingInstalls.size() > 0) {
1234                                    mPendingInstalls.remove(0);
1235                                }
1236                                if (mPendingInstalls.size() == 0) {
1237                                    if (mBound) {
1238                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1239                                                "Posting delayed MCS_UNBIND");
1240                                        removeMessages(MCS_UNBIND);
1241                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1242                                        // Unbind after a little delay, to avoid
1243                                        // continual thrashing.
1244                                        sendMessageDelayed(ubmsg, 10000);
1245                                    }
1246                                } else {
1247                                    // There are more pending requests in queue.
1248                                    // Just post MCS_BOUND message to trigger processing
1249                                    // of next pending install.
1250                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1251                                            "Posting MCS_BOUND for next work");
1252                                    mHandler.sendEmptyMessage(MCS_BOUND);
1253                                }
1254                            }
1255                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1256                        }
1257                    } else {
1258                        // Should never happen ideally.
1259                        Slog.w(TAG, "Empty queue");
1260                    }
1261                    break;
1262                }
1263                case MCS_RECONNECT: {
1264                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1265                    if (mPendingInstalls.size() > 0) {
1266                        if (mBound) {
1267                            disconnectService();
1268                        }
1269                        if (!connectToService()) {
1270                            Slog.e(TAG, "Failed to bind to media container service");
1271                            for (HandlerParams params : mPendingInstalls) {
1272                                // Indicate service bind error
1273                                params.serviceError();
1274                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1275                                        System.identityHashCode(params));
1276                            }
1277                            mPendingInstalls.clear();
1278                        }
1279                    }
1280                    break;
1281                }
1282                case MCS_UNBIND: {
1283                    // If there is no actual work left, then time to unbind.
1284                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1285
1286                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1287                        if (mBound) {
1288                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1289
1290                            disconnectService();
1291                        }
1292                    } else if (mPendingInstalls.size() > 0) {
1293                        // There are more pending requests in queue.
1294                        // Just post MCS_BOUND message to trigger processing
1295                        // of next pending install.
1296                        mHandler.sendEmptyMessage(MCS_BOUND);
1297                    }
1298
1299                    break;
1300                }
1301                case MCS_GIVE_UP: {
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1303                    HandlerParams params = mPendingInstalls.remove(0);
1304                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1305                            System.identityHashCode(params));
1306                    break;
1307                }
1308                case SEND_PENDING_BROADCAST: {
1309                    String packages[];
1310                    ArrayList<String> components[];
1311                    int size = 0;
1312                    int uids[];
1313                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1314                    synchronized (mPackages) {
1315                        if (mPendingBroadcasts == null) {
1316                            return;
1317                        }
1318                        size = mPendingBroadcasts.size();
1319                        if (size <= 0) {
1320                            // Nothing to be done. Just return
1321                            return;
1322                        }
1323                        packages = new String[size];
1324                        components = new ArrayList[size];
1325                        uids = new int[size];
1326                        int i = 0;  // filling out the above arrays
1327
1328                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1329                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1330                            Iterator<Map.Entry<String, ArrayList<String>>> it
1331                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1332                                            .entrySet().iterator();
1333                            while (it.hasNext() && i < size) {
1334                                Map.Entry<String, ArrayList<String>> ent = it.next();
1335                                packages[i] = ent.getKey();
1336                                components[i] = ent.getValue();
1337                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1338                                uids[i] = (ps != null)
1339                                        ? UserHandle.getUid(packageUserId, ps.appId)
1340                                        : -1;
1341                                i++;
1342                            }
1343                        }
1344                        size = i;
1345                        mPendingBroadcasts.clear();
1346                    }
1347                    // Send broadcasts
1348                    for (int i = 0; i < size; i++) {
1349                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1350                    }
1351                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1352                    break;
1353                }
1354                case START_CLEANING_PACKAGE: {
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356                    final String packageName = (String)msg.obj;
1357                    final int userId = msg.arg1;
1358                    final boolean andCode = msg.arg2 != 0;
1359                    synchronized (mPackages) {
1360                        if (userId == UserHandle.USER_ALL) {
1361                            int[] users = sUserManager.getUserIds();
1362                            for (int user : users) {
1363                                mSettings.addPackageToCleanLPw(
1364                                        new PackageCleanItem(user, packageName, andCode));
1365                            }
1366                        } else {
1367                            mSettings.addPackageToCleanLPw(
1368                                    new PackageCleanItem(userId, packageName, andCode));
1369                        }
1370                    }
1371                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1372                    startCleaningPackages();
1373                } break;
1374                case POST_INSTALL: {
1375                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1376
1377                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1378                    mRunningInstalls.delete(msg.arg1);
1379                    boolean deleteOld = false;
1380
1381                    if (data != null) {
1382                        InstallArgs args = data.args;
1383                        PackageInstalledInfo res = data.res;
1384
1385                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1386                            final String packageName = res.pkg.applicationInfo.packageName;
1387                            res.removedInfo.sendBroadcast(false, true, false);
1388                            Bundle extras = new Bundle(1);
1389                            extras.putInt(Intent.EXTRA_UID, res.uid);
1390
1391                            // Now that we successfully installed the package, grant runtime
1392                            // permissions if requested before broadcasting the install.
1393                            if ((args.installFlags
1394                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1395                                    && res.pkg.applicationInfo.targetSdkVersion
1396                                            >= Build.VERSION_CODES.M) {
1397                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1398                                        args.installGrantPermissions);
1399                            }
1400
1401                            synchronized (mPackages) {
1402                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1403                            }
1404
1405                            // Determine the set of users who are adding this
1406                            // package for the first time vs. those who are seeing
1407                            // an update.
1408                            int[] firstUsers;
1409                            int[] updateUsers = new int[0];
1410                            if (res.origUsers == null || res.origUsers.length == 0) {
1411                                firstUsers = res.newUsers;
1412                            } else {
1413                                firstUsers = new int[0];
1414                                for (int i=0; i<res.newUsers.length; i++) {
1415                                    int user = res.newUsers[i];
1416                                    boolean isNew = true;
1417                                    for (int j=0; j<res.origUsers.length; j++) {
1418                                        if (res.origUsers[j] == user) {
1419                                            isNew = false;
1420                                            break;
1421                                        }
1422                                    }
1423                                    if (isNew) {
1424                                        int[] newFirst = new int[firstUsers.length+1];
1425                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1426                                                firstUsers.length);
1427                                        newFirst[firstUsers.length] = user;
1428                                        firstUsers = newFirst;
1429                                    } else {
1430                                        int[] newUpdate = new int[updateUsers.length+1];
1431                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1432                                                updateUsers.length);
1433                                        newUpdate[updateUsers.length] = user;
1434                                        updateUsers = newUpdate;
1435                                    }
1436                                }
1437                            }
1438                            // don't broadcast for ephemeral installs/updates
1439                            final boolean isEphemeral = isEphemeral(res.pkg);
1440                            if (!isEphemeral) {
1441                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1442                                        extras, 0 /*flags*/, null /*targetPackage*/,
1443                                        null /*finishedReceiver*/, firstUsers);
1444                            }
1445                            final boolean update = res.removedInfo.removedPackage != null;
1446                            if (update) {
1447                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1448                            }
1449                            if (!isEphemeral) {
1450                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1451                                        extras, 0 /*flags*/, null /*targetPackage*/,
1452                                        null /*finishedReceiver*/, updateUsers);
1453                            }
1454                            if (update) {
1455                                if (!isEphemeral) {
1456                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1457                                            packageName, extras, 0 /*flags*/,
1458                                            null /*targetPackage*/, null /*finishedReceiver*/,
1459                                            updateUsers);
1460                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1461                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1462                                            packageName /*targetPackage*/,
1463                                            null /*finishedReceiver*/, updateUsers);
1464                                }
1465
1466                                // treat asec-hosted packages like removable media on upgrade
1467                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1468                                    if (DEBUG_INSTALL) {
1469                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1470                                                + " is ASEC-hosted -> AVAILABLE");
1471                                    }
1472                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1473                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1474                                    pkgList.add(packageName);
1475                                    sendResourcesChangedBroadcast(true, true,
1476                                            pkgList,uidArray, null);
1477                                }
1478                            }
1479                            if (res.removedInfo.args != null) {
1480                                // Remove the replaced package's older resources safely now
1481                                deleteOld = true;
1482                            }
1483
1484                            // If this app is a browser and it's newly-installed for some
1485                            // users, clear any default-browser state in those users
1486                            if (firstUsers.length > 0) {
1487                                // the app's nature doesn't depend on the user, so we can just
1488                                // check its browser nature in any user and generalize.
1489                                if (packageIsBrowser(packageName, firstUsers[0])) {
1490                                    synchronized (mPackages) {
1491                                        for (int userId : firstUsers) {
1492                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1493                                        }
1494                                    }
1495                                }
1496                            }
1497                            // Log current value of "unknown sources" setting
1498                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1499                                getUnknownSourcesSettings());
1500                        }
1501                        // Force a gc to clear up things
1502                        Runtime.getRuntime().gc();
1503                        // We delete after a gc for applications  on sdcard.
1504                        if (deleteOld) {
1505                            synchronized (mInstallLock) {
1506                                res.removedInfo.args.doPostDeleteLI(true);
1507                            }
1508                        }
1509                        if (args.observer != null) {
1510                            try {
1511                                Bundle extras = extrasForInstallResult(res);
1512                                args.observer.onPackageInstalled(res.name, res.returnCode,
1513                                        res.returnMsg, extras);
1514                            } catch (RemoteException e) {
1515                                Slog.i(TAG, "Observer no longer exists.");
1516                            }
1517                        }
1518                        if (args.traceMethod != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1520                                    args.traceCookie);
1521                        }
1522                        return;
1523                    } else {
1524                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1525                    }
1526
1527                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1528                } break;
1529                case UPDATED_MEDIA_STATUS: {
1530                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1531                    boolean reportStatus = msg.arg1 == 1;
1532                    boolean doGc = msg.arg2 == 1;
1533                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1534                    if (doGc) {
1535                        // Force a gc to clear up stale containers.
1536                        Runtime.getRuntime().gc();
1537                    }
1538                    if (msg.obj != null) {
1539                        @SuppressWarnings("unchecked")
1540                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1541                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1542                        // Unload containers
1543                        unloadAllContainers(args);
1544                    }
1545                    if (reportStatus) {
1546                        try {
1547                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1548                            PackageHelper.getMountService().finishMediaUpdate();
1549                        } catch (RemoteException e) {
1550                            Log.e(TAG, "MountService not running?");
1551                        }
1552                    }
1553                } break;
1554                case WRITE_SETTINGS: {
1555                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1556                    synchronized (mPackages) {
1557                        removeMessages(WRITE_SETTINGS);
1558                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1559                        mSettings.writeLPr();
1560                        mDirtyUsers.clear();
1561                    }
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1563                } break;
1564                case WRITE_PACKAGE_RESTRICTIONS: {
1565                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1566                    synchronized (mPackages) {
1567                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1568                        for (int userId : mDirtyUsers) {
1569                            mSettings.writePackageRestrictionsLPr(userId);
1570                        }
1571                        mDirtyUsers.clear();
1572                    }
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1574                } break;
1575                case CHECK_PENDING_VERIFICATION: {
1576                    final int verificationId = msg.arg1;
1577                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1578
1579                    if ((state != null) && !state.timeoutExtended()) {
1580                        final InstallArgs args = state.getInstallArgs();
1581                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1582
1583                        Slog.i(TAG, "Verification timed out for " + originUri);
1584                        mPendingVerification.remove(verificationId);
1585
1586                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1587
1588                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1589                            Slog.i(TAG, "Continuing with installation of " + originUri);
1590                            state.setVerifierResponse(Binder.getCallingUid(),
1591                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1592                            broadcastPackageVerified(verificationId, originUri,
1593                                    PackageManager.VERIFICATION_ALLOW,
1594                                    state.getInstallArgs().getUser());
1595                            try {
1596                                ret = args.copyApk(mContainerService, true);
1597                            } catch (RemoteException e) {
1598                                Slog.e(TAG, "Could not contact the ContainerService");
1599                            }
1600                        } else {
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    PackageManager.VERIFICATION_REJECT,
1603                                    state.getInstallArgs().getUser());
1604                        }
1605
1606                        Trace.asyncTraceEnd(
1607                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1608
1609                        processPendingInstall(args, ret);
1610                        mHandler.sendEmptyMessage(MCS_UNBIND);
1611                    }
1612                    break;
1613                }
1614                case PACKAGE_VERIFIED: {
1615                    final int verificationId = msg.arg1;
1616
1617                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1618                    if (state == null) {
1619                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1620                        break;
1621                    }
1622
1623                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1624
1625                    state.setVerifierResponse(response.callerUid, response.code);
1626
1627                    if (state.isVerificationComplete()) {
1628                        mPendingVerification.remove(verificationId);
1629
1630                        final InstallArgs args = state.getInstallArgs();
1631                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1632
1633                        int ret;
1634                        if (state.isInstallAllowed()) {
1635                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1636                            broadcastPackageVerified(verificationId, originUri,
1637                                    response.code, state.getInstallArgs().getUser());
1638                            try {
1639                                ret = args.copyApk(mContainerService, true);
1640                            } catch (RemoteException e) {
1641                                Slog.e(TAG, "Could not contact the ContainerService");
1642                            }
1643                        } else {
1644                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1645                        }
1646
1647                        Trace.asyncTraceEnd(
1648                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1649
1650                        processPendingInstall(args, ret);
1651                        mHandler.sendEmptyMessage(MCS_UNBIND);
1652                    }
1653
1654                    break;
1655                }
1656                case START_INTENT_FILTER_VERIFICATIONS: {
1657                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1658                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1659                            params.replacing, params.pkg);
1660                    break;
1661                }
1662                case INTENT_FILTER_VERIFIED: {
1663                    final int verificationId = msg.arg1;
1664
1665                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1666                            verificationId);
1667                    if (state == null) {
1668                        Slog.w(TAG, "Invalid IntentFilter verification token "
1669                                + verificationId + " received");
1670                        break;
1671                    }
1672
1673                    final int userId = state.getUserId();
1674
1675                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1676                            "Processing IntentFilter verification with token:"
1677                            + verificationId + " and userId:" + userId);
1678
1679                    final IntentFilterVerificationResponse response =
1680                            (IntentFilterVerificationResponse) msg.obj;
1681
1682                    state.setVerifierResponse(response.callerUid, response.code);
1683
1684                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1685                            "IntentFilter verification with token:" + verificationId
1686                            + " and userId:" + userId
1687                            + " is settings verifier response with response code:"
1688                            + response.code);
1689
1690                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1691                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1692                                + response.getFailedDomainsString());
1693                    }
1694
1695                    if (state.isVerificationComplete()) {
1696                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1697                    } else {
1698                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1699                                "IntentFilter verification with token:" + verificationId
1700                                + " was not said to be complete");
1701                    }
1702
1703                    break;
1704                }
1705            }
1706        }
1707    }
1708
1709    private StorageEventListener mStorageListener = new StorageEventListener() {
1710        @Override
1711        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1712            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1713                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1714                    final String volumeUuid = vol.getFsUuid();
1715
1716                    // Clean up any users or apps that were removed or recreated
1717                    // while this volume was missing
1718                    reconcileUsers(volumeUuid);
1719                    reconcileApps(volumeUuid);
1720
1721                    // Clean up any install sessions that expired or were
1722                    // cancelled while this volume was missing
1723                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1724
1725                    loadPrivatePackages(vol);
1726
1727                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1728                    unloadPrivatePackages(vol);
1729                }
1730            }
1731
1732            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1733                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1734                    updateExternalMediaStatus(true, false);
1735                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1736                    updateExternalMediaStatus(false, false);
1737                }
1738            }
1739        }
1740
1741        @Override
1742        public void onVolumeForgotten(String fsUuid) {
1743            if (TextUtils.isEmpty(fsUuid)) {
1744                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1745                return;
1746            }
1747
1748            // Remove any apps installed on the forgotten volume
1749            synchronized (mPackages) {
1750                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1751                for (PackageSetting ps : packages) {
1752                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1753                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1754                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1755                }
1756
1757                mSettings.onVolumeForgotten(fsUuid);
1758                mSettings.writeLPr();
1759            }
1760        }
1761    };
1762
1763    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1764            String[] grantedPermissions) {
1765        if (userId >= UserHandle.USER_SYSTEM) {
1766            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1767        } else if (userId == UserHandle.USER_ALL) {
1768            final int[] userIds;
1769            synchronized (mPackages) {
1770                userIds = UserManagerService.getInstance().getUserIds();
1771            }
1772            for (int someUserId : userIds) {
1773                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1774            }
1775        }
1776
1777        // We could have touched GID membership, so flush out packages.list
1778        synchronized (mPackages) {
1779            mSettings.writePackageListLPr();
1780        }
1781    }
1782
1783    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1784            String[] grantedPermissions) {
1785        SettingBase sb = (SettingBase) pkg.mExtras;
1786        if (sb == null) {
1787            return;
1788        }
1789
1790        PermissionsState permissionsState = sb.getPermissionsState();
1791
1792        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1793                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1794
1795        synchronized (mPackages) {
1796            for (String permission : pkg.requestedPermissions) {
1797                BasePermission bp = mSettings.mPermissions.get(permission);
1798                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1799                        && (grantedPermissions == null
1800                               || ArrayUtils.contains(grantedPermissions, permission))) {
1801                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1802                    // Installer cannot change immutable permissions.
1803                    if ((flags & immutableFlags) == 0) {
1804                        grantRuntimePermission(pkg.packageName, permission, userId);
1805                    }
1806                }
1807            }
1808        }
1809    }
1810
1811    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1812        Bundle extras = null;
1813        switch (res.returnCode) {
1814            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1815                extras = new Bundle();
1816                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1817                        res.origPermission);
1818                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1819                        res.origPackage);
1820                break;
1821            }
1822            case PackageManager.INSTALL_SUCCEEDED: {
1823                extras = new Bundle();
1824                extras.putBoolean(Intent.EXTRA_REPLACING,
1825                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1826                break;
1827            }
1828        }
1829        return extras;
1830    }
1831
1832    void scheduleWriteSettingsLocked() {
1833        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1834            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1835        }
1836    }
1837
1838    void scheduleWritePackageRestrictionsLocked(int userId) {
1839        if (!sUserManager.exists(userId)) return;
1840        mDirtyUsers.add(userId);
1841        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1842            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1843        }
1844    }
1845
1846    public static PackageManagerService main(Context context, Installer installer,
1847            boolean factoryTest, boolean onlyCore) {
1848        PackageManagerService m = new PackageManagerService(context, installer,
1849                factoryTest, onlyCore);
1850        m.enableSystemUserPackages();
1851        ServiceManager.addService("package", m);
1852        return m;
1853    }
1854
1855    private void enableSystemUserPackages() {
1856        if (!UserManager.isSplitSystemUser()) {
1857            return;
1858        }
1859        // For system user, enable apps based on the following conditions:
1860        // - app is whitelisted or belong to one of these groups:
1861        //   -- system app which has no launcher icons
1862        //   -- system app which has INTERACT_ACROSS_USERS permission
1863        //   -- system IME app
1864        // - app is not in the blacklist
1865        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1866        Set<String> enableApps = new ArraySet<>();
1867        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1868                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1869                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1870        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1871        enableApps.addAll(wlApps);
1872        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1873                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1874        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1875        enableApps.removeAll(blApps);
1876        Log.i(TAG, "Applications installed for system user: " + enableApps);
1877        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1878                UserHandle.SYSTEM);
1879        final int allAppsSize = allAps.size();
1880        synchronized (mPackages) {
1881            for (int i = 0; i < allAppsSize; i++) {
1882                String pName = allAps.get(i);
1883                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1884                // Should not happen, but we shouldn't be failing if it does
1885                if (pkgSetting == null) {
1886                    continue;
1887                }
1888                boolean install = enableApps.contains(pName);
1889                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1890                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1891                            + " for system user");
1892                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1893                }
1894            }
1895        }
1896    }
1897
1898    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1899        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1900                Context.DISPLAY_SERVICE);
1901        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1902    }
1903
1904    public PackageManagerService(Context context, Installer installer,
1905            boolean factoryTest, boolean onlyCore) {
1906        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1907                SystemClock.uptimeMillis());
1908
1909        if (mSdkVersion <= 0) {
1910            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1911        }
1912
1913        mContext = context;
1914        mFactoryTest = factoryTest;
1915        mOnlyCore = onlyCore;
1916        mMetrics = new DisplayMetrics();
1917        mSettings = new Settings(mPackages);
1918        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1919                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1920        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1921                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1922        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1923                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1924        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1929                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1930
1931        String separateProcesses = SystemProperties.get("debug.separate_processes");
1932        if (separateProcesses != null && separateProcesses.length() > 0) {
1933            if ("*".equals(separateProcesses)) {
1934                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1935                mSeparateProcesses = null;
1936                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1937            } else {
1938                mDefParseFlags = 0;
1939                mSeparateProcesses = separateProcesses.split(",");
1940                Slog.w(TAG, "Running with debug.separate_processes: "
1941                        + separateProcesses);
1942            }
1943        } else {
1944            mDefParseFlags = 0;
1945            mSeparateProcesses = null;
1946        }
1947
1948        mInstaller = installer;
1949        mPackageDexOptimizer = new PackageDexOptimizer(this);
1950        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1951
1952        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1953                FgThread.get().getLooper());
1954
1955        getDefaultDisplayMetrics(context, mMetrics);
1956
1957        SystemConfig systemConfig = SystemConfig.getInstance();
1958        mGlobalGids = systemConfig.getGlobalGids();
1959        mSystemPermissions = systemConfig.getSystemPermissions();
1960        mAvailableFeatures = systemConfig.getAvailableFeatures();
1961
1962        synchronized (mInstallLock) {
1963        // writer
1964        synchronized (mPackages) {
1965            mHandlerThread = new ServiceThread(TAG,
1966                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1967            mHandlerThread.start();
1968            mHandler = new PackageHandler(mHandlerThread.getLooper());
1969            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1970
1971            File dataDir = Environment.getDataDirectory();
1972            mAppInstallDir = new File(dataDir, "app");
1973            mAppLib32InstallDir = new File(dataDir, "app-lib");
1974            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1975            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1976            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1977
1978            sUserManager = new UserManagerService(context, this, mPackages);
1979
1980            // Propagate permission configuration in to package manager.
1981            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1982                    = systemConfig.getPermissions();
1983            for (int i=0; i<permConfig.size(); i++) {
1984                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1985                BasePermission bp = mSettings.mPermissions.get(perm.name);
1986                if (bp == null) {
1987                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1988                    mSettings.mPermissions.put(perm.name, bp);
1989                }
1990                if (perm.gids != null) {
1991                    bp.setGids(perm.gids, perm.perUser);
1992                }
1993            }
1994
1995            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1996            for (int i=0; i<libConfig.size(); i++) {
1997                mSharedLibraries.put(libConfig.keyAt(i),
1998                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1999            }
2000
2001            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2002
2003            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2004
2005            String customResolverActivity = Resources.getSystem().getString(
2006                    R.string.config_customResolverActivity);
2007            if (TextUtils.isEmpty(customResolverActivity)) {
2008                customResolverActivity = null;
2009            } else {
2010                mCustomResolverComponentName = ComponentName.unflattenFromString(
2011                        customResolverActivity);
2012            }
2013
2014            long startTime = SystemClock.uptimeMillis();
2015
2016            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2017                    startTime);
2018
2019            // Set flag to monitor and not change apk file paths when
2020            // scanning install directories.
2021            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2022
2023            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2024            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2025
2026            if (bootClassPath == null) {
2027                Slog.w(TAG, "No BOOTCLASSPATH found!");
2028            }
2029
2030            if (systemServerClassPath == null) {
2031                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2032            }
2033
2034            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2035            final String[] dexCodeInstructionSets =
2036                    getDexCodeInstructionSets(
2037                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2038
2039            /**
2040             * Ensure all external libraries have had dexopt run on them.
2041             */
2042            if (mSharedLibraries.size() > 0) {
2043                // NOTE: For now, we're compiling these system "shared libraries"
2044                // (and framework jars) into all available architectures. It's possible
2045                // to compile them only when we come across an app that uses them (there's
2046                // already logic for that in scanPackageLI) but that adds some complexity.
2047                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2048                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2049                        final String lib = libEntry.path;
2050                        if (lib == null) {
2051                            continue;
2052                        }
2053
2054                        try {
2055                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2056                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2057                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2058                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2059                            }
2060                        } catch (FileNotFoundException e) {
2061                            Slog.w(TAG, "Library not found: " + lib);
2062                        } catch (IOException e) {
2063                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2064                                    + e.getMessage());
2065                        }
2066                    }
2067                }
2068            }
2069
2070            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2071
2072            final VersionInfo ver = mSettings.getInternalVersion();
2073            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2074            // when upgrading from pre-M, promote system app permissions from install to runtime
2075            mPromoteSystemApps =
2076                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2077
2078            // save off the names of pre-existing system packages prior to scanning; we don't
2079            // want to automatically grant runtime permissions for new system apps
2080            if (mPromoteSystemApps) {
2081                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2082                while (pkgSettingIter.hasNext()) {
2083                    PackageSetting ps = pkgSettingIter.next();
2084                    if (isSystemApp(ps)) {
2085                        mExistingSystemPackages.add(ps.name);
2086                    }
2087                }
2088            }
2089
2090            // Collect vendor overlay packages.
2091            // (Do this before scanning any apps.)
2092            // For security and version matching reason, only consider
2093            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2094            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2095            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2096                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2097
2098            // Find base frameworks (resource packages without code).
2099            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2100                    | PackageParser.PARSE_IS_SYSTEM_DIR
2101                    | PackageParser.PARSE_IS_PRIVILEGED,
2102                    scanFlags | SCAN_NO_DEX, 0);
2103
2104            // Collected privileged system packages.
2105            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2106            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2107                    | PackageParser.PARSE_IS_SYSTEM_DIR
2108                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2109
2110            // Collect ordinary system packages.
2111            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2112            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2113                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2114
2115            // Collect all vendor packages.
2116            File vendorAppDir = new File("/vendor/app");
2117            try {
2118                vendorAppDir = vendorAppDir.getCanonicalFile();
2119            } catch (IOException e) {
2120                // failed to look up canonical path, continue with original one
2121            }
2122            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2123                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2124
2125            // Collect all OEM packages.
2126            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2127            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2128                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2129
2130            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2131            mInstaller.moveFiles();
2132
2133            // Prune any system packages that no longer exist.
2134            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2135            if (!mOnlyCore) {
2136                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2137                while (psit.hasNext()) {
2138                    PackageSetting ps = psit.next();
2139
2140                    /*
2141                     * If this is not a system app, it can't be a
2142                     * disable system app.
2143                     */
2144                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2145                        continue;
2146                    }
2147
2148                    /*
2149                     * If the package is scanned, it's not erased.
2150                     */
2151                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2152                    if (scannedPkg != null) {
2153                        /*
2154                         * If the system app is both scanned and in the
2155                         * disabled packages list, then it must have been
2156                         * added via OTA. Remove it from the currently
2157                         * scanned package so the previously user-installed
2158                         * application can be scanned.
2159                         */
2160                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2161                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2162                                    + ps.name + "; removing system app.  Last known codePath="
2163                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2164                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2165                                    + scannedPkg.mVersionCode);
2166                            removePackageLI(ps, true);
2167                            mExpectingBetter.put(ps.name, ps.codePath);
2168                        }
2169
2170                        continue;
2171                    }
2172
2173                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2174                        psit.remove();
2175                        logCriticalInfo(Log.WARN, "System package " + ps.name
2176                                + " no longer exists; wiping its data");
2177                        removeDataDirsLI(null, ps.name);
2178                    } else {
2179                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2180                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2181                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2182                        }
2183                    }
2184                }
2185            }
2186
2187            //look for any incomplete package installations
2188            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2189            //clean up list
2190            for(int i = 0; i < deletePkgsList.size(); i++) {
2191                //clean up here
2192                cleanupInstallFailedPackage(deletePkgsList.get(i));
2193            }
2194            //delete tmp files
2195            deleteTempPackageFiles();
2196
2197            // Remove any shared userIDs that have no associated packages
2198            mSettings.pruneSharedUsersLPw();
2199
2200            if (!mOnlyCore) {
2201                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2202                        SystemClock.uptimeMillis());
2203                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2204
2205                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2206                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2207
2208                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2209                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2210
2211                /**
2212                 * Remove disable package settings for any updated system
2213                 * apps that were removed via an OTA. If they're not a
2214                 * previously-updated app, remove them completely.
2215                 * Otherwise, just revoke their system-level permissions.
2216                 */
2217                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2218                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2219                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2220
2221                    String msg;
2222                    if (deletedPkg == null) {
2223                        msg = "Updated system package " + deletedAppName
2224                                + " no longer exists; wiping its data";
2225                        removeDataDirsLI(null, deletedAppName);
2226                    } else {
2227                        msg = "Updated system app + " + deletedAppName
2228                                + " no longer present; removing system privileges for "
2229                                + deletedAppName;
2230
2231                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2232
2233                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2234                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2235                    }
2236                    logCriticalInfo(Log.WARN, msg);
2237                }
2238
2239                /**
2240                 * Make sure all system apps that we expected to appear on
2241                 * the userdata partition actually showed up. If they never
2242                 * appeared, crawl back and revive the system version.
2243                 */
2244                for (int i = 0; i < mExpectingBetter.size(); i++) {
2245                    final String packageName = mExpectingBetter.keyAt(i);
2246                    if (!mPackages.containsKey(packageName)) {
2247                        final File scanFile = mExpectingBetter.valueAt(i);
2248
2249                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2250                                + " but never showed up; reverting to system");
2251
2252                        final int reparseFlags;
2253                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2254                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2255                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2256                                    | PackageParser.PARSE_IS_PRIVILEGED;
2257                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2258                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2259                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2260                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2261                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2262                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2263                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2264                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2265                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2266                        } else {
2267                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2268                            continue;
2269                        }
2270
2271                        mSettings.enableSystemPackageLPw(packageName);
2272
2273                        try {
2274                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2275                        } catch (PackageManagerException e) {
2276                            Slog.e(TAG, "Failed to parse original system package: "
2277                                    + e.getMessage());
2278                        }
2279                    }
2280                }
2281            }
2282            mExpectingBetter.clear();
2283
2284            // Now that we know all of the shared libraries, update all clients to have
2285            // the correct library paths.
2286            updateAllSharedLibrariesLPw();
2287
2288            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2289                // NOTE: We ignore potential failures here during a system scan (like
2290                // the rest of the commands above) because there's precious little we
2291                // can do about it. A settings error is reported, though.
2292                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2293                        false /* boot complete */);
2294            }
2295
2296            // Now that we know all the packages we are keeping,
2297            // read and update their last usage times.
2298            mPackageUsage.readLP();
2299
2300            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2301                    SystemClock.uptimeMillis());
2302            Slog.i(TAG, "Time to scan packages: "
2303                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2304                    + " seconds");
2305
2306            // If the platform SDK has changed since the last time we booted,
2307            // we need to re-grant app permission to catch any new ones that
2308            // appear.  This is really a hack, and means that apps can in some
2309            // cases get permissions that the user didn't initially explicitly
2310            // allow...  it would be nice to have some better way to handle
2311            // this situation.
2312            int updateFlags = UPDATE_PERMISSIONS_ALL;
2313            if (ver.sdkVersion != mSdkVersion) {
2314                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2315                        + mSdkVersion + "; regranting permissions for internal storage");
2316                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2317            }
2318            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2319            ver.sdkVersion = mSdkVersion;
2320
2321            // If this is the first boot or an update from pre-M, and it is a normal
2322            // boot, then we need to initialize the default preferred apps across
2323            // all defined users.
2324            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2325                for (UserInfo user : sUserManager.getUsers(true)) {
2326                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2327                    applyFactoryDefaultBrowserLPw(user.id);
2328                    primeDomainVerificationsLPw(user.id);
2329                }
2330            }
2331
2332            // If this is first boot after an OTA, and a normal boot, then
2333            // we need to clear code cache directories.
2334            if (mIsUpgrade && !onlyCore) {
2335                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2336                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2337                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2338                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2339                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2340                    }
2341                }
2342                ver.fingerprint = Build.FINGERPRINT;
2343            }
2344
2345            checkDefaultBrowser();
2346
2347            // clear only after permissions and other defaults have been updated
2348            mExistingSystemPackages.clear();
2349            mPromoteSystemApps = false;
2350
2351            // All the changes are done during package scanning.
2352            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2353
2354            // can downgrade to reader
2355            mSettings.writeLPr();
2356
2357            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2358                    SystemClock.uptimeMillis());
2359
2360            mRequiredVerifierPackage = getRequiredVerifierLPr();
2361            mRequiredInstallerPackage = getRequiredInstallerLPr();
2362
2363            mInstallerService = new PackageInstallerService(context, this);
2364
2365            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2366            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2367                    mIntentFilterVerifierComponent);
2368
2369            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2370            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2371            // both the installer and resolver must be present to enable ephemeral
2372            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2373                if (DEBUG_EPHEMERAL) {
2374                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2375                            + " installer:" + ephemeralInstallerComponent);
2376                }
2377                mEphemeralResolverComponent = ephemeralResolverComponent;
2378                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2379                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2380                mEphemeralResolverConnection =
2381                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2382            } else {
2383                if (DEBUG_EPHEMERAL) {
2384                    final String missingComponent =
2385                            (ephemeralResolverComponent == null)
2386                            ? (ephemeralInstallerComponent == null)
2387                                    ? "resolver and installer"
2388                                    : "resolver"
2389                            : "installer";
2390                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2391                }
2392                mEphemeralResolverComponent = null;
2393                mEphemeralInstallerComponent = null;
2394                mEphemeralResolverConnection = null;
2395            }
2396
2397            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2398        } // synchronized (mPackages)
2399        } // synchronized (mInstallLock)
2400
2401        // Now after opening every single application zip, make sure they
2402        // are all flushed.  Not really needed, but keeps things nice and
2403        // tidy.
2404        Runtime.getRuntime().gc();
2405
2406        // The initial scanning above does many calls into installd while
2407        // holding the mPackages lock, but we're mostly interested in yelling
2408        // once we have a booted system.
2409        mInstaller.setWarnIfHeld(mPackages);
2410
2411        // Expose private service for system components to use.
2412        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2413    }
2414
2415    @Override
2416    public boolean isFirstBoot() {
2417        return !mRestoredSettings;
2418    }
2419
2420    @Override
2421    public boolean isOnlyCoreApps() {
2422        return mOnlyCore;
2423    }
2424
2425    @Override
2426    public boolean isUpgrade() {
2427        return mIsUpgrade;
2428    }
2429
2430    private String getRequiredVerifierLPr() {
2431        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2432        // We only care about verifier that's installed under system user.
2433        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2434                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2435
2436        String requiredVerifier = null;
2437
2438        final int N = receivers.size();
2439        for (int i = 0; i < N; i++) {
2440            final ResolveInfo info = receivers.get(i);
2441
2442            if (info.activityInfo == null) {
2443                continue;
2444            }
2445
2446            final String packageName = info.activityInfo.packageName;
2447
2448            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2449                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2450                continue;
2451            }
2452
2453            if (requiredVerifier != null) {
2454                throw new RuntimeException("There can be only one required verifier");
2455            }
2456
2457            requiredVerifier = packageName;
2458        }
2459
2460        return requiredVerifier;
2461    }
2462
2463    private String getRequiredInstallerLPr() {
2464        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2465        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2466        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2467
2468        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2469                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2470
2471        String requiredInstaller = null;
2472
2473        final int N = installers.size();
2474        for (int i = 0; i < N; i++) {
2475            final ResolveInfo info = installers.get(i);
2476            final String packageName = info.activityInfo.packageName;
2477
2478            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2479                continue;
2480            }
2481
2482            if (requiredInstaller != null) {
2483                throw new RuntimeException("There must be one required installer");
2484            }
2485
2486            requiredInstaller = packageName;
2487        }
2488
2489        if (requiredInstaller == null) {
2490            throw new RuntimeException("There must be one required installer");
2491        }
2492
2493        return requiredInstaller;
2494    }
2495
2496    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2497        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2498        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2499                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2500
2501        ComponentName verifierComponentName = null;
2502
2503        int priority = -1000;
2504        final int N = receivers.size();
2505        for (int i = 0; i < N; i++) {
2506            final ResolveInfo info = receivers.get(i);
2507
2508            if (info.activityInfo == null) {
2509                continue;
2510            }
2511
2512            final String packageName = info.activityInfo.packageName;
2513
2514            final PackageSetting ps = mSettings.mPackages.get(packageName);
2515            if (ps == null) {
2516                continue;
2517            }
2518
2519            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2520                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2521                continue;
2522            }
2523
2524            // Select the IntentFilterVerifier with the highest priority
2525            if (priority < info.priority) {
2526                priority = info.priority;
2527                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2528                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2529                        + verifierComponentName + " with priority: " + info.priority);
2530            }
2531        }
2532
2533        return verifierComponentName;
2534    }
2535
2536    private ComponentName getEphemeralResolverLPr() {
2537        final String[] packageArray =
2538                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2539        if (packageArray.length == 0) {
2540            if (DEBUG_EPHEMERAL) {
2541                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2542            }
2543            return null;
2544        }
2545
2546        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2547        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2548                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2549
2550        final int N = resolvers.size();
2551        if (N == 0) {
2552            if (DEBUG_EPHEMERAL) {
2553                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2554            }
2555            return null;
2556        }
2557
2558        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2559        for (int i = 0; i < N; i++) {
2560            final ResolveInfo info = resolvers.get(i);
2561
2562            if (info.serviceInfo == null) {
2563                continue;
2564            }
2565
2566            final String packageName = info.serviceInfo.packageName;
2567            if (!possiblePackages.contains(packageName)) {
2568                if (DEBUG_EPHEMERAL) {
2569                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2570                            + " pkg: " + packageName + ", info:" + info);
2571                }
2572                continue;
2573            }
2574
2575            if (DEBUG_EPHEMERAL) {
2576                Slog.v(TAG, "Ephemeral resolver found;"
2577                        + " pkg: " + packageName + ", info:" + info);
2578            }
2579            return new ComponentName(packageName, info.serviceInfo.name);
2580        }
2581        if (DEBUG_EPHEMERAL) {
2582            Slog.v(TAG, "Ephemeral resolver NOT found");
2583        }
2584        return null;
2585    }
2586
2587    private ComponentName getEphemeralInstallerLPr() {
2588        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2589        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2590        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2591        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2592                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2593
2594        ComponentName ephemeralInstaller = null;
2595
2596        final int N = installers.size();
2597        for (int i = 0; i < N; i++) {
2598            final ResolveInfo info = installers.get(i);
2599            final String packageName = info.activityInfo.packageName;
2600
2601            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2602                if (DEBUG_EPHEMERAL) {
2603                    Slog.d(TAG, "Ephemeral installer is not system app;"
2604                            + " pkg: " + packageName + ", info:" + info);
2605                }
2606                continue;
2607            }
2608
2609            if (ephemeralInstaller != null) {
2610                throw new RuntimeException("There must only be one ephemeral installer");
2611            }
2612
2613            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2614        }
2615
2616        return ephemeralInstaller;
2617    }
2618
2619    private void primeDomainVerificationsLPw(int userId) {
2620        if (DEBUG_DOMAIN_VERIFICATION) {
2621            Slog.d(TAG, "Priming domain verifications in user " + userId);
2622        }
2623
2624        SystemConfig systemConfig = SystemConfig.getInstance();
2625        ArraySet<String> packages = systemConfig.getLinkedApps();
2626        ArraySet<String> domains = new ArraySet<String>();
2627
2628        for (String packageName : packages) {
2629            PackageParser.Package pkg = mPackages.get(packageName);
2630            if (pkg != null) {
2631                if (!pkg.isSystemApp()) {
2632                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2633                    continue;
2634                }
2635
2636                domains.clear();
2637                for (PackageParser.Activity a : pkg.activities) {
2638                    for (ActivityIntentInfo filter : a.intents) {
2639                        if (hasValidDomains(filter)) {
2640                            domains.addAll(filter.getHostsList());
2641                        }
2642                    }
2643                }
2644
2645                if (domains.size() > 0) {
2646                    if (DEBUG_DOMAIN_VERIFICATION) {
2647                        Slog.v(TAG, "      + " + packageName);
2648                    }
2649                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2650                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2651                    // and then 'always' in the per-user state actually used for intent resolution.
2652                    final IntentFilterVerificationInfo ivi;
2653                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2654                            new ArrayList<String>(domains));
2655                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2656                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2657                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2658                } else {
2659                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2660                            + "' does not handle web links");
2661                }
2662            } else {
2663                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2664            }
2665        }
2666
2667        scheduleWritePackageRestrictionsLocked(userId);
2668        scheduleWriteSettingsLocked();
2669    }
2670
2671    private void applyFactoryDefaultBrowserLPw(int userId) {
2672        // The default browser app's package name is stored in a string resource,
2673        // with a product-specific overlay used for vendor customization.
2674        String browserPkg = mContext.getResources().getString(
2675                com.android.internal.R.string.default_browser);
2676        if (!TextUtils.isEmpty(browserPkg)) {
2677            // non-empty string => required to be a known package
2678            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2679            if (ps == null) {
2680                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2681                browserPkg = null;
2682            } else {
2683                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2684            }
2685        }
2686
2687        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2688        // default.  If there's more than one, just leave everything alone.
2689        if (browserPkg == null) {
2690            calculateDefaultBrowserLPw(userId);
2691        }
2692    }
2693
2694    private void calculateDefaultBrowserLPw(int userId) {
2695        List<String> allBrowsers = resolveAllBrowserApps(userId);
2696        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2697        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2698    }
2699
2700    private List<String> resolveAllBrowserApps(int userId) {
2701        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2702        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2703                PackageManager.MATCH_ALL, userId);
2704
2705        final int count = list.size();
2706        List<String> result = new ArrayList<String>(count);
2707        for (int i=0; i<count; i++) {
2708            ResolveInfo info = list.get(i);
2709            if (info.activityInfo == null
2710                    || !info.handleAllWebDataURI
2711                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2712                    || result.contains(info.activityInfo.packageName)) {
2713                continue;
2714            }
2715            result.add(info.activityInfo.packageName);
2716        }
2717
2718        return result;
2719    }
2720
2721    private boolean packageIsBrowser(String packageName, int userId) {
2722        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2723                PackageManager.MATCH_ALL, userId);
2724        final int N = list.size();
2725        for (int i = 0; i < N; i++) {
2726            ResolveInfo info = list.get(i);
2727            if (packageName.equals(info.activityInfo.packageName)) {
2728                return true;
2729            }
2730        }
2731        return false;
2732    }
2733
2734    private void checkDefaultBrowser() {
2735        final int myUserId = UserHandle.myUserId();
2736        final String packageName = getDefaultBrowserPackageName(myUserId);
2737        if (packageName != null) {
2738            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2739            if (info == null) {
2740                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2741                synchronized (mPackages) {
2742                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2743                }
2744            }
2745        }
2746    }
2747
2748    @Override
2749    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2750            throws RemoteException {
2751        try {
2752            return super.onTransact(code, data, reply, flags);
2753        } catch (RuntimeException e) {
2754            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2755                Slog.wtf(TAG, "Package Manager Crash", e);
2756            }
2757            throw e;
2758        }
2759    }
2760
2761    void cleanupInstallFailedPackage(PackageSetting ps) {
2762        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2763
2764        removeDataDirsLI(ps.volumeUuid, ps.name);
2765        if (ps.codePath != null) {
2766            if (ps.codePath.isDirectory()) {
2767                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2768            } else {
2769                ps.codePath.delete();
2770            }
2771        }
2772        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2773            if (ps.resourcePath.isDirectory()) {
2774                FileUtils.deleteContents(ps.resourcePath);
2775            }
2776            ps.resourcePath.delete();
2777        }
2778        mSettings.removePackageLPw(ps.name);
2779    }
2780
2781    static int[] appendInts(int[] cur, int[] add) {
2782        if (add == null) return cur;
2783        if (cur == null) return add;
2784        final int N = add.length;
2785        for (int i=0; i<N; i++) {
2786            cur = appendInt(cur, add[i]);
2787        }
2788        return cur;
2789    }
2790
2791    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2792        if (!sUserManager.exists(userId)) return null;
2793        final PackageSetting ps = (PackageSetting) p.mExtras;
2794        if (ps == null) {
2795            return null;
2796        }
2797
2798        final PermissionsState permissionsState = ps.getPermissionsState();
2799
2800        final int[] gids = permissionsState.computeGids(userId);
2801        final Set<String> permissions = permissionsState.getPermissions(userId);
2802        final PackageUserState state = ps.readUserState(userId);
2803
2804        return PackageParser.generatePackageInfo(p, gids, flags,
2805                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2806    }
2807
2808    @Override
2809    public void checkPackageStartable(String packageName, int userId) {
2810        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2811
2812        synchronized (mPackages) {
2813            final PackageSetting ps = mSettings.mPackages.get(packageName);
2814            if (ps == null) {
2815                throw new SecurityException("Package " + packageName + " was not found!");
2816            }
2817
2818            if (ps.frozen) {
2819                throw new SecurityException("Package " + packageName + " is currently frozen!");
2820            }
2821
2822            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2823                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2824                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2825            }
2826        }
2827    }
2828
2829    @Override
2830    public boolean isPackageAvailable(String packageName, int userId) {
2831        if (!sUserManager.exists(userId)) return false;
2832        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2833        synchronized (mPackages) {
2834            PackageParser.Package p = mPackages.get(packageName);
2835            if (p != null) {
2836                final PackageSetting ps = (PackageSetting) p.mExtras;
2837                if (ps != null) {
2838                    final PackageUserState state = ps.readUserState(userId);
2839                    if (state != null) {
2840                        return PackageParser.isAvailable(state);
2841                    }
2842                }
2843            }
2844        }
2845        return false;
2846    }
2847
2848    @Override
2849    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2852        // reader
2853        synchronized (mPackages) {
2854            PackageParser.Package p = mPackages.get(packageName);
2855            if (DEBUG_PACKAGE_INFO)
2856                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2857            if (p != null) {
2858                return generatePackageInfo(p, flags, userId);
2859            }
2860            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2861                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2862            }
2863        }
2864        return null;
2865    }
2866
2867    @Override
2868    public String[] currentToCanonicalPackageNames(String[] names) {
2869        String[] out = new String[names.length];
2870        // reader
2871        synchronized (mPackages) {
2872            for (int i=names.length-1; i>=0; i--) {
2873                PackageSetting ps = mSettings.mPackages.get(names[i]);
2874                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2875            }
2876        }
2877        return out;
2878    }
2879
2880    @Override
2881    public String[] canonicalToCurrentPackageNames(String[] names) {
2882        String[] out = new String[names.length];
2883        // reader
2884        synchronized (mPackages) {
2885            for (int i=names.length-1; i>=0; i--) {
2886                String cur = mSettings.mRenamedPackages.get(names[i]);
2887                out[i] = cur != null ? cur : names[i];
2888            }
2889        }
2890        return out;
2891    }
2892
2893    @Override
2894    public int getPackageUid(String packageName, int userId) {
2895        return getPackageUidEtc(packageName, 0, userId);
2896    }
2897
2898    @Override
2899    public int getPackageUidEtc(String packageName, int flags, int userId) {
2900        if (!sUserManager.exists(userId)) return -1;
2901        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2902
2903        // reader
2904        synchronized (mPackages) {
2905            final PackageParser.Package p = mPackages.get(packageName);
2906            if (p != null) {
2907                return UserHandle.getUid(userId, p.applicationInfo.uid);
2908            }
2909            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2910                final PackageSetting ps = mSettings.mPackages.get(packageName);
2911                if (ps != null) {
2912                    return UserHandle.getUid(userId, ps.appId);
2913                }
2914            }
2915        }
2916
2917        return -1;
2918    }
2919
2920    @Override
2921    public int[] getPackageGids(String packageName, int userId) {
2922        return getPackageGidsEtc(packageName, 0, userId);
2923    }
2924
2925    @Override
2926    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2927        if (!sUserManager.exists(userId)) {
2928            return null;
2929        }
2930
2931        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2932                "getPackageGids");
2933
2934        // reader
2935        synchronized (mPackages) {
2936            final PackageParser.Package p = mPackages.get(packageName);
2937            if (p != null) {
2938                PackageSetting ps = (PackageSetting) p.mExtras;
2939                return ps.getPermissionsState().computeGids(userId);
2940            }
2941            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2942                final PackageSetting ps = mSettings.mPackages.get(packageName);
2943                if (ps != null) {
2944                    return ps.getPermissionsState().computeGids(userId);
2945                }
2946            }
2947        }
2948
2949        return null;
2950    }
2951
2952    static PermissionInfo generatePermissionInfo(
2953            BasePermission bp, int flags) {
2954        if (bp.perm != null) {
2955            return PackageParser.generatePermissionInfo(bp.perm, flags);
2956        }
2957        PermissionInfo pi = new PermissionInfo();
2958        pi.name = bp.name;
2959        pi.packageName = bp.sourcePackage;
2960        pi.nonLocalizedLabel = bp.name;
2961        pi.protectionLevel = bp.protectionLevel;
2962        return pi;
2963    }
2964
2965    @Override
2966    public PermissionInfo getPermissionInfo(String name, int flags) {
2967        // reader
2968        synchronized (mPackages) {
2969            final BasePermission p = mSettings.mPermissions.get(name);
2970            if (p != null) {
2971                return generatePermissionInfo(p, flags);
2972            }
2973            return null;
2974        }
2975    }
2976
2977    @Override
2978    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2979        // reader
2980        synchronized (mPackages) {
2981            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2982            for (BasePermission p : mSettings.mPermissions.values()) {
2983                if (group == null) {
2984                    if (p.perm == null || p.perm.info.group == null) {
2985                        out.add(generatePermissionInfo(p, flags));
2986                    }
2987                } else {
2988                    if (p.perm != null && group.equals(p.perm.info.group)) {
2989                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2990                    }
2991                }
2992            }
2993
2994            if (out.size() > 0) {
2995                return out;
2996            }
2997            return mPermissionGroups.containsKey(group) ? out : null;
2998        }
2999    }
3000
3001    @Override
3002    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3003        // reader
3004        synchronized (mPackages) {
3005            return PackageParser.generatePermissionGroupInfo(
3006                    mPermissionGroups.get(name), flags);
3007        }
3008    }
3009
3010    @Override
3011    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3012        // reader
3013        synchronized (mPackages) {
3014            final int N = mPermissionGroups.size();
3015            ArrayList<PermissionGroupInfo> out
3016                    = new ArrayList<PermissionGroupInfo>(N);
3017            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3018                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3019            }
3020            return out;
3021        }
3022    }
3023
3024    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3025            int userId) {
3026        if (!sUserManager.exists(userId)) return null;
3027        PackageSetting ps = mSettings.mPackages.get(packageName);
3028        if (ps != null) {
3029            if (ps.pkg == null) {
3030                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3031                        flags, userId);
3032                if (pInfo != null) {
3033                    return pInfo.applicationInfo;
3034                }
3035                return null;
3036            }
3037            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3038                    ps.readUserState(userId), userId);
3039        }
3040        return null;
3041    }
3042
3043    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3044            int userId) {
3045        if (!sUserManager.exists(userId)) return null;
3046        PackageSetting ps = mSettings.mPackages.get(packageName);
3047        if (ps != null) {
3048            PackageParser.Package pkg = ps.pkg;
3049            if (pkg == null) {
3050                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3051                    return null;
3052                }
3053                // Only data remains, so we aren't worried about code paths
3054                pkg = new PackageParser.Package(packageName);
3055                pkg.applicationInfo.packageName = packageName;
3056                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3057                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3058                pkg.applicationInfo.uid = ps.appId;
3059                pkg.applicationInfo.initForUser(userId);
3060                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3061                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3062            }
3063            return generatePackageInfo(pkg, flags, userId);
3064        }
3065        return null;
3066    }
3067
3068    @Override
3069    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3070        if (!sUserManager.exists(userId)) return null;
3071        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3072        // writer
3073        synchronized (mPackages) {
3074            PackageParser.Package p = mPackages.get(packageName);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                    TAG, "getApplicationInfo " + packageName
3077                    + ": " + p);
3078            if (p != null) {
3079                PackageSetting ps = mSettings.mPackages.get(packageName);
3080                if (ps == null) return null;
3081                // Note: isEnabledLP() does not apply here - always return info
3082                return PackageParser.generateApplicationInfo(
3083                        p, flags, ps.readUserState(userId), userId);
3084            }
3085            if ("android".equals(packageName)||"system".equals(packageName)) {
3086                return mAndroidApplication;
3087            }
3088            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3089                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3090            }
3091        }
3092        return null;
3093    }
3094
3095    @Override
3096    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3097            final IPackageDataObserver observer) {
3098        mContext.enforceCallingOrSelfPermission(
3099                android.Manifest.permission.CLEAR_APP_CACHE, null);
3100        // Queue up an async operation since clearing cache may take a little while.
3101        mHandler.post(new Runnable() {
3102            public void run() {
3103                mHandler.removeCallbacks(this);
3104                int retCode = -1;
3105                synchronized (mInstallLock) {
3106                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3107                    if (retCode < 0) {
3108                        Slog.w(TAG, "Couldn't clear application caches");
3109                    }
3110                }
3111                if (observer != null) {
3112                    try {
3113                        observer.onRemoveCompleted(null, (retCode >= 0));
3114                    } catch (RemoteException e) {
3115                        Slog.w(TAG, "RemoveException when invoking call back");
3116                    }
3117                }
3118            }
3119        });
3120    }
3121
3122    @Override
3123    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3124            final IntentSender pi) {
3125        mContext.enforceCallingOrSelfPermission(
3126                android.Manifest.permission.CLEAR_APP_CACHE, null);
3127        // Queue up an async operation since clearing cache may take a little while.
3128        mHandler.post(new Runnable() {
3129            public void run() {
3130                mHandler.removeCallbacks(this);
3131                int retCode = -1;
3132                synchronized (mInstallLock) {
3133                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3134                    if (retCode < 0) {
3135                        Slog.w(TAG, "Couldn't clear application caches");
3136                    }
3137                }
3138                if(pi != null) {
3139                    try {
3140                        // Callback via pending intent
3141                        int code = (retCode >= 0) ? 1 : 0;
3142                        pi.sendIntent(null, code, null,
3143                                null, null);
3144                    } catch (SendIntentException e1) {
3145                        Slog.i(TAG, "Failed to send pending intent");
3146                    }
3147                }
3148            }
3149        });
3150    }
3151
3152    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3153        synchronized (mInstallLock) {
3154            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3155                throw new IOException("Failed to free enough space");
3156            }
3157        }
3158    }
3159
3160    /**
3161     * Return if the user key is currently unlocked.
3162     */
3163    private boolean isUserKeyUnlocked(int userId) {
3164        if (StorageManager.isFileBasedEncryptionEnabled()) {
3165            final IMountService mount = IMountService.Stub
3166                    .asInterface(ServiceManager.getService("mount"));
3167            if (mount == null) {
3168                Slog.w(TAG, "Early during boot, assuming locked");
3169                return false;
3170            }
3171            final long token = Binder.clearCallingIdentity();
3172            try {
3173                return mount.isUserKeyUnlocked(userId);
3174            } catch (RemoteException e) {
3175                throw e.rethrowAsRuntimeException();
3176            } finally {
3177                Binder.restoreCallingIdentity(token);
3178            }
3179        } else {
3180            return true;
3181        }
3182    }
3183
3184    /**
3185     * Augment the given flags depending on current user running state. This is
3186     * purposefully done before acquiring {@link #mPackages} lock.
3187     */
3188    private int augmentFlagsForUser(int flags, int userId, Object cookie) {
3189        if (cookie instanceof Intent) {
3190            // If intent claims to be triaged, then we're fine with default
3191            // matching behavior below
3192            final Intent intent = (Intent) cookie;
3193            if ((intent.getFlags() & Intent.FLAG_DEBUG_ENCRYPTION_TRIAGED) != 0) {
3194                flags |= PackageManager.MATCH_ENCRYPTION_DEFAULT;
3195            }
3196        }
3197
3198        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE_ONLY
3199                | PackageManager.MATCH_ENCRYPTION_AWARE_ONLY)) != 0) {
3200            // Caller expressed an opinion about what components they want to
3201            // see, so fall through and give them what they want
3202        } else {
3203            // Caller expressed no opinion, so match based on user state
3204            if (isUserKeyUnlocked(userId)) {
3205                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3206            } else {
3207                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3208
3209                // If we have a system caller that hasn't done their homework to
3210                // decide they want this default behavior, yell at them
3211                if (DEBUG_ENCRYPTION_AWARE && (Binder.getCallingUid() == Process.SYSTEM_UID)
3212                        && ((flags & PackageManager.MATCH_ENCRYPTION_DEFAULT) == 0)) {
3213                    Log.v(TAG, "Caller hasn't been triaged for FBE; they asked about " + cookie,
3214                            new Throwable());
3215                }
3216            }
3217        }
3218        return flags;
3219    }
3220
3221    @Override
3222    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3223        if (!sUserManager.exists(userId)) return null;
3224        flags = augmentFlagsForUser(flags, userId, component);
3225        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3226        synchronized (mPackages) {
3227            PackageParser.Activity a = mActivities.mActivities.get(component);
3228
3229            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3230            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3231                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3232                if (ps == null) return null;
3233                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3234                        userId);
3235            }
3236            if (mResolveComponentName.equals(component)) {
3237                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3238                        new PackageUserState(), userId);
3239            }
3240        }
3241        return null;
3242    }
3243
3244    @Override
3245    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3246            String resolvedType) {
3247        synchronized (mPackages) {
3248            if (component.equals(mResolveComponentName)) {
3249                // The resolver supports EVERYTHING!
3250                return true;
3251            }
3252            PackageParser.Activity a = mActivities.mActivities.get(component);
3253            if (a == null) {
3254                return false;
3255            }
3256            for (int i=0; i<a.intents.size(); i++) {
3257                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3258                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3259                    return true;
3260                }
3261            }
3262            return false;
3263        }
3264    }
3265
3266    @Override
3267    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3268        if (!sUserManager.exists(userId)) return null;
3269        flags = augmentFlagsForUser(flags, userId, component);
3270        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3271        synchronized (mPackages) {
3272            PackageParser.Activity a = mReceivers.mActivities.get(component);
3273            if (DEBUG_PACKAGE_INFO) Log.v(
3274                TAG, "getReceiverInfo " + component + ": " + a);
3275            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3276                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3277                if (ps == null) return null;
3278                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3279                        userId);
3280            }
3281        }
3282        return null;
3283    }
3284
3285    @Override
3286    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3287        if (!sUserManager.exists(userId)) return null;
3288        flags = augmentFlagsForUser(flags, userId, component);
3289        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3290        synchronized (mPackages) {
3291            PackageParser.Service s = mServices.mServices.get(component);
3292            if (DEBUG_PACKAGE_INFO) Log.v(
3293                TAG, "getServiceInfo " + component + ": " + s);
3294            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3296                if (ps == null) return null;
3297                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3298                        userId);
3299            }
3300        }
3301        return null;
3302    }
3303
3304    @Override
3305    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3306        if (!sUserManager.exists(userId)) return null;
3307        flags = augmentFlagsForUser(flags, userId, component);
3308        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3309        synchronized (mPackages) {
3310            PackageParser.Provider p = mProviders.mProviders.get(component);
3311            if (DEBUG_PACKAGE_INFO) Log.v(
3312                TAG, "getProviderInfo " + component + ": " + p);
3313            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3314                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3315                if (ps == null) return null;
3316                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3317                        userId);
3318            }
3319        }
3320        return null;
3321    }
3322
3323    @Override
3324    public String[] getSystemSharedLibraryNames() {
3325        Set<String> libSet;
3326        synchronized (mPackages) {
3327            libSet = mSharedLibraries.keySet();
3328            int size = libSet.size();
3329            if (size > 0) {
3330                String[] libs = new String[size];
3331                libSet.toArray(libs);
3332                return libs;
3333            }
3334        }
3335        return null;
3336    }
3337
3338    /**
3339     * @hide
3340     */
3341    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3342        synchronized (mPackages) {
3343            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3344            if (lib != null && lib.apk != null) {
3345                return mPackages.get(lib.apk);
3346            }
3347        }
3348        return null;
3349    }
3350
3351    @Override
3352    public FeatureInfo[] getSystemAvailableFeatures() {
3353        Collection<FeatureInfo> featSet;
3354        synchronized (mPackages) {
3355            featSet = mAvailableFeatures.values();
3356            int size = featSet.size();
3357            if (size > 0) {
3358                FeatureInfo[] features = new FeatureInfo[size+1];
3359                featSet.toArray(features);
3360                FeatureInfo fi = new FeatureInfo();
3361                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3362                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3363                features[size] = fi;
3364                return features;
3365            }
3366        }
3367        return null;
3368    }
3369
3370    @Override
3371    public boolean hasSystemFeature(String name) {
3372        synchronized (mPackages) {
3373            return mAvailableFeatures.containsKey(name);
3374        }
3375    }
3376
3377    @Override
3378    public int checkPermission(String permName, String pkgName, int userId) {
3379        if (!sUserManager.exists(userId)) {
3380            return PackageManager.PERMISSION_DENIED;
3381        }
3382
3383        synchronized (mPackages) {
3384            final PackageParser.Package p = mPackages.get(pkgName);
3385            if (p != null && p.mExtras != null) {
3386                final PackageSetting ps = (PackageSetting) p.mExtras;
3387                final PermissionsState permissionsState = ps.getPermissionsState();
3388                if (permissionsState.hasPermission(permName, userId)) {
3389                    return PackageManager.PERMISSION_GRANTED;
3390                }
3391                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3392                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3393                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3394                    return PackageManager.PERMISSION_GRANTED;
3395                }
3396            }
3397        }
3398
3399        return PackageManager.PERMISSION_DENIED;
3400    }
3401
3402    @Override
3403    public int checkUidPermission(String permName, int uid) {
3404        final int userId = UserHandle.getUserId(uid);
3405
3406        if (!sUserManager.exists(userId)) {
3407            return PackageManager.PERMISSION_DENIED;
3408        }
3409
3410        synchronized (mPackages) {
3411            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3412            if (obj != null) {
3413                final SettingBase ps = (SettingBase) obj;
3414                final PermissionsState permissionsState = ps.getPermissionsState();
3415                if (permissionsState.hasPermission(permName, userId)) {
3416                    return PackageManager.PERMISSION_GRANTED;
3417                }
3418                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3419                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3420                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3421                    return PackageManager.PERMISSION_GRANTED;
3422                }
3423            } else {
3424                ArraySet<String> perms = mSystemPermissions.get(uid);
3425                if (perms != null) {
3426                    if (perms.contains(permName)) {
3427                        return PackageManager.PERMISSION_GRANTED;
3428                    }
3429                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3430                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3431                        return PackageManager.PERMISSION_GRANTED;
3432                    }
3433                }
3434            }
3435        }
3436
3437        return PackageManager.PERMISSION_DENIED;
3438    }
3439
3440    @Override
3441    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3442        if (UserHandle.getCallingUserId() != userId) {
3443            mContext.enforceCallingPermission(
3444                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3445                    "isPermissionRevokedByPolicy for user " + userId);
3446        }
3447
3448        if (checkPermission(permission, packageName, userId)
3449                == PackageManager.PERMISSION_GRANTED) {
3450            return false;
3451        }
3452
3453        final long identity = Binder.clearCallingIdentity();
3454        try {
3455            final int flags = getPermissionFlags(permission, packageName, userId);
3456            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3457        } finally {
3458            Binder.restoreCallingIdentity(identity);
3459        }
3460    }
3461
3462    @Override
3463    public String getPermissionControllerPackageName() {
3464        synchronized (mPackages) {
3465            return mRequiredInstallerPackage;
3466        }
3467    }
3468
3469    /**
3470     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3471     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3472     * @param checkShell TODO(yamasani):
3473     * @param message the message to log on security exception
3474     */
3475    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3476            boolean checkShell, String message) {
3477        if (userId < 0) {
3478            throw new IllegalArgumentException("Invalid userId " + userId);
3479        }
3480        if (checkShell) {
3481            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3482        }
3483        if (userId == UserHandle.getUserId(callingUid)) return;
3484        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3485            if (requireFullPermission) {
3486                mContext.enforceCallingOrSelfPermission(
3487                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3488            } else {
3489                try {
3490                    mContext.enforceCallingOrSelfPermission(
3491                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3492                } catch (SecurityException se) {
3493                    mContext.enforceCallingOrSelfPermission(
3494                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3495                }
3496            }
3497        }
3498    }
3499
3500    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3501        if (callingUid == Process.SHELL_UID) {
3502            if (userHandle >= 0
3503                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3504                throw new SecurityException("Shell does not have permission to access user "
3505                        + userHandle);
3506            } else if (userHandle < 0) {
3507                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3508                        + Debug.getCallers(3));
3509            }
3510        }
3511    }
3512
3513    private BasePermission findPermissionTreeLP(String permName) {
3514        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3515            if (permName.startsWith(bp.name) &&
3516                    permName.length() > bp.name.length() &&
3517                    permName.charAt(bp.name.length()) == '.') {
3518                return bp;
3519            }
3520        }
3521        return null;
3522    }
3523
3524    private BasePermission checkPermissionTreeLP(String permName) {
3525        if (permName != null) {
3526            BasePermission bp = findPermissionTreeLP(permName);
3527            if (bp != null) {
3528                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3529                    return bp;
3530                }
3531                throw new SecurityException("Calling uid "
3532                        + Binder.getCallingUid()
3533                        + " is not allowed to add to permission tree "
3534                        + bp.name + " owned by uid " + bp.uid);
3535            }
3536        }
3537        throw new SecurityException("No permission tree found for " + permName);
3538    }
3539
3540    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3541        if (s1 == null) {
3542            return s2 == null;
3543        }
3544        if (s2 == null) {
3545            return false;
3546        }
3547        if (s1.getClass() != s2.getClass()) {
3548            return false;
3549        }
3550        return s1.equals(s2);
3551    }
3552
3553    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3554        if (pi1.icon != pi2.icon) return false;
3555        if (pi1.logo != pi2.logo) return false;
3556        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3557        if (!compareStrings(pi1.name, pi2.name)) return false;
3558        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3559        // We'll take care of setting this one.
3560        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3561        // These are not currently stored in settings.
3562        //if (!compareStrings(pi1.group, pi2.group)) return false;
3563        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3564        //if (pi1.labelRes != pi2.labelRes) return false;
3565        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3566        return true;
3567    }
3568
3569    int permissionInfoFootprint(PermissionInfo info) {
3570        int size = info.name.length();
3571        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3572        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3573        return size;
3574    }
3575
3576    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3577        int size = 0;
3578        for (BasePermission perm : mSettings.mPermissions.values()) {
3579            if (perm.uid == tree.uid) {
3580                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3581            }
3582        }
3583        return size;
3584    }
3585
3586    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3587        // We calculate the max size of permissions defined by this uid and throw
3588        // if that plus the size of 'info' would exceed our stated maximum.
3589        if (tree.uid != Process.SYSTEM_UID) {
3590            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3591            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3592                throw new SecurityException("Permission tree size cap exceeded");
3593            }
3594        }
3595    }
3596
3597    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3598        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3599            throw new SecurityException("Label must be specified in permission");
3600        }
3601        BasePermission tree = checkPermissionTreeLP(info.name);
3602        BasePermission bp = mSettings.mPermissions.get(info.name);
3603        boolean added = bp == null;
3604        boolean changed = true;
3605        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3606        if (added) {
3607            enforcePermissionCapLocked(info, tree);
3608            bp = new BasePermission(info.name, tree.sourcePackage,
3609                    BasePermission.TYPE_DYNAMIC);
3610        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3611            throw new SecurityException(
3612                    "Not allowed to modify non-dynamic permission "
3613                    + info.name);
3614        } else {
3615            if (bp.protectionLevel == fixedLevel
3616                    && bp.perm.owner.equals(tree.perm.owner)
3617                    && bp.uid == tree.uid
3618                    && comparePermissionInfos(bp.perm.info, info)) {
3619                changed = false;
3620            }
3621        }
3622        bp.protectionLevel = fixedLevel;
3623        info = new PermissionInfo(info);
3624        info.protectionLevel = fixedLevel;
3625        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3626        bp.perm.info.packageName = tree.perm.info.packageName;
3627        bp.uid = tree.uid;
3628        if (added) {
3629            mSettings.mPermissions.put(info.name, bp);
3630        }
3631        if (changed) {
3632            if (!async) {
3633                mSettings.writeLPr();
3634            } else {
3635                scheduleWriteSettingsLocked();
3636            }
3637        }
3638        return added;
3639    }
3640
3641    @Override
3642    public boolean addPermission(PermissionInfo info) {
3643        synchronized (mPackages) {
3644            return addPermissionLocked(info, false);
3645        }
3646    }
3647
3648    @Override
3649    public boolean addPermissionAsync(PermissionInfo info) {
3650        synchronized (mPackages) {
3651            return addPermissionLocked(info, true);
3652        }
3653    }
3654
3655    @Override
3656    public void removePermission(String name) {
3657        synchronized (mPackages) {
3658            checkPermissionTreeLP(name);
3659            BasePermission bp = mSettings.mPermissions.get(name);
3660            if (bp != null) {
3661                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3662                    throw new SecurityException(
3663                            "Not allowed to modify non-dynamic permission "
3664                            + name);
3665                }
3666                mSettings.mPermissions.remove(name);
3667                mSettings.writeLPr();
3668            }
3669        }
3670    }
3671
3672    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3673            BasePermission bp) {
3674        int index = pkg.requestedPermissions.indexOf(bp.name);
3675        if (index == -1) {
3676            throw new SecurityException("Package " + pkg.packageName
3677                    + " has not requested permission " + bp.name);
3678        }
3679        if (!bp.isRuntime() && !bp.isDevelopment()) {
3680            throw new SecurityException("Permission " + bp.name
3681                    + " is not a changeable permission type");
3682        }
3683    }
3684
3685    @Override
3686    public void grantRuntimePermission(String packageName, String name, final int userId) {
3687        if (!sUserManager.exists(userId)) {
3688            Log.e(TAG, "No such user:" + userId);
3689            return;
3690        }
3691
3692        mContext.enforceCallingOrSelfPermission(
3693                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3694                "grantRuntimePermission");
3695
3696        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3697                "grantRuntimePermission");
3698
3699        final int uid;
3700        final SettingBase sb;
3701
3702        synchronized (mPackages) {
3703            final PackageParser.Package pkg = mPackages.get(packageName);
3704            if (pkg == null) {
3705                throw new IllegalArgumentException("Unknown package: " + packageName);
3706            }
3707
3708            final BasePermission bp = mSettings.mPermissions.get(name);
3709            if (bp == null) {
3710                throw new IllegalArgumentException("Unknown permission: " + name);
3711            }
3712
3713            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3714
3715            // If a permission review is required for legacy apps we represent
3716            // their permissions as always granted runtime ones since we need
3717            // to keep the review required permission flag per user while an
3718            // install permission's state is shared across all users.
3719            if (Build.PERMISSIONS_REVIEW_REQUIRED
3720                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3721                    && bp.isRuntime()) {
3722                return;
3723            }
3724
3725            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3726            sb = (SettingBase) pkg.mExtras;
3727            if (sb == null) {
3728                throw new IllegalArgumentException("Unknown package: " + packageName);
3729            }
3730
3731            final PermissionsState permissionsState = sb.getPermissionsState();
3732
3733            final int flags = permissionsState.getPermissionFlags(name, userId);
3734            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3735                throw new SecurityException("Cannot grant system fixed permission: "
3736                        + name + " for package: " + packageName);
3737            }
3738
3739            if (bp.isDevelopment()) {
3740                // Development permissions must be handled specially, since they are not
3741                // normal runtime permissions.  For now they apply to all users.
3742                if (permissionsState.grantInstallPermission(bp) !=
3743                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3744                    scheduleWriteSettingsLocked();
3745                }
3746                return;
3747            }
3748
3749            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3750                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3751                return;
3752            }
3753
3754            final int result = permissionsState.grantRuntimePermission(bp, userId);
3755            switch (result) {
3756                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3757                    return;
3758                }
3759
3760                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3761                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3762                    mHandler.post(new Runnable() {
3763                        @Override
3764                        public void run() {
3765                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3766                        }
3767                    });
3768                }
3769                break;
3770            }
3771
3772            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3773
3774            // Not critical if that is lost - app has to request again.
3775            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3776        }
3777
3778        // Only need to do this if user is initialized. Otherwise it's a new user
3779        // and there are no processes running as the user yet and there's no need
3780        // to make an expensive call to remount processes for the changed permissions.
3781        if (READ_EXTERNAL_STORAGE.equals(name)
3782                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3783            final long token = Binder.clearCallingIdentity();
3784            try {
3785                if (sUserManager.isInitialized(userId)) {
3786                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3787                            MountServiceInternal.class);
3788                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3789                }
3790            } finally {
3791                Binder.restoreCallingIdentity(token);
3792            }
3793        }
3794    }
3795
3796    @Override
3797    public void revokeRuntimePermission(String packageName, String name, int userId) {
3798        if (!sUserManager.exists(userId)) {
3799            Log.e(TAG, "No such user:" + userId);
3800            return;
3801        }
3802
3803        mContext.enforceCallingOrSelfPermission(
3804                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3805                "revokeRuntimePermission");
3806
3807        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3808                "revokeRuntimePermission");
3809
3810        final int appId;
3811
3812        synchronized (mPackages) {
3813            final PackageParser.Package pkg = mPackages.get(packageName);
3814            if (pkg == null) {
3815                throw new IllegalArgumentException("Unknown package: " + packageName);
3816            }
3817
3818            final BasePermission bp = mSettings.mPermissions.get(name);
3819            if (bp == null) {
3820                throw new IllegalArgumentException("Unknown permission: " + name);
3821            }
3822
3823            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3824
3825            // If a permission review is required for legacy apps we represent
3826            // their permissions as always granted runtime ones since we need
3827            // to keep the review required permission flag per user while an
3828            // install permission's state is shared across all users.
3829            if (Build.PERMISSIONS_REVIEW_REQUIRED
3830                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3831                    && bp.isRuntime()) {
3832                return;
3833            }
3834
3835            SettingBase sb = (SettingBase) pkg.mExtras;
3836            if (sb == null) {
3837                throw new IllegalArgumentException("Unknown package: " + packageName);
3838            }
3839
3840            final PermissionsState permissionsState = sb.getPermissionsState();
3841
3842            final int flags = permissionsState.getPermissionFlags(name, userId);
3843            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3844                throw new SecurityException("Cannot revoke system fixed permission: "
3845                        + name + " for package: " + packageName);
3846            }
3847
3848            if (bp.isDevelopment()) {
3849                // Development permissions must be handled specially, since they are not
3850                // normal runtime permissions.  For now they apply to all users.
3851                if (permissionsState.revokeInstallPermission(bp) !=
3852                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3853                    scheduleWriteSettingsLocked();
3854                }
3855                return;
3856            }
3857
3858            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3859                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3860                return;
3861            }
3862
3863            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3864
3865            // Critical, after this call app should never have the permission.
3866            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3867
3868            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3869        }
3870
3871        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3872    }
3873
3874    @Override
3875    public void resetRuntimePermissions() {
3876        mContext.enforceCallingOrSelfPermission(
3877                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3878                "revokeRuntimePermission");
3879
3880        int callingUid = Binder.getCallingUid();
3881        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3882            mContext.enforceCallingOrSelfPermission(
3883                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3884                    "resetRuntimePermissions");
3885        }
3886
3887        synchronized (mPackages) {
3888            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3889            for (int userId : UserManagerService.getInstance().getUserIds()) {
3890                final int packageCount = mPackages.size();
3891                for (int i = 0; i < packageCount; i++) {
3892                    PackageParser.Package pkg = mPackages.valueAt(i);
3893                    if (!(pkg.mExtras instanceof PackageSetting)) {
3894                        continue;
3895                    }
3896                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3897                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3898                }
3899            }
3900        }
3901    }
3902
3903    @Override
3904    public int getPermissionFlags(String name, String packageName, int userId) {
3905        if (!sUserManager.exists(userId)) {
3906            return 0;
3907        }
3908
3909        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3910
3911        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3912                "getPermissionFlags");
3913
3914        synchronized (mPackages) {
3915            final PackageParser.Package pkg = mPackages.get(packageName);
3916            if (pkg == null) {
3917                throw new IllegalArgumentException("Unknown package: " + packageName);
3918            }
3919
3920            final BasePermission bp = mSettings.mPermissions.get(name);
3921            if (bp == null) {
3922                throw new IllegalArgumentException("Unknown permission: " + name);
3923            }
3924
3925            SettingBase sb = (SettingBase) pkg.mExtras;
3926            if (sb == null) {
3927                throw new IllegalArgumentException("Unknown package: " + packageName);
3928            }
3929
3930            PermissionsState permissionsState = sb.getPermissionsState();
3931            return permissionsState.getPermissionFlags(name, userId);
3932        }
3933    }
3934
3935    @Override
3936    public void updatePermissionFlags(String name, String packageName, int flagMask,
3937            int flagValues, int userId) {
3938        if (!sUserManager.exists(userId)) {
3939            return;
3940        }
3941
3942        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3943
3944        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3945                "updatePermissionFlags");
3946
3947        // Only the system can change these flags and nothing else.
3948        if (getCallingUid() != Process.SYSTEM_UID) {
3949            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3950            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3951            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3952            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3953            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3954        }
3955
3956        synchronized (mPackages) {
3957            final PackageParser.Package pkg = mPackages.get(packageName);
3958            if (pkg == null) {
3959                throw new IllegalArgumentException("Unknown package: " + packageName);
3960            }
3961
3962            final BasePermission bp = mSettings.mPermissions.get(name);
3963            if (bp == null) {
3964                throw new IllegalArgumentException("Unknown permission: " + name);
3965            }
3966
3967            SettingBase sb = (SettingBase) pkg.mExtras;
3968            if (sb == null) {
3969                throw new IllegalArgumentException("Unknown package: " + packageName);
3970            }
3971
3972            PermissionsState permissionsState = sb.getPermissionsState();
3973
3974            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3975
3976            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3977                // Install and runtime permissions are stored in different places,
3978                // so figure out what permission changed and persist the change.
3979                if (permissionsState.getInstallPermissionState(name) != null) {
3980                    scheduleWriteSettingsLocked();
3981                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3982                        || hadState) {
3983                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3984                }
3985            }
3986        }
3987    }
3988
3989    /**
3990     * Update the permission flags for all packages and runtime permissions of a user in order
3991     * to allow device or profile owner to remove POLICY_FIXED.
3992     */
3993    @Override
3994    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3995        if (!sUserManager.exists(userId)) {
3996            return;
3997        }
3998
3999        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4000
4001        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4002                "updatePermissionFlagsForAllApps");
4003
4004        // Only the system can change system fixed flags.
4005        if (getCallingUid() != Process.SYSTEM_UID) {
4006            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4007            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4008        }
4009
4010        synchronized (mPackages) {
4011            boolean changed = false;
4012            final int packageCount = mPackages.size();
4013            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4014                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4015                SettingBase sb = (SettingBase) pkg.mExtras;
4016                if (sb == null) {
4017                    continue;
4018                }
4019                PermissionsState permissionsState = sb.getPermissionsState();
4020                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4021                        userId, flagMask, flagValues);
4022            }
4023            if (changed) {
4024                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4025            }
4026        }
4027    }
4028
4029    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4030        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4031                != PackageManager.PERMISSION_GRANTED
4032            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4033                != PackageManager.PERMISSION_GRANTED) {
4034            throw new SecurityException(message + " requires "
4035                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4036                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4037        }
4038    }
4039
4040    @Override
4041    public boolean shouldShowRequestPermissionRationale(String permissionName,
4042            String packageName, int userId) {
4043        if (UserHandle.getCallingUserId() != userId) {
4044            mContext.enforceCallingPermission(
4045                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4046                    "canShowRequestPermissionRationale for user " + userId);
4047        }
4048
4049        final int uid = getPackageUid(packageName, userId);
4050        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4051            return false;
4052        }
4053
4054        if (checkPermission(permissionName, packageName, userId)
4055                == PackageManager.PERMISSION_GRANTED) {
4056            return false;
4057        }
4058
4059        final int flags;
4060
4061        final long identity = Binder.clearCallingIdentity();
4062        try {
4063            flags = getPermissionFlags(permissionName,
4064                    packageName, userId);
4065        } finally {
4066            Binder.restoreCallingIdentity(identity);
4067        }
4068
4069        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4070                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4071                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4072
4073        if ((flags & fixedFlags) != 0) {
4074            return false;
4075        }
4076
4077        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4078    }
4079
4080    @Override
4081    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4082        mContext.enforceCallingOrSelfPermission(
4083                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4084                "addOnPermissionsChangeListener");
4085
4086        synchronized (mPackages) {
4087            mOnPermissionChangeListeners.addListenerLocked(listener);
4088        }
4089    }
4090
4091    @Override
4092    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4093        synchronized (mPackages) {
4094            mOnPermissionChangeListeners.removeListenerLocked(listener);
4095        }
4096    }
4097
4098    @Override
4099    public boolean isProtectedBroadcast(String actionName) {
4100        synchronized (mPackages) {
4101            if (mProtectedBroadcasts.contains(actionName)) {
4102                return true;
4103            } else if (actionName != null) {
4104                // TODO: remove these terrible hacks
4105                if (actionName.startsWith("android.net.netmon.lingerExpired")
4106                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4107                    return true;
4108                }
4109            }
4110        }
4111        return false;
4112    }
4113
4114    @Override
4115    public int checkSignatures(String pkg1, String pkg2) {
4116        synchronized (mPackages) {
4117            final PackageParser.Package p1 = mPackages.get(pkg1);
4118            final PackageParser.Package p2 = mPackages.get(pkg2);
4119            if (p1 == null || p1.mExtras == null
4120                    || p2 == null || p2.mExtras == null) {
4121                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4122            }
4123            return compareSignatures(p1.mSignatures, p2.mSignatures);
4124        }
4125    }
4126
4127    @Override
4128    public int checkUidSignatures(int uid1, int uid2) {
4129        // Map to base uids.
4130        uid1 = UserHandle.getAppId(uid1);
4131        uid2 = UserHandle.getAppId(uid2);
4132        // reader
4133        synchronized (mPackages) {
4134            Signature[] s1;
4135            Signature[] s2;
4136            Object obj = mSettings.getUserIdLPr(uid1);
4137            if (obj != null) {
4138                if (obj instanceof SharedUserSetting) {
4139                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4140                } else if (obj instanceof PackageSetting) {
4141                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4142                } else {
4143                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4144                }
4145            } else {
4146                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4147            }
4148            obj = mSettings.getUserIdLPr(uid2);
4149            if (obj != null) {
4150                if (obj instanceof SharedUserSetting) {
4151                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4152                } else if (obj instanceof PackageSetting) {
4153                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4154                } else {
4155                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4156                }
4157            } else {
4158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4159            }
4160            return compareSignatures(s1, s2);
4161        }
4162    }
4163
4164    private void killUid(int appId, int userId, String reason) {
4165        final long identity = Binder.clearCallingIdentity();
4166        try {
4167            IActivityManager am = ActivityManagerNative.getDefault();
4168            if (am != null) {
4169                try {
4170                    am.killUid(appId, userId, reason);
4171                } catch (RemoteException e) {
4172                    /* ignore - same process */
4173                }
4174            }
4175        } finally {
4176            Binder.restoreCallingIdentity(identity);
4177        }
4178    }
4179
4180    /**
4181     * Compares two sets of signatures. Returns:
4182     * <br />
4183     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4184     * <br />
4185     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4186     * <br />
4187     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4188     * <br />
4189     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4190     * <br />
4191     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4192     */
4193    static int compareSignatures(Signature[] s1, Signature[] s2) {
4194        if (s1 == null) {
4195            return s2 == null
4196                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4197                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4198        }
4199
4200        if (s2 == null) {
4201            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4202        }
4203
4204        if (s1.length != s2.length) {
4205            return PackageManager.SIGNATURE_NO_MATCH;
4206        }
4207
4208        // Since both signature sets are of size 1, we can compare without HashSets.
4209        if (s1.length == 1) {
4210            return s1[0].equals(s2[0]) ?
4211                    PackageManager.SIGNATURE_MATCH :
4212                    PackageManager.SIGNATURE_NO_MATCH;
4213        }
4214
4215        ArraySet<Signature> set1 = new ArraySet<Signature>();
4216        for (Signature sig : s1) {
4217            set1.add(sig);
4218        }
4219        ArraySet<Signature> set2 = new ArraySet<Signature>();
4220        for (Signature sig : s2) {
4221            set2.add(sig);
4222        }
4223        // Make sure s2 contains all signatures in s1.
4224        if (set1.equals(set2)) {
4225            return PackageManager.SIGNATURE_MATCH;
4226        }
4227        return PackageManager.SIGNATURE_NO_MATCH;
4228    }
4229
4230    /**
4231     * If the database version for this type of package (internal storage or
4232     * external storage) is less than the version where package signatures
4233     * were updated, return true.
4234     */
4235    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4236        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4237        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4238    }
4239
4240    /**
4241     * Used for backward compatibility to make sure any packages with
4242     * certificate chains get upgraded to the new style. {@code existingSigs}
4243     * will be in the old format (since they were stored on disk from before the
4244     * system upgrade) and {@code scannedSigs} will be in the newer format.
4245     */
4246    private int compareSignaturesCompat(PackageSignatures existingSigs,
4247            PackageParser.Package scannedPkg) {
4248        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4249            return PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4253        for (Signature sig : existingSigs.mSignatures) {
4254            existingSet.add(sig);
4255        }
4256        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4257        for (Signature sig : scannedPkg.mSignatures) {
4258            try {
4259                Signature[] chainSignatures = sig.getChainSignatures();
4260                for (Signature chainSig : chainSignatures) {
4261                    scannedCompatSet.add(chainSig);
4262                }
4263            } catch (CertificateEncodingException e) {
4264                scannedCompatSet.add(sig);
4265            }
4266        }
4267        /*
4268         * Make sure the expanded scanned set contains all signatures in the
4269         * existing one.
4270         */
4271        if (scannedCompatSet.equals(existingSet)) {
4272            // Migrate the old signatures to the new scheme.
4273            existingSigs.assignSignatures(scannedPkg.mSignatures);
4274            // The new KeySets will be re-added later in the scanning process.
4275            synchronized (mPackages) {
4276                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4277            }
4278            return PackageManager.SIGNATURE_MATCH;
4279        }
4280        return PackageManager.SIGNATURE_NO_MATCH;
4281    }
4282
4283    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4284        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4285        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4286    }
4287
4288    private int compareSignaturesRecover(PackageSignatures existingSigs,
4289            PackageParser.Package scannedPkg) {
4290        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4291            return PackageManager.SIGNATURE_NO_MATCH;
4292        }
4293
4294        String msg = null;
4295        try {
4296            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4297                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4298                        + scannedPkg.packageName);
4299                return PackageManager.SIGNATURE_MATCH;
4300            }
4301        } catch (CertificateException e) {
4302            msg = e.getMessage();
4303        }
4304
4305        logCriticalInfo(Log.INFO,
4306                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4307        return PackageManager.SIGNATURE_NO_MATCH;
4308    }
4309
4310    @Override
4311    public String[] getPackagesForUid(int uid) {
4312        uid = UserHandle.getAppId(uid);
4313        // reader
4314        synchronized (mPackages) {
4315            Object obj = mSettings.getUserIdLPr(uid);
4316            if (obj instanceof SharedUserSetting) {
4317                final SharedUserSetting sus = (SharedUserSetting) obj;
4318                final int N = sus.packages.size();
4319                final String[] res = new String[N];
4320                final Iterator<PackageSetting> it = sus.packages.iterator();
4321                int i = 0;
4322                while (it.hasNext()) {
4323                    res[i++] = it.next().name;
4324                }
4325                return res;
4326            } else if (obj instanceof PackageSetting) {
4327                final PackageSetting ps = (PackageSetting) obj;
4328                return new String[] { ps.name };
4329            }
4330        }
4331        return null;
4332    }
4333
4334    @Override
4335    public String getNameForUid(int uid) {
4336        // reader
4337        synchronized (mPackages) {
4338            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4339            if (obj instanceof SharedUserSetting) {
4340                final SharedUserSetting sus = (SharedUserSetting) obj;
4341                return sus.name + ":" + sus.userId;
4342            } else if (obj instanceof PackageSetting) {
4343                final PackageSetting ps = (PackageSetting) obj;
4344                return ps.name;
4345            }
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public int getUidForSharedUser(String sharedUserName) {
4352        if(sharedUserName == null) {
4353            return -1;
4354        }
4355        // reader
4356        synchronized (mPackages) {
4357            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4358            if (suid == null) {
4359                return -1;
4360            }
4361            return suid.userId;
4362        }
4363    }
4364
4365    @Override
4366    public int getFlagsForUid(int uid) {
4367        synchronized (mPackages) {
4368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4369            if (obj instanceof SharedUserSetting) {
4370                final SharedUserSetting sus = (SharedUserSetting) obj;
4371                return sus.pkgFlags;
4372            } else if (obj instanceof PackageSetting) {
4373                final PackageSetting ps = (PackageSetting) obj;
4374                return ps.pkgFlags;
4375            }
4376        }
4377        return 0;
4378    }
4379
4380    @Override
4381    public int getPrivateFlagsForUid(int uid) {
4382        synchronized (mPackages) {
4383            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4384            if (obj instanceof SharedUserSetting) {
4385                final SharedUserSetting sus = (SharedUserSetting) obj;
4386                return sus.pkgPrivateFlags;
4387            } else if (obj instanceof PackageSetting) {
4388                final PackageSetting ps = (PackageSetting) obj;
4389                return ps.pkgPrivateFlags;
4390            }
4391        }
4392        return 0;
4393    }
4394
4395    @Override
4396    public boolean isUidPrivileged(int uid) {
4397        uid = UserHandle.getAppId(uid);
4398        // reader
4399        synchronized (mPackages) {
4400            Object obj = mSettings.getUserIdLPr(uid);
4401            if (obj instanceof SharedUserSetting) {
4402                final SharedUserSetting sus = (SharedUserSetting) obj;
4403                final Iterator<PackageSetting> it = sus.packages.iterator();
4404                while (it.hasNext()) {
4405                    if (it.next().isPrivileged()) {
4406                        return true;
4407                    }
4408                }
4409            } else if (obj instanceof PackageSetting) {
4410                final PackageSetting ps = (PackageSetting) obj;
4411                return ps.isPrivileged();
4412            }
4413        }
4414        return false;
4415    }
4416
4417    @Override
4418    public String[] getAppOpPermissionPackages(String permissionName) {
4419        synchronized (mPackages) {
4420            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4421            if (pkgs == null) {
4422                return null;
4423            }
4424            return pkgs.toArray(new String[pkgs.size()]);
4425        }
4426    }
4427
4428    @Override
4429    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4430            int flags, int userId) {
4431        if (!sUserManager.exists(userId)) return null;
4432        flags = augmentFlagsForUser(flags, userId, intent);
4433        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4434        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4435        final ResolveInfo bestChoice =
4436                chooseBestActivity(intent, resolvedType, flags, query, userId);
4437
4438        if (isEphemeralAllowed(intent, query, userId)) {
4439            final EphemeralResolveInfo ai =
4440                    getEphemeralResolveInfo(intent, resolvedType, userId);
4441            if (ai != null) {
4442                if (DEBUG_EPHEMERAL) {
4443                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4444                }
4445                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4446                bestChoice.ephemeralResolveInfo = ai;
4447            }
4448        }
4449        return bestChoice;
4450    }
4451
4452    @Override
4453    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4454            IntentFilter filter, int match, ComponentName activity) {
4455        final int userId = UserHandle.getCallingUserId();
4456        if (DEBUG_PREFERRED) {
4457            Log.v(TAG, "setLastChosenActivity intent=" + intent
4458                + " resolvedType=" + resolvedType
4459                + " flags=" + flags
4460                + " filter=" + filter
4461                + " match=" + match
4462                + " activity=" + activity);
4463            filter.dump(new PrintStreamPrinter(System.out), "    ");
4464        }
4465        intent.setComponent(null);
4466        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4467        // Find any earlier preferred or last chosen entries and nuke them
4468        findPreferredActivity(intent, resolvedType,
4469                flags, query, 0, false, true, false, userId);
4470        // Add the new activity as the last chosen for this filter
4471        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4472                "Setting last chosen");
4473    }
4474
4475    @Override
4476    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4477        final int userId = UserHandle.getCallingUserId();
4478        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4479        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4480        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4481                false, false, false, userId);
4482    }
4483
4484
4485    private boolean isEphemeralAllowed(
4486            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4487        // Short circuit and return early if possible.
4488        final int callingUser = UserHandle.getCallingUserId();
4489        if (callingUser != UserHandle.USER_SYSTEM) {
4490            return false;
4491        }
4492        if (mEphemeralResolverConnection == null) {
4493            return false;
4494        }
4495        if (intent.getComponent() != null) {
4496            return false;
4497        }
4498        if (intent.getPackage() != null) {
4499            return false;
4500        }
4501        final boolean isWebUri = hasWebURI(intent);
4502        if (!isWebUri) {
4503            return false;
4504        }
4505        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4506        synchronized (mPackages) {
4507            final int count = resolvedActivites.size();
4508            for (int n = 0; n < count; n++) {
4509                ResolveInfo info = resolvedActivites.get(n);
4510                String packageName = info.activityInfo.packageName;
4511                PackageSetting ps = mSettings.mPackages.get(packageName);
4512                if (ps != null) {
4513                    // Try to get the status from User settings first
4514                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4515                    int status = (int) (packedStatus >> 32);
4516                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4517                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4518                        if (DEBUG_EPHEMERAL) {
4519                            Slog.v(TAG, "DENY ephemeral apps;"
4520                                + " pkg: " + packageName + ", status: " + status);
4521                        }
4522                        return false;
4523                    }
4524                }
4525            }
4526        }
4527        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4528        return true;
4529    }
4530
4531    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4532            int userId) {
4533        MessageDigest digest = null;
4534        try {
4535            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4536        } catch (NoSuchAlgorithmException e) {
4537            // If we can't create a digest, ignore ephemeral apps.
4538            return null;
4539        }
4540
4541        final byte[] hostBytes = intent.getData().getHost().getBytes();
4542        final byte[] digestBytes = digest.digest(hostBytes);
4543        int shaPrefix =
4544                digestBytes[0] << 24
4545                | digestBytes[1] << 16
4546                | digestBytes[2] << 8
4547                | digestBytes[3] << 0;
4548        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4549                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4550        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4551            // No hash prefix match; there are no ephemeral apps for this domain.
4552            return null;
4553        }
4554        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4555            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4556            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4557                continue;
4558            }
4559            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4560            // No filters; this should never happen.
4561            if (filters.isEmpty()) {
4562                continue;
4563            }
4564            // We have a domain match; resolve the filters to see if anything matches.
4565            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4566            for (int j = filters.size() - 1; j >= 0; --j) {
4567                final EphemeralResolveIntentInfo intentInfo =
4568                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4569                ephemeralResolver.addFilter(intentInfo);
4570            }
4571            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4572                    intent, resolvedType, false /*defaultOnly*/, userId);
4573            if (!matchedResolveInfoList.isEmpty()) {
4574                return matchedResolveInfoList.get(0);
4575            }
4576        }
4577        // Hash or filter mis-match; no ephemeral apps for this domain.
4578        return null;
4579    }
4580
4581    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4582            int flags, List<ResolveInfo> query, int userId) {
4583        if (query != null) {
4584            final int N = query.size();
4585            if (N == 1) {
4586                return query.get(0);
4587            } else if (N > 1) {
4588                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4589                // If there is more than one activity with the same priority,
4590                // then let the user decide between them.
4591                ResolveInfo r0 = query.get(0);
4592                ResolveInfo r1 = query.get(1);
4593                if (DEBUG_INTENT_MATCHING || debug) {
4594                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4595                            + r1.activityInfo.name + "=" + r1.priority);
4596                }
4597                // If the first activity has a higher priority, or a different
4598                // default, then it is always desirable to pick it.
4599                if (r0.priority != r1.priority
4600                        || r0.preferredOrder != r1.preferredOrder
4601                        || r0.isDefault != r1.isDefault) {
4602                    return query.get(0);
4603                }
4604                // If we have saved a preference for a preferred activity for
4605                // this Intent, use that.
4606                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4607                        flags, query, r0.priority, true, false, debug, userId);
4608                if (ri != null) {
4609                    return ri;
4610                }
4611                ri = new ResolveInfo(mResolveInfo);
4612                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4613                ri.activityInfo.applicationInfo = new ApplicationInfo(
4614                        ri.activityInfo.applicationInfo);
4615                if (userId != 0) {
4616                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4617                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4618                }
4619                // Make sure that the resolver is displayable in car mode
4620                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4621                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4622                return ri;
4623            }
4624        }
4625        return null;
4626    }
4627
4628    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4629            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4630        final int N = query.size();
4631        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4632                .get(userId);
4633        // Get the list of persistent preferred activities that handle the intent
4634        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4635        List<PersistentPreferredActivity> pprefs = ppir != null
4636                ? ppir.queryIntent(intent, resolvedType,
4637                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4638                : null;
4639        if (pprefs != null && pprefs.size() > 0) {
4640            final int M = pprefs.size();
4641            for (int i=0; i<M; i++) {
4642                final PersistentPreferredActivity ppa = pprefs.get(i);
4643                if (DEBUG_PREFERRED || debug) {
4644                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4645                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4646                            + "\n  component=" + ppa.mComponent);
4647                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4648                }
4649                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4650                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4651                if (DEBUG_PREFERRED || debug) {
4652                    Slog.v(TAG, "Found persistent preferred activity:");
4653                    if (ai != null) {
4654                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4655                    } else {
4656                        Slog.v(TAG, "  null");
4657                    }
4658                }
4659                if (ai == null) {
4660                    // This previously registered persistent preferred activity
4661                    // component is no longer known. Ignore it and do NOT remove it.
4662                    continue;
4663                }
4664                for (int j=0; j<N; j++) {
4665                    final ResolveInfo ri = query.get(j);
4666                    if (!ri.activityInfo.applicationInfo.packageName
4667                            .equals(ai.applicationInfo.packageName)) {
4668                        continue;
4669                    }
4670                    if (!ri.activityInfo.name.equals(ai.name)) {
4671                        continue;
4672                    }
4673                    //  Found a persistent preference that can handle the intent.
4674                    if (DEBUG_PREFERRED || debug) {
4675                        Slog.v(TAG, "Returning persistent preferred activity: " +
4676                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4677                    }
4678                    return ri;
4679                }
4680            }
4681        }
4682        return null;
4683    }
4684
4685    // TODO: handle preferred activities missing while user has amnesia
4686    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4687            List<ResolveInfo> query, int priority, boolean always,
4688            boolean removeMatches, boolean debug, int userId) {
4689        if (!sUserManager.exists(userId)) return null;
4690        flags = augmentFlagsForUser(flags, userId, intent);
4691        // writer
4692        synchronized (mPackages) {
4693            if (intent.getSelector() != null) {
4694                intent = intent.getSelector();
4695            }
4696            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4697
4698            // Try to find a matching persistent preferred activity.
4699            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4700                    debug, userId);
4701
4702            // If a persistent preferred activity matched, use it.
4703            if (pri != null) {
4704                return pri;
4705            }
4706
4707            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4708            // Get the list of preferred activities that handle the intent
4709            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4710            List<PreferredActivity> prefs = pir != null
4711                    ? pir.queryIntent(intent, resolvedType,
4712                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4713                    : null;
4714            if (prefs != null && prefs.size() > 0) {
4715                boolean changed = false;
4716                try {
4717                    // First figure out how good the original match set is.
4718                    // We will only allow preferred activities that came
4719                    // from the same match quality.
4720                    int match = 0;
4721
4722                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4723
4724                    final int N = query.size();
4725                    for (int j=0; j<N; j++) {
4726                        final ResolveInfo ri = query.get(j);
4727                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4728                                + ": 0x" + Integer.toHexString(match));
4729                        if (ri.match > match) {
4730                            match = ri.match;
4731                        }
4732                    }
4733
4734                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4735                            + Integer.toHexString(match));
4736
4737                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4738                    final int M = prefs.size();
4739                    for (int i=0; i<M; i++) {
4740                        final PreferredActivity pa = prefs.get(i);
4741                        if (DEBUG_PREFERRED || debug) {
4742                            Slog.v(TAG, "Checking PreferredActivity ds="
4743                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4744                                    + "\n  component=" + pa.mPref.mComponent);
4745                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4746                        }
4747                        if (pa.mPref.mMatch != match) {
4748                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4749                                    + Integer.toHexString(pa.mPref.mMatch));
4750                            continue;
4751                        }
4752                        // If it's not an "always" type preferred activity and that's what we're
4753                        // looking for, skip it.
4754                        if (always && !pa.mPref.mAlways) {
4755                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4756                            continue;
4757                        }
4758                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4759                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4760                        if (DEBUG_PREFERRED || debug) {
4761                            Slog.v(TAG, "Found preferred activity:");
4762                            if (ai != null) {
4763                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4764                            } else {
4765                                Slog.v(TAG, "  null");
4766                            }
4767                        }
4768                        if (ai == null) {
4769                            // This previously registered preferred activity
4770                            // component is no longer known.  Most likely an update
4771                            // to the app was installed and in the new version this
4772                            // component no longer exists.  Clean it up by removing
4773                            // it from the preferred activities list, and skip it.
4774                            Slog.w(TAG, "Removing dangling preferred activity: "
4775                                    + pa.mPref.mComponent);
4776                            pir.removeFilter(pa);
4777                            changed = true;
4778                            continue;
4779                        }
4780                        for (int j=0; j<N; j++) {
4781                            final ResolveInfo ri = query.get(j);
4782                            if (!ri.activityInfo.applicationInfo.packageName
4783                                    .equals(ai.applicationInfo.packageName)) {
4784                                continue;
4785                            }
4786                            if (!ri.activityInfo.name.equals(ai.name)) {
4787                                continue;
4788                            }
4789
4790                            if (removeMatches) {
4791                                pir.removeFilter(pa);
4792                                changed = true;
4793                                if (DEBUG_PREFERRED) {
4794                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4795                                }
4796                                break;
4797                            }
4798
4799                            // Okay we found a previously set preferred or last chosen app.
4800                            // If the result set is different from when this
4801                            // was created, we need to clear it and re-ask the
4802                            // user their preference, if we're looking for an "always" type entry.
4803                            if (always && !pa.mPref.sameSet(query)) {
4804                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4805                                        + intent + " type " + resolvedType);
4806                                if (DEBUG_PREFERRED) {
4807                                    Slog.v(TAG, "Removing preferred activity since set changed "
4808                                            + pa.mPref.mComponent);
4809                                }
4810                                pir.removeFilter(pa);
4811                                // Re-add the filter as a "last chosen" entry (!always)
4812                                PreferredActivity lastChosen = new PreferredActivity(
4813                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4814                                pir.addFilter(lastChosen);
4815                                changed = true;
4816                                return null;
4817                            }
4818
4819                            // Yay! Either the set matched or we're looking for the last chosen
4820                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4821                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4822                            return ri;
4823                        }
4824                    }
4825                } finally {
4826                    if (changed) {
4827                        if (DEBUG_PREFERRED) {
4828                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4829                        }
4830                        scheduleWritePackageRestrictionsLocked(userId);
4831                    }
4832                }
4833            }
4834        }
4835        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4836        return null;
4837    }
4838
4839    /*
4840     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4841     */
4842    @Override
4843    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4844            int targetUserId) {
4845        mContext.enforceCallingOrSelfPermission(
4846                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4847        List<CrossProfileIntentFilter> matches =
4848                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4849        if (matches != null) {
4850            int size = matches.size();
4851            for (int i = 0; i < size; i++) {
4852                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4853            }
4854        }
4855        if (hasWebURI(intent)) {
4856            // cross-profile app linking works only towards the parent.
4857            final UserInfo parent = getProfileParent(sourceUserId);
4858            synchronized(mPackages) {
4859                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4860                        intent, resolvedType, 0, sourceUserId, parent.id);
4861                return xpDomainInfo != null;
4862            }
4863        }
4864        return false;
4865    }
4866
4867    private UserInfo getProfileParent(int userId) {
4868        final long identity = Binder.clearCallingIdentity();
4869        try {
4870            return sUserManager.getProfileParent(userId);
4871        } finally {
4872            Binder.restoreCallingIdentity(identity);
4873        }
4874    }
4875
4876    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4877            String resolvedType, int userId) {
4878        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4879        if (resolver != null) {
4880            return resolver.queryIntent(intent, resolvedType, false, userId);
4881        }
4882        return null;
4883    }
4884
4885    @Override
4886    public List<ResolveInfo> queryIntentActivities(Intent intent,
4887            String resolvedType, int flags, int userId) {
4888        if (!sUserManager.exists(userId)) return Collections.emptyList();
4889        flags = augmentFlagsForUser(flags, userId, intent);
4890        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4891        ComponentName comp = intent.getComponent();
4892        if (comp == null) {
4893            if (intent.getSelector() != null) {
4894                intent = intent.getSelector();
4895                comp = intent.getComponent();
4896            }
4897        }
4898
4899        if (comp != null) {
4900            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4901            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4902            if (ai != null) {
4903                final ResolveInfo ri = new ResolveInfo();
4904                ri.activityInfo = ai;
4905                list.add(ri);
4906            }
4907            return list;
4908        }
4909
4910        // reader
4911        synchronized (mPackages) {
4912            final String pkgName = intent.getPackage();
4913            if (pkgName == null) {
4914                List<CrossProfileIntentFilter> matchingFilters =
4915                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4916                // Check for results that need to skip the current profile.
4917                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4918                        resolvedType, flags, userId);
4919                if (xpResolveInfo != null) {
4920                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4921                    result.add(xpResolveInfo);
4922                    return filterIfNotSystemUser(result, userId);
4923                }
4924
4925                // Check for results in the current profile.
4926                List<ResolveInfo> result = mActivities.queryIntent(
4927                        intent, resolvedType, flags, userId);
4928                result = filterIfNotSystemUser(result, userId);
4929
4930                // Check for cross profile results.
4931                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4932                xpResolveInfo = queryCrossProfileIntents(
4933                        matchingFilters, intent, resolvedType, flags, userId,
4934                        hasNonNegativePriorityResult);
4935                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4936                    boolean isVisibleToUser = filterIfNotSystemUser(
4937                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4938                    if (isVisibleToUser) {
4939                        result.add(xpResolveInfo);
4940                        Collections.sort(result, mResolvePrioritySorter);
4941                    }
4942                }
4943                if (hasWebURI(intent)) {
4944                    CrossProfileDomainInfo xpDomainInfo = null;
4945                    final UserInfo parent = getProfileParent(userId);
4946                    if (parent != null) {
4947                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4948                                flags, userId, parent.id);
4949                    }
4950                    if (xpDomainInfo != null) {
4951                        if (xpResolveInfo != null) {
4952                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4953                            // in the result.
4954                            result.remove(xpResolveInfo);
4955                        }
4956                        if (result.size() == 0) {
4957                            result.add(xpDomainInfo.resolveInfo);
4958                            return result;
4959                        }
4960                    } else if (result.size() <= 1) {
4961                        return result;
4962                    }
4963                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4964                            xpDomainInfo, userId);
4965                    Collections.sort(result, mResolvePrioritySorter);
4966                }
4967                return result;
4968            }
4969            final PackageParser.Package pkg = mPackages.get(pkgName);
4970            if (pkg != null) {
4971                return filterIfNotSystemUser(
4972                        mActivities.queryIntentForPackage(
4973                                intent, resolvedType, flags, pkg.activities, userId),
4974                        userId);
4975            }
4976            return new ArrayList<ResolveInfo>();
4977        }
4978    }
4979
4980    private static class CrossProfileDomainInfo {
4981        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4982        ResolveInfo resolveInfo;
4983        /* Best domain verification status of the activities found in the other profile */
4984        int bestDomainVerificationStatus;
4985    }
4986
4987    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4988            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4989        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4990                sourceUserId)) {
4991            return null;
4992        }
4993        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4994                resolvedType, flags, parentUserId);
4995
4996        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4997            return null;
4998        }
4999        CrossProfileDomainInfo result = null;
5000        int size = resultTargetUser.size();
5001        for (int i = 0; i < size; i++) {
5002            ResolveInfo riTargetUser = resultTargetUser.get(i);
5003            // Intent filter verification is only for filters that specify a host. So don't return
5004            // those that handle all web uris.
5005            if (riTargetUser.handleAllWebDataURI) {
5006                continue;
5007            }
5008            String packageName = riTargetUser.activityInfo.packageName;
5009            PackageSetting ps = mSettings.mPackages.get(packageName);
5010            if (ps == null) {
5011                continue;
5012            }
5013            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5014            int status = (int)(verificationState >> 32);
5015            if (result == null) {
5016                result = new CrossProfileDomainInfo();
5017                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5018                        sourceUserId, parentUserId);
5019                result.bestDomainVerificationStatus = status;
5020            } else {
5021                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5022                        result.bestDomainVerificationStatus);
5023            }
5024        }
5025        // Don't consider matches with status NEVER across profiles.
5026        if (result != null && result.bestDomainVerificationStatus
5027                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5028            return null;
5029        }
5030        return result;
5031    }
5032
5033    /**
5034     * Verification statuses are ordered from the worse to the best, except for
5035     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5036     */
5037    private int bestDomainVerificationStatus(int status1, int status2) {
5038        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5039            return status2;
5040        }
5041        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5042            return status1;
5043        }
5044        return (int) MathUtils.max(status1, status2);
5045    }
5046
5047    private boolean isUserEnabled(int userId) {
5048        long callingId = Binder.clearCallingIdentity();
5049        try {
5050            UserInfo userInfo = sUserManager.getUserInfo(userId);
5051            return userInfo != null && userInfo.isEnabled();
5052        } finally {
5053            Binder.restoreCallingIdentity(callingId);
5054        }
5055    }
5056
5057    /**
5058     * Filter out activities with systemUserOnly flag set, when current user is not System.
5059     *
5060     * @return filtered list
5061     */
5062    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5063        if (userId == UserHandle.USER_SYSTEM) {
5064            return resolveInfos;
5065        }
5066        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5067            ResolveInfo info = resolveInfos.get(i);
5068            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5069                resolveInfos.remove(i);
5070            }
5071        }
5072        return resolveInfos;
5073    }
5074
5075    /**
5076     * @param resolveInfos list of resolve infos in descending priority order
5077     * @return if the list contains a resolve info with non-negative priority
5078     */
5079    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5080        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5081    }
5082
5083    private static boolean hasWebURI(Intent intent) {
5084        if (intent.getData() == null) {
5085            return false;
5086        }
5087        final String scheme = intent.getScheme();
5088        if (TextUtils.isEmpty(scheme)) {
5089            return false;
5090        }
5091        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5092    }
5093
5094    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5095            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5096            int userId) {
5097        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5098
5099        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5100            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5101                    candidates.size());
5102        }
5103
5104        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5105        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5106        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5107        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5108        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5109        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5110
5111        synchronized (mPackages) {
5112            final int count = candidates.size();
5113            // First, try to use linked apps. Partition the candidates into four lists:
5114            // one for the final results, one for the "do not use ever", one for "undefined status"
5115            // and finally one for "browser app type".
5116            for (int n=0; n<count; n++) {
5117                ResolveInfo info = candidates.get(n);
5118                String packageName = info.activityInfo.packageName;
5119                PackageSetting ps = mSettings.mPackages.get(packageName);
5120                if (ps != null) {
5121                    // Add to the special match all list (Browser use case)
5122                    if (info.handleAllWebDataURI) {
5123                        matchAllList.add(info);
5124                        continue;
5125                    }
5126                    // Try to get the status from User settings first
5127                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5128                    int status = (int)(packedStatus >> 32);
5129                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5130                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5131                        if (DEBUG_DOMAIN_VERIFICATION) {
5132                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5133                                    + " : linkgen=" + linkGeneration);
5134                        }
5135                        // Use link-enabled generation as preferredOrder, i.e.
5136                        // prefer newly-enabled over earlier-enabled.
5137                        info.preferredOrder = linkGeneration;
5138                        alwaysList.add(info);
5139                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5140                        if (DEBUG_DOMAIN_VERIFICATION) {
5141                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5142                        }
5143                        neverList.add(info);
5144                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5145                        if (DEBUG_DOMAIN_VERIFICATION) {
5146                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5147                        }
5148                        alwaysAskList.add(info);
5149                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5150                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5151                        if (DEBUG_DOMAIN_VERIFICATION) {
5152                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5153                        }
5154                        undefinedList.add(info);
5155                    }
5156                }
5157            }
5158
5159            // We'll want to include browser possibilities in a few cases
5160            boolean includeBrowser = false;
5161
5162            // First try to add the "always" resolution(s) for the current user, if any
5163            if (alwaysList.size() > 0) {
5164                result.addAll(alwaysList);
5165            } else {
5166                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5167                result.addAll(undefinedList);
5168                // Maybe add one for the other profile.
5169                if (xpDomainInfo != null && (
5170                        xpDomainInfo.bestDomainVerificationStatus
5171                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5172                    result.add(xpDomainInfo.resolveInfo);
5173                }
5174                includeBrowser = true;
5175            }
5176
5177            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5178            // If there were 'always' entries their preferred order has been set, so we also
5179            // back that off to make the alternatives equivalent
5180            if (alwaysAskList.size() > 0) {
5181                for (ResolveInfo i : result) {
5182                    i.preferredOrder = 0;
5183                }
5184                result.addAll(alwaysAskList);
5185                includeBrowser = true;
5186            }
5187
5188            if (includeBrowser) {
5189                // Also add browsers (all of them or only the default one)
5190                if (DEBUG_DOMAIN_VERIFICATION) {
5191                    Slog.v(TAG, "   ...including browsers in candidate set");
5192                }
5193                if ((matchFlags & MATCH_ALL) != 0) {
5194                    result.addAll(matchAllList);
5195                } else {
5196                    // Browser/generic handling case.  If there's a default browser, go straight
5197                    // to that (but only if there is no other higher-priority match).
5198                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5199                    int maxMatchPrio = 0;
5200                    ResolveInfo defaultBrowserMatch = null;
5201                    final int numCandidates = matchAllList.size();
5202                    for (int n = 0; n < numCandidates; n++) {
5203                        ResolveInfo info = matchAllList.get(n);
5204                        // track the highest overall match priority...
5205                        if (info.priority > maxMatchPrio) {
5206                            maxMatchPrio = info.priority;
5207                        }
5208                        // ...and the highest-priority default browser match
5209                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5210                            if (defaultBrowserMatch == null
5211                                    || (defaultBrowserMatch.priority < info.priority)) {
5212                                if (debug) {
5213                                    Slog.v(TAG, "Considering default browser match " + info);
5214                                }
5215                                defaultBrowserMatch = info;
5216                            }
5217                        }
5218                    }
5219                    if (defaultBrowserMatch != null
5220                            && defaultBrowserMatch.priority >= maxMatchPrio
5221                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5222                    {
5223                        if (debug) {
5224                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5225                        }
5226                        result.add(defaultBrowserMatch);
5227                    } else {
5228                        result.addAll(matchAllList);
5229                    }
5230                }
5231
5232                // If there is nothing selected, add all candidates and remove the ones that the user
5233                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5234                if (result.size() == 0) {
5235                    result.addAll(candidates);
5236                    result.removeAll(neverList);
5237                }
5238            }
5239        }
5240        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5241            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5242                    result.size());
5243            for (ResolveInfo info : result) {
5244                Slog.v(TAG, "  + " + info.activityInfo);
5245            }
5246        }
5247        return result;
5248    }
5249
5250    // Returns a packed value as a long:
5251    //
5252    // high 'int'-sized word: link status: undefined/ask/never/always.
5253    // low 'int'-sized word: relative priority among 'always' results.
5254    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5255        long result = ps.getDomainVerificationStatusForUser(userId);
5256        // if none available, get the master status
5257        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5258            if (ps.getIntentFilterVerificationInfo() != null) {
5259                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5260            }
5261        }
5262        return result;
5263    }
5264
5265    private ResolveInfo querySkipCurrentProfileIntents(
5266            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5267            int flags, int sourceUserId) {
5268        if (matchingFilters != null) {
5269            int size = matchingFilters.size();
5270            for (int i = 0; i < size; i ++) {
5271                CrossProfileIntentFilter filter = matchingFilters.get(i);
5272                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5273                    // Checking if there are activities in the target user that can handle the
5274                    // intent.
5275                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5276                            resolvedType, flags, sourceUserId);
5277                    if (resolveInfo != null) {
5278                        return resolveInfo;
5279                    }
5280                }
5281            }
5282        }
5283        return null;
5284    }
5285
5286    // Return matching ResolveInfo in target user if any.
5287    private ResolveInfo queryCrossProfileIntents(
5288            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5289            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5290        if (matchingFilters != null) {
5291            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5292            // match the same intent. For performance reasons, it is better not to
5293            // run queryIntent twice for the same userId
5294            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5295            int size = matchingFilters.size();
5296            for (int i = 0; i < size; i++) {
5297                CrossProfileIntentFilter filter = matchingFilters.get(i);
5298                int targetUserId = filter.getTargetUserId();
5299                boolean skipCurrentProfile =
5300                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5301                boolean skipCurrentProfileIfNoMatchFound =
5302                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5303                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5304                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5305                    // Checking if there are activities in the target user that can handle the
5306                    // intent.
5307                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5308                            resolvedType, flags, sourceUserId);
5309                    if (resolveInfo != null) return resolveInfo;
5310                    alreadyTriedUserIds.put(targetUserId, true);
5311                }
5312            }
5313        }
5314        return null;
5315    }
5316
5317    /**
5318     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5319     * will forward the intent to the filter's target user.
5320     * Otherwise, returns null.
5321     */
5322    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5323            String resolvedType, int flags, int sourceUserId) {
5324        int targetUserId = filter.getTargetUserId();
5325        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5326                resolvedType, flags, targetUserId);
5327        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5328                && isUserEnabled(targetUserId)) {
5329            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5330        }
5331        return null;
5332    }
5333
5334    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5335            int sourceUserId, int targetUserId) {
5336        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5337        long ident = Binder.clearCallingIdentity();
5338        boolean targetIsProfile;
5339        try {
5340            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5341        } finally {
5342            Binder.restoreCallingIdentity(ident);
5343        }
5344        String className;
5345        if (targetIsProfile) {
5346            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5347        } else {
5348            className = FORWARD_INTENT_TO_PARENT;
5349        }
5350        ComponentName forwardingActivityComponentName = new ComponentName(
5351                mAndroidApplication.packageName, className);
5352        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5353                sourceUserId);
5354        if (!targetIsProfile) {
5355            forwardingActivityInfo.showUserIcon = targetUserId;
5356            forwardingResolveInfo.noResourceId = true;
5357        }
5358        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5359        forwardingResolveInfo.priority = 0;
5360        forwardingResolveInfo.preferredOrder = 0;
5361        forwardingResolveInfo.match = 0;
5362        forwardingResolveInfo.isDefault = true;
5363        forwardingResolveInfo.filter = filter;
5364        forwardingResolveInfo.targetUserId = targetUserId;
5365        return forwardingResolveInfo;
5366    }
5367
5368    @Override
5369    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5370            Intent[] specifics, String[] specificTypes, Intent intent,
5371            String resolvedType, int flags, int userId) {
5372        if (!sUserManager.exists(userId)) return Collections.emptyList();
5373        flags = augmentFlagsForUser(flags, userId, intent);
5374        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5375                false, "query intent activity options");
5376        final String resultsAction = intent.getAction();
5377
5378        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5379                | PackageManager.GET_RESOLVED_FILTER, userId);
5380
5381        if (DEBUG_INTENT_MATCHING) {
5382            Log.v(TAG, "Query " + intent + ": " + results);
5383        }
5384
5385        int specificsPos = 0;
5386        int N;
5387
5388        // todo: note that the algorithm used here is O(N^2).  This
5389        // isn't a problem in our current environment, but if we start running
5390        // into situations where we have more than 5 or 10 matches then this
5391        // should probably be changed to something smarter...
5392
5393        // First we go through and resolve each of the specific items
5394        // that were supplied, taking care of removing any corresponding
5395        // duplicate items in the generic resolve list.
5396        if (specifics != null) {
5397            for (int i=0; i<specifics.length; i++) {
5398                final Intent sintent = specifics[i];
5399                if (sintent == null) {
5400                    continue;
5401                }
5402
5403                if (DEBUG_INTENT_MATCHING) {
5404                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5405                }
5406
5407                String action = sintent.getAction();
5408                if (resultsAction != null && resultsAction.equals(action)) {
5409                    // If this action was explicitly requested, then don't
5410                    // remove things that have it.
5411                    action = null;
5412                }
5413
5414                ResolveInfo ri = null;
5415                ActivityInfo ai = null;
5416
5417                ComponentName comp = sintent.getComponent();
5418                if (comp == null) {
5419                    ri = resolveIntent(
5420                        sintent,
5421                        specificTypes != null ? specificTypes[i] : null,
5422                            flags, userId);
5423                    if (ri == null) {
5424                        continue;
5425                    }
5426                    if (ri == mResolveInfo) {
5427                        // ACK!  Must do something better with this.
5428                    }
5429                    ai = ri.activityInfo;
5430                    comp = new ComponentName(ai.applicationInfo.packageName,
5431                            ai.name);
5432                } else {
5433                    ai = getActivityInfo(comp, flags, userId);
5434                    if (ai == null) {
5435                        continue;
5436                    }
5437                }
5438
5439                // Look for any generic query activities that are duplicates
5440                // of this specific one, and remove them from the results.
5441                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5442                N = results.size();
5443                int j;
5444                for (j=specificsPos; j<N; j++) {
5445                    ResolveInfo sri = results.get(j);
5446                    if ((sri.activityInfo.name.equals(comp.getClassName())
5447                            && sri.activityInfo.applicationInfo.packageName.equals(
5448                                    comp.getPackageName()))
5449                        || (action != null && sri.filter.matchAction(action))) {
5450                        results.remove(j);
5451                        if (DEBUG_INTENT_MATCHING) Log.v(
5452                            TAG, "Removing duplicate item from " + j
5453                            + " due to specific " + specificsPos);
5454                        if (ri == null) {
5455                            ri = sri;
5456                        }
5457                        j--;
5458                        N--;
5459                    }
5460                }
5461
5462                // Add this specific item to its proper place.
5463                if (ri == null) {
5464                    ri = new ResolveInfo();
5465                    ri.activityInfo = ai;
5466                }
5467                results.add(specificsPos, ri);
5468                ri.specificIndex = i;
5469                specificsPos++;
5470            }
5471        }
5472
5473        // Now we go through the remaining generic results and remove any
5474        // duplicate actions that are found here.
5475        N = results.size();
5476        for (int i=specificsPos; i<N-1; i++) {
5477            final ResolveInfo rii = results.get(i);
5478            if (rii.filter == null) {
5479                continue;
5480            }
5481
5482            // Iterate over all of the actions of this result's intent
5483            // filter...  typically this should be just one.
5484            final Iterator<String> it = rii.filter.actionsIterator();
5485            if (it == null) {
5486                continue;
5487            }
5488            while (it.hasNext()) {
5489                final String action = it.next();
5490                if (resultsAction != null && resultsAction.equals(action)) {
5491                    // If this action was explicitly requested, then don't
5492                    // remove things that have it.
5493                    continue;
5494                }
5495                for (int j=i+1; j<N; j++) {
5496                    final ResolveInfo rij = results.get(j);
5497                    if (rij.filter != null && rij.filter.hasAction(action)) {
5498                        results.remove(j);
5499                        if (DEBUG_INTENT_MATCHING) Log.v(
5500                            TAG, "Removing duplicate item from " + j
5501                            + " due to action " + action + " at " + i);
5502                        j--;
5503                        N--;
5504                    }
5505                }
5506            }
5507
5508            // If the caller didn't request filter information, drop it now
5509            // so we don't have to marshall/unmarshall it.
5510            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5511                rii.filter = null;
5512            }
5513        }
5514
5515        // Filter out the caller activity if so requested.
5516        if (caller != null) {
5517            N = results.size();
5518            for (int i=0; i<N; i++) {
5519                ActivityInfo ainfo = results.get(i).activityInfo;
5520                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5521                        && caller.getClassName().equals(ainfo.name)) {
5522                    results.remove(i);
5523                    break;
5524                }
5525            }
5526        }
5527
5528        // If the caller didn't request filter information,
5529        // drop them now so we don't have to
5530        // marshall/unmarshall it.
5531        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5532            N = results.size();
5533            for (int i=0; i<N; i++) {
5534                results.get(i).filter = null;
5535            }
5536        }
5537
5538        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5539        return results;
5540    }
5541
5542    @Override
5543    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5544            int userId) {
5545        if (!sUserManager.exists(userId)) return Collections.emptyList();
5546        flags = augmentFlagsForUser(flags, userId, intent);
5547        ComponentName comp = intent.getComponent();
5548        if (comp == null) {
5549            if (intent.getSelector() != null) {
5550                intent = intent.getSelector();
5551                comp = intent.getComponent();
5552            }
5553        }
5554        if (comp != null) {
5555            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5556            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5557            if (ai != null) {
5558                ResolveInfo ri = new ResolveInfo();
5559                ri.activityInfo = ai;
5560                list.add(ri);
5561            }
5562            return list;
5563        }
5564
5565        // reader
5566        synchronized (mPackages) {
5567            String pkgName = intent.getPackage();
5568            if (pkgName == null) {
5569                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5570            }
5571            final PackageParser.Package pkg = mPackages.get(pkgName);
5572            if (pkg != null) {
5573                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5574                        userId);
5575            }
5576            return null;
5577        }
5578    }
5579
5580    @Override
5581    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5582        if (!sUserManager.exists(userId)) return null;
5583        flags = augmentFlagsForUser(flags, userId, intent);
5584        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5585        if (query != null) {
5586            if (query.size() >= 1) {
5587                // If there is more than one service with the same priority,
5588                // just arbitrarily pick the first one.
5589                return query.get(0);
5590            }
5591        }
5592        return null;
5593    }
5594
5595    @Override
5596    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5597            int userId) {
5598        if (!sUserManager.exists(userId)) return Collections.emptyList();
5599        flags = augmentFlagsForUser(flags, userId, intent);
5600        ComponentName comp = intent.getComponent();
5601        if (comp == null) {
5602            if (intent.getSelector() != null) {
5603                intent = intent.getSelector();
5604                comp = intent.getComponent();
5605            }
5606        }
5607        if (comp != null) {
5608            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5609            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5610            if (si != null) {
5611                final ResolveInfo ri = new ResolveInfo();
5612                ri.serviceInfo = si;
5613                list.add(ri);
5614            }
5615            return list;
5616        }
5617
5618        // reader
5619        synchronized (mPackages) {
5620            String pkgName = intent.getPackage();
5621            if (pkgName == null) {
5622                return mServices.queryIntent(intent, resolvedType, flags, userId);
5623            }
5624            final PackageParser.Package pkg = mPackages.get(pkgName);
5625            if (pkg != null) {
5626                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5627                        userId);
5628            }
5629            return null;
5630        }
5631    }
5632
5633    @Override
5634    public List<ResolveInfo> queryIntentContentProviders(
5635            Intent intent, String resolvedType, int flags, int userId) {
5636        if (!sUserManager.exists(userId)) return Collections.emptyList();
5637        flags = augmentFlagsForUser(flags, userId, intent);
5638        ComponentName comp = intent.getComponent();
5639        if (comp == null) {
5640            if (intent.getSelector() != null) {
5641                intent = intent.getSelector();
5642                comp = intent.getComponent();
5643            }
5644        }
5645        if (comp != null) {
5646            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5647            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5648            if (pi != null) {
5649                final ResolveInfo ri = new ResolveInfo();
5650                ri.providerInfo = pi;
5651                list.add(ri);
5652            }
5653            return list;
5654        }
5655
5656        // reader
5657        synchronized (mPackages) {
5658            String pkgName = intent.getPackage();
5659            if (pkgName == null) {
5660                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5661            }
5662            final PackageParser.Package pkg = mPackages.get(pkgName);
5663            if (pkg != null) {
5664                return mProviders.queryIntentForPackage(
5665                        intent, resolvedType, flags, pkg.providers, userId);
5666            }
5667            return null;
5668        }
5669    }
5670
5671    @Override
5672    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5673        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5674
5675        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5676
5677        // writer
5678        synchronized (mPackages) {
5679            ArrayList<PackageInfo> list;
5680            if (listUninstalled) {
5681                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5682                for (PackageSetting ps : mSettings.mPackages.values()) {
5683                    PackageInfo pi;
5684                    if (ps.pkg != null) {
5685                        pi = generatePackageInfo(ps.pkg, flags, userId);
5686                    } else {
5687                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5688                    }
5689                    if (pi != null) {
5690                        list.add(pi);
5691                    }
5692                }
5693            } else {
5694                list = new ArrayList<PackageInfo>(mPackages.size());
5695                for (PackageParser.Package p : mPackages.values()) {
5696                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5697                    if (pi != null) {
5698                        list.add(pi);
5699                    }
5700                }
5701            }
5702
5703            return new ParceledListSlice<PackageInfo>(list);
5704        }
5705    }
5706
5707    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5708            String[] permissions, boolean[] tmp, int flags, int userId) {
5709        int numMatch = 0;
5710        final PermissionsState permissionsState = ps.getPermissionsState();
5711        for (int i=0; i<permissions.length; i++) {
5712            final String permission = permissions[i];
5713            if (permissionsState.hasPermission(permission, userId)) {
5714                tmp[i] = true;
5715                numMatch++;
5716            } else {
5717                tmp[i] = false;
5718            }
5719        }
5720        if (numMatch == 0) {
5721            return;
5722        }
5723        PackageInfo pi;
5724        if (ps.pkg != null) {
5725            pi = generatePackageInfo(ps.pkg, flags, userId);
5726        } else {
5727            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5728        }
5729        // The above might return null in cases of uninstalled apps or install-state
5730        // skew across users/profiles.
5731        if (pi != null) {
5732            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5733                if (numMatch == permissions.length) {
5734                    pi.requestedPermissions = permissions;
5735                } else {
5736                    pi.requestedPermissions = new String[numMatch];
5737                    numMatch = 0;
5738                    for (int i=0; i<permissions.length; i++) {
5739                        if (tmp[i]) {
5740                            pi.requestedPermissions[numMatch] = permissions[i];
5741                            numMatch++;
5742                        }
5743                    }
5744                }
5745            }
5746            list.add(pi);
5747        }
5748    }
5749
5750    @Override
5751    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5752            String[] permissions, int flags, int userId) {
5753        if (!sUserManager.exists(userId)) return null;
5754        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5755
5756        // writer
5757        synchronized (mPackages) {
5758            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5759            boolean[] tmpBools = new boolean[permissions.length];
5760            if (listUninstalled) {
5761                for (PackageSetting ps : mSettings.mPackages.values()) {
5762                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5763                }
5764            } else {
5765                for (PackageParser.Package pkg : mPackages.values()) {
5766                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5767                    if (ps != null) {
5768                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5769                                userId);
5770                    }
5771                }
5772            }
5773
5774            return new ParceledListSlice<PackageInfo>(list);
5775        }
5776    }
5777
5778    @Override
5779    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5780        if (!sUserManager.exists(userId)) return null;
5781        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5782
5783        // writer
5784        synchronized (mPackages) {
5785            ArrayList<ApplicationInfo> list;
5786            if (listUninstalled) {
5787                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5788                for (PackageSetting ps : mSettings.mPackages.values()) {
5789                    ApplicationInfo ai;
5790                    if (ps.pkg != null) {
5791                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5792                                ps.readUserState(userId), userId);
5793                    } else {
5794                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5795                    }
5796                    if (ai != null) {
5797                        list.add(ai);
5798                    }
5799                }
5800            } else {
5801                list = new ArrayList<ApplicationInfo>(mPackages.size());
5802                for (PackageParser.Package p : mPackages.values()) {
5803                    if (p.mExtras != null) {
5804                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5805                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5806                        if (ai != null) {
5807                            list.add(ai);
5808                        }
5809                    }
5810                }
5811            }
5812
5813            return new ParceledListSlice<ApplicationInfo>(list);
5814        }
5815    }
5816
5817    @Override
5818    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5819        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5820                "getEphemeralApplications");
5821        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5822                "getEphemeralApplications");
5823        synchronized (mPackages) {
5824            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5825                    .getEphemeralApplicationsLPw(userId);
5826            if (ephemeralApps != null) {
5827                return new ParceledListSlice<>(ephemeralApps);
5828            }
5829        }
5830        return null;
5831    }
5832
5833    @Override
5834    public boolean isEphemeralApplication(String packageName, int userId) {
5835        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5836                "isEphemeral");
5837        if (!isCallerSameApp(packageName)) {
5838            return false;
5839        }
5840        synchronized (mPackages) {
5841            PackageParser.Package pkg = mPackages.get(packageName);
5842            if (pkg != null) {
5843                return pkg.applicationInfo.isEphemeralApp();
5844            }
5845        }
5846        return false;
5847    }
5848
5849    @Override
5850    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5851        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5852                "getCookie");
5853        if (!isCallerSameApp(packageName)) {
5854            return null;
5855        }
5856        synchronized (mPackages) {
5857            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5858                    packageName, userId);
5859        }
5860    }
5861
5862    @Override
5863    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5864        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5865                "setCookie");
5866        if (!isCallerSameApp(packageName)) {
5867            return false;
5868        }
5869        synchronized (mPackages) {
5870            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5871                    packageName, cookie, userId);
5872        }
5873    }
5874
5875    @Override
5876    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5877        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5878                "getEphemeralApplicationIcon");
5879        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5880                "getEphemeralApplicationIcon");
5881        synchronized (mPackages) {
5882            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5883                    packageName, userId);
5884        }
5885    }
5886
5887    private boolean isCallerSameApp(String packageName) {
5888        PackageParser.Package pkg = mPackages.get(packageName);
5889        return pkg != null
5890                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5891    }
5892
5893    public List<ApplicationInfo> getPersistentApplications(int flags) {
5894        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5895
5896        // reader
5897        synchronized (mPackages) {
5898            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5899            final int userId = UserHandle.getCallingUserId();
5900            while (i.hasNext()) {
5901                final PackageParser.Package p = i.next();
5902                if (p.applicationInfo != null
5903                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5904                        && (!mSafeMode || isSystemApp(p))) {
5905                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5906                    if (ps != null) {
5907                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5908                                ps.readUserState(userId), userId);
5909                        if (ai != null) {
5910                            finalList.add(ai);
5911                        }
5912                    }
5913                }
5914            }
5915        }
5916
5917        return finalList;
5918    }
5919
5920    @Override
5921    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5922        if (!sUserManager.exists(userId)) return null;
5923        flags = augmentFlagsForUser(flags, userId, name);
5924        // reader
5925        synchronized (mPackages) {
5926            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5927            PackageSetting ps = provider != null
5928                    ? mSettings.mPackages.get(provider.owner.packageName)
5929                    : null;
5930            return ps != null
5931                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5932                    && (!mSafeMode || (provider.info.applicationInfo.flags
5933                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5934                    ? PackageParser.generateProviderInfo(provider, flags,
5935                            ps.readUserState(userId), userId)
5936                    : null;
5937        }
5938    }
5939
5940    /**
5941     * @deprecated
5942     */
5943    @Deprecated
5944    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5945        // reader
5946        synchronized (mPackages) {
5947            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5948                    .entrySet().iterator();
5949            final int userId = UserHandle.getCallingUserId();
5950            while (i.hasNext()) {
5951                Map.Entry<String, PackageParser.Provider> entry = i.next();
5952                PackageParser.Provider p = entry.getValue();
5953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5954
5955                if (ps != null && p.syncable
5956                        && (!mSafeMode || (p.info.applicationInfo.flags
5957                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5958                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5959                            ps.readUserState(userId), userId);
5960                    if (info != null) {
5961                        outNames.add(entry.getKey());
5962                        outInfo.add(info);
5963                    }
5964                }
5965            }
5966        }
5967    }
5968
5969    @Override
5970    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5971            int uid, int flags) {
5972        final int userId = processName != null ? UserHandle.getUserId(uid)
5973                : UserHandle.getCallingUserId();
5974        if (!sUserManager.exists(userId)) return null;
5975        flags = augmentFlagsForUser(flags, userId, processName);
5976
5977        ArrayList<ProviderInfo> finalList = null;
5978        // reader
5979        synchronized (mPackages) {
5980            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5981            while (i.hasNext()) {
5982                final PackageParser.Provider p = i.next();
5983                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5984                if (ps != null && p.info.authority != null
5985                        && (processName == null
5986                                || (p.info.processName.equals(processName)
5987                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5988                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
5989                        && (!mSafeMode
5990                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5991                    if (finalList == null) {
5992                        finalList = new ArrayList<ProviderInfo>(3);
5993                    }
5994                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5995                            ps.readUserState(userId), userId);
5996                    if (info != null) {
5997                        finalList.add(info);
5998                    }
5999                }
6000            }
6001        }
6002
6003        if (finalList != null) {
6004            Collections.sort(finalList, mProviderInitOrderSorter);
6005            return new ParceledListSlice<ProviderInfo>(finalList);
6006        }
6007
6008        return null;
6009    }
6010
6011    @Override
6012    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
6013            int flags) {
6014        // reader
6015        synchronized (mPackages) {
6016            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6017            return PackageParser.generateInstrumentationInfo(i, flags);
6018        }
6019    }
6020
6021    @Override
6022    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6023            int flags) {
6024        ArrayList<InstrumentationInfo> finalList =
6025            new ArrayList<InstrumentationInfo>();
6026
6027        // reader
6028        synchronized (mPackages) {
6029            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6030            while (i.hasNext()) {
6031                final PackageParser.Instrumentation p = i.next();
6032                if (targetPackage == null
6033                        || targetPackage.equals(p.info.targetPackage)) {
6034                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6035                            flags);
6036                    if (ii != null) {
6037                        finalList.add(ii);
6038                    }
6039                }
6040            }
6041        }
6042
6043        return finalList;
6044    }
6045
6046    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6047        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6048        if (overlays == null) {
6049            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6050            return;
6051        }
6052        for (PackageParser.Package opkg : overlays.values()) {
6053            // Not much to do if idmap fails: we already logged the error
6054            // and we certainly don't want to abort installation of pkg simply
6055            // because an overlay didn't fit properly. For these reasons,
6056            // ignore the return value of createIdmapForPackagePairLI.
6057            createIdmapForPackagePairLI(pkg, opkg);
6058        }
6059    }
6060
6061    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6062            PackageParser.Package opkg) {
6063        if (!opkg.mTrustedOverlay) {
6064            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6065                    opkg.baseCodePath + ": overlay not trusted");
6066            return false;
6067        }
6068        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6069        if (overlaySet == null) {
6070            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6071                    opkg.baseCodePath + " but target package has no known overlays");
6072            return false;
6073        }
6074        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6075        // TODO: generate idmap for split APKs
6076        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6077            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6078                    + opkg.baseCodePath);
6079            return false;
6080        }
6081        PackageParser.Package[] overlayArray =
6082            overlaySet.values().toArray(new PackageParser.Package[0]);
6083        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6084            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6085                return p1.mOverlayPriority - p2.mOverlayPriority;
6086            }
6087        };
6088        Arrays.sort(overlayArray, cmp);
6089
6090        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6091        int i = 0;
6092        for (PackageParser.Package p : overlayArray) {
6093            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6094        }
6095        return true;
6096    }
6097
6098    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6099        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6100        try {
6101            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6102        } finally {
6103            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6104        }
6105    }
6106
6107    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6108        final File[] files = dir.listFiles();
6109        if (ArrayUtils.isEmpty(files)) {
6110            Log.d(TAG, "No files in app dir " + dir);
6111            return;
6112        }
6113
6114        if (DEBUG_PACKAGE_SCANNING) {
6115            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6116                    + " flags=0x" + Integer.toHexString(parseFlags));
6117        }
6118
6119        for (File file : files) {
6120            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6121                    && !PackageInstallerService.isStageName(file.getName());
6122            if (!isPackage) {
6123                // Ignore entries which are not packages
6124                continue;
6125            }
6126            try {
6127                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6128                        scanFlags, currentTime, null);
6129            } catch (PackageManagerException e) {
6130                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6131
6132                // Delete invalid userdata apps
6133                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6134                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6135                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6136                    if (file.isDirectory()) {
6137                        mInstaller.rmPackageDir(file.getAbsolutePath());
6138                    } else {
6139                        file.delete();
6140                    }
6141                }
6142            }
6143        }
6144    }
6145
6146    private static File getSettingsProblemFile() {
6147        File dataDir = Environment.getDataDirectory();
6148        File systemDir = new File(dataDir, "system");
6149        File fname = new File(systemDir, "uiderrors.txt");
6150        return fname;
6151    }
6152
6153    static void reportSettingsProblem(int priority, String msg) {
6154        logCriticalInfo(priority, msg);
6155    }
6156
6157    static void logCriticalInfo(int priority, String msg) {
6158        Slog.println(priority, TAG, msg);
6159        EventLogTags.writePmCriticalInfo(msg);
6160        try {
6161            File fname = getSettingsProblemFile();
6162            FileOutputStream out = new FileOutputStream(fname, true);
6163            PrintWriter pw = new FastPrintWriter(out);
6164            SimpleDateFormat formatter = new SimpleDateFormat();
6165            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6166            pw.println(dateString + ": " + msg);
6167            pw.close();
6168            FileUtils.setPermissions(
6169                    fname.toString(),
6170                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6171                    -1, -1);
6172        } catch (java.io.IOException e) {
6173        }
6174    }
6175
6176    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6177            PackageParser.Package pkg, File srcFile, int parseFlags)
6178            throws PackageManagerException {
6179        if (ps != null
6180                && ps.codePath.equals(srcFile)
6181                && ps.timeStamp == srcFile.lastModified()
6182                && !isCompatSignatureUpdateNeeded(pkg)
6183                && !isRecoverSignatureUpdateNeeded(pkg)) {
6184            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6185            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6186            ArraySet<PublicKey> signingKs;
6187            synchronized (mPackages) {
6188                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6189            }
6190            if (ps.signatures.mSignatures != null
6191                    && ps.signatures.mSignatures.length != 0
6192                    && signingKs != null) {
6193                // Optimization: reuse the existing cached certificates
6194                // if the package appears to be unchanged.
6195                pkg.mSignatures = ps.signatures.mSignatures;
6196                pkg.mSigningKeys = signingKs;
6197                return;
6198            }
6199
6200            Slog.w(TAG, "PackageSetting for " + ps.name
6201                    + " is missing signatures.  Collecting certs again to recover them.");
6202        } else {
6203            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6204        }
6205
6206        try {
6207            pp.collectCertificates(pkg, parseFlags);
6208            pp.collectManifestDigest(pkg);
6209        } catch (PackageParserException e) {
6210            throw PackageManagerException.from(e);
6211        }
6212    }
6213
6214    /**
6215     *  Traces a package scan.
6216     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6217     */
6218    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6219            long currentTime, UserHandle user) throws PackageManagerException {
6220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6221        try {
6222            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6223        } finally {
6224            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6225        }
6226    }
6227
6228    /**
6229     *  Scans a package and returns the newly parsed package.
6230     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6231     */
6232    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6233            long currentTime, UserHandle user) throws PackageManagerException {
6234        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6235        parseFlags |= mDefParseFlags;
6236        PackageParser pp = new PackageParser();
6237        pp.setSeparateProcesses(mSeparateProcesses);
6238        pp.setOnlyCoreApps(mOnlyCore);
6239        pp.setDisplayMetrics(mMetrics);
6240
6241        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6242            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6243        }
6244
6245        final PackageParser.Package pkg;
6246        try {
6247            pkg = pp.parsePackage(scanFile, parseFlags);
6248        } catch (PackageParserException e) {
6249            throw PackageManagerException.from(e);
6250        }
6251
6252        PackageSetting ps = null;
6253        PackageSetting updatedPkg;
6254        // reader
6255        synchronized (mPackages) {
6256            // Look to see if we already know about this package.
6257            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6258            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6259                // This package has been renamed to its original name.  Let's
6260                // use that.
6261                ps = mSettings.peekPackageLPr(oldName);
6262            }
6263            // If there was no original package, see one for the real package name.
6264            if (ps == null) {
6265                ps = mSettings.peekPackageLPr(pkg.packageName);
6266            }
6267            // Check to see if this package could be hiding/updating a system
6268            // package.  Must look for it either under the original or real
6269            // package name depending on our state.
6270            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6271            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6272        }
6273        boolean updatedPkgBetter = false;
6274        // First check if this is a system package that may involve an update
6275        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6276            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6277            // it needs to drop FLAG_PRIVILEGED.
6278            if (locationIsPrivileged(scanFile)) {
6279                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6280            } else {
6281                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6282            }
6283
6284            if (ps != null && !ps.codePath.equals(scanFile)) {
6285                // The path has changed from what was last scanned...  check the
6286                // version of the new path against what we have stored to determine
6287                // what to do.
6288                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6289                if (pkg.mVersionCode <= ps.versionCode) {
6290                    // The system package has been updated and the code path does not match
6291                    // Ignore entry. Skip it.
6292                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6293                            + " ignored: updated version " + ps.versionCode
6294                            + " better than this " + pkg.mVersionCode);
6295                    if (!updatedPkg.codePath.equals(scanFile)) {
6296                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6297                                + ps.name + " changing from " + updatedPkg.codePathString
6298                                + " to " + scanFile);
6299                        updatedPkg.codePath = scanFile;
6300                        updatedPkg.codePathString = scanFile.toString();
6301                        updatedPkg.resourcePath = scanFile;
6302                        updatedPkg.resourcePathString = scanFile.toString();
6303                    }
6304                    updatedPkg.pkg = pkg;
6305                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6306                            "Package " + ps.name + " at " + scanFile
6307                                    + " ignored: updated version " + ps.versionCode
6308                                    + " better than this " + pkg.mVersionCode);
6309                } else {
6310                    // The current app on the system partition is better than
6311                    // what we have updated to on the data partition; switch
6312                    // back to the system partition version.
6313                    // At this point, its safely assumed that package installation for
6314                    // apps in system partition will go through. If not there won't be a working
6315                    // version of the app
6316                    // writer
6317                    synchronized (mPackages) {
6318                        // Just remove the loaded entries from package lists.
6319                        mPackages.remove(ps.name);
6320                    }
6321
6322                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6323                            + " reverting from " + ps.codePathString
6324                            + ": new version " + pkg.mVersionCode
6325                            + " better than installed " + ps.versionCode);
6326
6327                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6328                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6329                    synchronized (mInstallLock) {
6330                        args.cleanUpResourcesLI();
6331                    }
6332                    synchronized (mPackages) {
6333                        mSettings.enableSystemPackageLPw(ps.name);
6334                    }
6335                    updatedPkgBetter = true;
6336                }
6337            }
6338        }
6339
6340        if (updatedPkg != null) {
6341            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6342            // initially
6343            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6344
6345            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6346            // flag set initially
6347            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6348                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6349            }
6350        }
6351
6352        // Verify certificates against what was last scanned
6353        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6354
6355        /*
6356         * A new system app appeared, but we already had a non-system one of the
6357         * same name installed earlier.
6358         */
6359        boolean shouldHideSystemApp = false;
6360        if (updatedPkg == null && ps != null
6361                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6362            /*
6363             * Check to make sure the signatures match first. If they don't,
6364             * wipe the installed application and its data.
6365             */
6366            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6367                    != PackageManager.SIGNATURE_MATCH) {
6368                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6369                        + " signatures don't match existing userdata copy; removing");
6370                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6371                ps = null;
6372            } else {
6373                /*
6374                 * If the newly-added system app is an older version than the
6375                 * already installed version, hide it. It will be scanned later
6376                 * and re-added like an update.
6377                 */
6378                if (pkg.mVersionCode <= ps.versionCode) {
6379                    shouldHideSystemApp = true;
6380                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6381                            + " but new version " + pkg.mVersionCode + " better than installed "
6382                            + ps.versionCode + "; hiding system");
6383                } else {
6384                    /*
6385                     * The newly found system app is a newer version that the
6386                     * one previously installed. Simply remove the
6387                     * already-installed application and replace it with our own
6388                     * while keeping the application data.
6389                     */
6390                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6391                            + " reverting from " + ps.codePathString + ": new version "
6392                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6393                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6394                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6395                    synchronized (mInstallLock) {
6396                        args.cleanUpResourcesLI();
6397                    }
6398                }
6399            }
6400        }
6401
6402        // The apk is forward locked (not public) if its code and resources
6403        // are kept in different files. (except for app in either system or
6404        // vendor path).
6405        // TODO grab this value from PackageSettings
6406        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6407            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6408                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6409            }
6410        }
6411
6412        // TODO: extend to support forward-locked splits
6413        String resourcePath = null;
6414        String baseResourcePath = null;
6415        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6416            if (ps != null && ps.resourcePathString != null) {
6417                resourcePath = ps.resourcePathString;
6418                baseResourcePath = ps.resourcePathString;
6419            } else {
6420                // Should not happen at all. Just log an error.
6421                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6422            }
6423        } else {
6424            resourcePath = pkg.codePath;
6425            baseResourcePath = pkg.baseCodePath;
6426        }
6427
6428        // Set application objects path explicitly.
6429        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6430        pkg.applicationInfo.setCodePath(pkg.codePath);
6431        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6432        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6433        pkg.applicationInfo.setResourcePath(resourcePath);
6434        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6435        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6436
6437        // Note that we invoke the following method only if we are about to unpack an application
6438        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6439                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6440
6441        /*
6442         * If the system app should be overridden by a previously installed
6443         * data, hide the system app now and let the /data/app scan pick it up
6444         * again.
6445         */
6446        if (shouldHideSystemApp) {
6447            synchronized (mPackages) {
6448                mSettings.disableSystemPackageLPw(pkg.packageName);
6449            }
6450        }
6451
6452        return scannedPkg;
6453    }
6454
6455    private static String fixProcessName(String defProcessName,
6456            String processName, int uid) {
6457        if (processName == null) {
6458            return defProcessName;
6459        }
6460        return processName;
6461    }
6462
6463    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6464            throws PackageManagerException {
6465        if (pkgSetting.signatures.mSignatures != null) {
6466            // Already existing package. Make sure signatures match
6467            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6468                    == PackageManager.SIGNATURE_MATCH;
6469            if (!match) {
6470                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6471                        == PackageManager.SIGNATURE_MATCH;
6472            }
6473            if (!match) {
6474                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6475                        == PackageManager.SIGNATURE_MATCH;
6476            }
6477            if (!match) {
6478                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6479                        + pkg.packageName + " signatures do not match the "
6480                        + "previously installed version; ignoring!");
6481            }
6482        }
6483
6484        // Check for shared user signatures
6485        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6486            // Already existing package. Make sure signatures match
6487            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6488                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6489            if (!match) {
6490                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6491                        == PackageManager.SIGNATURE_MATCH;
6492            }
6493            if (!match) {
6494                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6495                        == PackageManager.SIGNATURE_MATCH;
6496            }
6497            if (!match) {
6498                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6499                        "Package " + pkg.packageName
6500                        + " has no signatures that match those in shared user "
6501                        + pkgSetting.sharedUser.name + "; ignoring!");
6502            }
6503        }
6504    }
6505
6506    /**
6507     * Enforces that only the system UID or root's UID can call a method exposed
6508     * via Binder.
6509     *
6510     * @param message used as message if SecurityException is thrown
6511     * @throws SecurityException if the caller is not system or root
6512     */
6513    private static final void enforceSystemOrRoot(String message) {
6514        final int uid = Binder.getCallingUid();
6515        if (uid != Process.SYSTEM_UID && uid != 0) {
6516            throw new SecurityException(message);
6517        }
6518    }
6519
6520    @Override
6521    public void performFstrimIfNeeded() {
6522        enforceSystemOrRoot("Only the system can request fstrim");
6523
6524        // Before everything else, see whether we need to fstrim.
6525        try {
6526            IMountService ms = PackageHelper.getMountService();
6527            if (ms != null) {
6528                final boolean isUpgrade = isUpgrade();
6529                boolean doTrim = isUpgrade;
6530                if (doTrim) {
6531                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6532                } else {
6533                    final long interval = android.provider.Settings.Global.getLong(
6534                            mContext.getContentResolver(),
6535                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6536                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6537                    if (interval > 0) {
6538                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6539                        if (timeSinceLast > interval) {
6540                            doTrim = true;
6541                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6542                                    + "; running immediately");
6543                        }
6544                    }
6545                }
6546                if (doTrim) {
6547                    if (!isFirstBoot()) {
6548                        try {
6549                            ActivityManagerNative.getDefault().showBootMessage(
6550                                    mContext.getResources().getString(
6551                                            R.string.android_upgrading_fstrim), true);
6552                        } catch (RemoteException e) {
6553                        }
6554                    }
6555                    ms.runMaintenance();
6556                }
6557            } else {
6558                Slog.e(TAG, "Mount service unavailable!");
6559            }
6560        } catch (RemoteException e) {
6561            // Can't happen; MountService is local
6562        }
6563    }
6564
6565    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6566        List<ResolveInfo> ris = null;
6567        try {
6568            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6569                    intent, null, 0, userId);
6570        } catch (RemoteException e) {
6571        }
6572        ArraySet<String> pkgNames = new ArraySet<String>();
6573        if (ris != null) {
6574            for (ResolveInfo ri : ris) {
6575                pkgNames.add(ri.activityInfo.packageName);
6576            }
6577        }
6578        return pkgNames;
6579    }
6580
6581    @Override
6582    public void notifyPackageUse(String packageName) {
6583        synchronized (mPackages) {
6584            PackageParser.Package p = mPackages.get(packageName);
6585            if (p == null) {
6586                return;
6587            }
6588            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6589        }
6590    }
6591
6592    @Override
6593    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6594        return performDexOptTraced(packageName, instructionSet);
6595    }
6596
6597    public boolean performDexOpt(String packageName, String instructionSet) {
6598        return performDexOptTraced(packageName, instructionSet);
6599    }
6600
6601    private boolean performDexOptTraced(String packageName, String instructionSet) {
6602        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6603        try {
6604            return performDexOptInternal(packageName, instructionSet);
6605        } finally {
6606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6607        }
6608    }
6609
6610    private boolean performDexOptInternal(String packageName, String instructionSet) {
6611        PackageParser.Package p;
6612        final String targetInstructionSet;
6613        synchronized (mPackages) {
6614            p = mPackages.get(packageName);
6615            if (p == null) {
6616                return false;
6617            }
6618            mPackageUsage.write(false);
6619
6620            targetInstructionSet = instructionSet != null ? instructionSet :
6621                    getPrimaryInstructionSet(p.applicationInfo);
6622            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6623                return false;
6624            }
6625        }
6626        long callingId = Binder.clearCallingIdentity();
6627        try {
6628            synchronized (mInstallLock) {
6629                final String[] instructionSets = new String[] { targetInstructionSet };
6630                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6631                        true /* inclDependencies */);
6632                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6633            }
6634        } finally {
6635            Binder.restoreCallingIdentity(callingId);
6636        }
6637    }
6638
6639    public ArraySet<String> getPackagesThatNeedDexOpt() {
6640        ArraySet<String> pkgs = null;
6641        synchronized (mPackages) {
6642            for (PackageParser.Package p : mPackages.values()) {
6643                if (DEBUG_DEXOPT) {
6644                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6645                }
6646                if (!p.mDexOptPerformed.isEmpty()) {
6647                    continue;
6648                }
6649                if (pkgs == null) {
6650                    pkgs = new ArraySet<String>();
6651                }
6652                pkgs.add(p.packageName);
6653            }
6654        }
6655        return pkgs;
6656    }
6657
6658    public void shutdown() {
6659        mPackageUsage.write(true);
6660    }
6661
6662    @Override
6663    public void forceDexOpt(String packageName) {
6664        enforceSystemOrRoot("forceDexOpt");
6665
6666        PackageParser.Package pkg;
6667        synchronized (mPackages) {
6668            pkg = mPackages.get(packageName);
6669            if (pkg == null) {
6670                throw new IllegalArgumentException("Missing package: " + packageName);
6671            }
6672        }
6673
6674        synchronized (mInstallLock) {
6675            final String[] instructionSets = new String[] {
6676                    getPrimaryInstructionSet(pkg.applicationInfo) };
6677
6678            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6679
6680            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6681                    true /* inclDependencies */);
6682
6683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6684            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6685                throw new IllegalStateException("Failed to dexopt: " + res);
6686            }
6687        }
6688    }
6689
6690    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6691        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6692            Slog.w(TAG, "Unable to update from " + oldPkg.name
6693                    + " to " + newPkg.packageName
6694                    + ": old package not in system partition");
6695            return false;
6696        } else if (mPackages.get(oldPkg.name) != null) {
6697            Slog.w(TAG, "Unable to update from " + oldPkg.name
6698                    + " to " + newPkg.packageName
6699                    + ": old package still exists");
6700            return false;
6701        }
6702        return true;
6703    }
6704
6705    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6706            throws PackageManagerException {
6707        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6708        if (res != 0) {
6709            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6710                    "Failed to install " + packageName + ": " + res);
6711        }
6712
6713        final int[] users = sUserManager.getUserIds();
6714        for (int user : users) {
6715            if (user != 0) {
6716                res = mInstaller.createUserData(volumeUuid, packageName,
6717                        UserHandle.getUid(user, uid), user, seinfo);
6718                if (res != 0) {
6719                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6720                            "Failed to createUserData " + packageName + ": " + res);
6721                }
6722            }
6723        }
6724    }
6725
6726    private int removeDataDirsLI(String volumeUuid, String packageName) {
6727        int[] users = sUserManager.getUserIds();
6728        int res = 0;
6729        for (int user : users) {
6730            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6731            if (resInner < 0) {
6732                res = resInner;
6733            }
6734        }
6735
6736        return res;
6737    }
6738
6739    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6740        int[] users = sUserManager.getUserIds();
6741        int res = 0;
6742        for (int user : users) {
6743            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6744            if (resInner < 0) {
6745                res = resInner;
6746            }
6747        }
6748        return res;
6749    }
6750
6751    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6752            PackageParser.Package changingLib) {
6753        if (file.path != null) {
6754            usesLibraryFiles.add(file.path);
6755            return;
6756        }
6757        PackageParser.Package p = mPackages.get(file.apk);
6758        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6759            // If we are doing this while in the middle of updating a library apk,
6760            // then we need to make sure to use that new apk for determining the
6761            // dependencies here.  (We haven't yet finished committing the new apk
6762            // to the package manager state.)
6763            if (p == null || p.packageName.equals(changingLib.packageName)) {
6764                p = changingLib;
6765            }
6766        }
6767        if (p != null) {
6768            usesLibraryFiles.addAll(p.getAllCodePaths());
6769        }
6770    }
6771
6772    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6773            PackageParser.Package changingLib) throws PackageManagerException {
6774        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6775            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6776            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6777            for (int i=0; i<N; i++) {
6778                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6779                if (file == null) {
6780                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6781                            "Package " + pkg.packageName + " requires unavailable shared library "
6782                            + pkg.usesLibraries.get(i) + "; failing!");
6783                }
6784                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6785            }
6786            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6787            for (int i=0; i<N; i++) {
6788                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6789                if (file == null) {
6790                    Slog.w(TAG, "Package " + pkg.packageName
6791                            + " desires unavailable shared library "
6792                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6793                } else {
6794                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6795                }
6796            }
6797            N = usesLibraryFiles.size();
6798            if (N > 0) {
6799                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6800            } else {
6801                pkg.usesLibraryFiles = null;
6802            }
6803        }
6804    }
6805
6806    private static boolean hasString(List<String> list, List<String> which) {
6807        if (list == null) {
6808            return false;
6809        }
6810        for (int i=list.size()-1; i>=0; i--) {
6811            for (int j=which.size()-1; j>=0; j--) {
6812                if (which.get(j).equals(list.get(i))) {
6813                    return true;
6814                }
6815            }
6816        }
6817        return false;
6818    }
6819
6820    private void updateAllSharedLibrariesLPw() {
6821        for (PackageParser.Package pkg : mPackages.values()) {
6822            try {
6823                updateSharedLibrariesLPw(pkg, null);
6824            } catch (PackageManagerException e) {
6825                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6826            }
6827        }
6828    }
6829
6830    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6831            PackageParser.Package changingPkg) {
6832        ArrayList<PackageParser.Package> res = null;
6833        for (PackageParser.Package pkg : mPackages.values()) {
6834            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6835                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6836                if (res == null) {
6837                    res = new ArrayList<PackageParser.Package>();
6838                }
6839                res.add(pkg);
6840                try {
6841                    updateSharedLibrariesLPw(pkg, changingPkg);
6842                } catch (PackageManagerException e) {
6843                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6844                }
6845            }
6846        }
6847        return res;
6848    }
6849
6850    /**
6851     * Derive the value of the {@code cpuAbiOverride} based on the provided
6852     * value and an optional stored value from the package settings.
6853     */
6854    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6855        String cpuAbiOverride = null;
6856
6857        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6858            cpuAbiOverride = null;
6859        } else if (abiOverride != null) {
6860            cpuAbiOverride = abiOverride;
6861        } else if (settings != null) {
6862            cpuAbiOverride = settings.cpuAbiOverrideString;
6863        }
6864
6865        return cpuAbiOverride;
6866    }
6867
6868    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6869            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6870        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6871        try {
6872            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6873        } finally {
6874            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6875        }
6876    }
6877
6878    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6879            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6880        boolean success = false;
6881        try {
6882            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6883                    currentTime, user);
6884            success = true;
6885            return res;
6886        } finally {
6887            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6888                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6889            }
6890        }
6891    }
6892
6893    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6894            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6895        final File scanFile = new File(pkg.codePath);
6896        if (pkg.applicationInfo.getCodePath() == null ||
6897                pkg.applicationInfo.getResourcePath() == null) {
6898            // Bail out. The resource and code paths haven't been set.
6899            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6900                    "Code and resource paths haven't been set correctly");
6901        }
6902
6903        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6904            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6905        } else {
6906            // Only allow system apps to be flagged as core apps.
6907            pkg.coreApp = false;
6908        }
6909
6910        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6911            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6912        }
6913
6914        if (mCustomResolverComponentName != null &&
6915                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6916            setUpCustomResolverActivity(pkg);
6917        }
6918
6919        if (pkg.packageName.equals("android")) {
6920            synchronized (mPackages) {
6921                if (mAndroidApplication != null) {
6922                    Slog.w(TAG, "*************************************************");
6923                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6924                    Slog.w(TAG, " file=" + scanFile);
6925                    Slog.w(TAG, "*************************************************");
6926                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6927                            "Core android package being redefined.  Skipping.");
6928                }
6929
6930                // Set up information for our fall-back user intent resolution activity.
6931                mPlatformPackage = pkg;
6932                pkg.mVersionCode = mSdkVersion;
6933                mAndroidApplication = pkg.applicationInfo;
6934
6935                if (!mResolverReplaced) {
6936                    mResolveActivity.applicationInfo = mAndroidApplication;
6937                    mResolveActivity.name = ResolverActivity.class.getName();
6938                    mResolveActivity.packageName = mAndroidApplication.packageName;
6939                    mResolveActivity.processName = "system:ui";
6940                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6941                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6942                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6943                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6944                    mResolveActivity.exported = true;
6945                    mResolveActivity.enabled = true;
6946                    mResolveInfo.activityInfo = mResolveActivity;
6947                    mResolveInfo.priority = 0;
6948                    mResolveInfo.preferredOrder = 0;
6949                    mResolveInfo.match = 0;
6950                    mResolveComponentName = new ComponentName(
6951                            mAndroidApplication.packageName, mResolveActivity.name);
6952                }
6953            }
6954        }
6955
6956        if (DEBUG_PACKAGE_SCANNING) {
6957            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6958                Log.d(TAG, "Scanning package " + pkg.packageName);
6959        }
6960
6961        if (mPackages.containsKey(pkg.packageName)
6962                || mSharedLibraries.containsKey(pkg.packageName)) {
6963            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6964                    "Application package " + pkg.packageName
6965                    + " already installed.  Skipping duplicate.");
6966        }
6967
6968        // If we're only installing presumed-existing packages, require that the
6969        // scanned APK is both already known and at the path previously established
6970        // for it.  Previously unknown packages we pick up normally, but if we have an
6971        // a priori expectation about this package's install presence, enforce it.
6972        // With a singular exception for new system packages. When an OTA contains
6973        // a new system package, we allow the codepath to change from a system location
6974        // to the user-installed location. If we don't allow this change, any newer,
6975        // user-installed version of the application will be ignored.
6976        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6977            if (mExpectingBetter.containsKey(pkg.packageName)) {
6978                logCriticalInfo(Log.WARN,
6979                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6980            } else {
6981                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6982                if (known != null) {
6983                    if (DEBUG_PACKAGE_SCANNING) {
6984                        Log.d(TAG, "Examining " + pkg.codePath
6985                                + " and requiring known paths " + known.codePathString
6986                                + " & " + known.resourcePathString);
6987                    }
6988                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6989                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6990                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6991                                "Application package " + pkg.packageName
6992                                + " found at " + pkg.applicationInfo.getCodePath()
6993                                + " but expected at " + known.codePathString + "; ignoring.");
6994                    }
6995                }
6996            }
6997        }
6998
6999        // Initialize package source and resource directories
7000        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7001        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7002
7003        SharedUserSetting suid = null;
7004        PackageSetting pkgSetting = null;
7005
7006        if (!isSystemApp(pkg)) {
7007            // Only system apps can use these features.
7008            pkg.mOriginalPackages = null;
7009            pkg.mRealPackage = null;
7010            pkg.mAdoptPermissions = null;
7011        }
7012
7013        // writer
7014        synchronized (mPackages) {
7015            if (pkg.mSharedUserId != null) {
7016                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7017                if (suid == null) {
7018                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7019                            "Creating application package " + pkg.packageName
7020                            + " for shared user failed");
7021                }
7022                if (DEBUG_PACKAGE_SCANNING) {
7023                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7024                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7025                                + "): packages=" + suid.packages);
7026                }
7027            }
7028
7029            // Check if we are renaming from an original package name.
7030            PackageSetting origPackage = null;
7031            String realName = null;
7032            if (pkg.mOriginalPackages != null) {
7033                // This package may need to be renamed to a previously
7034                // installed name.  Let's check on that...
7035                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7036                if (pkg.mOriginalPackages.contains(renamed)) {
7037                    // This package had originally been installed as the
7038                    // original name, and we have already taken care of
7039                    // transitioning to the new one.  Just update the new
7040                    // one to continue using the old name.
7041                    realName = pkg.mRealPackage;
7042                    if (!pkg.packageName.equals(renamed)) {
7043                        // Callers into this function may have already taken
7044                        // care of renaming the package; only do it here if
7045                        // it is not already done.
7046                        pkg.setPackageName(renamed);
7047                    }
7048
7049                } else {
7050                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7051                        if ((origPackage = mSettings.peekPackageLPr(
7052                                pkg.mOriginalPackages.get(i))) != null) {
7053                            // We do have the package already installed under its
7054                            // original name...  should we use it?
7055                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7056                                // New package is not compatible with original.
7057                                origPackage = null;
7058                                continue;
7059                            } else if (origPackage.sharedUser != null) {
7060                                // Make sure uid is compatible between packages.
7061                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7062                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7063                                            + " to " + pkg.packageName + ": old uid "
7064                                            + origPackage.sharedUser.name
7065                                            + " differs from " + pkg.mSharedUserId);
7066                                    origPackage = null;
7067                                    continue;
7068                                }
7069                            } else {
7070                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7071                                        + pkg.packageName + " to old name " + origPackage.name);
7072                            }
7073                            break;
7074                        }
7075                    }
7076                }
7077            }
7078
7079            if (mTransferedPackages.contains(pkg.packageName)) {
7080                Slog.w(TAG, "Package " + pkg.packageName
7081                        + " was transferred to another, but its .apk remains");
7082            }
7083
7084            // Just create the setting, don't add it yet. For already existing packages
7085            // the PkgSetting exists already and doesn't have to be created.
7086            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7087                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7088                    pkg.applicationInfo.primaryCpuAbi,
7089                    pkg.applicationInfo.secondaryCpuAbi,
7090                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7091                    user, false);
7092            if (pkgSetting == null) {
7093                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7094                        "Creating application package " + pkg.packageName + " failed");
7095            }
7096
7097            if (pkgSetting.origPackage != null) {
7098                // If we are first transitioning from an original package,
7099                // fix up the new package's name now.  We need to do this after
7100                // looking up the package under its new name, so getPackageLP
7101                // can take care of fiddling things correctly.
7102                pkg.setPackageName(origPackage.name);
7103
7104                // File a report about this.
7105                String msg = "New package " + pkgSetting.realName
7106                        + " renamed to replace old package " + pkgSetting.name;
7107                reportSettingsProblem(Log.WARN, msg);
7108
7109                // Make a note of it.
7110                mTransferedPackages.add(origPackage.name);
7111
7112                // No longer need to retain this.
7113                pkgSetting.origPackage = null;
7114            }
7115
7116            if (realName != null) {
7117                // Make a note of it.
7118                mTransferedPackages.add(pkg.packageName);
7119            }
7120
7121            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7122                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7123            }
7124
7125            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7126                // Check all shared libraries and map to their actual file path.
7127                // We only do this here for apps not on a system dir, because those
7128                // are the only ones that can fail an install due to this.  We
7129                // will take care of the system apps by updating all of their
7130                // library paths after the scan is done.
7131                updateSharedLibrariesLPw(pkg, null);
7132            }
7133
7134            if (mFoundPolicyFile) {
7135                SELinuxMMAC.assignSeinfoValue(pkg);
7136            }
7137
7138            pkg.applicationInfo.uid = pkgSetting.appId;
7139            pkg.mExtras = pkgSetting;
7140            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7141                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7142                    // We just determined the app is signed correctly, so bring
7143                    // over the latest parsed certs.
7144                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7145                } else {
7146                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7147                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7148                                "Package " + pkg.packageName + " upgrade keys do not match the "
7149                                + "previously installed version");
7150                    } else {
7151                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7152                        String msg = "System package " + pkg.packageName
7153                            + " signature changed; retaining data.";
7154                        reportSettingsProblem(Log.WARN, msg);
7155                    }
7156                }
7157            } else {
7158                try {
7159                    verifySignaturesLP(pkgSetting, pkg);
7160                    // We just determined the app is signed correctly, so bring
7161                    // over the latest parsed certs.
7162                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7163                } catch (PackageManagerException e) {
7164                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7165                        throw e;
7166                    }
7167                    // The signature has changed, but this package is in the system
7168                    // image...  let's recover!
7169                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7170                    // However...  if this package is part of a shared user, but it
7171                    // doesn't match the signature of the shared user, let's fail.
7172                    // What this means is that you can't change the signatures
7173                    // associated with an overall shared user, which doesn't seem all
7174                    // that unreasonable.
7175                    if (pkgSetting.sharedUser != null) {
7176                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7177                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7178                            throw new PackageManagerException(
7179                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7180                                            "Signature mismatch for shared user : "
7181                                            + pkgSetting.sharedUser);
7182                        }
7183                    }
7184                    // File a report about this.
7185                    String msg = "System package " + pkg.packageName
7186                        + " signature changed; retaining data.";
7187                    reportSettingsProblem(Log.WARN, msg);
7188                }
7189            }
7190            // Verify that this new package doesn't have any content providers
7191            // that conflict with existing packages.  Only do this if the
7192            // package isn't already installed, since we don't want to break
7193            // things that are installed.
7194            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7195                final int N = pkg.providers.size();
7196                int i;
7197                for (i=0; i<N; i++) {
7198                    PackageParser.Provider p = pkg.providers.get(i);
7199                    if (p.info.authority != null) {
7200                        String names[] = p.info.authority.split(";");
7201                        for (int j = 0; j < names.length; j++) {
7202                            if (mProvidersByAuthority.containsKey(names[j])) {
7203                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7204                                final String otherPackageName =
7205                                        ((other != null && other.getComponentName() != null) ?
7206                                                other.getComponentName().getPackageName() : "?");
7207                                throw new PackageManagerException(
7208                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7209                                                "Can't install because provider name " + names[j]
7210                                                + " (in package " + pkg.applicationInfo.packageName
7211                                                + ") is already used by " + otherPackageName);
7212                            }
7213                        }
7214                    }
7215                }
7216            }
7217
7218            if (pkg.mAdoptPermissions != null) {
7219                // This package wants to adopt ownership of permissions from
7220                // another package.
7221                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7222                    final String origName = pkg.mAdoptPermissions.get(i);
7223                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7224                    if (orig != null) {
7225                        if (verifyPackageUpdateLPr(orig, pkg)) {
7226                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7227                                    + pkg.packageName);
7228                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7229                        }
7230                    }
7231                }
7232            }
7233        }
7234
7235        final String pkgName = pkg.packageName;
7236
7237        final long scanFileTime = scanFile.lastModified();
7238        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7239        pkg.applicationInfo.processName = fixProcessName(
7240                pkg.applicationInfo.packageName,
7241                pkg.applicationInfo.processName,
7242                pkg.applicationInfo.uid);
7243
7244        if (pkg != mPlatformPackage) {
7245            // This is a normal package, need to make its data directory.
7246            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7247                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7248
7249            boolean uidError = false;
7250            if (dataPath.exists()) {
7251                int currentUid = 0;
7252                try {
7253                    StructStat stat = Os.stat(dataPath.getPath());
7254                    currentUid = stat.st_uid;
7255                } catch (ErrnoException e) {
7256                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7257                }
7258
7259                // If we have mismatched owners for the data path, we have a problem.
7260                if (currentUid != pkg.applicationInfo.uid) {
7261                    boolean recovered = false;
7262                    if (currentUid == 0) {
7263                        // The directory somehow became owned by root.  Wow.
7264                        // This is probably because the system was stopped while
7265                        // installd was in the middle of messing with its libs
7266                        // directory.  Ask installd to fix that.
7267                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7268                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7269                        if (ret >= 0) {
7270                            recovered = true;
7271                            String msg = "Package " + pkg.packageName
7272                                    + " unexpectedly changed to uid 0; recovered to " +
7273                                    + pkg.applicationInfo.uid;
7274                            reportSettingsProblem(Log.WARN, msg);
7275                        }
7276                    }
7277                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7278                            || (scanFlags&SCAN_BOOTING) != 0)) {
7279                        // If this is a system app, we can at least delete its
7280                        // current data so the application will still work.
7281                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7282                        if (ret >= 0) {
7283                            // TODO: Kill the processes first
7284                            // Old data gone!
7285                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7286                                    ? "System package " : "Third party package ";
7287                            String msg = prefix + pkg.packageName
7288                                    + " has changed from uid: "
7289                                    + currentUid + " to "
7290                                    + pkg.applicationInfo.uid + "; old data erased";
7291                            reportSettingsProblem(Log.WARN, msg);
7292                            recovered = true;
7293                        }
7294                        if (!recovered) {
7295                            mHasSystemUidErrors = true;
7296                        }
7297                    } else if (!recovered) {
7298                        // If we allow this install to proceed, we will be broken.
7299                        // Abort, abort!
7300                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7301                                "scanPackageLI");
7302                    }
7303                    if (!recovered) {
7304                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7305                            + pkg.applicationInfo.uid + "/fs_"
7306                            + currentUid;
7307                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7308                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7309                        String msg = "Package " + pkg.packageName
7310                                + " has mismatched uid: "
7311                                + currentUid + " on disk, "
7312                                + pkg.applicationInfo.uid + " in settings";
7313                        // writer
7314                        synchronized (mPackages) {
7315                            mSettings.mReadMessages.append(msg);
7316                            mSettings.mReadMessages.append('\n');
7317                            uidError = true;
7318                            if (!pkgSetting.uidError) {
7319                                reportSettingsProblem(Log.ERROR, msg);
7320                            }
7321                        }
7322                    }
7323                }
7324
7325                // Ensure that directories are prepared
7326                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7327                        pkg.applicationInfo.seinfo);
7328
7329                if (mShouldRestoreconData) {
7330                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7331                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7332                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7333                }
7334            } else {
7335                if (DEBUG_PACKAGE_SCANNING) {
7336                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7337                        Log.v(TAG, "Want this data dir: " + dataPath);
7338                }
7339                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7340                        pkg.applicationInfo.seinfo);
7341            }
7342
7343            // Get all of our default paths setup
7344            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7345
7346            pkgSetting.uidError = uidError;
7347        }
7348
7349        final String path = scanFile.getPath();
7350        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7351
7352        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7353            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7354
7355            // Some system apps still use directory structure for native libraries
7356            // in which case we might end up not detecting abi solely based on apk
7357            // structure. Try to detect abi based on directory structure.
7358            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7359                    pkg.applicationInfo.primaryCpuAbi == null) {
7360                setBundledAppAbisAndRoots(pkg, pkgSetting);
7361                setNativeLibraryPaths(pkg);
7362            }
7363
7364        } else {
7365            if ((scanFlags & SCAN_MOVE) != 0) {
7366                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7367                // but we already have this packages package info in the PackageSetting. We just
7368                // use that and derive the native library path based on the new codepath.
7369                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7370                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7371            }
7372
7373            // Set native library paths again. For moves, the path will be updated based on the
7374            // ABIs we've determined above. For non-moves, the path will be updated based on the
7375            // ABIs we determined during compilation, but the path will depend on the final
7376            // package path (after the rename away from the stage path).
7377            setNativeLibraryPaths(pkg);
7378        }
7379
7380        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7381        final int[] userIds = sUserManager.getUserIds();
7382        synchronized (mInstallLock) {
7383            // Make sure all user data directories are ready to roll; we're okay
7384            // if they already exist
7385            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7386                for (int userId : userIds) {
7387                    if (userId != UserHandle.USER_SYSTEM) {
7388                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7389                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7390                                pkg.applicationInfo.seinfo);
7391                    }
7392                }
7393            }
7394
7395            // Create a native library symlink only if we have native libraries
7396            // and if the native libraries are 32 bit libraries. We do not provide
7397            // this symlink for 64 bit libraries.
7398            if (pkg.applicationInfo.primaryCpuAbi != null &&
7399                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7400                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7401                try {
7402                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7403                    for (int userId : userIds) {
7404                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7405                                nativeLibPath, userId) < 0) {
7406                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7407                                    "Failed linking native library dir (user=" + userId + ")");
7408                        }
7409                    }
7410                } finally {
7411                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7412                }
7413            }
7414        }
7415
7416        // This is a special case for the "system" package, where the ABI is
7417        // dictated by the zygote configuration (and init.rc). We should keep track
7418        // of this ABI so that we can deal with "normal" applications that run under
7419        // the same UID correctly.
7420        if (mPlatformPackage == pkg) {
7421            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7422                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7423        }
7424
7425        // If there's a mismatch between the abi-override in the package setting
7426        // and the abiOverride specified for the install. Warn about this because we
7427        // would've already compiled the app without taking the package setting into
7428        // account.
7429        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7430            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7431                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7432                        " for package: " + pkg.packageName);
7433            }
7434        }
7435
7436        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7437        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7438        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7439
7440        // Copy the derived override back to the parsed package, so that we can
7441        // update the package settings accordingly.
7442        pkg.cpuAbiOverride = cpuAbiOverride;
7443
7444        if (DEBUG_ABI_SELECTION) {
7445            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7446                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7447                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7448        }
7449
7450        // Push the derived path down into PackageSettings so we know what to
7451        // clean up at uninstall time.
7452        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7453
7454        if (DEBUG_ABI_SELECTION) {
7455            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7456                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7457                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7458        }
7459
7460        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7461            // We don't do this here during boot because we can do it all
7462            // at once after scanning all existing packages.
7463            //
7464            // We also do this *before* we perform dexopt on this package, so that
7465            // we can avoid redundant dexopts, and also to make sure we've got the
7466            // code and package path correct.
7467            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7468                    pkg, true /* boot complete */);
7469        }
7470
7471        if (mFactoryTest && pkg.requestedPermissions.contains(
7472                android.Manifest.permission.FACTORY_TEST)) {
7473            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7474        }
7475
7476        ArrayList<PackageParser.Package> clientLibPkgs = null;
7477
7478        // writer
7479        synchronized (mPackages) {
7480            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7481                // Only system apps can add new shared libraries.
7482                if (pkg.libraryNames != null) {
7483                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7484                        String name = pkg.libraryNames.get(i);
7485                        boolean allowed = false;
7486                        if (pkg.isUpdatedSystemApp()) {
7487                            // New library entries can only be added through the
7488                            // system image.  This is important to get rid of a lot
7489                            // of nasty edge cases: for example if we allowed a non-
7490                            // system update of the app to add a library, then uninstalling
7491                            // the update would make the library go away, and assumptions
7492                            // we made such as through app install filtering would now
7493                            // have allowed apps on the device which aren't compatible
7494                            // with it.  Better to just have the restriction here, be
7495                            // conservative, and create many fewer cases that can negatively
7496                            // impact the user experience.
7497                            final PackageSetting sysPs = mSettings
7498                                    .getDisabledSystemPkgLPr(pkg.packageName);
7499                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7500                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7501                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7502                                        allowed = true;
7503                                        break;
7504                                    }
7505                                }
7506                            }
7507                        } else {
7508                            allowed = true;
7509                        }
7510                        if (allowed) {
7511                            if (!mSharedLibraries.containsKey(name)) {
7512                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7513                            } else if (!name.equals(pkg.packageName)) {
7514                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7515                                        + name + " already exists; skipping");
7516                            }
7517                        } else {
7518                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7519                                    + name + " that is not declared on system image; skipping");
7520                        }
7521                    }
7522                    if ((scanFlags & SCAN_BOOTING) == 0) {
7523                        // If we are not booting, we need to update any applications
7524                        // that are clients of our shared library.  If we are booting,
7525                        // this will all be done once the scan is complete.
7526                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7527                    }
7528                }
7529            }
7530        }
7531
7532        // Request the ActivityManager to kill the process(only for existing packages)
7533        // so that we do not end up in a confused state while the user is still using the older
7534        // version of the application while the new one gets installed.
7535        if ((scanFlags & SCAN_REPLACING) != 0) {
7536            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7537
7538            killApplication(pkg.applicationInfo.packageName,
7539                        pkg.applicationInfo.uid, "replace pkg");
7540
7541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7542        }
7543
7544        // Also need to kill any apps that are dependent on the library.
7545        if (clientLibPkgs != null) {
7546            for (int i=0; i<clientLibPkgs.size(); i++) {
7547                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7548                killApplication(clientPkg.applicationInfo.packageName,
7549                        clientPkg.applicationInfo.uid, "update lib");
7550            }
7551        }
7552
7553        // Make sure we're not adding any bogus keyset info
7554        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7555        ksms.assertScannedPackageValid(pkg);
7556
7557        // writer
7558        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7559
7560        boolean createIdmapFailed = false;
7561        synchronized (mPackages) {
7562            // We don't expect installation to fail beyond this point
7563
7564            // Add the new setting to mSettings
7565            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7566            // Add the new setting to mPackages
7567            mPackages.put(pkg.applicationInfo.packageName, pkg);
7568            // Make sure we don't accidentally delete its data.
7569            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7570            while (iter.hasNext()) {
7571                PackageCleanItem item = iter.next();
7572                if (pkgName.equals(item.packageName)) {
7573                    iter.remove();
7574                }
7575            }
7576
7577            // Take care of first install / last update times.
7578            if (currentTime != 0) {
7579                if (pkgSetting.firstInstallTime == 0) {
7580                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7581                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7582                    pkgSetting.lastUpdateTime = currentTime;
7583                }
7584            } else if (pkgSetting.firstInstallTime == 0) {
7585                // We need *something*.  Take time time stamp of the file.
7586                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7587            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7588                if (scanFileTime != pkgSetting.timeStamp) {
7589                    // A package on the system image has changed; consider this
7590                    // to be an update.
7591                    pkgSetting.lastUpdateTime = scanFileTime;
7592                }
7593            }
7594
7595            // Add the package's KeySets to the global KeySetManagerService
7596            ksms.addScannedPackageLPw(pkg);
7597
7598            int N = pkg.providers.size();
7599            StringBuilder r = null;
7600            int i;
7601            for (i=0; i<N; i++) {
7602                PackageParser.Provider p = pkg.providers.get(i);
7603                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7604                        p.info.processName, pkg.applicationInfo.uid);
7605                mProviders.addProvider(p);
7606                p.syncable = p.info.isSyncable;
7607                if (p.info.authority != null) {
7608                    String names[] = p.info.authority.split(";");
7609                    p.info.authority = null;
7610                    for (int j = 0; j < names.length; j++) {
7611                        if (j == 1 && p.syncable) {
7612                            // We only want the first authority for a provider to possibly be
7613                            // syncable, so if we already added this provider using a different
7614                            // authority clear the syncable flag. We copy the provider before
7615                            // changing it because the mProviders object contains a reference
7616                            // to a provider that we don't want to change.
7617                            // Only do this for the second authority since the resulting provider
7618                            // object can be the same for all future authorities for this provider.
7619                            p = new PackageParser.Provider(p);
7620                            p.syncable = false;
7621                        }
7622                        if (!mProvidersByAuthority.containsKey(names[j])) {
7623                            mProvidersByAuthority.put(names[j], p);
7624                            if (p.info.authority == null) {
7625                                p.info.authority = names[j];
7626                            } else {
7627                                p.info.authority = p.info.authority + ";" + names[j];
7628                            }
7629                            if (DEBUG_PACKAGE_SCANNING) {
7630                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7631                                    Log.d(TAG, "Registered content provider: " + names[j]
7632                                            + ", className = " + p.info.name + ", isSyncable = "
7633                                            + p.info.isSyncable);
7634                            }
7635                        } else {
7636                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7637                            Slog.w(TAG, "Skipping provider name " + names[j] +
7638                                    " (in package " + pkg.applicationInfo.packageName +
7639                                    "): name already used by "
7640                                    + ((other != null && other.getComponentName() != null)
7641                                            ? other.getComponentName().getPackageName() : "?"));
7642                        }
7643                    }
7644                }
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(p.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7656            }
7657
7658            N = pkg.services.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.Service s = pkg.services.get(i);
7662                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7663                        s.info.processName, pkg.applicationInfo.uid);
7664                mServices.addService(s);
7665                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                    if (r == null) {
7667                        r = new StringBuilder(256);
7668                    } else {
7669                        r.append(' ');
7670                    }
7671                    r.append(s.info.name);
7672                }
7673            }
7674            if (r != null) {
7675                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7676            }
7677
7678            N = pkg.receivers.size();
7679            r = null;
7680            for (i=0; i<N; i++) {
7681                PackageParser.Activity a = pkg.receivers.get(i);
7682                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7683                        a.info.processName, pkg.applicationInfo.uid);
7684                mReceivers.addActivity(a, "receiver");
7685                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7686                    if (r == null) {
7687                        r = new StringBuilder(256);
7688                    } else {
7689                        r.append(' ');
7690                    }
7691                    r.append(a.info.name);
7692                }
7693            }
7694            if (r != null) {
7695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7696            }
7697
7698            N = pkg.activities.size();
7699            r = null;
7700            for (i=0; i<N; i++) {
7701                PackageParser.Activity a = pkg.activities.get(i);
7702                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7703                        a.info.processName, pkg.applicationInfo.uid);
7704                mActivities.addActivity(a, "activity");
7705                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7706                    if (r == null) {
7707                        r = new StringBuilder(256);
7708                    } else {
7709                        r.append(' ');
7710                    }
7711                    r.append(a.info.name);
7712                }
7713            }
7714            if (r != null) {
7715                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7716            }
7717
7718            N = pkg.permissionGroups.size();
7719            r = null;
7720            for (i=0; i<N; i++) {
7721                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7722                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7723                if (cur == null) {
7724                    mPermissionGroups.put(pg.info.name, pg);
7725                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7726                        if (r == null) {
7727                            r = new StringBuilder(256);
7728                        } else {
7729                            r.append(' ');
7730                        }
7731                        r.append(pg.info.name);
7732                    }
7733                } else {
7734                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7735                            + pg.info.packageName + " ignored: original from "
7736                            + cur.info.packageName);
7737                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7738                        if (r == null) {
7739                            r = new StringBuilder(256);
7740                        } else {
7741                            r.append(' ');
7742                        }
7743                        r.append("DUP:");
7744                        r.append(pg.info.name);
7745                    }
7746                }
7747            }
7748            if (r != null) {
7749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7750            }
7751
7752            N = pkg.permissions.size();
7753            r = null;
7754            for (i=0; i<N; i++) {
7755                PackageParser.Permission p = pkg.permissions.get(i);
7756
7757                // Assume by default that we did not install this permission into the system.
7758                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7759
7760                // Now that permission groups have a special meaning, we ignore permission
7761                // groups for legacy apps to prevent unexpected behavior. In particular,
7762                // permissions for one app being granted to someone just becuase they happen
7763                // to be in a group defined by another app (before this had no implications).
7764                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7765                    p.group = mPermissionGroups.get(p.info.group);
7766                    // Warn for a permission in an unknown group.
7767                    if (p.info.group != null && p.group == null) {
7768                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7769                                + p.info.packageName + " in an unknown group " + p.info.group);
7770                    }
7771                }
7772
7773                ArrayMap<String, BasePermission> permissionMap =
7774                        p.tree ? mSettings.mPermissionTrees
7775                                : mSettings.mPermissions;
7776                BasePermission bp = permissionMap.get(p.info.name);
7777
7778                // Allow system apps to redefine non-system permissions
7779                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7780                    final boolean currentOwnerIsSystem = (bp.perm != null
7781                            && isSystemApp(bp.perm.owner));
7782                    if (isSystemApp(p.owner)) {
7783                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7784                            // It's a built-in permission and no owner, take ownership now
7785                            bp.packageSetting = pkgSetting;
7786                            bp.perm = p;
7787                            bp.uid = pkg.applicationInfo.uid;
7788                            bp.sourcePackage = p.info.packageName;
7789                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7790                        } else if (!currentOwnerIsSystem) {
7791                            String msg = "New decl " + p.owner + " of permission  "
7792                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7793                            reportSettingsProblem(Log.WARN, msg);
7794                            bp = null;
7795                        }
7796                    }
7797                }
7798
7799                if (bp == null) {
7800                    bp = new BasePermission(p.info.name, p.info.packageName,
7801                            BasePermission.TYPE_NORMAL);
7802                    permissionMap.put(p.info.name, bp);
7803                }
7804
7805                if (bp.perm == null) {
7806                    if (bp.sourcePackage == null
7807                            || bp.sourcePackage.equals(p.info.packageName)) {
7808                        BasePermission tree = findPermissionTreeLP(p.info.name);
7809                        if (tree == null
7810                                || tree.sourcePackage.equals(p.info.packageName)) {
7811                            bp.packageSetting = pkgSetting;
7812                            bp.perm = p;
7813                            bp.uid = pkg.applicationInfo.uid;
7814                            bp.sourcePackage = p.info.packageName;
7815                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7816                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7817                                if (r == null) {
7818                                    r = new StringBuilder(256);
7819                                } else {
7820                                    r.append(' ');
7821                                }
7822                                r.append(p.info.name);
7823                            }
7824                        } else {
7825                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7826                                    + p.info.packageName + " ignored: base tree "
7827                                    + tree.name + " is from package "
7828                                    + tree.sourcePackage);
7829                        }
7830                    } else {
7831                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7832                                + p.info.packageName + " ignored: original from "
7833                                + bp.sourcePackage);
7834                    }
7835                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7836                    if (r == null) {
7837                        r = new StringBuilder(256);
7838                    } else {
7839                        r.append(' ');
7840                    }
7841                    r.append("DUP:");
7842                    r.append(p.info.name);
7843                }
7844                if (bp.perm == p) {
7845                    bp.protectionLevel = p.info.protectionLevel;
7846                }
7847            }
7848
7849            if (r != null) {
7850                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7851            }
7852
7853            N = pkg.instrumentation.size();
7854            r = null;
7855            for (i=0; i<N; i++) {
7856                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7857                a.info.packageName = pkg.applicationInfo.packageName;
7858                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7859                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7860                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7861                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7862                a.info.dataDir = pkg.applicationInfo.dataDir;
7863                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7864                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7865
7866                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7867                // need other information about the application, like the ABI and what not ?
7868                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7869                mInstrumentation.put(a.getComponentName(), a);
7870                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7871                    if (r == null) {
7872                        r = new StringBuilder(256);
7873                    } else {
7874                        r.append(' ');
7875                    }
7876                    r.append(a.info.name);
7877                }
7878            }
7879            if (r != null) {
7880                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7881            }
7882
7883            if (pkg.protectedBroadcasts != null) {
7884                N = pkg.protectedBroadcasts.size();
7885                for (i=0; i<N; i++) {
7886                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7887                }
7888            }
7889
7890            pkgSetting.setTimeStamp(scanFileTime);
7891
7892            // Create idmap files for pairs of (packages, overlay packages).
7893            // Note: "android", ie framework-res.apk, is handled by native layers.
7894            if (pkg.mOverlayTarget != null) {
7895                // This is an overlay package.
7896                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7897                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7898                        mOverlays.put(pkg.mOverlayTarget,
7899                                new ArrayMap<String, PackageParser.Package>());
7900                    }
7901                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7902                    map.put(pkg.packageName, pkg);
7903                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7904                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7905                        createIdmapFailed = true;
7906                    }
7907                }
7908            } else if (mOverlays.containsKey(pkg.packageName) &&
7909                    !pkg.packageName.equals("android")) {
7910                // This is a regular package, with one or more known overlay packages.
7911                createIdmapsForPackageLI(pkg);
7912            }
7913        }
7914
7915        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7916
7917        if (createIdmapFailed) {
7918            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7919                    "scanPackageLI failed to createIdmap");
7920        }
7921        return pkg;
7922    }
7923
7924    /**
7925     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7926     * is derived purely on the basis of the contents of {@code scanFile} and
7927     * {@code cpuAbiOverride}.
7928     *
7929     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7930     */
7931    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7932                                 String cpuAbiOverride, boolean extractLibs)
7933            throws PackageManagerException {
7934        // TODO: We can probably be smarter about this stuff. For installed apps,
7935        // we can calculate this information at install time once and for all. For
7936        // system apps, we can probably assume that this information doesn't change
7937        // after the first boot scan. As things stand, we do lots of unnecessary work.
7938
7939        // Give ourselves some initial paths; we'll come back for another
7940        // pass once we've determined ABI below.
7941        setNativeLibraryPaths(pkg);
7942
7943        // We would never need to extract libs for forward-locked and external packages,
7944        // since the container service will do it for us. We shouldn't attempt to
7945        // extract libs from system app when it was not updated.
7946        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7947                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7948            extractLibs = false;
7949        }
7950
7951        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7952        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7953
7954        NativeLibraryHelper.Handle handle = null;
7955        try {
7956            handle = NativeLibraryHelper.Handle.create(pkg);
7957            // TODO(multiArch): This can be null for apps that didn't go through the
7958            // usual installation process. We can calculate it again, like we
7959            // do during install time.
7960            //
7961            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7962            // unnecessary.
7963            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7964
7965            // Null out the abis so that they can be recalculated.
7966            pkg.applicationInfo.primaryCpuAbi = null;
7967            pkg.applicationInfo.secondaryCpuAbi = null;
7968            if (isMultiArch(pkg.applicationInfo)) {
7969                // Warn if we've set an abiOverride for multi-lib packages..
7970                // By definition, we need to copy both 32 and 64 bit libraries for
7971                // such packages.
7972                if (pkg.cpuAbiOverride != null
7973                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7974                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7975                }
7976
7977                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7978                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7979                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7980                    if (extractLibs) {
7981                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7982                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7983                                useIsaSpecificSubdirs);
7984                    } else {
7985                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7986                    }
7987                }
7988
7989                maybeThrowExceptionForMultiArchCopy(
7990                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7991
7992                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7993                    if (extractLibs) {
7994                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7995                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7996                                useIsaSpecificSubdirs);
7997                    } else {
7998                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7999                    }
8000                }
8001
8002                maybeThrowExceptionForMultiArchCopy(
8003                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8004
8005                if (abi64 >= 0) {
8006                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8007                }
8008
8009                if (abi32 >= 0) {
8010                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8011                    if (abi64 >= 0) {
8012                        pkg.applicationInfo.secondaryCpuAbi = abi;
8013                    } else {
8014                        pkg.applicationInfo.primaryCpuAbi = abi;
8015                    }
8016                }
8017            } else {
8018                String[] abiList = (cpuAbiOverride != null) ?
8019                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8020
8021                // Enable gross and lame hacks for apps that are built with old
8022                // SDK tools. We must scan their APKs for renderscript bitcode and
8023                // not launch them if it's present. Don't bother checking on devices
8024                // that don't have 64 bit support.
8025                boolean needsRenderScriptOverride = false;
8026                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8027                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8028                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8029                    needsRenderScriptOverride = true;
8030                }
8031
8032                final int copyRet;
8033                if (extractLibs) {
8034                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8035                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8036                } else {
8037                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8038                }
8039
8040                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8041                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8042                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8043                }
8044
8045                if (copyRet >= 0) {
8046                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8047                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8048                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8049                } else if (needsRenderScriptOverride) {
8050                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8051                }
8052            }
8053        } catch (IOException ioe) {
8054            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8055        } finally {
8056            IoUtils.closeQuietly(handle);
8057        }
8058
8059        // Now that we've calculated the ABIs and determined if it's an internal app,
8060        // we will go ahead and populate the nativeLibraryPath.
8061        setNativeLibraryPaths(pkg);
8062    }
8063
8064    /**
8065     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8066     * i.e, so that all packages can be run inside a single process if required.
8067     *
8068     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8069     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8070     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8071     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8072     * updating a package that belongs to a shared user.
8073     *
8074     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8075     * adds unnecessary complexity.
8076     */
8077    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8078            PackageParser.Package scannedPackage, boolean bootComplete) {
8079        String requiredInstructionSet = null;
8080        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8081            requiredInstructionSet = VMRuntime.getInstructionSet(
8082                     scannedPackage.applicationInfo.primaryCpuAbi);
8083        }
8084
8085        PackageSetting requirer = null;
8086        for (PackageSetting ps : packagesForUser) {
8087            // If packagesForUser contains scannedPackage, we skip it. This will happen
8088            // when scannedPackage is an update of an existing package. Without this check,
8089            // we will never be able to change the ABI of any package belonging to a shared
8090            // user, even if it's compatible with other packages.
8091            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8092                if (ps.primaryCpuAbiString == null) {
8093                    continue;
8094                }
8095
8096                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8097                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8098                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8099                    // this but there's not much we can do.
8100                    String errorMessage = "Instruction set mismatch, "
8101                            + ((requirer == null) ? "[caller]" : requirer)
8102                            + " requires " + requiredInstructionSet + " whereas " + ps
8103                            + " requires " + instructionSet;
8104                    Slog.w(TAG, errorMessage);
8105                }
8106
8107                if (requiredInstructionSet == null) {
8108                    requiredInstructionSet = instructionSet;
8109                    requirer = ps;
8110                }
8111            }
8112        }
8113
8114        if (requiredInstructionSet != null) {
8115            String adjustedAbi;
8116            if (requirer != null) {
8117                // requirer != null implies that either scannedPackage was null or that scannedPackage
8118                // did not require an ABI, in which case we have to adjust scannedPackage to match
8119                // the ABI of the set (which is the same as requirer's ABI)
8120                adjustedAbi = requirer.primaryCpuAbiString;
8121                if (scannedPackage != null) {
8122                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8123                }
8124            } else {
8125                // requirer == null implies that we're updating all ABIs in the set to
8126                // match scannedPackage.
8127                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8128            }
8129
8130            for (PackageSetting ps : packagesForUser) {
8131                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8132                    if (ps.primaryCpuAbiString != null) {
8133                        continue;
8134                    }
8135
8136                    ps.primaryCpuAbiString = adjustedAbi;
8137                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8138                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8139                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8140                        mInstaller.rmdex(ps.codePathString,
8141                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8142                    }
8143                }
8144            }
8145        }
8146    }
8147
8148    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8149        synchronized (mPackages) {
8150            mResolverReplaced = true;
8151            // Set up information for custom user intent resolution activity.
8152            mResolveActivity.applicationInfo = pkg.applicationInfo;
8153            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8154            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8155            mResolveActivity.processName = pkg.applicationInfo.packageName;
8156            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8157            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8158                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8159            mResolveActivity.theme = 0;
8160            mResolveActivity.exported = true;
8161            mResolveActivity.enabled = true;
8162            mResolveInfo.activityInfo = mResolveActivity;
8163            mResolveInfo.priority = 0;
8164            mResolveInfo.preferredOrder = 0;
8165            mResolveInfo.match = 0;
8166            mResolveComponentName = mCustomResolverComponentName;
8167            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8168                    mResolveComponentName);
8169        }
8170    }
8171
8172    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8173        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8174
8175        // Set up information for ephemeral installer activity
8176        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8177        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8178        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8179        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8180        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8181        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8182                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8183        mEphemeralInstallerActivity.theme = 0;
8184        mEphemeralInstallerActivity.exported = true;
8185        mEphemeralInstallerActivity.enabled = true;
8186        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8187        mEphemeralInstallerInfo.priority = 0;
8188        mEphemeralInstallerInfo.preferredOrder = 0;
8189        mEphemeralInstallerInfo.match = 0;
8190
8191        if (DEBUG_EPHEMERAL) {
8192            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8193        }
8194    }
8195
8196    private static String calculateBundledApkRoot(final String codePathString) {
8197        final File codePath = new File(codePathString);
8198        final File codeRoot;
8199        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8200            codeRoot = Environment.getRootDirectory();
8201        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8202            codeRoot = Environment.getOemDirectory();
8203        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8204            codeRoot = Environment.getVendorDirectory();
8205        } else {
8206            // Unrecognized code path; take its top real segment as the apk root:
8207            // e.g. /something/app/blah.apk => /something
8208            try {
8209                File f = codePath.getCanonicalFile();
8210                File parent = f.getParentFile();    // non-null because codePath is a file
8211                File tmp;
8212                while ((tmp = parent.getParentFile()) != null) {
8213                    f = parent;
8214                    parent = tmp;
8215                }
8216                codeRoot = f;
8217                Slog.w(TAG, "Unrecognized code path "
8218                        + codePath + " - using " + codeRoot);
8219            } catch (IOException e) {
8220                // Can't canonicalize the code path -- shenanigans?
8221                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8222                return Environment.getRootDirectory().getPath();
8223            }
8224        }
8225        return codeRoot.getPath();
8226    }
8227
8228    /**
8229     * Derive and set the location of native libraries for the given package,
8230     * which varies depending on where and how the package was installed.
8231     */
8232    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8233        final ApplicationInfo info = pkg.applicationInfo;
8234        final String codePath = pkg.codePath;
8235        final File codeFile = new File(codePath);
8236        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8237        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8238
8239        info.nativeLibraryRootDir = null;
8240        info.nativeLibraryRootRequiresIsa = false;
8241        info.nativeLibraryDir = null;
8242        info.secondaryNativeLibraryDir = null;
8243
8244        if (isApkFile(codeFile)) {
8245            // Monolithic install
8246            if (bundledApp) {
8247                // If "/system/lib64/apkname" exists, assume that is the per-package
8248                // native library directory to use; otherwise use "/system/lib/apkname".
8249                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8250                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8251                        getPrimaryInstructionSet(info));
8252
8253                // This is a bundled system app so choose the path based on the ABI.
8254                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8255                // is just the default path.
8256                final String apkName = deriveCodePathName(codePath);
8257                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8258                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8259                        apkName).getAbsolutePath();
8260
8261                if (info.secondaryCpuAbi != null) {
8262                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8263                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8264                            secondaryLibDir, apkName).getAbsolutePath();
8265                }
8266            } else if (asecApp) {
8267                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8268                        .getAbsolutePath();
8269            } else {
8270                final String apkName = deriveCodePathName(codePath);
8271                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8272                        .getAbsolutePath();
8273            }
8274
8275            info.nativeLibraryRootRequiresIsa = false;
8276            info.nativeLibraryDir = info.nativeLibraryRootDir;
8277        } else {
8278            // Cluster install
8279            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8280            info.nativeLibraryRootRequiresIsa = true;
8281
8282            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8283                    getPrimaryInstructionSet(info)).getAbsolutePath();
8284
8285            if (info.secondaryCpuAbi != null) {
8286                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8287                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8288            }
8289        }
8290    }
8291
8292    /**
8293     * Calculate the abis and roots for a bundled app. These can uniquely
8294     * be determined from the contents of the system partition, i.e whether
8295     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8296     * of this information, and instead assume that the system was built
8297     * sensibly.
8298     */
8299    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8300                                           PackageSetting pkgSetting) {
8301        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8302
8303        // If "/system/lib64/apkname" exists, assume that is the per-package
8304        // native library directory to use; otherwise use "/system/lib/apkname".
8305        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8306        setBundledAppAbi(pkg, apkRoot, apkName);
8307        // pkgSetting might be null during rescan following uninstall of updates
8308        // to a bundled app, so accommodate that possibility.  The settings in
8309        // that case will be established later from the parsed package.
8310        //
8311        // If the settings aren't null, sync them up with what we've just derived.
8312        // note that apkRoot isn't stored in the package settings.
8313        if (pkgSetting != null) {
8314            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8315            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8316        }
8317    }
8318
8319    /**
8320     * Deduces the ABI of a bundled app and sets the relevant fields on the
8321     * parsed pkg object.
8322     *
8323     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8324     *        under which system libraries are installed.
8325     * @param apkName the name of the installed package.
8326     */
8327    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8328        final File codeFile = new File(pkg.codePath);
8329
8330        final boolean has64BitLibs;
8331        final boolean has32BitLibs;
8332        if (isApkFile(codeFile)) {
8333            // Monolithic install
8334            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8335            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8336        } else {
8337            // Cluster install
8338            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8339            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8340                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8341                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8342                has64BitLibs = (new File(rootDir, isa)).exists();
8343            } else {
8344                has64BitLibs = false;
8345            }
8346            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8347                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8348                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8349                has32BitLibs = (new File(rootDir, isa)).exists();
8350            } else {
8351                has32BitLibs = false;
8352            }
8353        }
8354
8355        if (has64BitLibs && !has32BitLibs) {
8356            // The package has 64 bit libs, but not 32 bit libs. Its primary
8357            // ABI should be 64 bit. We can safely assume here that the bundled
8358            // native libraries correspond to the most preferred ABI in the list.
8359
8360            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8361            pkg.applicationInfo.secondaryCpuAbi = null;
8362        } else if (has32BitLibs && !has64BitLibs) {
8363            // The package has 32 bit libs but not 64 bit libs. Its primary
8364            // ABI should be 32 bit.
8365
8366            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8367            pkg.applicationInfo.secondaryCpuAbi = null;
8368        } else if (has32BitLibs && has64BitLibs) {
8369            // The application has both 64 and 32 bit bundled libraries. We check
8370            // here that the app declares multiArch support, and warn if it doesn't.
8371            //
8372            // We will be lenient here and record both ABIs. The primary will be the
8373            // ABI that's higher on the list, i.e, a device that's configured to prefer
8374            // 64 bit apps will see a 64 bit primary ABI,
8375
8376            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8377                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8378            }
8379
8380            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8381                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8382                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8383            } else {
8384                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8385                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8386            }
8387        } else {
8388            pkg.applicationInfo.primaryCpuAbi = null;
8389            pkg.applicationInfo.secondaryCpuAbi = null;
8390        }
8391    }
8392
8393    private void killApplication(String pkgName, int appId, String reason) {
8394        // Request the ActivityManager to kill the process(only for existing packages)
8395        // so that we do not end up in a confused state while the user is still using the older
8396        // version of the application while the new one gets installed.
8397        IActivityManager am = ActivityManagerNative.getDefault();
8398        if (am != null) {
8399            try {
8400                am.killApplicationWithAppId(pkgName, appId, reason);
8401            } catch (RemoteException e) {
8402            }
8403        }
8404    }
8405
8406    void removePackageLI(PackageSetting ps, boolean chatty) {
8407        if (DEBUG_INSTALL) {
8408            if (chatty)
8409                Log.d(TAG, "Removing package " + ps.name);
8410        }
8411
8412        // writer
8413        synchronized (mPackages) {
8414            mPackages.remove(ps.name);
8415            final PackageParser.Package pkg = ps.pkg;
8416            if (pkg != null) {
8417                cleanPackageDataStructuresLILPw(pkg, chatty);
8418            }
8419        }
8420    }
8421
8422    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8423        if (DEBUG_INSTALL) {
8424            if (chatty)
8425                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8426        }
8427
8428        // writer
8429        synchronized (mPackages) {
8430            mPackages.remove(pkg.applicationInfo.packageName);
8431            cleanPackageDataStructuresLILPw(pkg, chatty);
8432        }
8433    }
8434
8435    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8436        int N = pkg.providers.size();
8437        StringBuilder r = null;
8438        int i;
8439        for (i=0; i<N; i++) {
8440            PackageParser.Provider p = pkg.providers.get(i);
8441            mProviders.removeProvider(p);
8442            if (p.info.authority == null) {
8443
8444                /* There was another ContentProvider with this authority when
8445                 * this app was installed so this authority is null,
8446                 * Ignore it as we don't have to unregister the provider.
8447                 */
8448                continue;
8449            }
8450            String names[] = p.info.authority.split(";");
8451            for (int j = 0; j < names.length; j++) {
8452                if (mProvidersByAuthority.get(names[j]) == p) {
8453                    mProvidersByAuthority.remove(names[j]);
8454                    if (DEBUG_REMOVE) {
8455                        if (chatty)
8456                            Log.d(TAG, "Unregistered content provider: " + names[j]
8457                                    + ", className = " + p.info.name + ", isSyncable = "
8458                                    + p.info.isSyncable);
8459                    }
8460                }
8461            }
8462            if (DEBUG_REMOVE && chatty) {
8463                if (r == null) {
8464                    r = new StringBuilder(256);
8465                } else {
8466                    r.append(' ');
8467                }
8468                r.append(p.info.name);
8469            }
8470        }
8471        if (r != null) {
8472            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8473        }
8474
8475        N = pkg.services.size();
8476        r = null;
8477        for (i=0; i<N; i++) {
8478            PackageParser.Service s = pkg.services.get(i);
8479            mServices.removeService(s);
8480            if (chatty) {
8481                if (r == null) {
8482                    r = new StringBuilder(256);
8483                } else {
8484                    r.append(' ');
8485                }
8486                r.append(s.info.name);
8487            }
8488        }
8489        if (r != null) {
8490            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8491        }
8492
8493        N = pkg.receivers.size();
8494        r = null;
8495        for (i=0; i<N; i++) {
8496            PackageParser.Activity a = pkg.receivers.get(i);
8497            mReceivers.removeActivity(a, "receiver");
8498            if (DEBUG_REMOVE && chatty) {
8499                if (r == null) {
8500                    r = new StringBuilder(256);
8501                } else {
8502                    r.append(' ');
8503                }
8504                r.append(a.info.name);
8505            }
8506        }
8507        if (r != null) {
8508            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8509        }
8510
8511        N = pkg.activities.size();
8512        r = null;
8513        for (i=0; i<N; i++) {
8514            PackageParser.Activity a = pkg.activities.get(i);
8515            mActivities.removeActivity(a, "activity");
8516            if (DEBUG_REMOVE && chatty) {
8517                if (r == null) {
8518                    r = new StringBuilder(256);
8519                } else {
8520                    r.append(' ');
8521                }
8522                r.append(a.info.name);
8523            }
8524        }
8525        if (r != null) {
8526            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8527        }
8528
8529        N = pkg.permissions.size();
8530        r = null;
8531        for (i=0; i<N; i++) {
8532            PackageParser.Permission p = pkg.permissions.get(i);
8533            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8534            if (bp == null) {
8535                bp = mSettings.mPermissionTrees.get(p.info.name);
8536            }
8537            if (bp != null && bp.perm == p) {
8538                bp.perm = null;
8539                if (DEBUG_REMOVE && chatty) {
8540                    if (r == null) {
8541                        r = new StringBuilder(256);
8542                    } else {
8543                        r.append(' ');
8544                    }
8545                    r.append(p.info.name);
8546                }
8547            }
8548            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8549                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8550                if (appOpPkgs != null) {
8551                    appOpPkgs.remove(pkg.packageName);
8552                }
8553            }
8554        }
8555        if (r != null) {
8556            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8557        }
8558
8559        N = pkg.requestedPermissions.size();
8560        r = null;
8561        for (i=0; i<N; i++) {
8562            String perm = pkg.requestedPermissions.get(i);
8563            BasePermission bp = mSettings.mPermissions.get(perm);
8564            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8565                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8566                if (appOpPkgs != null) {
8567                    appOpPkgs.remove(pkg.packageName);
8568                    if (appOpPkgs.isEmpty()) {
8569                        mAppOpPermissionPackages.remove(perm);
8570                    }
8571                }
8572            }
8573        }
8574        if (r != null) {
8575            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8576        }
8577
8578        N = pkg.instrumentation.size();
8579        r = null;
8580        for (i=0; i<N; i++) {
8581            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8582            mInstrumentation.remove(a.getComponentName());
8583            if (DEBUG_REMOVE && chatty) {
8584                if (r == null) {
8585                    r = new StringBuilder(256);
8586                } else {
8587                    r.append(' ');
8588                }
8589                r.append(a.info.name);
8590            }
8591        }
8592        if (r != null) {
8593            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8594        }
8595
8596        r = null;
8597        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8598            // Only system apps can hold shared libraries.
8599            if (pkg.libraryNames != null) {
8600                for (i=0; i<pkg.libraryNames.size(); i++) {
8601                    String name = pkg.libraryNames.get(i);
8602                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8603                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8604                        mSharedLibraries.remove(name);
8605                        if (DEBUG_REMOVE && chatty) {
8606                            if (r == null) {
8607                                r = new StringBuilder(256);
8608                            } else {
8609                                r.append(' ');
8610                            }
8611                            r.append(name);
8612                        }
8613                    }
8614                }
8615            }
8616        }
8617        if (r != null) {
8618            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8619        }
8620    }
8621
8622    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8623        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8624            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8625                return true;
8626            }
8627        }
8628        return false;
8629    }
8630
8631    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8632    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8633    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8634
8635    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8636            int flags) {
8637        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8638        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8639    }
8640
8641    private void updatePermissionsLPw(String changingPkg,
8642            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8643        // Make sure there are no dangling permission trees.
8644        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8645        while (it.hasNext()) {
8646            final BasePermission bp = it.next();
8647            if (bp.packageSetting == null) {
8648                // We may not yet have parsed the package, so just see if
8649                // we still know about its settings.
8650                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8651            }
8652            if (bp.packageSetting == null) {
8653                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8654                        + " from package " + bp.sourcePackage);
8655                it.remove();
8656            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8657                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8658                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8659                            + " from package " + bp.sourcePackage);
8660                    flags |= UPDATE_PERMISSIONS_ALL;
8661                    it.remove();
8662                }
8663            }
8664        }
8665
8666        // Make sure all dynamic permissions have been assigned to a package,
8667        // and make sure there are no dangling permissions.
8668        it = mSettings.mPermissions.values().iterator();
8669        while (it.hasNext()) {
8670            final BasePermission bp = it.next();
8671            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8672                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8673                        + bp.name + " pkg=" + bp.sourcePackage
8674                        + " info=" + bp.pendingInfo);
8675                if (bp.packageSetting == null && bp.pendingInfo != null) {
8676                    final BasePermission tree = findPermissionTreeLP(bp.name);
8677                    if (tree != null && tree.perm != null) {
8678                        bp.packageSetting = tree.packageSetting;
8679                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8680                                new PermissionInfo(bp.pendingInfo));
8681                        bp.perm.info.packageName = tree.perm.info.packageName;
8682                        bp.perm.info.name = bp.name;
8683                        bp.uid = tree.uid;
8684                    }
8685                }
8686            }
8687            if (bp.packageSetting == null) {
8688                // We may not yet have parsed the package, so just see if
8689                // we still know about its settings.
8690                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8691            }
8692            if (bp.packageSetting == null) {
8693                Slog.w(TAG, "Removing dangling permission: " + bp.name
8694                        + " from package " + bp.sourcePackage);
8695                it.remove();
8696            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8697                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8698                    Slog.i(TAG, "Removing old permission: " + bp.name
8699                            + " from package " + bp.sourcePackage);
8700                    flags |= UPDATE_PERMISSIONS_ALL;
8701                    it.remove();
8702                }
8703            }
8704        }
8705
8706        // Now update the permissions for all packages, in particular
8707        // replace the granted permissions of the system packages.
8708        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8709            for (PackageParser.Package pkg : mPackages.values()) {
8710                if (pkg != pkgInfo) {
8711                    // Only replace for packages on requested volume
8712                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8713                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8714                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8715                    grantPermissionsLPw(pkg, replace, changingPkg);
8716                }
8717            }
8718        }
8719
8720        if (pkgInfo != null) {
8721            // Only replace for packages on requested volume
8722            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8723            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8724                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8725            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8726        }
8727    }
8728
8729    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8730            String packageOfInterest) {
8731        // IMPORTANT: There are two types of permissions: install and runtime.
8732        // Install time permissions are granted when the app is installed to
8733        // all device users and users added in the future. Runtime permissions
8734        // are granted at runtime explicitly to specific users. Normal and signature
8735        // protected permissions are install time permissions. Dangerous permissions
8736        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8737        // otherwise they are runtime permissions. This function does not manage
8738        // runtime permissions except for the case an app targeting Lollipop MR1
8739        // being upgraded to target a newer SDK, in which case dangerous permissions
8740        // are transformed from install time to runtime ones.
8741
8742        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8743        if (ps == null) {
8744            return;
8745        }
8746
8747        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8748
8749        PermissionsState permissionsState = ps.getPermissionsState();
8750        PermissionsState origPermissions = permissionsState;
8751
8752        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8753
8754        boolean runtimePermissionsRevoked = false;
8755        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8756
8757        boolean changedInstallPermission = false;
8758
8759        if (replace) {
8760            ps.installPermissionsFixed = false;
8761            if (!ps.isSharedUser()) {
8762                origPermissions = new PermissionsState(permissionsState);
8763                permissionsState.reset();
8764            } else {
8765                // We need to know only about runtime permission changes since the
8766                // calling code always writes the install permissions state but
8767                // the runtime ones are written only if changed. The only cases of
8768                // changed runtime permissions here are promotion of an install to
8769                // runtime and revocation of a runtime from a shared user.
8770                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8771                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8772                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8773                    runtimePermissionsRevoked = true;
8774                }
8775            }
8776        }
8777
8778        permissionsState.setGlobalGids(mGlobalGids);
8779
8780        final int N = pkg.requestedPermissions.size();
8781        for (int i=0; i<N; i++) {
8782            final String name = pkg.requestedPermissions.get(i);
8783            final BasePermission bp = mSettings.mPermissions.get(name);
8784
8785            if (DEBUG_INSTALL) {
8786                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8787            }
8788
8789            if (bp == null || bp.packageSetting == null) {
8790                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8791                    Slog.w(TAG, "Unknown permission " + name
8792                            + " in package " + pkg.packageName);
8793                }
8794                continue;
8795            }
8796
8797            final String perm = bp.name;
8798            boolean allowedSig = false;
8799            int grant = GRANT_DENIED;
8800
8801            // Keep track of app op permissions.
8802            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8803                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8804                if (pkgs == null) {
8805                    pkgs = new ArraySet<>();
8806                    mAppOpPermissionPackages.put(bp.name, pkgs);
8807                }
8808                pkgs.add(pkg.packageName);
8809            }
8810
8811            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8812            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8813                    >= Build.VERSION_CODES.M;
8814            switch (level) {
8815                case PermissionInfo.PROTECTION_NORMAL: {
8816                    // For all apps normal permissions are install time ones.
8817                    grant = GRANT_INSTALL;
8818                } break;
8819
8820                case PermissionInfo.PROTECTION_DANGEROUS: {
8821                    // If a permission review is required for legacy apps we represent
8822                    // their permissions as always granted runtime ones since we need
8823                    // to keep the review required permission flag per user while an
8824                    // install permission's state is shared across all users.
8825                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8826                        // For legacy apps dangerous permissions are install time ones.
8827                        grant = GRANT_INSTALL;
8828                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8829                        // For legacy apps that became modern, install becomes runtime.
8830                        grant = GRANT_UPGRADE;
8831                    } else if (mPromoteSystemApps
8832                            && isSystemApp(ps)
8833                            && mExistingSystemPackages.contains(ps.name)) {
8834                        // For legacy system apps, install becomes runtime.
8835                        // We cannot check hasInstallPermission() for system apps since those
8836                        // permissions were granted implicitly and not persisted pre-M.
8837                        grant = GRANT_UPGRADE;
8838                    } else {
8839                        // For modern apps keep runtime permissions unchanged.
8840                        grant = GRANT_RUNTIME;
8841                    }
8842                } break;
8843
8844                case PermissionInfo.PROTECTION_SIGNATURE: {
8845                    // For all apps signature permissions are install time ones.
8846                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8847                    if (allowedSig) {
8848                        grant = GRANT_INSTALL;
8849                    }
8850                } break;
8851            }
8852
8853            if (DEBUG_INSTALL) {
8854                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8855            }
8856
8857            if (grant != GRANT_DENIED) {
8858                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8859                    // If this is an existing, non-system package, then
8860                    // we can't add any new permissions to it.
8861                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8862                        // Except...  if this is a permission that was added
8863                        // to the platform (note: need to only do this when
8864                        // updating the platform).
8865                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8866                            grant = GRANT_DENIED;
8867                        }
8868                    }
8869                }
8870
8871                switch (grant) {
8872                    case GRANT_INSTALL: {
8873                        // Revoke this as runtime permission to handle the case of
8874                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8875                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8876                            if (origPermissions.getRuntimePermissionState(
8877                                    bp.name, userId) != null) {
8878                                // Revoke the runtime permission and clear the flags.
8879                                origPermissions.revokeRuntimePermission(bp, userId);
8880                                origPermissions.updatePermissionFlags(bp, userId,
8881                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8882                                // If we revoked a permission permission, we have to write.
8883                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8884                                        changedRuntimePermissionUserIds, userId);
8885                            }
8886                        }
8887                        // Grant an install permission.
8888                        if (permissionsState.grantInstallPermission(bp) !=
8889                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8890                            changedInstallPermission = true;
8891                        }
8892                    } break;
8893
8894                    case GRANT_RUNTIME: {
8895                        // Grant previously granted runtime permissions.
8896                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8897                            PermissionState permissionState = origPermissions
8898                                    .getRuntimePermissionState(bp.name, userId);
8899                            int flags = permissionState != null
8900                                    ? permissionState.getFlags() : 0;
8901                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8902                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8903                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8904                                    // If we cannot put the permission as it was, we have to write.
8905                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8906                                            changedRuntimePermissionUserIds, userId);
8907                                }
8908                                // If the app supports runtime permissions no need for a review.
8909                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8910                                        && appSupportsRuntimePermissions
8911                                        && (flags & PackageManager
8912                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8913                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8914                                    // Since we changed the flags, we have to write.
8915                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8916                                            changedRuntimePermissionUserIds, userId);
8917                                }
8918                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8919                                    && !appSupportsRuntimePermissions) {
8920                                // For legacy apps that need a permission review, every new
8921                                // runtime permission is granted but it is pending a review.
8922                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8923                                    permissionsState.grantRuntimePermission(bp, userId);
8924                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8925                                    // We changed the permission and flags, hence have to write.
8926                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8927                                            changedRuntimePermissionUserIds, userId);
8928                                }
8929                            }
8930                            // Propagate the permission flags.
8931                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8932                        }
8933                    } break;
8934
8935                    case GRANT_UPGRADE: {
8936                        // Grant runtime permissions for a previously held install permission.
8937                        PermissionState permissionState = origPermissions
8938                                .getInstallPermissionState(bp.name);
8939                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8940
8941                        if (origPermissions.revokeInstallPermission(bp)
8942                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8943                            // We will be transferring the permission flags, so clear them.
8944                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8945                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8946                            changedInstallPermission = true;
8947                        }
8948
8949                        // If the permission is not to be promoted to runtime we ignore it and
8950                        // also its other flags as they are not applicable to install permissions.
8951                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8952                            for (int userId : currentUserIds) {
8953                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8954                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8955                                    // Transfer the permission flags.
8956                                    permissionsState.updatePermissionFlags(bp, userId,
8957                                            flags, flags);
8958                                    // If we granted the permission, we have to write.
8959                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8960                                            changedRuntimePermissionUserIds, userId);
8961                                }
8962                            }
8963                        }
8964                    } break;
8965
8966                    default: {
8967                        if (packageOfInterest == null
8968                                || packageOfInterest.equals(pkg.packageName)) {
8969                            Slog.w(TAG, "Not granting permission " + perm
8970                                    + " to package " + pkg.packageName
8971                                    + " because it was previously installed without");
8972                        }
8973                    } break;
8974                }
8975            } else {
8976                if (permissionsState.revokeInstallPermission(bp) !=
8977                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8978                    // Also drop the permission flags.
8979                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8980                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8981                    changedInstallPermission = true;
8982                    Slog.i(TAG, "Un-granting permission " + perm
8983                            + " from package " + pkg.packageName
8984                            + " (protectionLevel=" + bp.protectionLevel
8985                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8986                            + ")");
8987                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8988                    // Don't print warning for app op permissions, since it is fine for them
8989                    // not to be granted, there is a UI for the user to decide.
8990                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8991                        Slog.w(TAG, "Not granting permission " + perm
8992                                + " to package " + pkg.packageName
8993                                + " (protectionLevel=" + bp.protectionLevel
8994                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8995                                + ")");
8996                    }
8997                }
8998            }
8999        }
9000
9001        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9002                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9003            // This is the first that we have heard about this package, so the
9004            // permissions we have now selected are fixed until explicitly
9005            // changed.
9006            ps.installPermissionsFixed = true;
9007        }
9008
9009        // Persist the runtime permissions state for users with changes. If permissions
9010        // were revoked because no app in the shared user declares them we have to
9011        // write synchronously to avoid losing runtime permissions state.
9012        for (int userId : changedRuntimePermissionUserIds) {
9013            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9014        }
9015
9016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9017    }
9018
9019    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9020        boolean allowed = false;
9021        final int NP = PackageParser.NEW_PERMISSIONS.length;
9022        for (int ip=0; ip<NP; ip++) {
9023            final PackageParser.NewPermissionInfo npi
9024                    = PackageParser.NEW_PERMISSIONS[ip];
9025            if (npi.name.equals(perm)
9026                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9027                allowed = true;
9028                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9029                        + pkg.packageName);
9030                break;
9031            }
9032        }
9033        return allowed;
9034    }
9035
9036    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9037            BasePermission bp, PermissionsState origPermissions) {
9038        boolean allowed;
9039        allowed = (compareSignatures(
9040                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9041                        == PackageManager.SIGNATURE_MATCH)
9042                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9043                        == PackageManager.SIGNATURE_MATCH);
9044        if (!allowed && (bp.protectionLevel
9045                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9046            if (isSystemApp(pkg)) {
9047                // For updated system applications, a system permission
9048                // is granted only if it had been defined by the original application.
9049                if (pkg.isUpdatedSystemApp()) {
9050                    final PackageSetting sysPs = mSettings
9051                            .getDisabledSystemPkgLPr(pkg.packageName);
9052                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9053                        // If the original was granted this permission, we take
9054                        // that grant decision as read and propagate it to the
9055                        // update.
9056                        if (sysPs.isPrivileged()) {
9057                            allowed = true;
9058                        }
9059                    } else {
9060                        // The system apk may have been updated with an older
9061                        // version of the one on the data partition, but which
9062                        // granted a new system permission that it didn't have
9063                        // before.  In this case we do want to allow the app to
9064                        // now get the new permission if the ancestral apk is
9065                        // privileged to get it.
9066                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9067                            for (int j=0;
9068                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9069                                if (perm.equals(
9070                                        sysPs.pkg.requestedPermissions.get(j))) {
9071                                    allowed = true;
9072                                    break;
9073                                }
9074                            }
9075                        }
9076                    }
9077                } else {
9078                    allowed = isPrivilegedApp(pkg);
9079                }
9080            }
9081        }
9082        if (!allowed) {
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9085                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9086                // If this was a previously normal/dangerous permission that got moved
9087                // to a system permission as part of the runtime permission redesign, then
9088                // we still want to blindly grant it to old apps.
9089                allowed = true;
9090            }
9091            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9092                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9093                // If this permission is to be granted to the system installer and
9094                // this app is an installer, then it gets the permission.
9095                allowed = true;
9096            }
9097            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9098                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9099                // If this permission is to be granted to the system verifier and
9100                // this app is a verifier, then it gets the permission.
9101                allowed = true;
9102            }
9103            if (!allowed && (bp.protectionLevel
9104                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9105                    && isSystemApp(pkg)) {
9106                // Any pre-installed system app is allowed to get this permission.
9107                allowed = true;
9108            }
9109            if (!allowed && (bp.protectionLevel
9110                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9111                // For development permissions, a development permission
9112                // is granted only if it was already granted.
9113                allowed = origPermissions.hasInstallPermission(perm);
9114            }
9115        }
9116        return allowed;
9117    }
9118
9119    final class ActivityIntentResolver
9120            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9121        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9122                boolean defaultOnly, int userId) {
9123            if (!sUserManager.exists(userId)) return null;
9124            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9125            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9126        }
9127
9128        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9129                int userId) {
9130            if (!sUserManager.exists(userId)) return null;
9131            mFlags = flags;
9132            return super.queryIntent(intent, resolvedType,
9133                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9134        }
9135
9136        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9137                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9138            if (!sUserManager.exists(userId)) return null;
9139            if (packageActivities == null) {
9140                return null;
9141            }
9142            mFlags = flags;
9143            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9144            final int N = packageActivities.size();
9145            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9146                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9147
9148            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9149            for (int i = 0; i < N; ++i) {
9150                intentFilters = packageActivities.get(i).intents;
9151                if (intentFilters != null && intentFilters.size() > 0) {
9152                    PackageParser.ActivityIntentInfo[] array =
9153                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9154                    intentFilters.toArray(array);
9155                    listCut.add(array);
9156                }
9157            }
9158            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9159        }
9160
9161        public final void addActivity(PackageParser.Activity a, String type) {
9162            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9163            mActivities.put(a.getComponentName(), a);
9164            if (DEBUG_SHOW_INFO)
9165                Log.v(
9166                TAG, "  " + type + " " +
9167                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9168            if (DEBUG_SHOW_INFO)
9169                Log.v(TAG, "    Class=" + a.info.name);
9170            final int NI = a.intents.size();
9171            for (int j=0; j<NI; j++) {
9172                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9173                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9174                    intent.setPriority(0);
9175                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9176                            + a.className + " with priority > 0, forcing to 0");
9177                }
9178                if (DEBUG_SHOW_INFO) {
9179                    Log.v(TAG, "    IntentFilter:");
9180                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9181                }
9182                if (!intent.debugCheck()) {
9183                    Log.w(TAG, "==> For Activity " + a.info.name);
9184                }
9185                addFilter(intent);
9186            }
9187        }
9188
9189        public final void removeActivity(PackageParser.Activity a, String type) {
9190            mActivities.remove(a.getComponentName());
9191            if (DEBUG_SHOW_INFO) {
9192                Log.v(TAG, "  " + type + " "
9193                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9194                                : a.info.name) + ":");
9195                Log.v(TAG, "    Class=" + a.info.name);
9196            }
9197            final int NI = a.intents.size();
9198            for (int j=0; j<NI; j++) {
9199                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9200                if (DEBUG_SHOW_INFO) {
9201                    Log.v(TAG, "    IntentFilter:");
9202                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9203                }
9204                removeFilter(intent);
9205            }
9206        }
9207
9208        @Override
9209        protected boolean allowFilterResult(
9210                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9211            ActivityInfo filterAi = filter.activity.info;
9212            for (int i=dest.size()-1; i>=0; i--) {
9213                ActivityInfo destAi = dest.get(i).activityInfo;
9214                if (destAi.name == filterAi.name
9215                        && destAi.packageName == filterAi.packageName) {
9216                    return false;
9217                }
9218            }
9219            return true;
9220        }
9221
9222        @Override
9223        protected ActivityIntentInfo[] newArray(int size) {
9224            return new ActivityIntentInfo[size];
9225        }
9226
9227        @Override
9228        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9229            if (!sUserManager.exists(userId)) return true;
9230            PackageParser.Package p = filter.activity.owner;
9231            if (p != null) {
9232                PackageSetting ps = (PackageSetting)p.mExtras;
9233                if (ps != null) {
9234                    // System apps are never considered stopped for purposes of
9235                    // filtering, because there may be no way for the user to
9236                    // actually re-launch them.
9237                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9238                            && ps.getStopped(userId);
9239                }
9240            }
9241            return false;
9242        }
9243
9244        @Override
9245        protected boolean isPackageForFilter(String packageName,
9246                PackageParser.ActivityIntentInfo info) {
9247            return packageName.equals(info.activity.owner.packageName);
9248        }
9249
9250        @Override
9251        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9252                int match, int userId) {
9253            if (!sUserManager.exists(userId)) return null;
9254            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9255                return null;
9256            }
9257            final PackageParser.Activity activity = info.activity;
9258            if (mSafeMode && (activity.info.applicationInfo.flags
9259                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9260                return null;
9261            }
9262            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9263            if (ps == null) {
9264                return null;
9265            }
9266            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9267                    ps.readUserState(userId), userId);
9268            if (ai == null) {
9269                return null;
9270            }
9271            final ResolveInfo res = new ResolveInfo();
9272            res.activityInfo = ai;
9273            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9274                res.filter = info;
9275            }
9276            if (info != null) {
9277                res.handleAllWebDataURI = info.handleAllWebDataURI();
9278            }
9279            res.priority = info.getPriority();
9280            res.preferredOrder = activity.owner.mPreferredOrder;
9281            //System.out.println("Result: " + res.activityInfo.className +
9282            //                   " = " + res.priority);
9283            res.match = match;
9284            res.isDefault = info.hasDefault;
9285            res.labelRes = info.labelRes;
9286            res.nonLocalizedLabel = info.nonLocalizedLabel;
9287            if (userNeedsBadging(userId)) {
9288                res.noResourceId = true;
9289            } else {
9290                res.icon = info.icon;
9291            }
9292            res.iconResourceId = info.icon;
9293            res.system = res.activityInfo.applicationInfo.isSystemApp();
9294            return res;
9295        }
9296
9297        @Override
9298        protected void sortResults(List<ResolveInfo> results) {
9299            Collections.sort(results, mResolvePrioritySorter);
9300        }
9301
9302        @Override
9303        protected void dumpFilter(PrintWriter out, String prefix,
9304                PackageParser.ActivityIntentInfo filter) {
9305            out.print(prefix); out.print(
9306                    Integer.toHexString(System.identityHashCode(filter.activity)));
9307                    out.print(' ');
9308                    filter.activity.printComponentShortName(out);
9309                    out.print(" filter ");
9310                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9311        }
9312
9313        @Override
9314        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9315            return filter.activity;
9316        }
9317
9318        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9319            PackageParser.Activity activity = (PackageParser.Activity)label;
9320            out.print(prefix); out.print(
9321                    Integer.toHexString(System.identityHashCode(activity)));
9322                    out.print(' ');
9323                    activity.printComponentShortName(out);
9324            if (count > 1) {
9325                out.print(" ("); out.print(count); out.print(" filters)");
9326            }
9327            out.println();
9328        }
9329
9330//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9331//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9332//            final List<ResolveInfo> retList = Lists.newArrayList();
9333//            while (i.hasNext()) {
9334//                final ResolveInfo resolveInfo = i.next();
9335//                if (isEnabledLP(resolveInfo.activityInfo)) {
9336//                    retList.add(resolveInfo);
9337//                }
9338//            }
9339//            return retList;
9340//        }
9341
9342        // Keys are String (activity class name), values are Activity.
9343        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9344                = new ArrayMap<ComponentName, PackageParser.Activity>();
9345        private int mFlags;
9346    }
9347
9348    private final class ServiceIntentResolver
9349            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9350        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9351                boolean defaultOnly, int userId) {
9352            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9353            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9354        }
9355
9356        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9357                int userId) {
9358            if (!sUserManager.exists(userId)) return null;
9359            mFlags = flags;
9360            return super.queryIntent(intent, resolvedType,
9361                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9362        }
9363
9364        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9365                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9366            if (!sUserManager.exists(userId)) return null;
9367            if (packageServices == null) {
9368                return null;
9369            }
9370            mFlags = flags;
9371            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9372            final int N = packageServices.size();
9373            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9374                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9375
9376            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9377            for (int i = 0; i < N; ++i) {
9378                intentFilters = packageServices.get(i).intents;
9379                if (intentFilters != null && intentFilters.size() > 0) {
9380                    PackageParser.ServiceIntentInfo[] array =
9381                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9382                    intentFilters.toArray(array);
9383                    listCut.add(array);
9384                }
9385            }
9386            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9387        }
9388
9389        public final void addService(PackageParser.Service s) {
9390            mServices.put(s.getComponentName(), s);
9391            if (DEBUG_SHOW_INFO) {
9392                Log.v(TAG, "  "
9393                        + (s.info.nonLocalizedLabel != null
9394                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9395                Log.v(TAG, "    Class=" + s.info.name);
9396            }
9397            final int NI = s.intents.size();
9398            int j;
9399            for (j=0; j<NI; j++) {
9400                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9401                if (DEBUG_SHOW_INFO) {
9402                    Log.v(TAG, "    IntentFilter:");
9403                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9404                }
9405                if (!intent.debugCheck()) {
9406                    Log.w(TAG, "==> For Service " + s.info.name);
9407                }
9408                addFilter(intent);
9409            }
9410        }
9411
9412        public final void removeService(PackageParser.Service s) {
9413            mServices.remove(s.getComponentName());
9414            if (DEBUG_SHOW_INFO) {
9415                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9416                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9417                Log.v(TAG, "    Class=" + s.info.name);
9418            }
9419            final int NI = s.intents.size();
9420            int j;
9421            for (j=0; j<NI; j++) {
9422                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9423                if (DEBUG_SHOW_INFO) {
9424                    Log.v(TAG, "    IntentFilter:");
9425                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9426                }
9427                removeFilter(intent);
9428            }
9429        }
9430
9431        @Override
9432        protected boolean allowFilterResult(
9433                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9434            ServiceInfo filterSi = filter.service.info;
9435            for (int i=dest.size()-1; i>=0; i--) {
9436                ServiceInfo destAi = dest.get(i).serviceInfo;
9437                if (destAi.name == filterSi.name
9438                        && destAi.packageName == filterSi.packageName) {
9439                    return false;
9440                }
9441            }
9442            return true;
9443        }
9444
9445        @Override
9446        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9447            return new PackageParser.ServiceIntentInfo[size];
9448        }
9449
9450        @Override
9451        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9452            if (!sUserManager.exists(userId)) return true;
9453            PackageParser.Package p = filter.service.owner;
9454            if (p != null) {
9455                PackageSetting ps = (PackageSetting)p.mExtras;
9456                if (ps != null) {
9457                    // System apps are never considered stopped for purposes of
9458                    // filtering, because there may be no way for the user to
9459                    // actually re-launch them.
9460                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9461                            && ps.getStopped(userId);
9462                }
9463            }
9464            return false;
9465        }
9466
9467        @Override
9468        protected boolean isPackageForFilter(String packageName,
9469                PackageParser.ServiceIntentInfo info) {
9470            return packageName.equals(info.service.owner.packageName);
9471        }
9472
9473        @Override
9474        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9475                int match, int userId) {
9476            if (!sUserManager.exists(userId)) return null;
9477            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9478            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9479                return null;
9480            }
9481            final PackageParser.Service service = info.service;
9482            if (mSafeMode && (service.info.applicationInfo.flags
9483                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9484                return null;
9485            }
9486            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9487            if (ps == null) {
9488                return null;
9489            }
9490            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9491                    ps.readUserState(userId), userId);
9492            if (si == null) {
9493                return null;
9494            }
9495            final ResolveInfo res = new ResolveInfo();
9496            res.serviceInfo = si;
9497            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9498                res.filter = filter;
9499            }
9500            res.priority = info.getPriority();
9501            res.preferredOrder = service.owner.mPreferredOrder;
9502            res.match = match;
9503            res.isDefault = info.hasDefault;
9504            res.labelRes = info.labelRes;
9505            res.nonLocalizedLabel = info.nonLocalizedLabel;
9506            res.icon = info.icon;
9507            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9508            return res;
9509        }
9510
9511        @Override
9512        protected void sortResults(List<ResolveInfo> results) {
9513            Collections.sort(results, mResolvePrioritySorter);
9514        }
9515
9516        @Override
9517        protected void dumpFilter(PrintWriter out, String prefix,
9518                PackageParser.ServiceIntentInfo filter) {
9519            out.print(prefix); out.print(
9520                    Integer.toHexString(System.identityHashCode(filter.service)));
9521                    out.print(' ');
9522                    filter.service.printComponentShortName(out);
9523                    out.print(" filter ");
9524                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9525        }
9526
9527        @Override
9528        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9529            return filter.service;
9530        }
9531
9532        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9533            PackageParser.Service service = (PackageParser.Service)label;
9534            out.print(prefix); out.print(
9535                    Integer.toHexString(System.identityHashCode(service)));
9536                    out.print(' ');
9537                    service.printComponentShortName(out);
9538            if (count > 1) {
9539                out.print(" ("); out.print(count); out.print(" filters)");
9540            }
9541            out.println();
9542        }
9543
9544//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9545//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9546//            final List<ResolveInfo> retList = Lists.newArrayList();
9547//            while (i.hasNext()) {
9548//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9549//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9550//                    retList.add(resolveInfo);
9551//                }
9552//            }
9553//            return retList;
9554//        }
9555
9556        // Keys are String (activity class name), values are Activity.
9557        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9558                = new ArrayMap<ComponentName, PackageParser.Service>();
9559        private int mFlags;
9560    };
9561
9562    private final class ProviderIntentResolver
9563            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9564        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9565                boolean defaultOnly, int userId) {
9566            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9567            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9568        }
9569
9570        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9571                int userId) {
9572            if (!sUserManager.exists(userId))
9573                return null;
9574            mFlags = flags;
9575            return super.queryIntent(intent, resolvedType,
9576                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9577        }
9578
9579        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9580                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9581            if (!sUserManager.exists(userId))
9582                return null;
9583            if (packageProviders == null) {
9584                return null;
9585            }
9586            mFlags = flags;
9587            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9588            final int N = packageProviders.size();
9589            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9590                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9591
9592            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9593            for (int i = 0; i < N; ++i) {
9594                intentFilters = packageProviders.get(i).intents;
9595                if (intentFilters != null && intentFilters.size() > 0) {
9596                    PackageParser.ProviderIntentInfo[] array =
9597                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9598                    intentFilters.toArray(array);
9599                    listCut.add(array);
9600                }
9601            }
9602            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9603        }
9604
9605        public final void addProvider(PackageParser.Provider p) {
9606            if (mProviders.containsKey(p.getComponentName())) {
9607                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9608                return;
9609            }
9610
9611            mProviders.put(p.getComponentName(), p);
9612            if (DEBUG_SHOW_INFO) {
9613                Log.v(TAG, "  "
9614                        + (p.info.nonLocalizedLabel != null
9615                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9616                Log.v(TAG, "    Class=" + p.info.name);
9617            }
9618            final int NI = p.intents.size();
9619            int j;
9620            for (j = 0; j < NI; j++) {
9621                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9622                if (DEBUG_SHOW_INFO) {
9623                    Log.v(TAG, "    IntentFilter:");
9624                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9625                }
9626                if (!intent.debugCheck()) {
9627                    Log.w(TAG, "==> For Provider " + p.info.name);
9628                }
9629                addFilter(intent);
9630            }
9631        }
9632
9633        public final void removeProvider(PackageParser.Provider p) {
9634            mProviders.remove(p.getComponentName());
9635            if (DEBUG_SHOW_INFO) {
9636                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9637                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9638                Log.v(TAG, "    Class=" + p.info.name);
9639            }
9640            final int NI = p.intents.size();
9641            int j;
9642            for (j = 0; j < NI; j++) {
9643                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9644                if (DEBUG_SHOW_INFO) {
9645                    Log.v(TAG, "    IntentFilter:");
9646                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9647                }
9648                removeFilter(intent);
9649            }
9650        }
9651
9652        @Override
9653        protected boolean allowFilterResult(
9654                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9655            ProviderInfo filterPi = filter.provider.info;
9656            for (int i = dest.size() - 1; i >= 0; i--) {
9657                ProviderInfo destPi = dest.get(i).providerInfo;
9658                if (destPi.name == filterPi.name
9659                        && destPi.packageName == filterPi.packageName) {
9660                    return false;
9661                }
9662            }
9663            return true;
9664        }
9665
9666        @Override
9667        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9668            return new PackageParser.ProviderIntentInfo[size];
9669        }
9670
9671        @Override
9672        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9673            if (!sUserManager.exists(userId))
9674                return true;
9675            PackageParser.Package p = filter.provider.owner;
9676            if (p != null) {
9677                PackageSetting ps = (PackageSetting) p.mExtras;
9678                if (ps != null) {
9679                    // System apps are never considered stopped for purposes of
9680                    // filtering, because there may be no way for the user to
9681                    // actually re-launch them.
9682                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9683                            && ps.getStopped(userId);
9684                }
9685            }
9686            return false;
9687        }
9688
9689        @Override
9690        protected boolean isPackageForFilter(String packageName,
9691                PackageParser.ProviderIntentInfo info) {
9692            return packageName.equals(info.provider.owner.packageName);
9693        }
9694
9695        @Override
9696        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9697                int match, int userId) {
9698            if (!sUserManager.exists(userId))
9699                return null;
9700            final PackageParser.ProviderIntentInfo info = filter;
9701            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9702                return null;
9703            }
9704            final PackageParser.Provider provider = info.provider;
9705            if (mSafeMode && (provider.info.applicationInfo.flags
9706                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9707                return null;
9708            }
9709            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9710            if (ps == null) {
9711                return null;
9712            }
9713            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9714                    ps.readUserState(userId), userId);
9715            if (pi == null) {
9716                return null;
9717            }
9718            final ResolveInfo res = new ResolveInfo();
9719            res.providerInfo = pi;
9720            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9721                res.filter = filter;
9722            }
9723            res.priority = info.getPriority();
9724            res.preferredOrder = provider.owner.mPreferredOrder;
9725            res.match = match;
9726            res.isDefault = info.hasDefault;
9727            res.labelRes = info.labelRes;
9728            res.nonLocalizedLabel = info.nonLocalizedLabel;
9729            res.icon = info.icon;
9730            res.system = res.providerInfo.applicationInfo.isSystemApp();
9731            return res;
9732        }
9733
9734        @Override
9735        protected void sortResults(List<ResolveInfo> results) {
9736            Collections.sort(results, mResolvePrioritySorter);
9737        }
9738
9739        @Override
9740        protected void dumpFilter(PrintWriter out, String prefix,
9741                PackageParser.ProviderIntentInfo filter) {
9742            out.print(prefix);
9743            out.print(
9744                    Integer.toHexString(System.identityHashCode(filter.provider)));
9745            out.print(' ');
9746            filter.provider.printComponentShortName(out);
9747            out.print(" filter ");
9748            out.println(Integer.toHexString(System.identityHashCode(filter)));
9749        }
9750
9751        @Override
9752        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9753            return filter.provider;
9754        }
9755
9756        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9757            PackageParser.Provider provider = (PackageParser.Provider)label;
9758            out.print(prefix); out.print(
9759                    Integer.toHexString(System.identityHashCode(provider)));
9760                    out.print(' ');
9761                    provider.printComponentShortName(out);
9762            if (count > 1) {
9763                out.print(" ("); out.print(count); out.print(" filters)");
9764            }
9765            out.println();
9766        }
9767
9768        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9769                = new ArrayMap<ComponentName, PackageParser.Provider>();
9770        private int mFlags;
9771    }
9772
9773    private static final class EphemeralIntentResolver
9774            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9775        @Override
9776        protected EphemeralResolveIntentInfo[] newArray(int size) {
9777            return new EphemeralResolveIntentInfo[size];
9778        }
9779
9780        @Override
9781        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9782            return true;
9783        }
9784
9785        @Override
9786        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9787                int userId) {
9788            if (!sUserManager.exists(userId)) {
9789                return null;
9790            }
9791            return info.getEphemeralResolveInfo();
9792        }
9793    }
9794
9795    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9796            new Comparator<ResolveInfo>() {
9797        public int compare(ResolveInfo r1, ResolveInfo r2) {
9798            int v1 = r1.priority;
9799            int v2 = r2.priority;
9800            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9801            if (v1 != v2) {
9802                return (v1 > v2) ? -1 : 1;
9803            }
9804            v1 = r1.preferredOrder;
9805            v2 = r2.preferredOrder;
9806            if (v1 != v2) {
9807                return (v1 > v2) ? -1 : 1;
9808            }
9809            if (r1.isDefault != r2.isDefault) {
9810                return r1.isDefault ? -1 : 1;
9811            }
9812            v1 = r1.match;
9813            v2 = r2.match;
9814            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9815            if (v1 != v2) {
9816                return (v1 > v2) ? -1 : 1;
9817            }
9818            if (r1.system != r2.system) {
9819                return r1.system ? -1 : 1;
9820            }
9821            if (r1.activityInfo != null) {
9822                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9823            }
9824            if (r1.serviceInfo != null) {
9825                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9826            }
9827            if (r1.providerInfo != null) {
9828                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9829            }
9830            return 0;
9831        }
9832    };
9833
9834    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9835            new Comparator<ProviderInfo>() {
9836        public int compare(ProviderInfo p1, ProviderInfo p2) {
9837            final int v1 = p1.initOrder;
9838            final int v2 = p2.initOrder;
9839            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9840        }
9841    };
9842
9843    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9844            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9845            final int[] userIds) {
9846        mHandler.post(new Runnable() {
9847            @Override
9848            public void run() {
9849                try {
9850                    final IActivityManager am = ActivityManagerNative.getDefault();
9851                    if (am == null) return;
9852                    final int[] resolvedUserIds;
9853                    if (userIds == null) {
9854                        resolvedUserIds = am.getRunningUserIds();
9855                    } else {
9856                        resolvedUserIds = userIds;
9857                    }
9858                    for (int id : resolvedUserIds) {
9859                        final Intent intent = new Intent(action,
9860                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9861                        if (extras != null) {
9862                            intent.putExtras(extras);
9863                        }
9864                        if (targetPkg != null) {
9865                            intent.setPackage(targetPkg);
9866                        }
9867                        // Modify the UID when posting to other users
9868                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9869                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9870                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9871                            intent.putExtra(Intent.EXTRA_UID, uid);
9872                        }
9873                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9874                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9875                        if (DEBUG_BROADCASTS) {
9876                            RuntimeException here = new RuntimeException("here");
9877                            here.fillInStackTrace();
9878                            Slog.d(TAG, "Sending to user " + id + ": "
9879                                    + intent.toShortString(false, true, false, false)
9880                                    + " " + intent.getExtras(), here);
9881                        }
9882                        am.broadcastIntent(null, intent, null, finishedReceiver,
9883                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9884                                null, finishedReceiver != null, false, id);
9885                    }
9886                } catch (RemoteException ex) {
9887                }
9888            }
9889        });
9890    }
9891
9892    /**
9893     * Check if the external storage media is available. This is true if there
9894     * is a mounted external storage medium or if the external storage is
9895     * emulated.
9896     */
9897    private boolean isExternalMediaAvailable() {
9898        return mMediaMounted || Environment.isExternalStorageEmulated();
9899    }
9900
9901    @Override
9902    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9903        // writer
9904        synchronized (mPackages) {
9905            if (!isExternalMediaAvailable()) {
9906                // If the external storage is no longer mounted at this point,
9907                // the caller may not have been able to delete all of this
9908                // packages files and can not delete any more.  Bail.
9909                return null;
9910            }
9911            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9912            if (lastPackage != null) {
9913                pkgs.remove(lastPackage);
9914            }
9915            if (pkgs.size() > 0) {
9916                return pkgs.get(0);
9917            }
9918        }
9919        return null;
9920    }
9921
9922    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9923        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9924                userId, andCode ? 1 : 0, packageName);
9925        if (mSystemReady) {
9926            msg.sendToTarget();
9927        } else {
9928            if (mPostSystemReadyMessages == null) {
9929                mPostSystemReadyMessages = new ArrayList<>();
9930            }
9931            mPostSystemReadyMessages.add(msg);
9932        }
9933    }
9934
9935    void startCleaningPackages() {
9936        // reader
9937        synchronized (mPackages) {
9938            if (!isExternalMediaAvailable()) {
9939                return;
9940            }
9941            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9942                return;
9943            }
9944        }
9945        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9946        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9947        IActivityManager am = ActivityManagerNative.getDefault();
9948        if (am != null) {
9949            try {
9950                am.startService(null, intent, null, mContext.getOpPackageName(),
9951                        UserHandle.USER_SYSTEM);
9952            } catch (RemoteException e) {
9953            }
9954        }
9955    }
9956
9957    @Override
9958    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9959            int installFlags, String installerPackageName, VerificationParams verificationParams,
9960            String packageAbiOverride) {
9961        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9962                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9963    }
9964
9965    @Override
9966    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9967            int installFlags, String installerPackageName, VerificationParams verificationParams,
9968            String packageAbiOverride, int userId) {
9969        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9970
9971        final int callingUid = Binder.getCallingUid();
9972        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9973
9974        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9975            try {
9976                if (observer != null) {
9977                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9978                }
9979            } catch (RemoteException re) {
9980            }
9981            return;
9982        }
9983
9984        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9985            installFlags |= PackageManager.INSTALL_FROM_ADB;
9986
9987        } else {
9988            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9989            // about installerPackageName.
9990
9991            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9992            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9993        }
9994
9995        UserHandle user;
9996        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9997            user = UserHandle.ALL;
9998        } else {
9999            user = new UserHandle(userId);
10000        }
10001
10002        // Only system components can circumvent runtime permissions when installing.
10003        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10004                && mContext.checkCallingOrSelfPermission(Manifest.permission
10005                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10006            throw new SecurityException("You need the "
10007                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10008                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10009        }
10010
10011        verificationParams.setInstallerUid(callingUid);
10012
10013        final File originFile = new File(originPath);
10014        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10015
10016        final Message msg = mHandler.obtainMessage(INIT_COPY);
10017        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10018                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10019        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10020        msg.obj = params;
10021
10022        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10023                System.identityHashCode(msg.obj));
10024        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10025                System.identityHashCode(msg.obj));
10026
10027        mHandler.sendMessage(msg);
10028    }
10029
10030    void installStage(String packageName, File stagedDir, String stagedCid,
10031            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10032            String installerPackageName, int installerUid, UserHandle user) {
10033        if (DEBUG_EPHEMERAL) {
10034            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10035                Slog.d(TAG, "Ephemeral install of " + packageName);
10036            }
10037        }
10038        final VerificationParams verifParams = new VerificationParams(
10039                null, sessionParams.originatingUri, sessionParams.referrerUri,
10040                sessionParams.originatingUid, null);
10041        verifParams.setInstallerUid(installerUid);
10042
10043        final OriginInfo origin;
10044        if (stagedDir != null) {
10045            origin = OriginInfo.fromStagedFile(stagedDir);
10046        } else {
10047            origin = OriginInfo.fromStagedContainer(stagedCid);
10048        }
10049
10050        final Message msg = mHandler.obtainMessage(INIT_COPY);
10051        final InstallParams params = new InstallParams(origin, null, observer,
10052                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10053                verifParams, user, sessionParams.abiOverride,
10054                sessionParams.grantedRuntimePermissions);
10055        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10056        msg.obj = params;
10057
10058        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10059                System.identityHashCode(msg.obj));
10060        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10061                System.identityHashCode(msg.obj));
10062
10063        mHandler.sendMessage(msg);
10064    }
10065
10066    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10067        Bundle extras = new Bundle(1);
10068        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10069
10070        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10071                packageName, extras, 0, null, null, new int[] {userId});
10072        try {
10073            IActivityManager am = ActivityManagerNative.getDefault();
10074            final boolean isSystem =
10075                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10076            if (isSystem && am.isUserRunning(userId, 0)) {
10077                // The just-installed/enabled app is bundled on the system, so presumed
10078                // to be able to run automatically without needing an explicit launch.
10079                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10080                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10081                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10082                        .setPackage(packageName);
10083                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10084                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10085            }
10086        } catch (RemoteException e) {
10087            // shouldn't happen
10088            Slog.w(TAG, "Unable to bootstrap installed package", e);
10089        }
10090    }
10091
10092    @Override
10093    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10094            int userId) {
10095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10096        PackageSetting pkgSetting;
10097        final int uid = Binder.getCallingUid();
10098        enforceCrossUserPermission(uid, userId, true, true,
10099                "setApplicationHiddenSetting for user " + userId);
10100
10101        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10102            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10103            return false;
10104        }
10105
10106        long callingId = Binder.clearCallingIdentity();
10107        try {
10108            boolean sendAdded = false;
10109            boolean sendRemoved = false;
10110            // writer
10111            synchronized (mPackages) {
10112                pkgSetting = mSettings.mPackages.get(packageName);
10113                if (pkgSetting == null) {
10114                    return false;
10115                }
10116                if (pkgSetting.getHidden(userId) != hidden) {
10117                    pkgSetting.setHidden(hidden, userId);
10118                    mSettings.writePackageRestrictionsLPr(userId);
10119                    if (hidden) {
10120                        sendRemoved = true;
10121                    } else {
10122                        sendAdded = true;
10123                    }
10124                }
10125            }
10126            if (sendAdded) {
10127                sendPackageAddedForUser(packageName, pkgSetting, userId);
10128                return true;
10129            }
10130            if (sendRemoved) {
10131                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10132                        "hiding pkg");
10133                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10134                return true;
10135            }
10136        } finally {
10137            Binder.restoreCallingIdentity(callingId);
10138        }
10139        return false;
10140    }
10141
10142    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10143            int userId) {
10144        final PackageRemovedInfo info = new PackageRemovedInfo();
10145        info.removedPackage = packageName;
10146        info.removedUsers = new int[] {userId};
10147        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10148        info.sendBroadcast(false, false, false);
10149    }
10150
10151    /**
10152     * Returns true if application is not found or there was an error. Otherwise it returns
10153     * the hidden state of the package for the given user.
10154     */
10155    @Override
10156    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10158        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10159                false, "getApplicationHidden for user " + userId);
10160        PackageSetting pkgSetting;
10161        long callingId = Binder.clearCallingIdentity();
10162        try {
10163            // writer
10164            synchronized (mPackages) {
10165                pkgSetting = mSettings.mPackages.get(packageName);
10166                if (pkgSetting == null) {
10167                    return true;
10168                }
10169                return pkgSetting.getHidden(userId);
10170            }
10171        } finally {
10172            Binder.restoreCallingIdentity(callingId);
10173        }
10174    }
10175
10176    /**
10177     * @hide
10178     */
10179    @Override
10180    public int installExistingPackageAsUser(String packageName, int userId) {
10181        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10182                null);
10183        PackageSetting pkgSetting;
10184        final int uid = Binder.getCallingUid();
10185        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10186                + userId);
10187        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10188            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10189        }
10190
10191        long callingId = Binder.clearCallingIdentity();
10192        try {
10193            boolean sendAdded = false;
10194
10195            // writer
10196            synchronized (mPackages) {
10197                pkgSetting = mSettings.mPackages.get(packageName);
10198                if (pkgSetting == null) {
10199                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10200                }
10201                if (!pkgSetting.getInstalled(userId)) {
10202                    pkgSetting.setInstalled(true, userId);
10203                    pkgSetting.setHidden(false, userId);
10204                    mSettings.writePackageRestrictionsLPr(userId);
10205                    sendAdded = true;
10206                }
10207            }
10208
10209            if (sendAdded) {
10210                sendPackageAddedForUser(packageName, pkgSetting, userId);
10211            }
10212        } finally {
10213            Binder.restoreCallingIdentity(callingId);
10214        }
10215
10216        return PackageManager.INSTALL_SUCCEEDED;
10217    }
10218
10219    boolean isUserRestricted(int userId, String restrictionKey) {
10220        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10221        if (restrictions.getBoolean(restrictionKey, false)) {
10222            Log.w(TAG, "User is restricted: " + restrictionKey);
10223            return true;
10224        }
10225        return false;
10226    }
10227
10228    @Override
10229    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10230        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10231        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10232                "setPackageSuspended for user " + userId);
10233
10234        long callingId = Binder.clearCallingIdentity();
10235        try {
10236            synchronized (mPackages) {
10237                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10238                if (pkgSetting != null) {
10239                    if (pkgSetting.getSuspended(userId) != suspended) {
10240                        pkgSetting.setSuspended(suspended, userId);
10241                        mSettings.writePackageRestrictionsLPr(userId);
10242                    }
10243
10244                    // TODO:
10245                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10246                    // * remove app from recents (kill app it if it is running)
10247                    // * erase existing notifications for this app
10248                    return true;
10249                }
10250
10251                return false;
10252            }
10253        } finally {
10254            Binder.restoreCallingIdentity(callingId);
10255        }
10256    }
10257
10258    @Override
10259    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10260        mContext.enforceCallingOrSelfPermission(
10261                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10262                "Only package verification agents can verify applications");
10263
10264        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10265        final PackageVerificationResponse response = new PackageVerificationResponse(
10266                verificationCode, Binder.getCallingUid());
10267        msg.arg1 = id;
10268        msg.obj = response;
10269        mHandler.sendMessage(msg);
10270    }
10271
10272    @Override
10273    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10274            long millisecondsToDelay) {
10275        mContext.enforceCallingOrSelfPermission(
10276                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10277                "Only package verification agents can extend verification timeouts");
10278
10279        final PackageVerificationState state = mPendingVerification.get(id);
10280        final PackageVerificationResponse response = new PackageVerificationResponse(
10281                verificationCodeAtTimeout, Binder.getCallingUid());
10282
10283        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10284            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10285        }
10286        if (millisecondsToDelay < 0) {
10287            millisecondsToDelay = 0;
10288        }
10289        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10290                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10291            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10292        }
10293
10294        if ((state != null) && !state.timeoutExtended()) {
10295            state.extendTimeout();
10296
10297            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10298            msg.arg1 = id;
10299            msg.obj = response;
10300            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10301        }
10302    }
10303
10304    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10305            int verificationCode, UserHandle user) {
10306        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10307        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10308        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10309        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10310        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10311
10312        mContext.sendBroadcastAsUser(intent, user,
10313                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10314    }
10315
10316    private ComponentName matchComponentForVerifier(String packageName,
10317            List<ResolveInfo> receivers) {
10318        ActivityInfo targetReceiver = null;
10319
10320        final int NR = receivers.size();
10321        for (int i = 0; i < NR; i++) {
10322            final ResolveInfo info = receivers.get(i);
10323            if (info.activityInfo == null) {
10324                continue;
10325            }
10326
10327            if (packageName.equals(info.activityInfo.packageName)) {
10328                targetReceiver = info.activityInfo;
10329                break;
10330            }
10331        }
10332
10333        if (targetReceiver == null) {
10334            return null;
10335        }
10336
10337        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10338    }
10339
10340    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10341            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10342        if (pkgInfo.verifiers.length == 0) {
10343            return null;
10344        }
10345
10346        final int N = pkgInfo.verifiers.length;
10347        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10348        for (int i = 0; i < N; i++) {
10349            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10350
10351            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10352                    receivers);
10353            if (comp == null) {
10354                continue;
10355            }
10356
10357            final int verifierUid = getUidForVerifier(verifierInfo);
10358            if (verifierUid == -1) {
10359                continue;
10360            }
10361
10362            if (DEBUG_VERIFY) {
10363                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10364                        + " with the correct signature");
10365            }
10366            sufficientVerifiers.add(comp);
10367            verificationState.addSufficientVerifier(verifierUid);
10368        }
10369
10370        return sufficientVerifiers;
10371    }
10372
10373    private int getUidForVerifier(VerifierInfo verifierInfo) {
10374        synchronized (mPackages) {
10375            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10376            if (pkg == null) {
10377                return -1;
10378            } else if (pkg.mSignatures.length != 1) {
10379                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10380                        + " has more than one signature; ignoring");
10381                return -1;
10382            }
10383
10384            /*
10385             * If the public key of the package's signature does not match
10386             * our expected public key, then this is a different package and
10387             * we should skip.
10388             */
10389
10390            final byte[] expectedPublicKey;
10391            try {
10392                final Signature verifierSig = pkg.mSignatures[0];
10393                final PublicKey publicKey = verifierSig.getPublicKey();
10394                expectedPublicKey = publicKey.getEncoded();
10395            } catch (CertificateException e) {
10396                return -1;
10397            }
10398
10399            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10400
10401            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10402                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10403                        + " does not have the expected public key; ignoring");
10404                return -1;
10405            }
10406
10407            return pkg.applicationInfo.uid;
10408        }
10409    }
10410
10411    @Override
10412    public void finishPackageInstall(int token) {
10413        enforceSystemOrRoot("Only the system is allowed to finish installs");
10414
10415        if (DEBUG_INSTALL) {
10416            Slog.v(TAG, "BM finishing package install for " + token);
10417        }
10418        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10419
10420        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10421        mHandler.sendMessage(msg);
10422    }
10423
10424    /**
10425     * Get the verification agent timeout.
10426     *
10427     * @return verification timeout in milliseconds
10428     */
10429    private long getVerificationTimeout() {
10430        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10431                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10432                DEFAULT_VERIFICATION_TIMEOUT);
10433    }
10434
10435    /**
10436     * Get the default verification agent response code.
10437     *
10438     * @return default verification response code
10439     */
10440    private int getDefaultVerificationResponse() {
10441        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10442                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10443                DEFAULT_VERIFICATION_RESPONSE);
10444    }
10445
10446    /**
10447     * Check whether or not package verification has been enabled.
10448     *
10449     * @return true if verification should be performed
10450     */
10451    private boolean isVerificationEnabled(int userId, int installFlags) {
10452        if (!DEFAULT_VERIFY_ENABLE) {
10453            return false;
10454        }
10455        // Ephemeral apps don't get the full verification treatment
10456        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10457            if (DEBUG_EPHEMERAL) {
10458                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10459            }
10460            return false;
10461        }
10462
10463        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10464
10465        // Check if installing from ADB
10466        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10467            // Do not run verification in a test harness environment
10468            if (ActivityManager.isRunningInTestHarness()) {
10469                return false;
10470            }
10471            if (ensureVerifyAppsEnabled) {
10472                return true;
10473            }
10474            // Check if the developer does not want package verification for ADB installs
10475            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10476                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10477                return false;
10478            }
10479        }
10480
10481        if (ensureVerifyAppsEnabled) {
10482            return true;
10483        }
10484
10485        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10486                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10487    }
10488
10489    @Override
10490    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10491            throws RemoteException {
10492        mContext.enforceCallingOrSelfPermission(
10493                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10494                "Only intentfilter verification agents can verify applications");
10495
10496        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10497        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10498                Binder.getCallingUid(), verificationCode, failedDomains);
10499        msg.arg1 = id;
10500        msg.obj = response;
10501        mHandler.sendMessage(msg);
10502    }
10503
10504    @Override
10505    public int getIntentVerificationStatus(String packageName, int userId) {
10506        synchronized (mPackages) {
10507            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10508        }
10509    }
10510
10511    @Override
10512    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10513        mContext.enforceCallingOrSelfPermission(
10514                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10515
10516        boolean result = false;
10517        synchronized (mPackages) {
10518            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10519        }
10520        if (result) {
10521            scheduleWritePackageRestrictionsLocked(userId);
10522        }
10523        return result;
10524    }
10525
10526    @Override
10527    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10528        synchronized (mPackages) {
10529            return mSettings.getIntentFilterVerificationsLPr(packageName);
10530        }
10531    }
10532
10533    @Override
10534    public List<IntentFilter> getAllIntentFilters(String packageName) {
10535        if (TextUtils.isEmpty(packageName)) {
10536            return Collections.<IntentFilter>emptyList();
10537        }
10538        synchronized (mPackages) {
10539            PackageParser.Package pkg = mPackages.get(packageName);
10540            if (pkg == null || pkg.activities == null) {
10541                return Collections.<IntentFilter>emptyList();
10542            }
10543            final int count = pkg.activities.size();
10544            ArrayList<IntentFilter> result = new ArrayList<>();
10545            for (int n=0; n<count; n++) {
10546                PackageParser.Activity activity = pkg.activities.get(n);
10547                if (activity.intents != null && activity.intents.size() > 0) {
10548                    result.addAll(activity.intents);
10549                }
10550            }
10551            return result;
10552        }
10553    }
10554
10555    @Override
10556    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10557        mContext.enforceCallingOrSelfPermission(
10558                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10559
10560        synchronized (mPackages) {
10561            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10562            if (packageName != null) {
10563                result |= updateIntentVerificationStatus(packageName,
10564                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10565                        userId);
10566                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10567                        packageName, userId);
10568            }
10569            return result;
10570        }
10571    }
10572
10573    @Override
10574    public String getDefaultBrowserPackageName(int userId) {
10575        synchronized (mPackages) {
10576            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10577        }
10578    }
10579
10580    /**
10581     * Get the "allow unknown sources" setting.
10582     *
10583     * @return the current "allow unknown sources" setting
10584     */
10585    private int getUnknownSourcesSettings() {
10586        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10587                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10588                -1);
10589    }
10590
10591    @Override
10592    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10593        final int uid = Binder.getCallingUid();
10594        // writer
10595        synchronized (mPackages) {
10596            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10597            if (targetPackageSetting == null) {
10598                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10599            }
10600
10601            PackageSetting installerPackageSetting;
10602            if (installerPackageName != null) {
10603                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10604                if (installerPackageSetting == null) {
10605                    throw new IllegalArgumentException("Unknown installer package: "
10606                            + installerPackageName);
10607                }
10608            } else {
10609                installerPackageSetting = null;
10610            }
10611
10612            Signature[] callerSignature;
10613            Object obj = mSettings.getUserIdLPr(uid);
10614            if (obj != null) {
10615                if (obj instanceof SharedUserSetting) {
10616                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10617                } else if (obj instanceof PackageSetting) {
10618                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10619                } else {
10620                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10621                }
10622            } else {
10623                throw new SecurityException("Unknown calling uid " + uid);
10624            }
10625
10626            // Verify: can't set installerPackageName to a package that is
10627            // not signed with the same cert as the caller.
10628            if (installerPackageSetting != null) {
10629                if (compareSignatures(callerSignature,
10630                        installerPackageSetting.signatures.mSignatures)
10631                        != PackageManager.SIGNATURE_MATCH) {
10632                    throw new SecurityException(
10633                            "Caller does not have same cert as new installer package "
10634                            + installerPackageName);
10635                }
10636            }
10637
10638            // Verify: if target already has an installer package, it must
10639            // be signed with the same cert as the caller.
10640            if (targetPackageSetting.installerPackageName != null) {
10641                PackageSetting setting = mSettings.mPackages.get(
10642                        targetPackageSetting.installerPackageName);
10643                // If the currently set package isn't valid, then it's always
10644                // okay to change it.
10645                if (setting != null) {
10646                    if (compareSignatures(callerSignature,
10647                            setting.signatures.mSignatures)
10648                            != PackageManager.SIGNATURE_MATCH) {
10649                        throw new SecurityException(
10650                                "Caller does not have same cert as old installer package "
10651                                + targetPackageSetting.installerPackageName);
10652                    }
10653                }
10654            }
10655
10656            // Okay!
10657            targetPackageSetting.installerPackageName = installerPackageName;
10658            scheduleWriteSettingsLocked();
10659        }
10660    }
10661
10662    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10663        // Queue up an async operation since the package installation may take a little while.
10664        mHandler.post(new Runnable() {
10665            public void run() {
10666                mHandler.removeCallbacks(this);
10667                 // Result object to be returned
10668                PackageInstalledInfo res = new PackageInstalledInfo();
10669                res.returnCode = currentStatus;
10670                res.uid = -1;
10671                res.pkg = null;
10672                res.removedInfo = new PackageRemovedInfo();
10673                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10674                    args.doPreInstall(res.returnCode);
10675                    synchronized (mInstallLock) {
10676                        installPackageTracedLI(args, res);
10677                    }
10678                    args.doPostInstall(res.returnCode, res.uid);
10679                }
10680
10681                // A restore should be performed at this point if (a) the install
10682                // succeeded, (b) the operation is not an update, and (c) the new
10683                // package has not opted out of backup participation.
10684                final boolean update = res.removedInfo.removedPackage != null;
10685                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10686                boolean doRestore = !update
10687                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10688
10689                // Set up the post-install work request bookkeeping.  This will be used
10690                // and cleaned up by the post-install event handling regardless of whether
10691                // there's a restore pass performed.  Token values are >= 1.
10692                int token;
10693                if (mNextInstallToken < 0) mNextInstallToken = 1;
10694                token = mNextInstallToken++;
10695
10696                PostInstallData data = new PostInstallData(args, res);
10697                mRunningInstalls.put(token, data);
10698                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10699
10700                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10701                    // Pass responsibility to the Backup Manager.  It will perform a
10702                    // restore if appropriate, then pass responsibility back to the
10703                    // Package Manager to run the post-install observer callbacks
10704                    // and broadcasts.
10705                    IBackupManager bm = IBackupManager.Stub.asInterface(
10706                            ServiceManager.getService(Context.BACKUP_SERVICE));
10707                    if (bm != null) {
10708                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10709                                + " to BM for possible restore");
10710                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10711                        try {
10712                            // TODO: http://b/22388012
10713                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10714                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10715                            } else {
10716                                doRestore = false;
10717                            }
10718                        } catch (RemoteException e) {
10719                            // can't happen; the backup manager is local
10720                        } catch (Exception e) {
10721                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10722                            doRestore = false;
10723                        }
10724                    } else {
10725                        Slog.e(TAG, "Backup Manager not found!");
10726                        doRestore = false;
10727                    }
10728                }
10729
10730                if (!doRestore) {
10731                    // No restore possible, or the Backup Manager was mysteriously not
10732                    // available -- just fire the post-install work request directly.
10733                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10734
10735                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10736
10737                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10738                    mHandler.sendMessage(msg);
10739                }
10740            }
10741        });
10742    }
10743
10744    private abstract class HandlerParams {
10745        private static final int MAX_RETRIES = 4;
10746
10747        /**
10748         * Number of times startCopy() has been attempted and had a non-fatal
10749         * error.
10750         */
10751        private int mRetries = 0;
10752
10753        /** User handle for the user requesting the information or installation. */
10754        private final UserHandle mUser;
10755        String traceMethod;
10756        int traceCookie;
10757
10758        HandlerParams(UserHandle user) {
10759            mUser = user;
10760        }
10761
10762        UserHandle getUser() {
10763            return mUser;
10764        }
10765
10766        HandlerParams setTraceMethod(String traceMethod) {
10767            this.traceMethod = traceMethod;
10768            return this;
10769        }
10770
10771        HandlerParams setTraceCookie(int traceCookie) {
10772            this.traceCookie = traceCookie;
10773            return this;
10774        }
10775
10776        final boolean startCopy() {
10777            boolean res;
10778            try {
10779                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10780
10781                if (++mRetries > MAX_RETRIES) {
10782                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10783                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10784                    handleServiceError();
10785                    return false;
10786                } else {
10787                    handleStartCopy();
10788                    res = true;
10789                }
10790            } catch (RemoteException e) {
10791                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10792                mHandler.sendEmptyMessage(MCS_RECONNECT);
10793                res = false;
10794            }
10795            handleReturnCode();
10796            return res;
10797        }
10798
10799        final void serviceError() {
10800            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10801            handleServiceError();
10802            handleReturnCode();
10803        }
10804
10805        abstract void handleStartCopy() throws RemoteException;
10806        abstract void handleServiceError();
10807        abstract void handleReturnCode();
10808    }
10809
10810    class MeasureParams extends HandlerParams {
10811        private final PackageStats mStats;
10812        private boolean mSuccess;
10813
10814        private final IPackageStatsObserver mObserver;
10815
10816        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10817            super(new UserHandle(stats.userHandle));
10818            mObserver = observer;
10819            mStats = stats;
10820        }
10821
10822        @Override
10823        public String toString() {
10824            return "MeasureParams{"
10825                + Integer.toHexString(System.identityHashCode(this))
10826                + " " + mStats.packageName + "}";
10827        }
10828
10829        @Override
10830        void handleStartCopy() throws RemoteException {
10831            synchronized (mInstallLock) {
10832                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10833            }
10834
10835            if (mSuccess) {
10836                final boolean mounted;
10837                if (Environment.isExternalStorageEmulated()) {
10838                    mounted = true;
10839                } else {
10840                    final String status = Environment.getExternalStorageState();
10841                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10842                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10843                }
10844
10845                if (mounted) {
10846                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10847
10848                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10849                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10850
10851                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10852                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10853
10854                    // Always subtract cache size, since it's a subdirectory
10855                    mStats.externalDataSize -= mStats.externalCacheSize;
10856
10857                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10858                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10859
10860                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10861                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10862                }
10863            }
10864        }
10865
10866        @Override
10867        void handleReturnCode() {
10868            if (mObserver != null) {
10869                try {
10870                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10871                } catch (RemoteException e) {
10872                    Slog.i(TAG, "Observer no longer exists.");
10873                }
10874            }
10875        }
10876
10877        @Override
10878        void handleServiceError() {
10879            Slog.e(TAG, "Could not measure application " + mStats.packageName
10880                            + " external storage");
10881        }
10882    }
10883
10884    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10885            throws RemoteException {
10886        long result = 0;
10887        for (File path : paths) {
10888            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10889        }
10890        return result;
10891    }
10892
10893    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10894        for (File path : paths) {
10895            try {
10896                mcs.clearDirectory(path.getAbsolutePath());
10897            } catch (RemoteException e) {
10898            }
10899        }
10900    }
10901
10902    static class OriginInfo {
10903        /**
10904         * Location where install is coming from, before it has been
10905         * copied/renamed into place. This could be a single monolithic APK
10906         * file, or a cluster directory. This location may be untrusted.
10907         */
10908        final File file;
10909        final String cid;
10910
10911        /**
10912         * Flag indicating that {@link #file} or {@link #cid} has already been
10913         * staged, meaning downstream users don't need to defensively copy the
10914         * contents.
10915         */
10916        final boolean staged;
10917
10918        /**
10919         * Flag indicating that {@link #file} or {@link #cid} is an already
10920         * installed app that is being moved.
10921         */
10922        final boolean existing;
10923
10924        final String resolvedPath;
10925        final File resolvedFile;
10926
10927        static OriginInfo fromNothing() {
10928            return new OriginInfo(null, null, false, false);
10929        }
10930
10931        static OriginInfo fromUntrustedFile(File file) {
10932            return new OriginInfo(file, null, false, false);
10933        }
10934
10935        static OriginInfo fromExistingFile(File file) {
10936            return new OriginInfo(file, null, false, true);
10937        }
10938
10939        static OriginInfo fromStagedFile(File file) {
10940            return new OriginInfo(file, null, true, false);
10941        }
10942
10943        static OriginInfo fromStagedContainer(String cid) {
10944            return new OriginInfo(null, cid, true, false);
10945        }
10946
10947        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10948            this.file = file;
10949            this.cid = cid;
10950            this.staged = staged;
10951            this.existing = existing;
10952
10953            if (cid != null) {
10954                resolvedPath = PackageHelper.getSdDir(cid);
10955                resolvedFile = new File(resolvedPath);
10956            } else if (file != null) {
10957                resolvedPath = file.getAbsolutePath();
10958                resolvedFile = file;
10959            } else {
10960                resolvedPath = null;
10961                resolvedFile = null;
10962            }
10963        }
10964    }
10965
10966    static class MoveInfo {
10967        final int moveId;
10968        final String fromUuid;
10969        final String toUuid;
10970        final String packageName;
10971        final String dataAppName;
10972        final int appId;
10973        final String seinfo;
10974
10975        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10976                String dataAppName, int appId, String seinfo) {
10977            this.moveId = moveId;
10978            this.fromUuid = fromUuid;
10979            this.toUuid = toUuid;
10980            this.packageName = packageName;
10981            this.dataAppName = dataAppName;
10982            this.appId = appId;
10983            this.seinfo = seinfo;
10984        }
10985    }
10986
10987    class InstallParams extends HandlerParams {
10988        final OriginInfo origin;
10989        final MoveInfo move;
10990        final IPackageInstallObserver2 observer;
10991        int installFlags;
10992        final String installerPackageName;
10993        final String volumeUuid;
10994        final VerificationParams verificationParams;
10995        private InstallArgs mArgs;
10996        private int mRet;
10997        final String packageAbiOverride;
10998        final String[] grantedRuntimePermissions;
10999
11000        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11001                int installFlags, String installerPackageName, String volumeUuid,
11002                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11003                String[] grantedPermissions) {
11004            super(user);
11005            this.origin = origin;
11006            this.move = move;
11007            this.observer = observer;
11008            this.installFlags = installFlags;
11009            this.installerPackageName = installerPackageName;
11010            this.volumeUuid = volumeUuid;
11011            this.verificationParams = verificationParams;
11012            this.packageAbiOverride = packageAbiOverride;
11013            this.grantedRuntimePermissions = grantedPermissions;
11014        }
11015
11016        @Override
11017        public String toString() {
11018            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11019                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11020        }
11021
11022        public ManifestDigest getManifestDigest() {
11023            if (verificationParams == null) {
11024                return null;
11025            }
11026            return verificationParams.getManifestDigest();
11027        }
11028
11029        private int installLocationPolicy(PackageInfoLite pkgLite) {
11030            String packageName = pkgLite.packageName;
11031            int installLocation = pkgLite.installLocation;
11032            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11033            // reader
11034            synchronized (mPackages) {
11035                PackageParser.Package pkg = mPackages.get(packageName);
11036                if (pkg != null) {
11037                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11038                        // Check for downgrading.
11039                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11040                            try {
11041                                checkDowngrade(pkg, pkgLite);
11042                            } catch (PackageManagerException e) {
11043                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11044                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11045                            }
11046                        }
11047                        // Check for updated system application.
11048                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11049                            if (onSd) {
11050                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11051                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11052                            }
11053                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11054                        } else {
11055                            if (onSd) {
11056                                // Install flag overrides everything.
11057                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11058                            }
11059                            // If current upgrade specifies particular preference
11060                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11061                                // Application explicitly specified internal.
11062                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11063                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11064                                // App explictly prefers external. Let policy decide
11065                            } else {
11066                                // Prefer previous location
11067                                if (isExternal(pkg)) {
11068                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11069                                }
11070                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11071                            }
11072                        }
11073                    } else {
11074                        // Invalid install. Return error code
11075                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11076                    }
11077                }
11078            }
11079            // All the special cases have been taken care of.
11080            // Return result based on recommended install location.
11081            if (onSd) {
11082                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11083            }
11084            return pkgLite.recommendedInstallLocation;
11085        }
11086
11087        /*
11088         * Invoke remote method to get package information and install
11089         * location values. Override install location based on default
11090         * policy if needed and then create install arguments based
11091         * on the install location.
11092         */
11093        public void handleStartCopy() throws RemoteException {
11094            int ret = PackageManager.INSTALL_SUCCEEDED;
11095
11096            // If we're already staged, we've firmly committed to an install location
11097            if (origin.staged) {
11098                if (origin.file != null) {
11099                    installFlags |= PackageManager.INSTALL_INTERNAL;
11100                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11101                } else if (origin.cid != null) {
11102                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11103                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11104                } else {
11105                    throw new IllegalStateException("Invalid stage location");
11106                }
11107            }
11108
11109            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11110            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11111            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11112            PackageInfoLite pkgLite = null;
11113
11114            if (onInt && onSd) {
11115                // Check if both bits are set.
11116                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11117                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11118            } else if (onSd && ephemeral) {
11119                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11120                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11121            } else {
11122                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11123                        packageAbiOverride);
11124
11125                if (DEBUG_EPHEMERAL && ephemeral) {
11126                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11127                }
11128
11129                /*
11130                 * If we have too little free space, try to free cache
11131                 * before giving up.
11132                 */
11133                if (!origin.staged && pkgLite.recommendedInstallLocation
11134                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11135                    // TODO: focus freeing disk space on the target device
11136                    final StorageManager storage = StorageManager.from(mContext);
11137                    final long lowThreshold = storage.getStorageLowBytes(
11138                            Environment.getDataDirectory());
11139
11140                    final long sizeBytes = mContainerService.calculateInstalledSize(
11141                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11142
11143                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11144                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11145                                installFlags, packageAbiOverride);
11146                    }
11147
11148                    /*
11149                     * The cache free must have deleted the file we
11150                     * downloaded to install.
11151                     *
11152                     * TODO: fix the "freeCache" call to not delete
11153                     *       the file we care about.
11154                     */
11155                    if (pkgLite.recommendedInstallLocation
11156                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11157                        pkgLite.recommendedInstallLocation
11158                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11159                    }
11160                }
11161            }
11162
11163            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11164                int loc = pkgLite.recommendedInstallLocation;
11165                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11166                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11167                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11168                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11169                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11170                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11171                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11172                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11173                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11174                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11175                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11176                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11177                } else {
11178                    // Override with defaults if needed.
11179                    loc = installLocationPolicy(pkgLite);
11180                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11181                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11182                    } else if (!onSd && !onInt) {
11183                        // Override install location with flags
11184                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11185                            // Set the flag to install on external media.
11186                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11187                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11188                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11189                            if (DEBUG_EPHEMERAL) {
11190                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11191                            }
11192                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11193                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11194                                    |PackageManager.INSTALL_INTERNAL);
11195                        } else {
11196                            // Make sure the flag for installing on external
11197                            // media is unset
11198                            installFlags |= PackageManager.INSTALL_INTERNAL;
11199                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11200                        }
11201                    }
11202                }
11203            }
11204
11205            final InstallArgs args = createInstallArgs(this);
11206            mArgs = args;
11207
11208            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11209                // TODO: http://b/22976637
11210                // Apps installed for "all" users use the device owner to verify the app
11211                UserHandle verifierUser = getUser();
11212                if (verifierUser == UserHandle.ALL) {
11213                    verifierUser = UserHandle.SYSTEM;
11214                }
11215
11216                /*
11217                 * Determine if we have any installed package verifiers. If we
11218                 * do, then we'll defer to them to verify the packages.
11219                 */
11220                final int requiredUid = mRequiredVerifierPackage == null ? -1
11221                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11222                if (!origin.existing && requiredUid != -1
11223                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11224                    final Intent verification = new Intent(
11225                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11226                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11227                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11228                            PACKAGE_MIME_TYPE);
11229                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11230
11231                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11232                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11233                            verifierUser.getIdentifier());
11234
11235                    if (DEBUG_VERIFY) {
11236                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11237                                + verification.toString() + " with " + pkgLite.verifiers.length
11238                                + " optional verifiers");
11239                    }
11240
11241                    final int verificationId = mPendingVerificationToken++;
11242
11243                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11244
11245                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11246                            installerPackageName);
11247
11248                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11249                            installFlags);
11250
11251                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11252                            pkgLite.packageName);
11253
11254                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11255                            pkgLite.versionCode);
11256
11257                    if (verificationParams != null) {
11258                        if (verificationParams.getVerificationURI() != null) {
11259                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11260                                 verificationParams.getVerificationURI());
11261                        }
11262                        if (verificationParams.getOriginatingURI() != null) {
11263                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11264                                  verificationParams.getOriginatingURI());
11265                        }
11266                        if (verificationParams.getReferrer() != null) {
11267                            verification.putExtra(Intent.EXTRA_REFERRER,
11268                                  verificationParams.getReferrer());
11269                        }
11270                        if (verificationParams.getOriginatingUid() >= 0) {
11271                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11272                                  verificationParams.getOriginatingUid());
11273                        }
11274                        if (verificationParams.getInstallerUid() >= 0) {
11275                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11276                                  verificationParams.getInstallerUid());
11277                        }
11278                    }
11279
11280                    final PackageVerificationState verificationState = new PackageVerificationState(
11281                            requiredUid, args);
11282
11283                    mPendingVerification.append(verificationId, verificationState);
11284
11285                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11286                            receivers, verificationState);
11287
11288                    /*
11289                     * If any sufficient verifiers were listed in the package
11290                     * manifest, attempt to ask them.
11291                     */
11292                    if (sufficientVerifiers != null) {
11293                        final int N = sufficientVerifiers.size();
11294                        if (N == 0) {
11295                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11296                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11297                        } else {
11298                            for (int i = 0; i < N; i++) {
11299                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11300
11301                                final Intent sufficientIntent = new Intent(verification);
11302                                sufficientIntent.setComponent(verifierComponent);
11303                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11304                            }
11305                        }
11306                    }
11307
11308                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11309                            mRequiredVerifierPackage, receivers);
11310                    if (ret == PackageManager.INSTALL_SUCCEEDED
11311                            && mRequiredVerifierPackage != null) {
11312                        Trace.asyncTraceBegin(
11313                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11314                        /*
11315                         * Send the intent to the required verification agent,
11316                         * but only start the verification timeout after the
11317                         * target BroadcastReceivers have run.
11318                         */
11319                        verification.setComponent(requiredVerifierComponent);
11320                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11321                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11322                                new BroadcastReceiver() {
11323                                    @Override
11324                                    public void onReceive(Context context, Intent intent) {
11325                                        final Message msg = mHandler
11326                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11327                                        msg.arg1 = verificationId;
11328                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11329                                    }
11330                                }, null, 0, null, null);
11331
11332                        /*
11333                         * We don't want the copy to proceed until verification
11334                         * succeeds, so null out this field.
11335                         */
11336                        mArgs = null;
11337                    }
11338                } else {
11339                    /*
11340                     * No package verification is enabled, so immediately start
11341                     * the remote call to initiate copy using temporary file.
11342                     */
11343                    ret = args.copyApk(mContainerService, true);
11344                }
11345            }
11346
11347            mRet = ret;
11348        }
11349
11350        @Override
11351        void handleReturnCode() {
11352            // If mArgs is null, then MCS couldn't be reached. When it
11353            // reconnects, it will try again to install. At that point, this
11354            // will succeed.
11355            if (mArgs != null) {
11356                processPendingInstall(mArgs, mRet);
11357            }
11358        }
11359
11360        @Override
11361        void handleServiceError() {
11362            mArgs = createInstallArgs(this);
11363            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11364        }
11365
11366        public boolean isForwardLocked() {
11367            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11368        }
11369    }
11370
11371    /**
11372     * Used during creation of InstallArgs
11373     *
11374     * @param installFlags package installation flags
11375     * @return true if should be installed on external storage
11376     */
11377    private static boolean installOnExternalAsec(int installFlags) {
11378        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11379            return false;
11380        }
11381        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11382            return true;
11383        }
11384        return false;
11385    }
11386
11387    /**
11388     * Used during creation of InstallArgs
11389     *
11390     * @param installFlags package installation flags
11391     * @return true if should be installed as forward locked
11392     */
11393    private static boolean installForwardLocked(int installFlags) {
11394        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11395    }
11396
11397    private InstallArgs createInstallArgs(InstallParams params) {
11398        if (params.move != null) {
11399            return new MoveInstallArgs(params);
11400        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11401            return new AsecInstallArgs(params);
11402        } else {
11403            return new FileInstallArgs(params);
11404        }
11405    }
11406
11407    /**
11408     * Create args that describe an existing installed package. Typically used
11409     * when cleaning up old installs, or used as a move source.
11410     */
11411    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11412            String resourcePath, String[] instructionSets) {
11413        final boolean isInAsec;
11414        if (installOnExternalAsec(installFlags)) {
11415            /* Apps on SD card are always in ASEC containers. */
11416            isInAsec = true;
11417        } else if (installForwardLocked(installFlags)
11418                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11419            /*
11420             * Forward-locked apps are only in ASEC containers if they're the
11421             * new style
11422             */
11423            isInAsec = true;
11424        } else {
11425            isInAsec = false;
11426        }
11427
11428        if (isInAsec) {
11429            return new AsecInstallArgs(codePath, instructionSets,
11430                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11431        } else {
11432            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11433        }
11434    }
11435
11436    static abstract class InstallArgs {
11437        /** @see InstallParams#origin */
11438        final OriginInfo origin;
11439        /** @see InstallParams#move */
11440        final MoveInfo move;
11441
11442        final IPackageInstallObserver2 observer;
11443        // Always refers to PackageManager flags only
11444        final int installFlags;
11445        final String installerPackageName;
11446        final String volumeUuid;
11447        final ManifestDigest manifestDigest;
11448        final UserHandle user;
11449        final String abiOverride;
11450        final String[] installGrantPermissions;
11451        /** If non-null, drop an async trace when the install completes */
11452        final String traceMethod;
11453        final int traceCookie;
11454
11455        // The list of instruction sets supported by this app. This is currently
11456        // only used during the rmdex() phase to clean up resources. We can get rid of this
11457        // if we move dex files under the common app path.
11458        /* nullable */ String[] instructionSets;
11459
11460        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11461                int installFlags, String installerPackageName, String volumeUuid,
11462                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11463                String abiOverride, String[] installGrantPermissions,
11464                String traceMethod, int traceCookie) {
11465            this.origin = origin;
11466            this.move = move;
11467            this.installFlags = installFlags;
11468            this.observer = observer;
11469            this.installerPackageName = installerPackageName;
11470            this.volumeUuid = volumeUuid;
11471            this.manifestDigest = manifestDigest;
11472            this.user = user;
11473            this.instructionSets = instructionSets;
11474            this.abiOverride = abiOverride;
11475            this.installGrantPermissions = installGrantPermissions;
11476            this.traceMethod = traceMethod;
11477            this.traceCookie = traceCookie;
11478        }
11479
11480        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11481        abstract int doPreInstall(int status);
11482
11483        /**
11484         * Rename package into final resting place. All paths on the given
11485         * scanned package should be updated to reflect the rename.
11486         */
11487        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11488        abstract int doPostInstall(int status, int uid);
11489
11490        /** @see PackageSettingBase#codePathString */
11491        abstract String getCodePath();
11492        /** @see PackageSettingBase#resourcePathString */
11493        abstract String getResourcePath();
11494
11495        // Need installer lock especially for dex file removal.
11496        abstract void cleanUpResourcesLI();
11497        abstract boolean doPostDeleteLI(boolean delete);
11498
11499        /**
11500         * Called before the source arguments are copied. This is used mostly
11501         * for MoveParams when it needs to read the source file to put it in the
11502         * destination.
11503         */
11504        int doPreCopy() {
11505            return PackageManager.INSTALL_SUCCEEDED;
11506        }
11507
11508        /**
11509         * Called after the source arguments are copied. This is used mostly for
11510         * MoveParams when it needs to read the source file to put it in the
11511         * destination.
11512         *
11513         * @return
11514         */
11515        int doPostCopy(int uid) {
11516            return PackageManager.INSTALL_SUCCEEDED;
11517        }
11518
11519        protected boolean isFwdLocked() {
11520            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11521        }
11522
11523        protected boolean isExternalAsec() {
11524            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11525        }
11526
11527        protected boolean isEphemeral() {
11528            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11529        }
11530
11531        UserHandle getUser() {
11532            return user;
11533        }
11534    }
11535
11536    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11537        if (!allCodePaths.isEmpty()) {
11538            if (instructionSets == null) {
11539                throw new IllegalStateException("instructionSet == null");
11540            }
11541            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11542            for (String codePath : allCodePaths) {
11543                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11544                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11545                    if (retCode < 0) {
11546                        Slog.w(TAG, "Couldn't remove dex file for package: "
11547                                + " at location " + codePath + ", retcode=" + retCode);
11548                        // we don't consider this to be a failure of the core package deletion
11549                    }
11550                }
11551            }
11552        }
11553    }
11554
11555    /**
11556     * Logic to handle installation of non-ASEC applications, including copying
11557     * and renaming logic.
11558     */
11559    class FileInstallArgs extends InstallArgs {
11560        private File codeFile;
11561        private File resourceFile;
11562
11563        // Example topology:
11564        // /data/app/com.example/base.apk
11565        // /data/app/com.example/split_foo.apk
11566        // /data/app/com.example/lib/arm/libfoo.so
11567        // /data/app/com.example/lib/arm64/libfoo.so
11568        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11569
11570        /** New install */
11571        FileInstallArgs(InstallParams params) {
11572            super(params.origin, params.move, params.observer, params.installFlags,
11573                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11574                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11575                    params.grantedRuntimePermissions,
11576                    params.traceMethod, params.traceCookie);
11577            if (isFwdLocked()) {
11578                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11579            }
11580        }
11581
11582        /** Existing install */
11583        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11584            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11585                    null, null, null, 0);
11586            this.codeFile = (codePath != null) ? new File(codePath) : null;
11587            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11588        }
11589
11590        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11592            try {
11593                return doCopyApk(imcs, temp);
11594            } finally {
11595                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11596            }
11597        }
11598
11599        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11600            if (origin.staged) {
11601                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11602                codeFile = origin.file;
11603                resourceFile = origin.file;
11604                return PackageManager.INSTALL_SUCCEEDED;
11605            }
11606
11607            try {
11608                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11609                final File tempDir =
11610                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11611                codeFile = tempDir;
11612                resourceFile = tempDir;
11613            } catch (IOException e) {
11614                Slog.w(TAG, "Failed to create copy file: " + e);
11615                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11616            }
11617
11618            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11619                @Override
11620                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11621                    if (!FileUtils.isValidExtFilename(name)) {
11622                        throw new IllegalArgumentException("Invalid filename: " + name);
11623                    }
11624                    try {
11625                        final File file = new File(codeFile, name);
11626                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11627                                O_RDWR | O_CREAT, 0644);
11628                        Os.chmod(file.getAbsolutePath(), 0644);
11629                        return new ParcelFileDescriptor(fd);
11630                    } catch (ErrnoException e) {
11631                        throw new RemoteException("Failed to open: " + e.getMessage());
11632                    }
11633                }
11634            };
11635
11636            int ret = PackageManager.INSTALL_SUCCEEDED;
11637            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11638            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11639                Slog.e(TAG, "Failed to copy package");
11640                return ret;
11641            }
11642
11643            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11644            NativeLibraryHelper.Handle handle = null;
11645            try {
11646                handle = NativeLibraryHelper.Handle.create(codeFile);
11647                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11648                        abiOverride);
11649            } catch (IOException e) {
11650                Slog.e(TAG, "Copying native libraries failed", e);
11651                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11652            } finally {
11653                IoUtils.closeQuietly(handle);
11654            }
11655
11656            return ret;
11657        }
11658
11659        int doPreInstall(int status) {
11660            if (status != PackageManager.INSTALL_SUCCEEDED) {
11661                cleanUp();
11662            }
11663            return status;
11664        }
11665
11666        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11667            if (status != PackageManager.INSTALL_SUCCEEDED) {
11668                cleanUp();
11669                return false;
11670            }
11671
11672            final File targetDir = codeFile.getParentFile();
11673            final File beforeCodeFile = codeFile;
11674            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11675
11676            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11677            try {
11678                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11679            } catch (ErrnoException e) {
11680                Slog.w(TAG, "Failed to rename", e);
11681                return false;
11682            }
11683
11684            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11685                Slog.w(TAG, "Failed to restorecon");
11686                return false;
11687            }
11688
11689            // Reflect the rename internally
11690            codeFile = afterCodeFile;
11691            resourceFile = afterCodeFile;
11692
11693            // Reflect the rename in scanned details
11694            pkg.codePath = afterCodeFile.getAbsolutePath();
11695            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11696                    pkg.baseCodePath);
11697            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11698                    pkg.splitCodePaths);
11699
11700            // Reflect the rename in app info
11701            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11702            pkg.applicationInfo.setCodePath(pkg.codePath);
11703            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11704            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11705            pkg.applicationInfo.setResourcePath(pkg.codePath);
11706            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11707            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11708
11709            return true;
11710        }
11711
11712        int doPostInstall(int status, int uid) {
11713            if (status != PackageManager.INSTALL_SUCCEEDED) {
11714                cleanUp();
11715            }
11716            return status;
11717        }
11718
11719        @Override
11720        String getCodePath() {
11721            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11722        }
11723
11724        @Override
11725        String getResourcePath() {
11726            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11727        }
11728
11729        private boolean cleanUp() {
11730            if (codeFile == null || !codeFile.exists()) {
11731                return false;
11732            }
11733
11734            if (codeFile.isDirectory()) {
11735                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11736            } else {
11737                codeFile.delete();
11738            }
11739
11740            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11741                resourceFile.delete();
11742            }
11743
11744            return true;
11745        }
11746
11747        void cleanUpResourcesLI() {
11748            // Try enumerating all code paths before deleting
11749            List<String> allCodePaths = Collections.EMPTY_LIST;
11750            if (codeFile != null && codeFile.exists()) {
11751                try {
11752                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11753                    allCodePaths = pkg.getAllCodePaths();
11754                } catch (PackageParserException e) {
11755                    // Ignored; we tried our best
11756                }
11757            }
11758
11759            cleanUp();
11760            removeDexFiles(allCodePaths, instructionSets);
11761        }
11762
11763        boolean doPostDeleteLI(boolean delete) {
11764            // XXX err, shouldn't we respect the delete flag?
11765            cleanUpResourcesLI();
11766            return true;
11767        }
11768    }
11769
11770    private boolean isAsecExternal(String cid) {
11771        final String asecPath = PackageHelper.getSdFilesystem(cid);
11772        return !asecPath.startsWith(mAsecInternalPath);
11773    }
11774
11775    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11776            PackageManagerException {
11777        if (copyRet < 0) {
11778            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11779                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11780                throw new PackageManagerException(copyRet, message);
11781            }
11782        }
11783    }
11784
11785    /**
11786     * Extract the MountService "container ID" from the full code path of an
11787     * .apk.
11788     */
11789    static String cidFromCodePath(String fullCodePath) {
11790        int eidx = fullCodePath.lastIndexOf("/");
11791        String subStr1 = fullCodePath.substring(0, eidx);
11792        int sidx = subStr1.lastIndexOf("/");
11793        return subStr1.substring(sidx+1, eidx);
11794    }
11795
11796    /**
11797     * Logic to handle installation of ASEC applications, including copying and
11798     * renaming logic.
11799     */
11800    class AsecInstallArgs extends InstallArgs {
11801        static final String RES_FILE_NAME = "pkg.apk";
11802        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11803
11804        String cid;
11805        String packagePath;
11806        String resourcePath;
11807
11808        /** New install */
11809        AsecInstallArgs(InstallParams params) {
11810            super(params.origin, params.move, params.observer, params.installFlags,
11811                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11812                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11813                    params.grantedRuntimePermissions,
11814                    params.traceMethod, params.traceCookie);
11815        }
11816
11817        /** Existing install */
11818        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11819                        boolean isExternal, boolean isForwardLocked) {
11820            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11821                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11822                    instructionSets, null, null, null, 0);
11823            // Hackily pretend we're still looking at a full code path
11824            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11825                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11826            }
11827
11828            // Extract cid from fullCodePath
11829            int eidx = fullCodePath.lastIndexOf("/");
11830            String subStr1 = fullCodePath.substring(0, eidx);
11831            int sidx = subStr1.lastIndexOf("/");
11832            cid = subStr1.substring(sidx+1, eidx);
11833            setMountPath(subStr1);
11834        }
11835
11836        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11837            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11838                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11839                    instructionSets, null, null, null, 0);
11840            this.cid = cid;
11841            setMountPath(PackageHelper.getSdDir(cid));
11842        }
11843
11844        void createCopyFile() {
11845            cid = mInstallerService.allocateExternalStageCidLegacy();
11846        }
11847
11848        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11849            if (origin.staged && origin.cid != null) {
11850                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11851                cid = origin.cid;
11852                setMountPath(PackageHelper.getSdDir(cid));
11853                return PackageManager.INSTALL_SUCCEEDED;
11854            }
11855
11856            if (temp) {
11857                createCopyFile();
11858            } else {
11859                /*
11860                 * Pre-emptively destroy the container since it's destroyed if
11861                 * copying fails due to it existing anyway.
11862                 */
11863                PackageHelper.destroySdDir(cid);
11864            }
11865
11866            final String newMountPath = imcs.copyPackageToContainer(
11867                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11868                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11869
11870            if (newMountPath != null) {
11871                setMountPath(newMountPath);
11872                return PackageManager.INSTALL_SUCCEEDED;
11873            } else {
11874                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11875            }
11876        }
11877
11878        @Override
11879        String getCodePath() {
11880            return packagePath;
11881        }
11882
11883        @Override
11884        String getResourcePath() {
11885            return resourcePath;
11886        }
11887
11888        int doPreInstall(int status) {
11889            if (status != PackageManager.INSTALL_SUCCEEDED) {
11890                // Destroy container
11891                PackageHelper.destroySdDir(cid);
11892            } else {
11893                boolean mounted = PackageHelper.isContainerMounted(cid);
11894                if (!mounted) {
11895                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11896                            Process.SYSTEM_UID);
11897                    if (newMountPath != null) {
11898                        setMountPath(newMountPath);
11899                    } else {
11900                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11901                    }
11902                }
11903            }
11904            return status;
11905        }
11906
11907        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11908            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11909            String newMountPath = null;
11910            if (PackageHelper.isContainerMounted(cid)) {
11911                // Unmount the container
11912                if (!PackageHelper.unMountSdDir(cid)) {
11913                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11914                    return false;
11915                }
11916            }
11917            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11918                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11919                        " which might be stale. Will try to clean up.");
11920                // Clean up the stale container and proceed to recreate.
11921                if (!PackageHelper.destroySdDir(newCacheId)) {
11922                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11923                    return false;
11924                }
11925                // Successfully cleaned up stale container. Try to rename again.
11926                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11927                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11928                            + " inspite of cleaning it up.");
11929                    return false;
11930                }
11931            }
11932            if (!PackageHelper.isContainerMounted(newCacheId)) {
11933                Slog.w(TAG, "Mounting container " + newCacheId);
11934                newMountPath = PackageHelper.mountSdDir(newCacheId,
11935                        getEncryptKey(), Process.SYSTEM_UID);
11936            } else {
11937                newMountPath = PackageHelper.getSdDir(newCacheId);
11938            }
11939            if (newMountPath == null) {
11940                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11941                return false;
11942            }
11943            Log.i(TAG, "Succesfully renamed " + cid +
11944                    " to " + newCacheId +
11945                    " at new path: " + newMountPath);
11946            cid = newCacheId;
11947
11948            final File beforeCodeFile = new File(packagePath);
11949            setMountPath(newMountPath);
11950            final File afterCodeFile = new File(packagePath);
11951
11952            // Reflect the rename in scanned details
11953            pkg.codePath = afterCodeFile.getAbsolutePath();
11954            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11955                    pkg.baseCodePath);
11956            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11957                    pkg.splitCodePaths);
11958
11959            // Reflect the rename in app info
11960            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11961            pkg.applicationInfo.setCodePath(pkg.codePath);
11962            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11963            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11964            pkg.applicationInfo.setResourcePath(pkg.codePath);
11965            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11966            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11967
11968            return true;
11969        }
11970
11971        private void setMountPath(String mountPath) {
11972            final File mountFile = new File(mountPath);
11973
11974            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11975            if (monolithicFile.exists()) {
11976                packagePath = monolithicFile.getAbsolutePath();
11977                if (isFwdLocked()) {
11978                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11979                } else {
11980                    resourcePath = packagePath;
11981                }
11982            } else {
11983                packagePath = mountFile.getAbsolutePath();
11984                resourcePath = packagePath;
11985            }
11986        }
11987
11988        int doPostInstall(int status, int uid) {
11989            if (status != PackageManager.INSTALL_SUCCEEDED) {
11990                cleanUp();
11991            } else {
11992                final int groupOwner;
11993                final String protectedFile;
11994                if (isFwdLocked()) {
11995                    groupOwner = UserHandle.getSharedAppGid(uid);
11996                    protectedFile = RES_FILE_NAME;
11997                } else {
11998                    groupOwner = -1;
11999                    protectedFile = null;
12000                }
12001
12002                if (uid < Process.FIRST_APPLICATION_UID
12003                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12004                    Slog.e(TAG, "Failed to finalize " + cid);
12005                    PackageHelper.destroySdDir(cid);
12006                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12007                }
12008
12009                boolean mounted = PackageHelper.isContainerMounted(cid);
12010                if (!mounted) {
12011                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12012                }
12013            }
12014            return status;
12015        }
12016
12017        private void cleanUp() {
12018            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12019
12020            // Destroy secure container
12021            PackageHelper.destroySdDir(cid);
12022        }
12023
12024        private List<String> getAllCodePaths() {
12025            final File codeFile = new File(getCodePath());
12026            if (codeFile != null && codeFile.exists()) {
12027                try {
12028                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12029                    return pkg.getAllCodePaths();
12030                } catch (PackageParserException e) {
12031                    // Ignored; we tried our best
12032                }
12033            }
12034            return Collections.EMPTY_LIST;
12035        }
12036
12037        void cleanUpResourcesLI() {
12038            // Enumerate all code paths before deleting
12039            cleanUpResourcesLI(getAllCodePaths());
12040        }
12041
12042        private void cleanUpResourcesLI(List<String> allCodePaths) {
12043            cleanUp();
12044            removeDexFiles(allCodePaths, instructionSets);
12045        }
12046
12047        String getPackageName() {
12048            return getAsecPackageName(cid);
12049        }
12050
12051        boolean doPostDeleteLI(boolean delete) {
12052            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12053            final List<String> allCodePaths = getAllCodePaths();
12054            boolean mounted = PackageHelper.isContainerMounted(cid);
12055            if (mounted) {
12056                // Unmount first
12057                if (PackageHelper.unMountSdDir(cid)) {
12058                    mounted = false;
12059                }
12060            }
12061            if (!mounted && delete) {
12062                cleanUpResourcesLI(allCodePaths);
12063            }
12064            return !mounted;
12065        }
12066
12067        @Override
12068        int doPreCopy() {
12069            if (isFwdLocked()) {
12070                if (!PackageHelper.fixSdPermissions(cid,
12071                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12072                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12073                }
12074            }
12075
12076            return PackageManager.INSTALL_SUCCEEDED;
12077        }
12078
12079        @Override
12080        int doPostCopy(int uid) {
12081            if (isFwdLocked()) {
12082                if (uid < Process.FIRST_APPLICATION_UID
12083                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12084                                RES_FILE_NAME)) {
12085                    Slog.e(TAG, "Failed to finalize " + cid);
12086                    PackageHelper.destroySdDir(cid);
12087                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12088                }
12089            }
12090
12091            return PackageManager.INSTALL_SUCCEEDED;
12092        }
12093    }
12094
12095    /**
12096     * Logic to handle movement of existing installed applications.
12097     */
12098    class MoveInstallArgs extends InstallArgs {
12099        private File codeFile;
12100        private File resourceFile;
12101
12102        /** New install */
12103        MoveInstallArgs(InstallParams params) {
12104            super(params.origin, params.move, params.observer, params.installFlags,
12105                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12106                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12107                    params.grantedRuntimePermissions,
12108                    params.traceMethod, params.traceCookie);
12109        }
12110
12111        int copyApk(IMediaContainerService imcs, boolean temp) {
12112            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12113                    + move.fromUuid + " to " + move.toUuid);
12114            synchronized (mInstaller) {
12115                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12116                        move.dataAppName, move.appId, move.seinfo) != 0) {
12117                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12118                }
12119            }
12120
12121            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12122            resourceFile = codeFile;
12123            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12124
12125            return PackageManager.INSTALL_SUCCEEDED;
12126        }
12127
12128        int doPreInstall(int status) {
12129            if (status != PackageManager.INSTALL_SUCCEEDED) {
12130                cleanUp(move.toUuid);
12131            }
12132            return status;
12133        }
12134
12135        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12136            if (status != PackageManager.INSTALL_SUCCEEDED) {
12137                cleanUp(move.toUuid);
12138                return false;
12139            }
12140
12141            // Reflect the move in app info
12142            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12143            pkg.applicationInfo.setCodePath(pkg.codePath);
12144            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12145            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12146            pkg.applicationInfo.setResourcePath(pkg.codePath);
12147            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12148            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12149
12150            return true;
12151        }
12152
12153        int doPostInstall(int status, int uid) {
12154            if (status == PackageManager.INSTALL_SUCCEEDED) {
12155                cleanUp(move.fromUuid);
12156            } else {
12157                cleanUp(move.toUuid);
12158            }
12159            return status;
12160        }
12161
12162        @Override
12163        String getCodePath() {
12164            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12165        }
12166
12167        @Override
12168        String getResourcePath() {
12169            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12170        }
12171
12172        private boolean cleanUp(String volumeUuid) {
12173            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12174                    move.dataAppName);
12175            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12176            synchronized (mInstallLock) {
12177                // Clean up both app data and code
12178                removeDataDirsLI(volumeUuid, move.packageName);
12179                if (codeFile.isDirectory()) {
12180                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12181                } else {
12182                    codeFile.delete();
12183                }
12184            }
12185            return true;
12186        }
12187
12188        void cleanUpResourcesLI() {
12189            throw new UnsupportedOperationException();
12190        }
12191
12192        boolean doPostDeleteLI(boolean delete) {
12193            throw new UnsupportedOperationException();
12194        }
12195    }
12196
12197    static String getAsecPackageName(String packageCid) {
12198        int idx = packageCid.lastIndexOf("-");
12199        if (idx == -1) {
12200            return packageCid;
12201        }
12202        return packageCid.substring(0, idx);
12203    }
12204
12205    // Utility method used to create code paths based on package name and available index.
12206    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12207        String idxStr = "";
12208        int idx = 1;
12209        // Fall back to default value of idx=1 if prefix is not
12210        // part of oldCodePath
12211        if (oldCodePath != null) {
12212            String subStr = oldCodePath;
12213            // Drop the suffix right away
12214            if (suffix != null && subStr.endsWith(suffix)) {
12215                subStr = subStr.substring(0, subStr.length() - suffix.length());
12216            }
12217            // If oldCodePath already contains prefix find out the
12218            // ending index to either increment or decrement.
12219            int sidx = subStr.lastIndexOf(prefix);
12220            if (sidx != -1) {
12221                subStr = subStr.substring(sidx + prefix.length());
12222                if (subStr != null) {
12223                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12224                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12225                    }
12226                    try {
12227                        idx = Integer.parseInt(subStr);
12228                        if (idx <= 1) {
12229                            idx++;
12230                        } else {
12231                            idx--;
12232                        }
12233                    } catch(NumberFormatException e) {
12234                    }
12235                }
12236            }
12237        }
12238        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12239        return prefix + idxStr;
12240    }
12241
12242    private File getNextCodePath(File targetDir, String packageName) {
12243        int suffix = 1;
12244        File result;
12245        do {
12246            result = new File(targetDir, packageName + "-" + suffix);
12247            suffix++;
12248        } while (result.exists());
12249        return result;
12250    }
12251
12252    // Utility method that returns the relative package path with respect
12253    // to the installation directory. Like say for /data/data/com.test-1.apk
12254    // string com.test-1 is returned.
12255    static String deriveCodePathName(String codePath) {
12256        if (codePath == null) {
12257            return null;
12258        }
12259        final File codeFile = new File(codePath);
12260        final String name = codeFile.getName();
12261        if (codeFile.isDirectory()) {
12262            return name;
12263        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12264            final int lastDot = name.lastIndexOf('.');
12265            return name.substring(0, lastDot);
12266        } else {
12267            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12268            return null;
12269        }
12270    }
12271
12272    static class PackageInstalledInfo {
12273        String name;
12274        int uid;
12275        // The set of users that originally had this package installed.
12276        int[] origUsers;
12277        // The set of users that now have this package installed.
12278        int[] newUsers;
12279        PackageParser.Package pkg;
12280        int returnCode;
12281        String returnMsg;
12282        PackageRemovedInfo removedInfo;
12283
12284        public void setError(int code, String msg) {
12285            returnCode = code;
12286            returnMsg = msg;
12287            Slog.w(TAG, msg);
12288        }
12289
12290        public void setError(String msg, PackageParserException e) {
12291            returnCode = e.error;
12292            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12293            Slog.w(TAG, msg, e);
12294        }
12295
12296        public void setError(String msg, PackageManagerException e) {
12297            returnCode = e.error;
12298            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12299            Slog.w(TAG, msg, e);
12300        }
12301
12302        // In some error cases we want to convey more info back to the observer
12303        String origPackage;
12304        String origPermission;
12305    }
12306
12307    /*
12308     * Install a non-existing package.
12309     */
12310    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12311            UserHandle user, String installerPackageName, String volumeUuid,
12312            PackageInstalledInfo res) {
12313        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12314
12315        // Remember this for later, in case we need to rollback this install
12316        String pkgName = pkg.packageName;
12317
12318        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12319        // TODO: b/23350563
12320        final boolean dataDirExists = Environment
12321                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12322
12323        synchronized(mPackages) {
12324            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12325                // A package with the same name is already installed, though
12326                // it has been renamed to an older name.  The package we
12327                // are trying to install should be installed as an update to
12328                // the existing one, but that has not been requested, so bail.
12329                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12330                        + " without first uninstalling package running as "
12331                        + mSettings.mRenamedPackages.get(pkgName));
12332                return;
12333            }
12334            if (mPackages.containsKey(pkgName)) {
12335                // Don't allow installation over an existing package with the same name.
12336                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12337                        + " without first uninstalling.");
12338                return;
12339            }
12340        }
12341
12342        try {
12343            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12344                    System.currentTimeMillis(), user);
12345
12346            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12347            // delete the partially installed application. the data directory will have to be
12348            // restored if it was already existing
12349            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12350                // remove package from internal structures.  Note that we want deletePackageX to
12351                // delete the package data and cache directories that it created in
12352                // scanPackageLocked, unless those directories existed before we even tried to
12353                // install.
12354                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12355                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12356                                res.removedInfo, true);
12357            }
12358
12359        } catch (PackageManagerException e) {
12360            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12361        }
12362
12363        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12364    }
12365
12366    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12367        // Can't rotate keys during boot or if sharedUser.
12368        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12369                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12370            return false;
12371        }
12372        // app is using upgradeKeySets; make sure all are valid
12373        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12374        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12375        for (int i = 0; i < upgradeKeySets.length; i++) {
12376            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12377                Slog.wtf(TAG, "Package "
12378                         + (oldPs.name != null ? oldPs.name : "<null>")
12379                         + " contains upgrade-key-set reference to unknown key-set: "
12380                         + upgradeKeySets[i]
12381                         + " reverting to signatures check.");
12382                return false;
12383            }
12384        }
12385        return true;
12386    }
12387
12388    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12389        // Upgrade keysets are being used.  Determine if new package has a superset of the
12390        // required keys.
12391        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12392        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12393        for (int i = 0; i < upgradeKeySets.length; i++) {
12394            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12395            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12396                return true;
12397            }
12398        }
12399        return false;
12400    }
12401
12402    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12403            UserHandle user, String installerPackageName, String volumeUuid,
12404            PackageInstalledInfo res) {
12405        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12406
12407        final PackageParser.Package oldPackage;
12408        final String pkgName = pkg.packageName;
12409        final int[] allUsers;
12410        final boolean[] perUserInstalled;
12411
12412        // First find the old package info and check signatures
12413        synchronized(mPackages) {
12414            oldPackage = mPackages.get(pkgName);
12415            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12416            if (isEphemeral && !oldIsEphemeral) {
12417                // can't downgrade from full to ephemeral
12418                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12419                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12420                return;
12421            }
12422            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12423            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12424            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12425                if(!checkUpgradeKeySetLP(ps, pkg)) {
12426                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12427                            "New package not signed by keys specified by upgrade-keysets: "
12428                            + pkgName);
12429                    return;
12430                }
12431            } else {
12432                // default to original signature matching
12433                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12434                    != PackageManager.SIGNATURE_MATCH) {
12435                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12436                            "New package has a different signature: " + pkgName);
12437                    return;
12438                }
12439            }
12440
12441            // In case of rollback, remember per-user/profile install state
12442            allUsers = sUserManager.getUserIds();
12443            perUserInstalled = new boolean[allUsers.length];
12444            for (int i = 0; i < allUsers.length; i++) {
12445                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12446            }
12447        }
12448
12449        boolean sysPkg = (isSystemApp(oldPackage));
12450        if (sysPkg) {
12451            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12452                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12453        } else {
12454            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12455                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12456        }
12457    }
12458
12459    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12460            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12461            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12462            String volumeUuid, PackageInstalledInfo res) {
12463        String pkgName = deletedPackage.packageName;
12464        boolean deletedPkg = true;
12465        boolean updatedSettings = false;
12466
12467        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12468                + deletedPackage);
12469        long origUpdateTime;
12470        if (pkg.mExtras != null) {
12471            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12472        } else {
12473            origUpdateTime = 0;
12474        }
12475
12476        // First delete the existing package while retaining the data directory
12477        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12478                res.removedInfo, true)) {
12479            // If the existing package wasn't successfully deleted
12480            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12481            deletedPkg = false;
12482        } else {
12483            // Successfully deleted the old package; proceed with replace.
12484
12485            // If deleted package lived in a container, give users a chance to
12486            // relinquish resources before killing.
12487            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12488                if (DEBUG_INSTALL) {
12489                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12490                }
12491                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12492                final ArrayList<String> pkgList = new ArrayList<String>(1);
12493                pkgList.add(deletedPackage.applicationInfo.packageName);
12494                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12495            }
12496
12497            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12498            try {
12499                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12500                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12501                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12502                        perUserInstalled, res, user);
12503                updatedSettings = true;
12504            } catch (PackageManagerException e) {
12505                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12506            }
12507        }
12508
12509        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12510            // remove package from internal structures.  Note that we want deletePackageX to
12511            // delete the package data and cache directories that it created in
12512            // scanPackageLocked, unless those directories existed before we even tried to
12513            // install.
12514            if(updatedSettings) {
12515                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12516                deletePackageLI(
12517                        pkgName, null, true, allUsers, perUserInstalled,
12518                        PackageManager.DELETE_KEEP_DATA,
12519                                res.removedInfo, true);
12520            }
12521            // Since we failed to install the new package we need to restore the old
12522            // package that we deleted.
12523            if (deletedPkg) {
12524                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12525                File restoreFile = new File(deletedPackage.codePath);
12526                // Parse old package
12527                boolean oldExternal = isExternal(deletedPackage);
12528                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12529                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12530                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12531                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12532                try {
12533                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12534                            null);
12535                } catch (PackageManagerException e) {
12536                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12537                            + e.getMessage());
12538                    return;
12539                }
12540                // Restore of old package succeeded. Update permissions.
12541                // writer
12542                synchronized (mPackages) {
12543                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12544                            UPDATE_PERMISSIONS_ALL);
12545                    // can downgrade to reader
12546                    mSettings.writeLPr();
12547                }
12548                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12549            }
12550        }
12551    }
12552
12553    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12554            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12555            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12556            String volumeUuid, PackageInstalledInfo res) {
12557        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12558                + ", old=" + deletedPackage);
12559        boolean disabledSystem = false;
12560        boolean updatedSettings = false;
12561        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12562        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12563                != 0) {
12564            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12565        }
12566        String packageName = deletedPackage.packageName;
12567        if (packageName == null) {
12568            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12569                    "Attempt to delete null packageName.");
12570            return;
12571        }
12572        PackageParser.Package oldPkg;
12573        PackageSetting oldPkgSetting;
12574        // reader
12575        synchronized (mPackages) {
12576            oldPkg = mPackages.get(packageName);
12577            oldPkgSetting = mSettings.mPackages.get(packageName);
12578            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12579                    (oldPkgSetting == null)) {
12580                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12581                        "Couldn't find package:" + packageName + " information");
12582                return;
12583            }
12584        }
12585
12586        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12587
12588        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12589        res.removedInfo.removedPackage = packageName;
12590        // Remove existing system package
12591        removePackageLI(oldPkgSetting, true);
12592        // writer
12593        synchronized (mPackages) {
12594            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12595            if (!disabledSystem && deletedPackage != null) {
12596                // We didn't need to disable the .apk as a current system package,
12597                // which means we are replacing another update that is already
12598                // installed.  We need to make sure to delete the older one's .apk.
12599                res.removedInfo.args = createInstallArgsForExisting(0,
12600                        deletedPackage.applicationInfo.getCodePath(),
12601                        deletedPackage.applicationInfo.getResourcePath(),
12602                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12603            } else {
12604                res.removedInfo.args = null;
12605            }
12606        }
12607
12608        // Successfully disabled the old package. Now proceed with re-installation
12609        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12610
12611        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12612        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12613
12614        PackageParser.Package newPackage = null;
12615        try {
12616            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12617            if (newPackage.mExtras != null) {
12618                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12619                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12620                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12621
12622                // is the update attempting to change shared user? that isn't going to work...
12623                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12624                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12625                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12626                            + " to " + newPkgSetting.sharedUser);
12627                    updatedSettings = true;
12628                }
12629            }
12630
12631            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12632                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12633                        perUserInstalled, res, user);
12634                updatedSettings = true;
12635            }
12636
12637        } catch (PackageManagerException e) {
12638            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12639        }
12640
12641        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12642            // Re installation failed. Restore old information
12643            // Remove new pkg information
12644            if (newPackage != null) {
12645                removeInstalledPackageLI(newPackage, true);
12646            }
12647            // Add back the old system package
12648            try {
12649                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12650            } catch (PackageManagerException e) {
12651                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12652            }
12653            // Restore the old system information in Settings
12654            synchronized (mPackages) {
12655                if (disabledSystem) {
12656                    mSettings.enableSystemPackageLPw(packageName);
12657                }
12658                if (updatedSettings) {
12659                    mSettings.setInstallerPackageName(packageName,
12660                            oldPkgSetting.installerPackageName);
12661                }
12662                mSettings.writeLPr();
12663            }
12664        }
12665    }
12666
12667    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12668        // Collect all used permissions in the UID
12669        ArraySet<String> usedPermissions = new ArraySet<>();
12670        final int packageCount = su.packages.size();
12671        for (int i = 0; i < packageCount; i++) {
12672            PackageSetting ps = su.packages.valueAt(i);
12673            if (ps.pkg == null) {
12674                continue;
12675            }
12676            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12677            for (int j = 0; j < requestedPermCount; j++) {
12678                String permission = ps.pkg.requestedPermissions.get(j);
12679                BasePermission bp = mSettings.mPermissions.get(permission);
12680                if (bp != null) {
12681                    usedPermissions.add(permission);
12682                }
12683            }
12684        }
12685
12686        PermissionsState permissionsState = su.getPermissionsState();
12687        // Prune install permissions
12688        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12689        final int installPermCount = installPermStates.size();
12690        for (int i = installPermCount - 1; i >= 0;  i--) {
12691            PermissionState permissionState = installPermStates.get(i);
12692            if (!usedPermissions.contains(permissionState.getName())) {
12693                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12694                if (bp != null) {
12695                    permissionsState.revokeInstallPermission(bp);
12696                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12697                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12698                }
12699            }
12700        }
12701
12702        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12703
12704        // Prune runtime permissions
12705        for (int userId : allUserIds) {
12706            List<PermissionState> runtimePermStates = permissionsState
12707                    .getRuntimePermissionStates(userId);
12708            final int runtimePermCount = runtimePermStates.size();
12709            for (int i = runtimePermCount - 1; i >= 0; i--) {
12710                PermissionState permissionState = runtimePermStates.get(i);
12711                if (!usedPermissions.contains(permissionState.getName())) {
12712                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12713                    if (bp != null) {
12714                        permissionsState.revokeRuntimePermission(bp, userId);
12715                        permissionsState.updatePermissionFlags(bp, userId,
12716                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12717                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12718                                runtimePermissionChangedUserIds, userId);
12719                    }
12720                }
12721            }
12722        }
12723
12724        return runtimePermissionChangedUserIds;
12725    }
12726
12727    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12728            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12729            UserHandle user) {
12730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12731
12732        String pkgName = newPackage.packageName;
12733        synchronized (mPackages) {
12734            //write settings. the installStatus will be incomplete at this stage.
12735            //note that the new package setting would have already been
12736            //added to mPackages. It hasn't been persisted yet.
12737            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12739            mSettings.writeLPr();
12740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12741        }
12742
12743        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12744        synchronized (mPackages) {
12745            updatePermissionsLPw(newPackage.packageName, newPackage,
12746                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12747                            ? UPDATE_PERMISSIONS_ALL : 0));
12748            // For system-bundled packages, we assume that installing an upgraded version
12749            // of the package implies that the user actually wants to run that new code,
12750            // so we enable the package.
12751            PackageSetting ps = mSettings.mPackages.get(pkgName);
12752            if (ps != null) {
12753                if (isSystemApp(newPackage)) {
12754                    // NB: implicit assumption that system package upgrades apply to all users
12755                    if (DEBUG_INSTALL) {
12756                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12757                    }
12758                    if (res.origUsers != null) {
12759                        for (int userHandle : res.origUsers) {
12760                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12761                                    userHandle, installerPackageName);
12762                        }
12763                    }
12764                    // Also convey the prior install/uninstall state
12765                    if (allUsers != null && perUserInstalled != null) {
12766                        for (int i = 0; i < allUsers.length; i++) {
12767                            if (DEBUG_INSTALL) {
12768                                Slog.d(TAG, "    user " + allUsers[i]
12769                                        + " => " + perUserInstalled[i]);
12770                            }
12771                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12772                        }
12773                        // these install state changes will be persisted in the
12774                        // upcoming call to mSettings.writeLPr().
12775                    }
12776                }
12777                // It's implied that when a user requests installation, they want the app to be
12778                // installed and enabled.
12779                int userId = user.getIdentifier();
12780                if (userId != UserHandle.USER_ALL) {
12781                    ps.setInstalled(true, userId);
12782                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12783                }
12784            }
12785            res.name = pkgName;
12786            res.uid = newPackage.applicationInfo.uid;
12787            res.pkg = newPackage;
12788            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12789            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12790            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12791            //to update install status
12792            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12793            mSettings.writeLPr();
12794            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12795        }
12796
12797        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12798    }
12799
12800    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12801        try {
12802            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12803            installPackageLI(args, res);
12804        } finally {
12805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12806        }
12807    }
12808
12809    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12810        final int installFlags = args.installFlags;
12811        final String installerPackageName = args.installerPackageName;
12812        final String volumeUuid = args.volumeUuid;
12813        final File tmpPackageFile = new File(args.getCodePath());
12814        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12815        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12816                || (args.volumeUuid != null));
12817        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12818        boolean replace = false;
12819        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12820        if (args.move != null) {
12821            // moving a complete application; perfom an initial scan on the new install location
12822            scanFlags |= SCAN_INITIAL;
12823        }
12824        // Result object to be returned
12825        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12826
12827        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12828
12829        // Sanity check
12830        if (ephemeral && (forwardLocked || onExternal)) {
12831            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12832                    + " external=" + onExternal);
12833            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12834            return;
12835        }
12836
12837        // Retrieve PackageSettings and parse package
12838        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12839                | PackageParser.PARSE_ENFORCE_CODE
12840                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12841                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12842                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12843        PackageParser pp = new PackageParser();
12844        pp.setSeparateProcesses(mSeparateProcesses);
12845        pp.setDisplayMetrics(mMetrics);
12846
12847        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12848        final PackageParser.Package pkg;
12849        try {
12850            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12851        } catch (PackageParserException e) {
12852            res.setError("Failed parse during installPackageLI", e);
12853            return;
12854        } finally {
12855            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12856        }
12857
12858        // Mark that we have an install time CPU ABI override.
12859        pkg.cpuAbiOverride = args.abiOverride;
12860
12861        String pkgName = res.name = pkg.packageName;
12862        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12863            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12864                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12865                return;
12866            }
12867        }
12868
12869        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12870        try {
12871            pp.collectCertificates(pkg, parseFlags);
12872        } catch (PackageParserException e) {
12873            res.setError("Failed collect during installPackageLI", e);
12874            return;
12875        } finally {
12876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12877        }
12878
12879        /* If the installer passed in a manifest digest, compare it now. */
12880        if (args.manifestDigest != null) {
12881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12882            try {
12883                pp.collectManifestDigest(pkg);
12884            } catch (PackageParserException e) {
12885                res.setError("Failed collect during installPackageLI", e);
12886                return;
12887            } finally {
12888                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12889            }
12890
12891            if (DEBUG_INSTALL) {
12892                final String parsedManifest = pkg.manifestDigest == null ? "null"
12893                        : pkg.manifestDigest.toString();
12894                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12895                        + parsedManifest);
12896            }
12897
12898            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12899                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12900                return;
12901            }
12902        } else if (DEBUG_INSTALL) {
12903            final String parsedManifest = pkg.manifestDigest == null
12904                    ? "null" : pkg.manifestDigest.toString();
12905            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12906        }
12907
12908        // Get rid of all references to package scan path via parser.
12909        pp = null;
12910        String oldCodePath = null;
12911        boolean systemApp = false;
12912        synchronized (mPackages) {
12913            // Check if installing already existing package
12914            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12915                String oldName = mSettings.mRenamedPackages.get(pkgName);
12916                if (pkg.mOriginalPackages != null
12917                        && pkg.mOriginalPackages.contains(oldName)
12918                        && mPackages.containsKey(oldName)) {
12919                    // This package is derived from an original package,
12920                    // and this device has been updating from that original
12921                    // name.  We must continue using the original name, so
12922                    // rename the new package here.
12923                    pkg.setPackageName(oldName);
12924                    pkgName = pkg.packageName;
12925                    replace = true;
12926                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12927                            + oldName + " pkgName=" + pkgName);
12928                } else if (mPackages.containsKey(pkgName)) {
12929                    // This package, under its official name, already exists
12930                    // on the device; we should replace it.
12931                    replace = true;
12932                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12933                }
12934
12935                // Prevent apps opting out from runtime permissions
12936                if (replace) {
12937                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12938                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12939                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12940                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12941                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12942                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12943                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12944                                        + " doesn't support runtime permissions but the old"
12945                                        + " target SDK " + oldTargetSdk + " does.");
12946                        return;
12947                    }
12948                }
12949            }
12950
12951            PackageSetting ps = mSettings.mPackages.get(pkgName);
12952            if (ps != null) {
12953                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12954
12955                // Quick sanity check that we're signed correctly if updating;
12956                // we'll check this again later when scanning, but we want to
12957                // bail early here before tripping over redefined permissions.
12958                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12959                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12960                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12961                                + pkg.packageName + " upgrade keys do not match the "
12962                                + "previously installed version");
12963                        return;
12964                    }
12965                } else {
12966                    try {
12967                        verifySignaturesLP(ps, pkg);
12968                    } catch (PackageManagerException e) {
12969                        res.setError(e.error, e.getMessage());
12970                        return;
12971                    }
12972                }
12973
12974                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12975                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12976                    systemApp = (ps.pkg.applicationInfo.flags &
12977                            ApplicationInfo.FLAG_SYSTEM) != 0;
12978                }
12979                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12980            }
12981
12982            // Check whether the newly-scanned package wants to define an already-defined perm
12983            int N = pkg.permissions.size();
12984            for (int i = N-1; i >= 0; i--) {
12985                PackageParser.Permission perm = pkg.permissions.get(i);
12986                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12987                if (bp != null) {
12988                    // If the defining package is signed with our cert, it's okay.  This
12989                    // also includes the "updating the same package" case, of course.
12990                    // "updating same package" could also involve key-rotation.
12991                    final boolean sigsOk;
12992                    if (bp.sourcePackage.equals(pkg.packageName)
12993                            && (bp.packageSetting instanceof PackageSetting)
12994                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12995                                    scanFlags))) {
12996                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12997                    } else {
12998                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12999                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13000                    }
13001                    if (!sigsOk) {
13002                        // If the owning package is the system itself, we log but allow
13003                        // install to proceed; we fail the install on all other permission
13004                        // redefinitions.
13005                        if (!bp.sourcePackage.equals("android")) {
13006                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13007                                    + pkg.packageName + " attempting to redeclare permission "
13008                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13009                            res.origPermission = perm.info.name;
13010                            res.origPackage = bp.sourcePackage;
13011                            return;
13012                        } else {
13013                            Slog.w(TAG, "Package " + pkg.packageName
13014                                    + " attempting to redeclare system permission "
13015                                    + perm.info.name + "; ignoring new declaration");
13016                            pkg.permissions.remove(i);
13017                        }
13018                    }
13019                }
13020            }
13021
13022        }
13023
13024        if (systemApp) {
13025            if (onExternal) {
13026                // Abort update; system app can't be replaced with app on sdcard
13027                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13028                        "Cannot install updates to system apps on sdcard");
13029                return;
13030            } else if (ephemeral) {
13031                // Abort update; system app can't be replaced with an ephemeral app
13032                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13033                        "Cannot update a system app with an ephemeral app");
13034                return;
13035            }
13036        }
13037
13038        if (args.move != null) {
13039            // We did an in-place move, so dex is ready to roll
13040            scanFlags |= SCAN_NO_DEX;
13041            scanFlags |= SCAN_MOVE;
13042
13043            synchronized (mPackages) {
13044                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13045                if (ps == null) {
13046                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13047                            "Missing settings for moved package " + pkgName);
13048                }
13049
13050                // We moved the entire application as-is, so bring over the
13051                // previously derived ABI information.
13052                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13053                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13054            }
13055
13056        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13057            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13058            scanFlags |= SCAN_NO_DEX;
13059
13060            try {
13061                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13062                        true /* extract libs */);
13063            } catch (PackageManagerException pme) {
13064                Slog.e(TAG, "Error deriving application ABI", pme);
13065                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13066                return;
13067            }
13068        }
13069
13070        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13071            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13072            return;
13073        }
13074
13075        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13076
13077        if (replace) {
13078            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13079                    installerPackageName, volumeUuid, res);
13080        } else {
13081            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13082                    args.user, installerPackageName, volumeUuid, res);
13083        }
13084        synchronized (mPackages) {
13085            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13086            if (ps != null) {
13087                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13088            }
13089        }
13090    }
13091
13092    private void startIntentFilterVerifications(int userId, boolean replacing,
13093            PackageParser.Package pkg) {
13094        if (mIntentFilterVerifierComponent == null) {
13095            Slog.w(TAG, "No IntentFilter verification will not be done as "
13096                    + "there is no IntentFilterVerifier available!");
13097            return;
13098        }
13099
13100        final int verifierUid = getPackageUid(
13101                mIntentFilterVerifierComponent.getPackageName(),
13102                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13103
13104        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13105        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13106        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13107        mHandler.sendMessage(msg);
13108    }
13109
13110    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13111            PackageParser.Package pkg) {
13112        int size = pkg.activities.size();
13113        if (size == 0) {
13114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13115                    "No activity, so no need to verify any IntentFilter!");
13116            return;
13117        }
13118
13119        final boolean hasDomainURLs = hasDomainURLs(pkg);
13120        if (!hasDomainURLs) {
13121            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13122                    "No domain URLs, so no need to verify any IntentFilter!");
13123            return;
13124        }
13125
13126        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13127                + " if any IntentFilter from the " + size
13128                + " Activities needs verification ...");
13129
13130        int count = 0;
13131        final String packageName = pkg.packageName;
13132
13133        synchronized (mPackages) {
13134            // If this is a new install and we see that we've already run verification for this
13135            // package, we have nothing to do: it means the state was restored from backup.
13136            if (!replacing) {
13137                IntentFilterVerificationInfo ivi =
13138                        mSettings.getIntentFilterVerificationLPr(packageName);
13139                if (ivi != null) {
13140                    if (DEBUG_DOMAIN_VERIFICATION) {
13141                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13142                                + ivi.getStatusString());
13143                    }
13144                    return;
13145                }
13146            }
13147
13148            // If any filters need to be verified, then all need to be.
13149            boolean needToVerify = false;
13150            for (PackageParser.Activity a : pkg.activities) {
13151                for (ActivityIntentInfo filter : a.intents) {
13152                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13153                        if (DEBUG_DOMAIN_VERIFICATION) {
13154                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13155                        }
13156                        needToVerify = true;
13157                        break;
13158                    }
13159                }
13160            }
13161
13162            if (needToVerify) {
13163                final int verificationId = mIntentFilterVerificationToken++;
13164                for (PackageParser.Activity a : pkg.activities) {
13165                    for (ActivityIntentInfo filter : a.intents) {
13166                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13167                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13168                                    "Verification needed for IntentFilter:" + filter.toString());
13169                            mIntentFilterVerifier.addOneIntentFilterVerification(
13170                                    verifierUid, userId, verificationId, filter, packageName);
13171                            count++;
13172                        }
13173                    }
13174                }
13175            }
13176        }
13177
13178        if (count > 0) {
13179            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13180                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13181                    +  " for userId:" + userId);
13182            mIntentFilterVerifier.startVerifications(userId);
13183        } else {
13184            if (DEBUG_DOMAIN_VERIFICATION) {
13185                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13186            }
13187        }
13188    }
13189
13190    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13191        final ComponentName cn  = filter.activity.getComponentName();
13192        final String packageName = cn.getPackageName();
13193
13194        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13195                packageName);
13196        if (ivi == null) {
13197            return true;
13198        }
13199        int status = ivi.getStatus();
13200        switch (status) {
13201            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13202            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13203                return true;
13204
13205            default:
13206                // Nothing to do
13207                return false;
13208        }
13209    }
13210
13211    private static boolean isMultiArch(ApplicationInfo info) {
13212        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13213    }
13214
13215    private static boolean isExternal(PackageParser.Package pkg) {
13216        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13217    }
13218
13219    private static boolean isExternal(PackageSetting ps) {
13220        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13221    }
13222
13223    private static boolean isEphemeral(PackageParser.Package pkg) {
13224        return pkg.applicationInfo.isEphemeralApp();
13225    }
13226
13227    private static boolean isEphemeral(PackageSetting ps) {
13228        return ps.pkg != null && isEphemeral(ps.pkg);
13229    }
13230
13231    private static boolean isSystemApp(PackageParser.Package pkg) {
13232        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13233    }
13234
13235    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13236        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13237    }
13238
13239    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13240        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13241    }
13242
13243    private static boolean isSystemApp(PackageSetting ps) {
13244        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13245    }
13246
13247    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13248        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13249    }
13250
13251    private int packageFlagsToInstallFlags(PackageSetting ps) {
13252        int installFlags = 0;
13253        if (isEphemeral(ps)) {
13254            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13255        }
13256        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13257            // This existing package was an external ASEC install when we have
13258            // the external flag without a UUID
13259            installFlags |= PackageManager.INSTALL_EXTERNAL;
13260        }
13261        if (ps.isForwardLocked()) {
13262            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13263        }
13264        return installFlags;
13265    }
13266
13267    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13268        if (isExternal(pkg)) {
13269            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13270                return StorageManager.UUID_PRIMARY_PHYSICAL;
13271            } else {
13272                return pkg.volumeUuid;
13273            }
13274        } else {
13275            return StorageManager.UUID_PRIVATE_INTERNAL;
13276        }
13277    }
13278
13279    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13280        if (isExternal(pkg)) {
13281            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13282                return mSettings.getExternalVersion();
13283            } else {
13284                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13285            }
13286        } else {
13287            return mSettings.getInternalVersion();
13288        }
13289    }
13290
13291    private void deleteTempPackageFiles() {
13292        final FilenameFilter filter = new FilenameFilter() {
13293            public boolean accept(File dir, String name) {
13294                return name.startsWith("vmdl") && name.endsWith(".tmp");
13295            }
13296        };
13297        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13298            file.delete();
13299        }
13300    }
13301
13302    @Override
13303    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13304            int flags) {
13305        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13306                flags);
13307    }
13308
13309    @Override
13310    public void deletePackage(final String packageName,
13311            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13312        mContext.enforceCallingOrSelfPermission(
13313                android.Manifest.permission.DELETE_PACKAGES, null);
13314        Preconditions.checkNotNull(packageName);
13315        Preconditions.checkNotNull(observer);
13316        final int uid = Binder.getCallingUid();
13317        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13318        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13319        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13320            mContext.enforceCallingOrSelfPermission(
13321                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13322                    "deletePackage for user " + userId);
13323        }
13324
13325        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13326            try {
13327                observer.onPackageDeleted(packageName,
13328                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13329            } catch (RemoteException re) {
13330            }
13331            return;
13332        }
13333
13334        for (int currentUserId : users) {
13335            if (getBlockUninstallForUser(packageName, currentUserId)) {
13336                try {
13337                    observer.onPackageDeleted(packageName,
13338                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13339                } catch (RemoteException re) {
13340                }
13341                return;
13342            }
13343        }
13344
13345        if (DEBUG_REMOVE) {
13346            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13347        }
13348        // Queue up an async operation since the package deletion may take a little while.
13349        mHandler.post(new Runnable() {
13350            public void run() {
13351                mHandler.removeCallbacks(this);
13352                final int returnCode = deletePackageX(packageName, userId, flags);
13353                try {
13354                    observer.onPackageDeleted(packageName, returnCode, null);
13355                } catch (RemoteException e) {
13356                    Log.i(TAG, "Observer no longer exists.");
13357                } //end catch
13358            } //end run
13359        });
13360    }
13361
13362    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13363        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13364                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13365        try {
13366            if (dpm != null) {
13367                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13368                        /* callingUserOnly =*/ false);
13369                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13370                        : deviceOwnerComponentName.getPackageName();
13371                // Does the package contains the device owner?
13372                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13373                // this check is probably not needed, since DO should be registered as a device
13374                // admin on some user too. (Original bug for this: b/17657954)
13375                if (packageName.equals(deviceOwnerPackageName)) {
13376                    return true;
13377                }
13378                // Does it contain a device admin for any user?
13379                int[] users;
13380                if (userId == UserHandle.USER_ALL) {
13381                    users = sUserManager.getUserIds();
13382                } else {
13383                    users = new int[]{userId};
13384                }
13385                for (int i = 0; i < users.length; ++i) {
13386                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13387                        return true;
13388                    }
13389                }
13390            }
13391        } catch (RemoteException e) {
13392        }
13393        return false;
13394    }
13395
13396    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13397        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13398    }
13399
13400    /**
13401     *  This method is an internal method that could be get invoked either
13402     *  to delete an installed package or to clean up a failed installation.
13403     *  After deleting an installed package, a broadcast is sent to notify any
13404     *  listeners that the package has been installed. For cleaning up a failed
13405     *  installation, the broadcast is not necessary since the package's
13406     *  installation wouldn't have sent the initial broadcast either
13407     *  The key steps in deleting a package are
13408     *  deleting the package information in internal structures like mPackages,
13409     *  deleting the packages base directories through installd
13410     *  updating mSettings to reflect current status
13411     *  persisting settings for later use
13412     *  sending a broadcast if necessary
13413     */
13414    private int deletePackageX(String packageName, int userId, int flags) {
13415        final PackageRemovedInfo info = new PackageRemovedInfo();
13416        final boolean res;
13417
13418        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13419                ? UserHandle.ALL : new UserHandle(userId);
13420
13421        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13422            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13423            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13424        }
13425
13426        boolean removedForAllUsers = false;
13427        boolean systemUpdate = false;
13428
13429        PackageParser.Package uninstalledPkg;
13430
13431        // for the uninstall-updates case and restricted profiles, remember the per-
13432        // userhandle installed state
13433        int[] allUsers;
13434        boolean[] perUserInstalled;
13435        synchronized (mPackages) {
13436            uninstalledPkg = mPackages.get(packageName);
13437            PackageSetting ps = mSettings.mPackages.get(packageName);
13438            allUsers = sUserManager.getUserIds();
13439            perUserInstalled = new boolean[allUsers.length];
13440            for (int i = 0; i < allUsers.length; i++) {
13441                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13442            }
13443        }
13444
13445        synchronized (mInstallLock) {
13446            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13447            res = deletePackageLI(packageName, removeForUser,
13448                    true, allUsers, perUserInstalled,
13449                    flags | REMOVE_CHATTY, info, true);
13450            systemUpdate = info.isRemovedPackageSystemUpdate;
13451            synchronized (mPackages) {
13452                if (res) {
13453                    if (!systemUpdate && mPackages.get(packageName) == null) {
13454                        removedForAllUsers = true;
13455                    }
13456                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13457                }
13458            }
13459            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13460                    + " removedForAllUsers=" + removedForAllUsers);
13461        }
13462
13463        if (res) {
13464            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13465
13466            // If the removed package was a system update, the old system package
13467            // was re-enabled; we need to broadcast this information
13468            if (systemUpdate) {
13469                Bundle extras = new Bundle(1);
13470                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13471                        ? info.removedAppId : info.uid);
13472                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13473
13474                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13475                        extras, 0, null, null, null);
13476                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13477                        extras, 0, null, null, null);
13478                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13479                        null, 0, packageName, null, null);
13480            }
13481        }
13482        // Force a gc here.
13483        Runtime.getRuntime().gc();
13484        // Delete the resources here after sending the broadcast to let
13485        // other processes clean up before deleting resources.
13486        if (info.args != null) {
13487            synchronized (mInstallLock) {
13488                info.args.doPostDeleteLI(true);
13489            }
13490        }
13491
13492        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13493    }
13494
13495    class PackageRemovedInfo {
13496        String removedPackage;
13497        int uid = -1;
13498        int removedAppId = -1;
13499        int[] removedUsers = null;
13500        boolean isRemovedPackageSystemUpdate = false;
13501        // Clean up resources deleted packages.
13502        InstallArgs args = null;
13503
13504        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13505            Bundle extras = new Bundle(1);
13506            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13507            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13508            if (replacing) {
13509                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13510            }
13511            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13512            if (removedPackage != null) {
13513                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13514                        extras, 0, null, null, removedUsers);
13515                if (fullRemove && !replacing) {
13516                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13517                            extras, 0, null, null, removedUsers);
13518                }
13519            }
13520            if (removedAppId >= 0) {
13521                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13522                        removedUsers);
13523            }
13524        }
13525    }
13526
13527    /*
13528     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13529     * flag is not set, the data directory is removed as well.
13530     * make sure this flag is set for partially installed apps. If not its meaningless to
13531     * delete a partially installed application.
13532     */
13533    private void removePackageDataLI(PackageSetting ps,
13534            int[] allUserHandles, boolean[] perUserInstalled,
13535            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13536        String packageName = ps.name;
13537        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13538        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13539        // Retrieve object to delete permissions for shared user later on
13540        final PackageSetting deletedPs;
13541        // reader
13542        synchronized (mPackages) {
13543            deletedPs = mSettings.mPackages.get(packageName);
13544            if (outInfo != null) {
13545                outInfo.removedPackage = packageName;
13546                outInfo.removedUsers = deletedPs != null
13547                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13548                        : null;
13549            }
13550        }
13551        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13552            removeDataDirsLI(ps.volumeUuid, packageName);
13553            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13554        }
13555        // writer
13556        synchronized (mPackages) {
13557            if (deletedPs != null) {
13558                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13559                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13560                    clearDefaultBrowserIfNeeded(packageName);
13561                    if (outInfo != null) {
13562                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13563                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13564                    }
13565                    updatePermissionsLPw(deletedPs.name, null, 0);
13566                    if (deletedPs.sharedUser != null) {
13567                        // Remove permissions associated with package. Since runtime
13568                        // permissions are per user we have to kill the removed package
13569                        // or packages running under the shared user of the removed
13570                        // package if revoking the permissions requested only by the removed
13571                        // package is successful and this causes a change in gids.
13572                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13573                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13574                                    userId);
13575                            if (userIdToKill == UserHandle.USER_ALL
13576                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13577                                // If gids changed for this user, kill all affected packages.
13578                                mHandler.post(new Runnable() {
13579                                    @Override
13580                                    public void run() {
13581                                        // This has to happen with no lock held.
13582                                        killApplication(deletedPs.name, deletedPs.appId,
13583                                                KILL_APP_REASON_GIDS_CHANGED);
13584                                    }
13585                                });
13586                                break;
13587                            }
13588                        }
13589                    }
13590                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13591                }
13592                // make sure to preserve per-user disabled state if this removal was just
13593                // a downgrade of a system app to the factory package
13594                if (allUserHandles != null && perUserInstalled != null) {
13595                    if (DEBUG_REMOVE) {
13596                        Slog.d(TAG, "Propagating install state across downgrade");
13597                    }
13598                    for (int i = 0; i < allUserHandles.length; i++) {
13599                        if (DEBUG_REMOVE) {
13600                            Slog.d(TAG, "    user " + allUserHandles[i]
13601                                    + " => " + perUserInstalled[i]);
13602                        }
13603                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13604                    }
13605                }
13606            }
13607            // can downgrade to reader
13608            if (writeSettings) {
13609                // Save settings now
13610                mSettings.writeLPr();
13611            }
13612        }
13613        if (outInfo != null) {
13614            // A user ID was deleted here. Go through all users and remove it
13615            // from KeyStore.
13616            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13617        }
13618    }
13619
13620    static boolean locationIsPrivileged(File path) {
13621        try {
13622            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13623                    .getCanonicalPath();
13624            return path.getCanonicalPath().startsWith(privilegedAppDir);
13625        } catch (IOException e) {
13626            Slog.e(TAG, "Unable to access code path " + path);
13627        }
13628        return false;
13629    }
13630
13631    /*
13632     * Tries to delete system package.
13633     */
13634    private boolean deleteSystemPackageLI(PackageSetting newPs,
13635            int[] allUserHandles, boolean[] perUserInstalled,
13636            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13637        final boolean applyUserRestrictions
13638                = (allUserHandles != null) && (perUserInstalled != null);
13639        PackageSetting disabledPs = null;
13640        // Confirm if the system package has been updated
13641        // An updated system app can be deleted. This will also have to restore
13642        // the system pkg from system partition
13643        // reader
13644        synchronized (mPackages) {
13645            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13646        }
13647        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13648                + " disabledPs=" + disabledPs);
13649        if (disabledPs == null) {
13650            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13651            return false;
13652        } else if (DEBUG_REMOVE) {
13653            Slog.d(TAG, "Deleting system pkg from data partition");
13654        }
13655        if (DEBUG_REMOVE) {
13656            if (applyUserRestrictions) {
13657                Slog.d(TAG, "Remembering install states:");
13658                for (int i = 0; i < allUserHandles.length; i++) {
13659                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13660                }
13661            }
13662        }
13663        // Delete the updated package
13664        outInfo.isRemovedPackageSystemUpdate = true;
13665        if (disabledPs.versionCode < newPs.versionCode) {
13666            // Delete data for downgrades
13667            flags &= ~PackageManager.DELETE_KEEP_DATA;
13668        } else {
13669            // Preserve data by setting flag
13670            flags |= PackageManager.DELETE_KEEP_DATA;
13671        }
13672        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13673                allUserHandles, perUserInstalled, outInfo, writeSettings);
13674        if (!ret) {
13675            return false;
13676        }
13677        // writer
13678        synchronized (mPackages) {
13679            // Reinstate the old system package
13680            mSettings.enableSystemPackageLPw(newPs.name);
13681            // Remove any native libraries from the upgraded package.
13682            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13683        }
13684        // Install the system package
13685        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13686        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13687        if (locationIsPrivileged(disabledPs.codePath)) {
13688            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13689        }
13690
13691        final PackageParser.Package newPkg;
13692        try {
13693            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13694        } catch (PackageManagerException e) {
13695            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13696            return false;
13697        }
13698
13699        // writer
13700        synchronized (mPackages) {
13701            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13702
13703            // Propagate the permissions state as we do not want to drop on the floor
13704            // runtime permissions. The update permissions method below will take
13705            // care of removing obsolete permissions and grant install permissions.
13706            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13707            updatePermissionsLPw(newPkg.packageName, newPkg,
13708                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13709
13710            if (applyUserRestrictions) {
13711                if (DEBUG_REMOVE) {
13712                    Slog.d(TAG, "Propagating install state across reinstall");
13713                }
13714                for (int i = 0; i < allUserHandles.length; i++) {
13715                    if (DEBUG_REMOVE) {
13716                        Slog.d(TAG, "    user " + allUserHandles[i]
13717                                + " => " + perUserInstalled[i]);
13718                    }
13719                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13720
13721                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13722                }
13723                // Regardless of writeSettings we need to ensure that this restriction
13724                // state propagation is persisted
13725                mSettings.writeAllUsersPackageRestrictionsLPr();
13726            }
13727            // can downgrade to reader here
13728            if (writeSettings) {
13729                mSettings.writeLPr();
13730            }
13731        }
13732        return true;
13733    }
13734
13735    private boolean deleteInstalledPackageLI(PackageSetting ps,
13736            boolean deleteCodeAndResources, int flags,
13737            int[] allUserHandles, boolean[] perUserInstalled,
13738            PackageRemovedInfo outInfo, boolean writeSettings) {
13739        if (outInfo != null) {
13740            outInfo.uid = ps.appId;
13741        }
13742
13743        // Delete package data from internal structures and also remove data if flag is set
13744        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13745
13746        // Delete application code and resources
13747        if (deleteCodeAndResources && (outInfo != null)) {
13748            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13749                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13750            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13751        }
13752        return true;
13753    }
13754
13755    @Override
13756    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13757            int userId) {
13758        mContext.enforceCallingOrSelfPermission(
13759                android.Manifest.permission.DELETE_PACKAGES, null);
13760        synchronized (mPackages) {
13761            PackageSetting ps = mSettings.mPackages.get(packageName);
13762            if (ps == null) {
13763                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13764                return false;
13765            }
13766            if (!ps.getInstalled(userId)) {
13767                // Can't block uninstall for an app that is not installed or enabled.
13768                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13769                return false;
13770            }
13771            ps.setBlockUninstall(blockUninstall, userId);
13772            mSettings.writePackageRestrictionsLPr(userId);
13773        }
13774        return true;
13775    }
13776
13777    @Override
13778    public boolean getBlockUninstallForUser(String packageName, int userId) {
13779        synchronized (mPackages) {
13780            PackageSetting ps = mSettings.mPackages.get(packageName);
13781            if (ps == null) {
13782                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13783                return false;
13784            }
13785            return ps.getBlockUninstall(userId);
13786        }
13787    }
13788
13789    @Override
13790    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13791        int callingUid = Binder.getCallingUid();
13792        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13793            throw new SecurityException(
13794                    "setRequiredForSystemUser can only be run by the system or root");
13795        }
13796        synchronized (mPackages) {
13797            PackageSetting ps = mSettings.mPackages.get(packageName);
13798            if (ps == null) {
13799                Log.w(TAG, "Package doesn't exist: " + packageName);
13800                return false;
13801            }
13802            if (systemUserApp) {
13803                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13804            } else {
13805                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13806            }
13807            mSettings.writeLPr();
13808        }
13809        return true;
13810    }
13811
13812    /*
13813     * This method handles package deletion in general
13814     */
13815    private boolean deletePackageLI(String packageName, UserHandle user,
13816            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13817            int flags, PackageRemovedInfo outInfo,
13818            boolean writeSettings) {
13819        if (packageName == null) {
13820            Slog.w(TAG, "Attempt to delete null packageName.");
13821            return false;
13822        }
13823        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13824        PackageSetting ps;
13825        boolean dataOnly = false;
13826        int removeUser = -1;
13827        int appId = -1;
13828        synchronized (mPackages) {
13829            ps = mSettings.mPackages.get(packageName);
13830            if (ps == null) {
13831                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13832                return false;
13833            }
13834            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13835                    && user.getIdentifier() != UserHandle.USER_ALL) {
13836                // The caller is asking that the package only be deleted for a single
13837                // user.  To do this, we just mark its uninstalled state and delete
13838                // its data.  If this is a system app, we only allow this to happen if
13839                // they have set the special DELETE_SYSTEM_APP which requests different
13840                // semantics than normal for uninstalling system apps.
13841                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13842                final int userId = user.getIdentifier();
13843                ps.setUserState(userId,
13844                        COMPONENT_ENABLED_STATE_DEFAULT,
13845                        false, //installed
13846                        true,  //stopped
13847                        true,  //notLaunched
13848                        false, //hidden
13849                        false, //suspended
13850                        null, null, null,
13851                        false, // blockUninstall
13852                        ps.readUserState(userId).domainVerificationStatus, 0);
13853                if (!isSystemApp(ps)) {
13854                    // Do not uninstall the APK if an app should be cached
13855                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13856                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13857                        // Other user still have this package installed, so all
13858                        // we need to do is clear this user's data and save that
13859                        // it is uninstalled.
13860                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13861                        removeUser = user.getIdentifier();
13862                        appId = ps.appId;
13863                        scheduleWritePackageRestrictionsLocked(removeUser);
13864                    } else {
13865                        // We need to set it back to 'installed' so the uninstall
13866                        // broadcasts will be sent correctly.
13867                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13868                        ps.setInstalled(true, user.getIdentifier());
13869                    }
13870                } else {
13871                    // This is a system app, so we assume that the
13872                    // other users still have this package installed, so all
13873                    // we need to do is clear this user's data and save that
13874                    // it is uninstalled.
13875                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13876                    removeUser = user.getIdentifier();
13877                    appId = ps.appId;
13878                    scheduleWritePackageRestrictionsLocked(removeUser);
13879                }
13880            }
13881        }
13882
13883        if (removeUser >= 0) {
13884            // From above, we determined that we are deleting this only
13885            // for a single user.  Continue the work here.
13886            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13887            if (outInfo != null) {
13888                outInfo.removedPackage = packageName;
13889                outInfo.removedAppId = appId;
13890                outInfo.removedUsers = new int[] {removeUser};
13891            }
13892            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13893            removeKeystoreDataIfNeeded(removeUser, appId);
13894            schedulePackageCleaning(packageName, removeUser, false);
13895            synchronized (mPackages) {
13896                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13897                    scheduleWritePackageRestrictionsLocked(removeUser);
13898                }
13899                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13900            }
13901            return true;
13902        }
13903
13904        if (dataOnly) {
13905            // Delete application data first
13906            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13907            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13908            return true;
13909        }
13910
13911        boolean ret = false;
13912        if (isSystemApp(ps)) {
13913            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13914            // When an updated system application is deleted we delete the existing resources as well and
13915            // fall back to existing code in system partition
13916            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13917                    flags, outInfo, writeSettings);
13918        } else {
13919            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13920            // Kill application pre-emptively especially for apps on sd.
13921            killApplication(packageName, ps.appId, "uninstall pkg");
13922            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13923                    allUserHandles, perUserInstalled,
13924                    outInfo, writeSettings);
13925        }
13926
13927        return ret;
13928    }
13929
13930    private final static class ClearStorageConnection implements ServiceConnection {
13931        IMediaContainerService mContainerService;
13932
13933        @Override
13934        public void onServiceConnected(ComponentName name, IBinder service) {
13935            synchronized (this) {
13936                mContainerService = IMediaContainerService.Stub.asInterface(service);
13937                notifyAll();
13938            }
13939        }
13940
13941        @Override
13942        public void onServiceDisconnected(ComponentName name) {
13943        }
13944    }
13945
13946    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13947        final boolean mounted;
13948        if (Environment.isExternalStorageEmulated()) {
13949            mounted = true;
13950        } else {
13951            final String status = Environment.getExternalStorageState();
13952
13953            mounted = status.equals(Environment.MEDIA_MOUNTED)
13954                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13955        }
13956
13957        if (!mounted) {
13958            return;
13959        }
13960
13961        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13962        int[] users;
13963        if (userId == UserHandle.USER_ALL) {
13964            users = sUserManager.getUserIds();
13965        } else {
13966            users = new int[] { userId };
13967        }
13968        final ClearStorageConnection conn = new ClearStorageConnection();
13969        if (mContext.bindServiceAsUser(
13970                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13971            try {
13972                for (int curUser : users) {
13973                    long timeout = SystemClock.uptimeMillis() + 5000;
13974                    synchronized (conn) {
13975                        long now = SystemClock.uptimeMillis();
13976                        while (conn.mContainerService == null && now < timeout) {
13977                            try {
13978                                conn.wait(timeout - now);
13979                            } catch (InterruptedException e) {
13980                            }
13981                        }
13982                    }
13983                    if (conn.mContainerService == null) {
13984                        return;
13985                    }
13986
13987                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13988                    clearDirectory(conn.mContainerService,
13989                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13990                    if (allData) {
13991                        clearDirectory(conn.mContainerService,
13992                                userEnv.buildExternalStorageAppDataDirs(packageName));
13993                        clearDirectory(conn.mContainerService,
13994                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13995                    }
13996                }
13997            } finally {
13998                mContext.unbindService(conn);
13999            }
14000        }
14001    }
14002
14003    @Override
14004    public void clearApplicationUserData(final String packageName,
14005            final IPackageDataObserver observer, final int userId) {
14006        mContext.enforceCallingOrSelfPermission(
14007                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14008        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14009        // Queue up an async operation since the package deletion may take a little while.
14010        mHandler.post(new Runnable() {
14011            public void run() {
14012                mHandler.removeCallbacks(this);
14013                final boolean succeeded;
14014                synchronized (mInstallLock) {
14015                    succeeded = clearApplicationUserDataLI(packageName, userId);
14016                }
14017                clearExternalStorageDataSync(packageName, userId, true);
14018                if (succeeded) {
14019                    // invoke DeviceStorageMonitor's update method to clear any notifications
14020                    DeviceStorageMonitorInternal
14021                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14022                    if (dsm != null) {
14023                        dsm.checkMemory();
14024                    }
14025                }
14026                if(observer != null) {
14027                    try {
14028                        observer.onRemoveCompleted(packageName, succeeded);
14029                    } catch (RemoteException e) {
14030                        Log.i(TAG, "Observer no longer exists.");
14031                    }
14032                } //end if observer
14033            } //end run
14034        });
14035    }
14036
14037    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14038        if (packageName == null) {
14039            Slog.w(TAG, "Attempt to delete null packageName.");
14040            return false;
14041        }
14042
14043        // Try finding details about the requested package
14044        PackageParser.Package pkg;
14045        synchronized (mPackages) {
14046            pkg = mPackages.get(packageName);
14047            if (pkg == null) {
14048                final PackageSetting ps = mSettings.mPackages.get(packageName);
14049                if (ps != null) {
14050                    pkg = ps.pkg;
14051                }
14052            }
14053
14054            if (pkg == null) {
14055                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14056                return false;
14057            }
14058
14059            PackageSetting ps = (PackageSetting) pkg.mExtras;
14060            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14061        }
14062
14063        // Always delete data directories for package, even if we found no other
14064        // record of app. This helps users recover from UID mismatches without
14065        // resorting to a full data wipe.
14066        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14067        if (retCode < 0) {
14068            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14069            return false;
14070        }
14071
14072        final int appId = pkg.applicationInfo.uid;
14073        removeKeystoreDataIfNeeded(userId, appId);
14074
14075        // Create a native library symlink only if we have native libraries
14076        // and if the native libraries are 32 bit libraries. We do not provide
14077        // this symlink for 64 bit libraries.
14078        if (pkg.applicationInfo.primaryCpuAbi != null &&
14079                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14080            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14081            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14082                    nativeLibPath, userId) < 0) {
14083                Slog.w(TAG, "Failed linking native library dir");
14084                return false;
14085            }
14086        }
14087
14088        return true;
14089    }
14090
14091    /**
14092     * Reverts user permission state changes (permissions and flags) in
14093     * all packages for a given user.
14094     *
14095     * @param userId The device user for which to do a reset.
14096     */
14097    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14098        final int packageCount = mPackages.size();
14099        for (int i = 0; i < packageCount; i++) {
14100            PackageParser.Package pkg = mPackages.valueAt(i);
14101            PackageSetting ps = (PackageSetting) pkg.mExtras;
14102            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14103        }
14104    }
14105
14106    /**
14107     * Reverts user permission state changes (permissions and flags).
14108     *
14109     * @param ps The package for which to reset.
14110     * @param userId The device user for which to do a reset.
14111     */
14112    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14113            final PackageSetting ps, final int userId) {
14114        if (ps.pkg == null) {
14115            return;
14116        }
14117
14118        // These are flags that can change base on user actions.
14119        final int userSettableMask = FLAG_PERMISSION_USER_SET
14120                | FLAG_PERMISSION_USER_FIXED
14121                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14122                | FLAG_PERMISSION_REVIEW_REQUIRED;
14123
14124        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14125                | FLAG_PERMISSION_POLICY_FIXED;
14126
14127        boolean writeInstallPermissions = false;
14128        boolean writeRuntimePermissions = false;
14129
14130        final int permissionCount = ps.pkg.requestedPermissions.size();
14131        for (int i = 0; i < permissionCount; i++) {
14132            String permission = ps.pkg.requestedPermissions.get(i);
14133
14134            BasePermission bp = mSettings.mPermissions.get(permission);
14135            if (bp == null) {
14136                continue;
14137            }
14138
14139            // If shared user we just reset the state to which only this app contributed.
14140            if (ps.sharedUser != null) {
14141                boolean used = false;
14142                final int packageCount = ps.sharedUser.packages.size();
14143                for (int j = 0; j < packageCount; j++) {
14144                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14145                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14146                            && pkg.pkg.requestedPermissions.contains(permission)) {
14147                        used = true;
14148                        break;
14149                    }
14150                }
14151                if (used) {
14152                    continue;
14153                }
14154            }
14155
14156            PermissionsState permissionsState = ps.getPermissionsState();
14157
14158            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14159
14160            // Always clear the user settable flags.
14161            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14162                    bp.name) != null;
14163            // If permission review is enabled and this is a legacy app, mark the
14164            // permission as requiring a review as this is the initial state.
14165            int flags = 0;
14166            if (Build.PERMISSIONS_REVIEW_REQUIRED
14167                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14168                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14169            }
14170            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14171                if (hasInstallState) {
14172                    writeInstallPermissions = true;
14173                } else {
14174                    writeRuntimePermissions = true;
14175                }
14176            }
14177
14178            // Below is only runtime permission handling.
14179            if (!bp.isRuntime()) {
14180                continue;
14181            }
14182
14183            // Never clobber system or policy.
14184            if ((oldFlags & policyOrSystemFlags) != 0) {
14185                continue;
14186            }
14187
14188            // If this permission was granted by default, make sure it is.
14189            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14190                if (permissionsState.grantRuntimePermission(bp, userId)
14191                        != PERMISSION_OPERATION_FAILURE) {
14192                    writeRuntimePermissions = true;
14193                }
14194            // If permission review is enabled the permissions for a legacy apps
14195            // are represented as constantly granted runtime ones, so don't revoke.
14196            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14197                // Otherwise, reset the permission.
14198                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14199                switch (revokeResult) {
14200                    case PERMISSION_OPERATION_SUCCESS: {
14201                        writeRuntimePermissions = true;
14202                    } break;
14203
14204                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14205                        writeRuntimePermissions = true;
14206                        final int appId = ps.appId;
14207                        mHandler.post(new Runnable() {
14208                            @Override
14209                            public void run() {
14210                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14211                            }
14212                        });
14213                    } break;
14214                }
14215            }
14216        }
14217
14218        // Synchronously write as we are taking permissions away.
14219        if (writeRuntimePermissions) {
14220            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14221        }
14222
14223        // Synchronously write as we are taking permissions away.
14224        if (writeInstallPermissions) {
14225            mSettings.writeLPr();
14226        }
14227    }
14228
14229    /**
14230     * Remove entries from the keystore daemon. Will only remove it if the
14231     * {@code appId} is valid.
14232     */
14233    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14234        if (appId < 0) {
14235            return;
14236        }
14237
14238        final KeyStore keyStore = KeyStore.getInstance();
14239        if (keyStore != null) {
14240            if (userId == UserHandle.USER_ALL) {
14241                for (final int individual : sUserManager.getUserIds()) {
14242                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14243                }
14244            } else {
14245                keyStore.clearUid(UserHandle.getUid(userId, appId));
14246            }
14247        } else {
14248            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14249        }
14250    }
14251
14252    @Override
14253    public void deleteApplicationCacheFiles(final String packageName,
14254            final IPackageDataObserver observer) {
14255        mContext.enforceCallingOrSelfPermission(
14256                android.Manifest.permission.DELETE_CACHE_FILES, null);
14257        // Queue up an async operation since the package deletion may take a little while.
14258        final int userId = UserHandle.getCallingUserId();
14259        mHandler.post(new Runnable() {
14260            public void run() {
14261                mHandler.removeCallbacks(this);
14262                final boolean succeded;
14263                synchronized (mInstallLock) {
14264                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14265                }
14266                clearExternalStorageDataSync(packageName, userId, false);
14267                if (observer != null) {
14268                    try {
14269                        observer.onRemoveCompleted(packageName, succeded);
14270                    } catch (RemoteException e) {
14271                        Log.i(TAG, "Observer no longer exists.");
14272                    }
14273                } //end if observer
14274            } //end run
14275        });
14276    }
14277
14278    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14279        if (packageName == null) {
14280            Slog.w(TAG, "Attempt to delete null packageName.");
14281            return false;
14282        }
14283        PackageParser.Package p;
14284        synchronized (mPackages) {
14285            p = mPackages.get(packageName);
14286        }
14287        if (p == null) {
14288            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14289            return false;
14290        }
14291        final ApplicationInfo applicationInfo = p.applicationInfo;
14292        if (applicationInfo == null) {
14293            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14294            return false;
14295        }
14296        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14297        if (retCode < 0) {
14298            Slog.w(TAG, "Couldn't remove cache files for package: "
14299                       + packageName + " u" + userId);
14300            return false;
14301        }
14302        return true;
14303    }
14304
14305    @Override
14306    public void getPackageSizeInfo(final String packageName, int userHandle,
14307            final IPackageStatsObserver observer) {
14308        mContext.enforceCallingOrSelfPermission(
14309                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14310        if (packageName == null) {
14311            throw new IllegalArgumentException("Attempt to get size of null packageName");
14312        }
14313
14314        PackageStats stats = new PackageStats(packageName, userHandle);
14315
14316        /*
14317         * Queue up an async operation since the package measurement may take a
14318         * little while.
14319         */
14320        Message msg = mHandler.obtainMessage(INIT_COPY);
14321        msg.obj = new MeasureParams(stats, observer);
14322        mHandler.sendMessage(msg);
14323    }
14324
14325    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14326            PackageStats pStats) {
14327        if (packageName == null) {
14328            Slog.w(TAG, "Attempt to get size of null packageName.");
14329            return false;
14330        }
14331        PackageParser.Package p;
14332        boolean dataOnly = false;
14333        String libDirRoot = null;
14334        String asecPath = null;
14335        PackageSetting ps = null;
14336        synchronized (mPackages) {
14337            p = mPackages.get(packageName);
14338            ps = mSettings.mPackages.get(packageName);
14339            if(p == null) {
14340                dataOnly = true;
14341                if((ps == null) || (ps.pkg == null)) {
14342                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14343                    return false;
14344                }
14345                p = ps.pkg;
14346            }
14347            if (ps != null) {
14348                libDirRoot = ps.legacyNativeLibraryPathString;
14349            }
14350            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14351                final long token = Binder.clearCallingIdentity();
14352                try {
14353                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14354                    if (secureContainerId != null) {
14355                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14356                    }
14357                } finally {
14358                    Binder.restoreCallingIdentity(token);
14359                }
14360            }
14361        }
14362        String publicSrcDir = null;
14363        if(!dataOnly) {
14364            final ApplicationInfo applicationInfo = p.applicationInfo;
14365            if (applicationInfo == null) {
14366                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14367                return false;
14368            }
14369            if (p.isForwardLocked()) {
14370                publicSrcDir = applicationInfo.getBaseResourcePath();
14371            }
14372        }
14373        // TODO: extend to measure size of split APKs
14374        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14375        // not just the first level.
14376        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14377        // just the primary.
14378        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14379
14380        String apkPath;
14381        File packageDir = new File(p.codePath);
14382
14383        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14384            apkPath = packageDir.getAbsolutePath();
14385            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14386            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14387                libDirRoot = null;
14388            }
14389        } else {
14390            apkPath = p.baseCodePath;
14391        }
14392
14393        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14394                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14395        if (res < 0) {
14396            return false;
14397        }
14398
14399        // Fix-up for forward-locked applications in ASEC containers.
14400        if (!isExternal(p)) {
14401            pStats.codeSize += pStats.externalCodeSize;
14402            pStats.externalCodeSize = 0L;
14403        }
14404
14405        return true;
14406    }
14407
14408
14409    @Override
14410    public void addPackageToPreferred(String packageName) {
14411        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14412    }
14413
14414    @Override
14415    public void removePackageFromPreferred(String packageName) {
14416        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14417    }
14418
14419    @Override
14420    public List<PackageInfo> getPreferredPackages(int flags) {
14421        return new ArrayList<PackageInfo>();
14422    }
14423
14424    private int getUidTargetSdkVersionLockedLPr(int uid) {
14425        Object obj = mSettings.getUserIdLPr(uid);
14426        if (obj instanceof SharedUserSetting) {
14427            final SharedUserSetting sus = (SharedUserSetting) obj;
14428            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14429            final Iterator<PackageSetting> it = sus.packages.iterator();
14430            while (it.hasNext()) {
14431                final PackageSetting ps = it.next();
14432                if (ps.pkg != null) {
14433                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14434                    if (v < vers) vers = v;
14435                }
14436            }
14437            return vers;
14438        } else if (obj instanceof PackageSetting) {
14439            final PackageSetting ps = (PackageSetting) obj;
14440            if (ps.pkg != null) {
14441                return ps.pkg.applicationInfo.targetSdkVersion;
14442            }
14443        }
14444        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14445    }
14446
14447    @Override
14448    public void addPreferredActivity(IntentFilter filter, int match,
14449            ComponentName[] set, ComponentName activity, int userId) {
14450        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14451                "Adding preferred");
14452    }
14453
14454    private void addPreferredActivityInternal(IntentFilter filter, int match,
14455            ComponentName[] set, ComponentName activity, boolean always, int userId,
14456            String opname) {
14457        // writer
14458        int callingUid = Binder.getCallingUid();
14459        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14460        if (filter.countActions() == 0) {
14461            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14462            return;
14463        }
14464        synchronized (mPackages) {
14465            if (mContext.checkCallingOrSelfPermission(
14466                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14467                    != PackageManager.PERMISSION_GRANTED) {
14468                if (getUidTargetSdkVersionLockedLPr(callingUid)
14469                        < Build.VERSION_CODES.FROYO) {
14470                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14471                            + callingUid);
14472                    return;
14473                }
14474                mContext.enforceCallingOrSelfPermission(
14475                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14476            }
14477
14478            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14479            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14480                    + userId + ":");
14481            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14482            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14483            scheduleWritePackageRestrictionsLocked(userId);
14484        }
14485    }
14486
14487    @Override
14488    public void replacePreferredActivity(IntentFilter filter, int match,
14489            ComponentName[] set, ComponentName activity, int userId) {
14490        if (filter.countActions() != 1) {
14491            throw new IllegalArgumentException(
14492                    "replacePreferredActivity expects filter to have only 1 action.");
14493        }
14494        if (filter.countDataAuthorities() != 0
14495                || filter.countDataPaths() != 0
14496                || filter.countDataSchemes() > 1
14497                || filter.countDataTypes() != 0) {
14498            throw new IllegalArgumentException(
14499                    "replacePreferredActivity expects filter to have no data authorities, " +
14500                    "paths, or types; and at most one scheme.");
14501        }
14502
14503        final int callingUid = Binder.getCallingUid();
14504        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14505        synchronized (mPackages) {
14506            if (mContext.checkCallingOrSelfPermission(
14507                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14508                    != PackageManager.PERMISSION_GRANTED) {
14509                if (getUidTargetSdkVersionLockedLPr(callingUid)
14510                        < Build.VERSION_CODES.FROYO) {
14511                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14512                            + Binder.getCallingUid());
14513                    return;
14514                }
14515                mContext.enforceCallingOrSelfPermission(
14516                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14517            }
14518
14519            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14520            if (pir != null) {
14521                // Get all of the existing entries that exactly match this filter.
14522                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14523                if (existing != null && existing.size() == 1) {
14524                    PreferredActivity cur = existing.get(0);
14525                    if (DEBUG_PREFERRED) {
14526                        Slog.i(TAG, "Checking replace of preferred:");
14527                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14528                        if (!cur.mPref.mAlways) {
14529                            Slog.i(TAG, "  -- CUR; not mAlways!");
14530                        } else {
14531                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14532                            Slog.i(TAG, "  -- CUR: mSet="
14533                                    + Arrays.toString(cur.mPref.mSetComponents));
14534                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14535                            Slog.i(TAG, "  -- NEW: mMatch="
14536                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14537                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14538                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14539                        }
14540                    }
14541                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14542                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14543                            && cur.mPref.sameSet(set)) {
14544                        // Setting the preferred activity to what it happens to be already
14545                        if (DEBUG_PREFERRED) {
14546                            Slog.i(TAG, "Replacing with same preferred activity "
14547                                    + cur.mPref.mShortComponent + " for user "
14548                                    + userId + ":");
14549                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14550                        }
14551                        return;
14552                    }
14553                }
14554
14555                if (existing != null) {
14556                    if (DEBUG_PREFERRED) {
14557                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14558                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14559                    }
14560                    for (int i = 0; i < existing.size(); i++) {
14561                        PreferredActivity pa = existing.get(i);
14562                        if (DEBUG_PREFERRED) {
14563                            Slog.i(TAG, "Removing existing preferred activity "
14564                                    + pa.mPref.mComponent + ":");
14565                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14566                        }
14567                        pir.removeFilter(pa);
14568                    }
14569                }
14570            }
14571            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14572                    "Replacing preferred");
14573        }
14574    }
14575
14576    @Override
14577    public void clearPackagePreferredActivities(String packageName) {
14578        final int uid = Binder.getCallingUid();
14579        // writer
14580        synchronized (mPackages) {
14581            PackageParser.Package pkg = mPackages.get(packageName);
14582            if (pkg == null || pkg.applicationInfo.uid != uid) {
14583                if (mContext.checkCallingOrSelfPermission(
14584                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14585                        != PackageManager.PERMISSION_GRANTED) {
14586                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14587                            < Build.VERSION_CODES.FROYO) {
14588                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14589                                + Binder.getCallingUid());
14590                        return;
14591                    }
14592                    mContext.enforceCallingOrSelfPermission(
14593                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14594                }
14595            }
14596
14597            int user = UserHandle.getCallingUserId();
14598            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14599                scheduleWritePackageRestrictionsLocked(user);
14600            }
14601        }
14602    }
14603
14604    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14605    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14606        ArrayList<PreferredActivity> removed = null;
14607        boolean changed = false;
14608        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14609            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14610            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14611            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14612                continue;
14613            }
14614            Iterator<PreferredActivity> it = pir.filterIterator();
14615            while (it.hasNext()) {
14616                PreferredActivity pa = it.next();
14617                // Mark entry for removal only if it matches the package name
14618                // and the entry is of type "always".
14619                if (packageName == null ||
14620                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14621                                && pa.mPref.mAlways)) {
14622                    if (removed == null) {
14623                        removed = new ArrayList<PreferredActivity>();
14624                    }
14625                    removed.add(pa);
14626                }
14627            }
14628            if (removed != null) {
14629                for (int j=0; j<removed.size(); j++) {
14630                    PreferredActivity pa = removed.get(j);
14631                    pir.removeFilter(pa);
14632                }
14633                changed = true;
14634            }
14635        }
14636        return changed;
14637    }
14638
14639    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14640    private void clearIntentFilterVerificationsLPw(int userId) {
14641        final int packageCount = mPackages.size();
14642        for (int i = 0; i < packageCount; i++) {
14643            PackageParser.Package pkg = mPackages.valueAt(i);
14644            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14645        }
14646    }
14647
14648    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14649    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14650        if (userId == UserHandle.USER_ALL) {
14651            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14652                    sUserManager.getUserIds())) {
14653                for (int oneUserId : sUserManager.getUserIds()) {
14654                    scheduleWritePackageRestrictionsLocked(oneUserId);
14655                }
14656            }
14657        } else {
14658            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14659                scheduleWritePackageRestrictionsLocked(userId);
14660            }
14661        }
14662    }
14663
14664    void clearDefaultBrowserIfNeeded(String packageName) {
14665        for (int oneUserId : sUserManager.getUserIds()) {
14666            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14667            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14668            if (packageName.equals(defaultBrowserPackageName)) {
14669                setDefaultBrowserPackageName(null, oneUserId);
14670            }
14671        }
14672    }
14673
14674    @Override
14675    public void resetApplicationPreferences(int userId) {
14676        mContext.enforceCallingOrSelfPermission(
14677                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14678        // writer
14679        synchronized (mPackages) {
14680            final long identity = Binder.clearCallingIdentity();
14681            try {
14682                clearPackagePreferredActivitiesLPw(null, userId);
14683                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14684                // TODO: We have to reset the default SMS and Phone. This requires
14685                // significant refactoring to keep all default apps in the package
14686                // manager (cleaner but more work) or have the services provide
14687                // callbacks to the package manager to request a default app reset.
14688                applyFactoryDefaultBrowserLPw(userId);
14689                clearIntentFilterVerificationsLPw(userId);
14690                primeDomainVerificationsLPw(userId);
14691                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14692                scheduleWritePackageRestrictionsLocked(userId);
14693            } finally {
14694                Binder.restoreCallingIdentity(identity);
14695            }
14696        }
14697    }
14698
14699    @Override
14700    public int getPreferredActivities(List<IntentFilter> outFilters,
14701            List<ComponentName> outActivities, String packageName) {
14702
14703        int num = 0;
14704        final int userId = UserHandle.getCallingUserId();
14705        // reader
14706        synchronized (mPackages) {
14707            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14708            if (pir != null) {
14709                final Iterator<PreferredActivity> it = pir.filterIterator();
14710                while (it.hasNext()) {
14711                    final PreferredActivity pa = it.next();
14712                    if (packageName == null
14713                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14714                                    && pa.mPref.mAlways)) {
14715                        if (outFilters != null) {
14716                            outFilters.add(new IntentFilter(pa));
14717                        }
14718                        if (outActivities != null) {
14719                            outActivities.add(pa.mPref.mComponent);
14720                        }
14721                    }
14722                }
14723            }
14724        }
14725
14726        return num;
14727    }
14728
14729    @Override
14730    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14731            int userId) {
14732        int callingUid = Binder.getCallingUid();
14733        if (callingUid != Process.SYSTEM_UID) {
14734            throw new SecurityException(
14735                    "addPersistentPreferredActivity can only be run by the system");
14736        }
14737        if (filter.countActions() == 0) {
14738            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14739            return;
14740        }
14741        synchronized (mPackages) {
14742            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14743                    " :");
14744            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14745            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14746                    new PersistentPreferredActivity(filter, activity));
14747            scheduleWritePackageRestrictionsLocked(userId);
14748        }
14749    }
14750
14751    @Override
14752    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14753        int callingUid = Binder.getCallingUid();
14754        if (callingUid != Process.SYSTEM_UID) {
14755            throw new SecurityException(
14756                    "clearPackagePersistentPreferredActivities can only be run by the system");
14757        }
14758        ArrayList<PersistentPreferredActivity> removed = null;
14759        boolean changed = false;
14760        synchronized (mPackages) {
14761            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14762                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14763                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14764                        .valueAt(i);
14765                if (userId != thisUserId) {
14766                    continue;
14767                }
14768                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14769                while (it.hasNext()) {
14770                    PersistentPreferredActivity ppa = it.next();
14771                    // Mark entry for removal only if it matches the package name.
14772                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14773                        if (removed == null) {
14774                            removed = new ArrayList<PersistentPreferredActivity>();
14775                        }
14776                        removed.add(ppa);
14777                    }
14778                }
14779                if (removed != null) {
14780                    for (int j=0; j<removed.size(); j++) {
14781                        PersistentPreferredActivity ppa = removed.get(j);
14782                        ppir.removeFilter(ppa);
14783                    }
14784                    changed = true;
14785                }
14786            }
14787
14788            if (changed) {
14789                scheduleWritePackageRestrictionsLocked(userId);
14790            }
14791        }
14792    }
14793
14794    /**
14795     * Common machinery for picking apart a restored XML blob and passing
14796     * it to a caller-supplied functor to be applied to the running system.
14797     */
14798    private void restoreFromXml(XmlPullParser parser, int userId,
14799            String expectedStartTag, BlobXmlRestorer functor)
14800            throws IOException, XmlPullParserException {
14801        int type;
14802        while ((type = parser.next()) != XmlPullParser.START_TAG
14803                && type != XmlPullParser.END_DOCUMENT) {
14804        }
14805        if (type != XmlPullParser.START_TAG) {
14806            // oops didn't find a start tag?!
14807            if (DEBUG_BACKUP) {
14808                Slog.e(TAG, "Didn't find start tag during restore");
14809            }
14810            return;
14811        }
14812
14813        // this is supposed to be TAG_PREFERRED_BACKUP
14814        if (!expectedStartTag.equals(parser.getName())) {
14815            if (DEBUG_BACKUP) {
14816                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14817            }
14818            return;
14819        }
14820
14821        // skip interfering stuff, then we're aligned with the backing implementation
14822        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14823        functor.apply(parser, userId);
14824    }
14825
14826    private interface BlobXmlRestorer {
14827        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14828    }
14829
14830    /**
14831     * Non-Binder method, support for the backup/restore mechanism: write the
14832     * full set of preferred activities in its canonical XML format.  Returns the
14833     * XML output as a byte array, or null if there is none.
14834     */
14835    @Override
14836    public byte[] getPreferredActivityBackup(int userId) {
14837        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14838            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14839        }
14840
14841        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14842        try {
14843            final XmlSerializer serializer = new FastXmlSerializer();
14844            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14845            serializer.startDocument(null, true);
14846            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14847
14848            synchronized (mPackages) {
14849                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14850            }
14851
14852            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14853            serializer.endDocument();
14854            serializer.flush();
14855        } catch (Exception e) {
14856            if (DEBUG_BACKUP) {
14857                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14858            }
14859            return null;
14860        }
14861
14862        return dataStream.toByteArray();
14863    }
14864
14865    @Override
14866    public void restorePreferredActivities(byte[] backup, int userId) {
14867        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14868            throw new SecurityException("Only the system may call restorePreferredActivities()");
14869        }
14870
14871        try {
14872            final XmlPullParser parser = Xml.newPullParser();
14873            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14874            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14875                    new BlobXmlRestorer() {
14876                        @Override
14877                        public void apply(XmlPullParser parser, int userId)
14878                                throws XmlPullParserException, IOException {
14879                            synchronized (mPackages) {
14880                                mSettings.readPreferredActivitiesLPw(parser, userId);
14881                            }
14882                        }
14883                    } );
14884        } catch (Exception e) {
14885            if (DEBUG_BACKUP) {
14886                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14887            }
14888        }
14889    }
14890
14891    /**
14892     * Non-Binder method, support for the backup/restore mechanism: write the
14893     * default browser (etc) settings in its canonical XML format.  Returns the default
14894     * browser XML representation as a byte array, or null if there is none.
14895     */
14896    @Override
14897    public byte[] getDefaultAppsBackup(int userId) {
14898        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14899            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14900        }
14901
14902        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14903        try {
14904            final XmlSerializer serializer = new FastXmlSerializer();
14905            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14906            serializer.startDocument(null, true);
14907            serializer.startTag(null, TAG_DEFAULT_APPS);
14908
14909            synchronized (mPackages) {
14910                mSettings.writeDefaultAppsLPr(serializer, userId);
14911            }
14912
14913            serializer.endTag(null, TAG_DEFAULT_APPS);
14914            serializer.endDocument();
14915            serializer.flush();
14916        } catch (Exception e) {
14917            if (DEBUG_BACKUP) {
14918                Slog.e(TAG, "Unable to write default apps for backup", e);
14919            }
14920            return null;
14921        }
14922
14923        return dataStream.toByteArray();
14924    }
14925
14926    @Override
14927    public void restoreDefaultApps(byte[] backup, int userId) {
14928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14929            throw new SecurityException("Only the system may call restoreDefaultApps()");
14930        }
14931
14932        try {
14933            final XmlPullParser parser = Xml.newPullParser();
14934            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14935            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14936                    new BlobXmlRestorer() {
14937                        @Override
14938                        public void apply(XmlPullParser parser, int userId)
14939                                throws XmlPullParserException, IOException {
14940                            synchronized (mPackages) {
14941                                mSettings.readDefaultAppsLPw(parser, userId);
14942                            }
14943                        }
14944                    } );
14945        } catch (Exception e) {
14946            if (DEBUG_BACKUP) {
14947                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14948            }
14949        }
14950    }
14951
14952    @Override
14953    public byte[] getIntentFilterVerificationBackup(int userId) {
14954        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14955            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14956        }
14957
14958        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14959        try {
14960            final XmlSerializer serializer = new FastXmlSerializer();
14961            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14962            serializer.startDocument(null, true);
14963            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14964
14965            synchronized (mPackages) {
14966                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14967            }
14968
14969            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14970            serializer.endDocument();
14971            serializer.flush();
14972        } catch (Exception e) {
14973            if (DEBUG_BACKUP) {
14974                Slog.e(TAG, "Unable to write default apps for backup", e);
14975            }
14976            return null;
14977        }
14978
14979        return dataStream.toByteArray();
14980    }
14981
14982    @Override
14983    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14984        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14985            throw new SecurityException("Only the system may call restorePreferredActivities()");
14986        }
14987
14988        try {
14989            final XmlPullParser parser = Xml.newPullParser();
14990            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14991            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14992                    new BlobXmlRestorer() {
14993                        @Override
14994                        public void apply(XmlPullParser parser, int userId)
14995                                throws XmlPullParserException, IOException {
14996                            synchronized (mPackages) {
14997                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14998                                mSettings.writeLPr();
14999                            }
15000                        }
15001                    } );
15002        } catch (Exception e) {
15003            if (DEBUG_BACKUP) {
15004                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15005            }
15006        }
15007    }
15008
15009    @Override
15010    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15011            int sourceUserId, int targetUserId, int flags) {
15012        mContext.enforceCallingOrSelfPermission(
15013                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15014        int callingUid = Binder.getCallingUid();
15015        enforceOwnerRights(ownerPackage, callingUid);
15016        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15017        if (intentFilter.countActions() == 0) {
15018            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15019            return;
15020        }
15021        synchronized (mPackages) {
15022            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15023                    ownerPackage, targetUserId, flags);
15024            CrossProfileIntentResolver resolver =
15025                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15026            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15027            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15028            if (existing != null) {
15029                int size = existing.size();
15030                for (int i = 0; i < size; i++) {
15031                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15032                        return;
15033                    }
15034                }
15035            }
15036            resolver.addFilter(newFilter);
15037            scheduleWritePackageRestrictionsLocked(sourceUserId);
15038        }
15039    }
15040
15041    @Override
15042    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15043        mContext.enforceCallingOrSelfPermission(
15044                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15045        int callingUid = Binder.getCallingUid();
15046        enforceOwnerRights(ownerPackage, callingUid);
15047        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15048        synchronized (mPackages) {
15049            CrossProfileIntentResolver resolver =
15050                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15051            ArraySet<CrossProfileIntentFilter> set =
15052                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15053            for (CrossProfileIntentFilter filter : set) {
15054                if (filter.getOwnerPackage().equals(ownerPackage)) {
15055                    resolver.removeFilter(filter);
15056                }
15057            }
15058            scheduleWritePackageRestrictionsLocked(sourceUserId);
15059        }
15060    }
15061
15062    // Enforcing that callingUid is owning pkg on userId
15063    private void enforceOwnerRights(String pkg, int callingUid) {
15064        // The system owns everything.
15065        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15066            return;
15067        }
15068        int callingUserId = UserHandle.getUserId(callingUid);
15069        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15070        if (pi == null) {
15071            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15072                    + callingUserId);
15073        }
15074        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15075            throw new SecurityException("Calling uid " + callingUid
15076                    + " does not own package " + pkg);
15077        }
15078    }
15079
15080    @Override
15081    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15082        Intent intent = new Intent(Intent.ACTION_MAIN);
15083        intent.addCategory(Intent.CATEGORY_HOME);
15084
15085        final int callingUserId = UserHandle.getCallingUserId();
15086        List<ResolveInfo> list = queryIntentActivities(intent, null,
15087                PackageManager.GET_META_DATA, callingUserId);
15088        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15089                true, false, false, callingUserId);
15090
15091        allHomeCandidates.clear();
15092        if (list != null) {
15093            for (ResolveInfo ri : list) {
15094                allHomeCandidates.add(ri);
15095            }
15096        }
15097        return (preferred == null || preferred.activityInfo == null)
15098                ? null
15099                : new ComponentName(preferred.activityInfo.packageName,
15100                        preferred.activityInfo.name);
15101    }
15102
15103    @Override
15104    public void setApplicationEnabledSetting(String appPackageName,
15105            int newState, int flags, int userId, String callingPackage) {
15106        if (!sUserManager.exists(userId)) return;
15107        if (callingPackage == null) {
15108            callingPackage = Integer.toString(Binder.getCallingUid());
15109        }
15110        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15111    }
15112
15113    @Override
15114    public void setComponentEnabledSetting(ComponentName componentName,
15115            int newState, int flags, int userId) {
15116        if (!sUserManager.exists(userId)) return;
15117        setEnabledSetting(componentName.getPackageName(),
15118                componentName.getClassName(), newState, flags, userId, null);
15119    }
15120
15121    private void setEnabledSetting(final String packageName, String className, int newState,
15122            final int flags, int userId, String callingPackage) {
15123        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15124              || newState == COMPONENT_ENABLED_STATE_ENABLED
15125              || newState == COMPONENT_ENABLED_STATE_DISABLED
15126              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15127              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15128            throw new IllegalArgumentException("Invalid new component state: "
15129                    + newState);
15130        }
15131        PackageSetting pkgSetting;
15132        final int uid = Binder.getCallingUid();
15133        final int permission = mContext.checkCallingOrSelfPermission(
15134                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15135        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15136        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15137        boolean sendNow = false;
15138        boolean isApp = (className == null);
15139        String componentName = isApp ? packageName : className;
15140        int packageUid = -1;
15141        ArrayList<String> components;
15142
15143        // writer
15144        synchronized (mPackages) {
15145            pkgSetting = mSettings.mPackages.get(packageName);
15146            if (pkgSetting == null) {
15147                if (className == null) {
15148                    throw new IllegalArgumentException(
15149                            "Unknown package: " + packageName);
15150                }
15151                throw new IllegalArgumentException(
15152                        "Unknown component: " + packageName
15153                        + "/" + className);
15154            }
15155            // Allow root and verify that userId is not being specified by a different user
15156            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15157                throw new SecurityException(
15158                        "Permission Denial: attempt to change component state from pid="
15159                        + Binder.getCallingPid()
15160                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15161            }
15162            if (className == null) {
15163                // We're dealing with an application/package level state change
15164                if (pkgSetting.getEnabled(userId) == newState) {
15165                    // Nothing to do
15166                    return;
15167                }
15168                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15169                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15170                    // Don't care about who enables an app.
15171                    callingPackage = null;
15172                }
15173                pkgSetting.setEnabled(newState, userId, callingPackage);
15174                // pkgSetting.pkg.mSetEnabled = newState;
15175            } else {
15176                // We're dealing with a component level state change
15177                // First, verify that this is a valid class name.
15178                PackageParser.Package pkg = pkgSetting.pkg;
15179                if (pkg == null || !pkg.hasComponentClassName(className)) {
15180                    if (pkg != null &&
15181                            pkg.applicationInfo.targetSdkVersion >=
15182                                    Build.VERSION_CODES.JELLY_BEAN) {
15183                        throw new IllegalArgumentException("Component class " + className
15184                                + " does not exist in " + packageName);
15185                    } else {
15186                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15187                                + className + " does not exist in " + packageName);
15188                    }
15189                }
15190                switch (newState) {
15191                case COMPONENT_ENABLED_STATE_ENABLED:
15192                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15193                        return;
15194                    }
15195                    break;
15196                case COMPONENT_ENABLED_STATE_DISABLED:
15197                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15198                        return;
15199                    }
15200                    break;
15201                case COMPONENT_ENABLED_STATE_DEFAULT:
15202                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15203                        return;
15204                    }
15205                    break;
15206                default:
15207                    Slog.e(TAG, "Invalid new component state: " + newState);
15208                    return;
15209                }
15210            }
15211            scheduleWritePackageRestrictionsLocked(userId);
15212            components = mPendingBroadcasts.get(userId, packageName);
15213            final boolean newPackage = components == null;
15214            if (newPackage) {
15215                components = new ArrayList<String>();
15216            }
15217            if (!components.contains(componentName)) {
15218                components.add(componentName);
15219            }
15220            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15221                sendNow = true;
15222                // Purge entry from pending broadcast list if another one exists already
15223                // since we are sending one right away.
15224                mPendingBroadcasts.remove(userId, packageName);
15225            } else {
15226                if (newPackage) {
15227                    mPendingBroadcasts.put(userId, packageName, components);
15228                }
15229                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15230                    // Schedule a message
15231                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15232                }
15233            }
15234        }
15235
15236        long callingId = Binder.clearCallingIdentity();
15237        try {
15238            if (sendNow) {
15239                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15240                sendPackageChangedBroadcast(packageName,
15241                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15242            }
15243        } finally {
15244            Binder.restoreCallingIdentity(callingId);
15245        }
15246    }
15247
15248    private void sendPackageChangedBroadcast(String packageName,
15249            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15250        if (DEBUG_INSTALL)
15251            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15252                    + componentNames);
15253        Bundle extras = new Bundle(4);
15254        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15255        String nameList[] = new String[componentNames.size()];
15256        componentNames.toArray(nameList);
15257        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15258        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15259        extras.putInt(Intent.EXTRA_UID, packageUid);
15260        // If this is not reporting a change of the overall package, then only send it
15261        // to registered receivers.  We don't want to launch a swath of apps for every
15262        // little component state change.
15263        final int flags = !componentNames.contains(packageName)
15264                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15265        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15266                new int[] {UserHandle.getUserId(packageUid)});
15267    }
15268
15269    @Override
15270    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15271        if (!sUserManager.exists(userId)) return;
15272        final int uid = Binder.getCallingUid();
15273        final int permission = mContext.checkCallingOrSelfPermission(
15274                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15275        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15276        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15277        // writer
15278        synchronized (mPackages) {
15279            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15280                    allowedByPermission, uid, userId)) {
15281                scheduleWritePackageRestrictionsLocked(userId);
15282            }
15283        }
15284    }
15285
15286    @Override
15287    public String getInstallerPackageName(String packageName) {
15288        // reader
15289        synchronized (mPackages) {
15290            return mSettings.getInstallerPackageNameLPr(packageName);
15291        }
15292    }
15293
15294    @Override
15295    public int getApplicationEnabledSetting(String packageName, int userId) {
15296        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15297        int uid = Binder.getCallingUid();
15298        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15299        // reader
15300        synchronized (mPackages) {
15301            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15302        }
15303    }
15304
15305    @Override
15306    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15307        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15308        int uid = Binder.getCallingUid();
15309        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15310        // reader
15311        synchronized (mPackages) {
15312            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15313        }
15314    }
15315
15316    @Override
15317    public void enterSafeMode() {
15318        enforceSystemOrRoot("Only the system can request entering safe mode");
15319
15320        if (!mSystemReady) {
15321            mSafeMode = true;
15322        }
15323    }
15324
15325    @Override
15326    public void systemReady() {
15327        mSystemReady = true;
15328
15329        // Read the compatibilty setting when the system is ready.
15330        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15331                mContext.getContentResolver(),
15332                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15333        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15334        if (DEBUG_SETTINGS) {
15335            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15336        }
15337
15338        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15339
15340        synchronized (mPackages) {
15341            // Verify that all of the preferred activity components actually
15342            // exist.  It is possible for applications to be updated and at
15343            // that point remove a previously declared activity component that
15344            // had been set as a preferred activity.  We try to clean this up
15345            // the next time we encounter that preferred activity, but it is
15346            // possible for the user flow to never be able to return to that
15347            // situation so here we do a sanity check to make sure we haven't
15348            // left any junk around.
15349            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15350            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15351                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15352                removed.clear();
15353                for (PreferredActivity pa : pir.filterSet()) {
15354                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15355                        removed.add(pa);
15356                    }
15357                }
15358                if (removed.size() > 0) {
15359                    for (int r=0; r<removed.size(); r++) {
15360                        PreferredActivity pa = removed.get(r);
15361                        Slog.w(TAG, "Removing dangling preferred activity: "
15362                                + pa.mPref.mComponent);
15363                        pir.removeFilter(pa);
15364                    }
15365                    mSettings.writePackageRestrictionsLPr(
15366                            mSettings.mPreferredActivities.keyAt(i));
15367                }
15368            }
15369
15370            for (int userId : UserManagerService.getInstance().getUserIds()) {
15371                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15372                    grantPermissionsUserIds = ArrayUtils.appendInt(
15373                            grantPermissionsUserIds, userId);
15374                }
15375            }
15376        }
15377        sUserManager.systemReady();
15378
15379        // If we upgraded grant all default permissions before kicking off.
15380        for (int userId : grantPermissionsUserIds) {
15381            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15382        }
15383
15384        // Kick off any messages waiting for system ready
15385        if (mPostSystemReadyMessages != null) {
15386            for (Message msg : mPostSystemReadyMessages) {
15387                msg.sendToTarget();
15388            }
15389            mPostSystemReadyMessages = null;
15390        }
15391
15392        // Watch for external volumes that come and go over time
15393        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15394        storage.registerListener(mStorageListener);
15395
15396        mInstallerService.systemReady();
15397        mPackageDexOptimizer.systemReady();
15398
15399        MountServiceInternal mountServiceInternal = LocalServices.getService(
15400                MountServiceInternal.class);
15401        mountServiceInternal.addExternalStoragePolicy(
15402                new MountServiceInternal.ExternalStorageMountPolicy() {
15403            @Override
15404            public int getMountMode(int uid, String packageName) {
15405                if (Process.isIsolated(uid)) {
15406                    return Zygote.MOUNT_EXTERNAL_NONE;
15407                }
15408                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15409                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15410                }
15411                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15412                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15413                }
15414                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15415                    return Zygote.MOUNT_EXTERNAL_READ;
15416                }
15417                return Zygote.MOUNT_EXTERNAL_WRITE;
15418            }
15419
15420            @Override
15421            public boolean hasExternalStorage(int uid, String packageName) {
15422                return true;
15423            }
15424        });
15425    }
15426
15427    @Override
15428    public boolean isSafeMode() {
15429        return mSafeMode;
15430    }
15431
15432    @Override
15433    public boolean hasSystemUidErrors() {
15434        return mHasSystemUidErrors;
15435    }
15436
15437    static String arrayToString(int[] array) {
15438        StringBuffer buf = new StringBuffer(128);
15439        buf.append('[');
15440        if (array != null) {
15441            for (int i=0; i<array.length; i++) {
15442                if (i > 0) buf.append(", ");
15443                buf.append(array[i]);
15444            }
15445        }
15446        buf.append(']');
15447        return buf.toString();
15448    }
15449
15450    static class DumpState {
15451        public static final int DUMP_LIBS = 1 << 0;
15452        public static final int DUMP_FEATURES = 1 << 1;
15453        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15454        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15455        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15456        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15457        public static final int DUMP_PERMISSIONS = 1 << 6;
15458        public static final int DUMP_PACKAGES = 1 << 7;
15459        public static final int DUMP_SHARED_USERS = 1 << 8;
15460        public static final int DUMP_MESSAGES = 1 << 9;
15461        public static final int DUMP_PROVIDERS = 1 << 10;
15462        public static final int DUMP_VERIFIERS = 1 << 11;
15463        public static final int DUMP_PREFERRED = 1 << 12;
15464        public static final int DUMP_PREFERRED_XML = 1 << 13;
15465        public static final int DUMP_KEYSETS = 1 << 14;
15466        public static final int DUMP_VERSION = 1 << 15;
15467        public static final int DUMP_INSTALLS = 1 << 16;
15468        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15469        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15470
15471        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15472
15473        private int mTypes;
15474
15475        private int mOptions;
15476
15477        private boolean mTitlePrinted;
15478
15479        private SharedUserSetting mSharedUser;
15480
15481        public boolean isDumping(int type) {
15482            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15483                return true;
15484            }
15485
15486            return (mTypes & type) != 0;
15487        }
15488
15489        public void setDump(int type) {
15490            mTypes |= type;
15491        }
15492
15493        public boolean isOptionEnabled(int option) {
15494            return (mOptions & option) != 0;
15495        }
15496
15497        public void setOptionEnabled(int option) {
15498            mOptions |= option;
15499        }
15500
15501        public boolean onTitlePrinted() {
15502            final boolean printed = mTitlePrinted;
15503            mTitlePrinted = true;
15504            return printed;
15505        }
15506
15507        public boolean getTitlePrinted() {
15508            return mTitlePrinted;
15509        }
15510
15511        public void setTitlePrinted(boolean enabled) {
15512            mTitlePrinted = enabled;
15513        }
15514
15515        public SharedUserSetting getSharedUser() {
15516            return mSharedUser;
15517        }
15518
15519        public void setSharedUser(SharedUserSetting user) {
15520            mSharedUser = user;
15521        }
15522    }
15523
15524    @Override
15525    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15526            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15527        (new PackageManagerShellCommand(this)).exec(
15528                this, in, out, err, args, resultReceiver);
15529    }
15530
15531    @Override
15532    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15533        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15534                != PackageManager.PERMISSION_GRANTED) {
15535            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15536                    + Binder.getCallingPid()
15537                    + ", uid=" + Binder.getCallingUid()
15538                    + " without permission "
15539                    + android.Manifest.permission.DUMP);
15540            return;
15541        }
15542
15543        DumpState dumpState = new DumpState();
15544        boolean fullPreferred = false;
15545        boolean checkin = false;
15546
15547        String packageName = null;
15548        ArraySet<String> permissionNames = null;
15549
15550        int opti = 0;
15551        while (opti < args.length) {
15552            String opt = args[opti];
15553            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15554                break;
15555            }
15556            opti++;
15557
15558            if ("-a".equals(opt)) {
15559                // Right now we only know how to print all.
15560            } else if ("-h".equals(opt)) {
15561                pw.println("Package manager dump options:");
15562                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15563                pw.println("    --checkin: dump for a checkin");
15564                pw.println("    -f: print details of intent filters");
15565                pw.println("    -h: print this help");
15566                pw.println("  cmd may be one of:");
15567                pw.println("    l[ibraries]: list known shared libraries");
15568                pw.println("    f[eatures]: list device features");
15569                pw.println("    k[eysets]: print known keysets");
15570                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15571                pw.println("    perm[issions]: dump permissions");
15572                pw.println("    permission [name ...]: dump declaration and use of given permission");
15573                pw.println("    pref[erred]: print preferred package settings");
15574                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15575                pw.println("    prov[iders]: dump content providers");
15576                pw.println("    p[ackages]: dump installed packages");
15577                pw.println("    s[hared-users]: dump shared user IDs");
15578                pw.println("    m[essages]: print collected runtime messages");
15579                pw.println("    v[erifiers]: print package verifier info");
15580                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15581                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15582                pw.println("    version: print database version info");
15583                pw.println("    write: write current settings now");
15584                pw.println("    installs: details about install sessions");
15585                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15586                pw.println("    <package.name>: info about given package");
15587                return;
15588            } else if ("--checkin".equals(opt)) {
15589                checkin = true;
15590            } else if ("-f".equals(opt)) {
15591                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15592            } else {
15593                pw.println("Unknown argument: " + opt + "; use -h for help");
15594            }
15595        }
15596
15597        // Is the caller requesting to dump a particular piece of data?
15598        if (opti < args.length) {
15599            String cmd = args[opti];
15600            opti++;
15601            // Is this a package name?
15602            if ("android".equals(cmd) || cmd.contains(".")) {
15603                packageName = cmd;
15604                // When dumping a single package, we always dump all of its
15605                // filter information since the amount of data will be reasonable.
15606                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15607            } else if ("check-permission".equals(cmd)) {
15608                if (opti >= args.length) {
15609                    pw.println("Error: check-permission missing permission argument");
15610                    return;
15611                }
15612                String perm = args[opti];
15613                opti++;
15614                if (opti >= args.length) {
15615                    pw.println("Error: check-permission missing package argument");
15616                    return;
15617                }
15618                String pkg = args[opti];
15619                opti++;
15620                int user = UserHandle.getUserId(Binder.getCallingUid());
15621                if (opti < args.length) {
15622                    try {
15623                        user = Integer.parseInt(args[opti]);
15624                    } catch (NumberFormatException e) {
15625                        pw.println("Error: check-permission user argument is not a number: "
15626                                + args[opti]);
15627                        return;
15628                    }
15629                }
15630                pw.println(checkPermission(perm, pkg, user));
15631                return;
15632            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15633                dumpState.setDump(DumpState.DUMP_LIBS);
15634            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_FEATURES);
15636            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15637                if (opti >= args.length) {
15638                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15639                            | DumpState.DUMP_SERVICE_RESOLVERS
15640                            | DumpState.DUMP_RECEIVER_RESOLVERS
15641                            | DumpState.DUMP_CONTENT_RESOLVERS);
15642                } else {
15643                    while (opti < args.length) {
15644                        String name = args[opti];
15645                        if ("a".equals(name) || "activity".equals(name)) {
15646                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15647                        } else if ("s".equals(name) || "service".equals(name)) {
15648                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15649                        } else if ("r".equals(name) || "receiver".equals(name)) {
15650                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15651                        } else if ("c".equals(name) || "content".equals(name)) {
15652                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15653                        } else {
15654                            pw.println("Error: unknown resolver table type: " + name);
15655                            return;
15656                        }
15657                        opti++;
15658                    }
15659                }
15660            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15661                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15662            } else if ("permission".equals(cmd)) {
15663                if (opti >= args.length) {
15664                    pw.println("Error: permission requires permission name");
15665                    return;
15666                }
15667                permissionNames = new ArraySet<>();
15668                while (opti < args.length) {
15669                    permissionNames.add(args[opti]);
15670                    opti++;
15671                }
15672                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15673                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15674            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15675                dumpState.setDump(DumpState.DUMP_PREFERRED);
15676            } else if ("preferred-xml".equals(cmd)) {
15677                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15678                if (opti < args.length && "--full".equals(args[opti])) {
15679                    fullPreferred = true;
15680                    opti++;
15681                }
15682            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15683                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15684            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15685                dumpState.setDump(DumpState.DUMP_PACKAGES);
15686            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15687                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15688            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15689                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15690            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15691                dumpState.setDump(DumpState.DUMP_MESSAGES);
15692            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15693                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15694            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15695                    || "intent-filter-verifiers".equals(cmd)) {
15696                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15697            } else if ("version".equals(cmd)) {
15698                dumpState.setDump(DumpState.DUMP_VERSION);
15699            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15700                dumpState.setDump(DumpState.DUMP_KEYSETS);
15701            } else if ("installs".equals(cmd)) {
15702                dumpState.setDump(DumpState.DUMP_INSTALLS);
15703            } else if ("write".equals(cmd)) {
15704                synchronized (mPackages) {
15705                    mSettings.writeLPr();
15706                    pw.println("Settings written.");
15707                    return;
15708                }
15709            }
15710        }
15711
15712        if (checkin) {
15713            pw.println("vers,1");
15714        }
15715
15716        // reader
15717        synchronized (mPackages) {
15718            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15719                if (!checkin) {
15720                    if (dumpState.onTitlePrinted())
15721                        pw.println();
15722                    pw.println("Database versions:");
15723                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15724                }
15725            }
15726
15727            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15728                if (!checkin) {
15729                    if (dumpState.onTitlePrinted())
15730                        pw.println();
15731                    pw.println("Verifiers:");
15732                    pw.print("  Required: ");
15733                    pw.print(mRequiredVerifierPackage);
15734                    pw.print(" (uid=");
15735                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15736                    pw.println(")");
15737                } else if (mRequiredVerifierPackage != null) {
15738                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15739                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15740                }
15741            }
15742
15743            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15744                    packageName == null) {
15745                if (mIntentFilterVerifierComponent != null) {
15746                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15747                    if (!checkin) {
15748                        if (dumpState.onTitlePrinted())
15749                            pw.println();
15750                        pw.println("Intent Filter Verifier:");
15751                        pw.print("  Using: ");
15752                        pw.print(verifierPackageName);
15753                        pw.print(" (uid=");
15754                        pw.print(getPackageUid(verifierPackageName, 0));
15755                        pw.println(")");
15756                    } else if (verifierPackageName != null) {
15757                        pw.print("ifv,"); pw.print(verifierPackageName);
15758                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15759                    }
15760                } else {
15761                    pw.println();
15762                    pw.println("No Intent Filter Verifier available!");
15763                }
15764            }
15765
15766            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15767                boolean printedHeader = false;
15768                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15769                while (it.hasNext()) {
15770                    String name = it.next();
15771                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15772                    if (!checkin) {
15773                        if (!printedHeader) {
15774                            if (dumpState.onTitlePrinted())
15775                                pw.println();
15776                            pw.println("Libraries:");
15777                            printedHeader = true;
15778                        }
15779                        pw.print("  ");
15780                    } else {
15781                        pw.print("lib,");
15782                    }
15783                    pw.print(name);
15784                    if (!checkin) {
15785                        pw.print(" -> ");
15786                    }
15787                    if (ent.path != null) {
15788                        if (!checkin) {
15789                            pw.print("(jar) ");
15790                            pw.print(ent.path);
15791                        } else {
15792                            pw.print(",jar,");
15793                            pw.print(ent.path);
15794                        }
15795                    } else {
15796                        if (!checkin) {
15797                            pw.print("(apk) ");
15798                            pw.print(ent.apk);
15799                        } else {
15800                            pw.print(",apk,");
15801                            pw.print(ent.apk);
15802                        }
15803                    }
15804                    pw.println();
15805                }
15806            }
15807
15808            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15809                if (dumpState.onTitlePrinted())
15810                    pw.println();
15811                if (!checkin) {
15812                    pw.println("Features:");
15813                }
15814                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15815                while (it.hasNext()) {
15816                    String name = it.next();
15817                    if (!checkin) {
15818                        pw.print("  ");
15819                    } else {
15820                        pw.print("feat,");
15821                    }
15822                    pw.println(name);
15823                }
15824            }
15825
15826            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15827                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15828                        : "Activity Resolver Table:", "  ", packageName,
15829                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15830                    dumpState.setTitlePrinted(true);
15831                }
15832            }
15833            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15834                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15835                        : "Receiver Resolver Table:", "  ", packageName,
15836                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15837                    dumpState.setTitlePrinted(true);
15838                }
15839            }
15840            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15841                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15842                        : "Service Resolver Table:", "  ", packageName,
15843                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15844                    dumpState.setTitlePrinted(true);
15845                }
15846            }
15847            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15848                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15849                        : "Provider Resolver Table:", "  ", packageName,
15850                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15851                    dumpState.setTitlePrinted(true);
15852                }
15853            }
15854
15855            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15856                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15857                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15858                    int user = mSettings.mPreferredActivities.keyAt(i);
15859                    if (pir.dump(pw,
15860                            dumpState.getTitlePrinted()
15861                                ? "\nPreferred Activities User " + user + ":"
15862                                : "Preferred Activities User " + user + ":", "  ",
15863                            packageName, true, false)) {
15864                        dumpState.setTitlePrinted(true);
15865                    }
15866                }
15867            }
15868
15869            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15870                pw.flush();
15871                FileOutputStream fout = new FileOutputStream(fd);
15872                BufferedOutputStream str = new BufferedOutputStream(fout);
15873                XmlSerializer serializer = new FastXmlSerializer();
15874                try {
15875                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15876                    serializer.startDocument(null, true);
15877                    serializer.setFeature(
15878                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15879                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15880                    serializer.endDocument();
15881                    serializer.flush();
15882                } catch (IllegalArgumentException e) {
15883                    pw.println("Failed writing: " + e);
15884                } catch (IllegalStateException e) {
15885                    pw.println("Failed writing: " + e);
15886                } catch (IOException e) {
15887                    pw.println("Failed writing: " + e);
15888                }
15889            }
15890
15891            if (!checkin
15892                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15893                    && packageName == null) {
15894                pw.println();
15895                int count = mSettings.mPackages.size();
15896                if (count == 0) {
15897                    pw.println("No applications!");
15898                    pw.println();
15899                } else {
15900                    final String prefix = "  ";
15901                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15902                    if (allPackageSettings.size() == 0) {
15903                        pw.println("No domain preferred apps!");
15904                        pw.println();
15905                    } else {
15906                        pw.println("App verification status:");
15907                        pw.println();
15908                        count = 0;
15909                        for (PackageSetting ps : allPackageSettings) {
15910                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15911                            if (ivi == null || ivi.getPackageName() == null) continue;
15912                            pw.println(prefix + "Package: " + ivi.getPackageName());
15913                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15914                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15915                            pw.println();
15916                            count++;
15917                        }
15918                        if (count == 0) {
15919                            pw.println(prefix + "No app verification established.");
15920                            pw.println();
15921                        }
15922                        for (int userId : sUserManager.getUserIds()) {
15923                            pw.println("App linkages for user " + userId + ":");
15924                            pw.println();
15925                            count = 0;
15926                            for (PackageSetting ps : allPackageSettings) {
15927                                final long status = ps.getDomainVerificationStatusForUser(userId);
15928                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15929                                    continue;
15930                                }
15931                                pw.println(prefix + "Package: " + ps.name);
15932                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15933                                String statusStr = IntentFilterVerificationInfo.
15934                                        getStatusStringFromValue(status);
15935                                pw.println(prefix + "Status:  " + statusStr);
15936                                pw.println();
15937                                count++;
15938                            }
15939                            if (count == 0) {
15940                                pw.println(prefix + "No configured app linkages.");
15941                                pw.println();
15942                            }
15943                        }
15944                    }
15945                }
15946            }
15947
15948            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15949                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15950                if (packageName == null && permissionNames == null) {
15951                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15952                        if (iperm == 0) {
15953                            if (dumpState.onTitlePrinted())
15954                                pw.println();
15955                            pw.println("AppOp Permissions:");
15956                        }
15957                        pw.print("  AppOp Permission ");
15958                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15959                        pw.println(":");
15960                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15961                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15962                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15963                        }
15964                    }
15965                }
15966            }
15967
15968            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15969                boolean printedSomething = false;
15970                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15971                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15972                        continue;
15973                    }
15974                    if (!printedSomething) {
15975                        if (dumpState.onTitlePrinted())
15976                            pw.println();
15977                        pw.println("Registered ContentProviders:");
15978                        printedSomething = true;
15979                    }
15980                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15981                    pw.print("    "); pw.println(p.toString());
15982                }
15983                printedSomething = false;
15984                for (Map.Entry<String, PackageParser.Provider> entry :
15985                        mProvidersByAuthority.entrySet()) {
15986                    PackageParser.Provider p = entry.getValue();
15987                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15988                        continue;
15989                    }
15990                    if (!printedSomething) {
15991                        if (dumpState.onTitlePrinted())
15992                            pw.println();
15993                        pw.println("ContentProvider Authorities:");
15994                        printedSomething = true;
15995                    }
15996                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15997                    pw.print("    "); pw.println(p.toString());
15998                    if (p.info != null && p.info.applicationInfo != null) {
15999                        final String appInfo = p.info.applicationInfo.toString();
16000                        pw.print("      applicationInfo="); pw.println(appInfo);
16001                    }
16002                }
16003            }
16004
16005            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16006                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16007            }
16008
16009            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16010                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16011            }
16012
16013            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16014                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16015            }
16016
16017            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16018                // XXX should handle packageName != null by dumping only install data that
16019                // the given package is involved with.
16020                if (dumpState.onTitlePrinted()) pw.println();
16021                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16022            }
16023
16024            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16025                if (dumpState.onTitlePrinted()) pw.println();
16026                mSettings.dumpReadMessagesLPr(pw, dumpState);
16027
16028                pw.println();
16029                pw.println("Package warning messages:");
16030                BufferedReader in = null;
16031                String line = null;
16032                try {
16033                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16034                    while ((line = in.readLine()) != null) {
16035                        if (line.contains("ignored: updated version")) continue;
16036                        pw.println(line);
16037                    }
16038                } catch (IOException ignored) {
16039                } finally {
16040                    IoUtils.closeQuietly(in);
16041                }
16042            }
16043
16044            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16045                BufferedReader in = null;
16046                String line = null;
16047                try {
16048                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16049                    while ((line = in.readLine()) != null) {
16050                        if (line.contains("ignored: updated version")) continue;
16051                        pw.print("msg,");
16052                        pw.println(line);
16053                    }
16054                } catch (IOException ignored) {
16055                } finally {
16056                    IoUtils.closeQuietly(in);
16057                }
16058            }
16059        }
16060    }
16061
16062    private String dumpDomainString(String packageName) {
16063        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16064        List<IntentFilter> filters = getAllIntentFilters(packageName);
16065
16066        ArraySet<String> result = new ArraySet<>();
16067        if (iviList.size() > 0) {
16068            for (IntentFilterVerificationInfo ivi : iviList) {
16069                for (String host : ivi.getDomains()) {
16070                    result.add(host);
16071                }
16072            }
16073        }
16074        if (filters != null && filters.size() > 0) {
16075            for (IntentFilter filter : filters) {
16076                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16077                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16078                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16079                    result.addAll(filter.getHostsList());
16080                }
16081            }
16082        }
16083
16084        StringBuilder sb = new StringBuilder(result.size() * 16);
16085        for (String domain : result) {
16086            if (sb.length() > 0) sb.append(" ");
16087            sb.append(domain);
16088        }
16089        return sb.toString();
16090    }
16091
16092    // ------- apps on sdcard specific code -------
16093    static final boolean DEBUG_SD_INSTALL = false;
16094
16095    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16096
16097    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16098
16099    private boolean mMediaMounted = false;
16100
16101    static String getEncryptKey() {
16102        try {
16103            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16104                    SD_ENCRYPTION_KEYSTORE_NAME);
16105            if (sdEncKey == null) {
16106                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16107                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16108                if (sdEncKey == null) {
16109                    Slog.e(TAG, "Failed to create encryption keys");
16110                    return null;
16111                }
16112            }
16113            return sdEncKey;
16114        } catch (NoSuchAlgorithmException nsae) {
16115            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16116            return null;
16117        } catch (IOException ioe) {
16118            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16119            return null;
16120        }
16121    }
16122
16123    /*
16124     * Update media status on PackageManager.
16125     */
16126    @Override
16127    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16128        int callingUid = Binder.getCallingUid();
16129        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16130            throw new SecurityException("Media status can only be updated by the system");
16131        }
16132        // reader; this apparently protects mMediaMounted, but should probably
16133        // be a different lock in that case.
16134        synchronized (mPackages) {
16135            Log.i(TAG, "Updating external media status from "
16136                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16137                    + (mediaStatus ? "mounted" : "unmounted"));
16138            if (DEBUG_SD_INSTALL)
16139                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16140                        + ", mMediaMounted=" + mMediaMounted);
16141            if (mediaStatus == mMediaMounted) {
16142                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16143                        : 0, -1);
16144                mHandler.sendMessage(msg);
16145                return;
16146            }
16147            mMediaMounted = mediaStatus;
16148        }
16149        // Queue up an async operation since the package installation may take a
16150        // little while.
16151        mHandler.post(new Runnable() {
16152            public void run() {
16153                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16154            }
16155        });
16156    }
16157
16158    /**
16159     * Called by MountService when the initial ASECs to scan are available.
16160     * Should block until all the ASEC containers are finished being scanned.
16161     */
16162    public void scanAvailableAsecs() {
16163        updateExternalMediaStatusInner(true, false, false);
16164        if (mShouldRestoreconData) {
16165            SELinuxMMAC.setRestoreconDone();
16166            mShouldRestoreconData = false;
16167        }
16168    }
16169
16170    /*
16171     * Collect information of applications on external media, map them against
16172     * existing containers and update information based on current mount status.
16173     * Please note that we always have to report status if reportStatus has been
16174     * set to true especially when unloading packages.
16175     */
16176    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16177            boolean externalStorage) {
16178        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16179        int[] uidArr = EmptyArray.INT;
16180
16181        final String[] list = PackageHelper.getSecureContainerList();
16182        if (ArrayUtils.isEmpty(list)) {
16183            Log.i(TAG, "No secure containers found");
16184        } else {
16185            // Process list of secure containers and categorize them
16186            // as active or stale based on their package internal state.
16187
16188            // reader
16189            synchronized (mPackages) {
16190                for (String cid : list) {
16191                    // Leave stages untouched for now; installer service owns them
16192                    if (PackageInstallerService.isStageName(cid)) continue;
16193
16194                    if (DEBUG_SD_INSTALL)
16195                        Log.i(TAG, "Processing container " + cid);
16196                    String pkgName = getAsecPackageName(cid);
16197                    if (pkgName == null) {
16198                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16199                        continue;
16200                    }
16201                    if (DEBUG_SD_INSTALL)
16202                        Log.i(TAG, "Looking for pkg : " + pkgName);
16203
16204                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16205                    if (ps == null) {
16206                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16207                        continue;
16208                    }
16209
16210                    /*
16211                     * Skip packages that are not external if we're unmounting
16212                     * external storage.
16213                     */
16214                    if (externalStorage && !isMounted && !isExternal(ps)) {
16215                        continue;
16216                    }
16217
16218                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16219                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16220                    // The package status is changed only if the code path
16221                    // matches between settings and the container id.
16222                    if (ps.codePathString != null
16223                            && ps.codePathString.startsWith(args.getCodePath())) {
16224                        if (DEBUG_SD_INSTALL) {
16225                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16226                                    + " at code path: " + ps.codePathString);
16227                        }
16228
16229                        // We do have a valid package installed on sdcard
16230                        processCids.put(args, ps.codePathString);
16231                        final int uid = ps.appId;
16232                        if (uid != -1) {
16233                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16234                        }
16235                    } else {
16236                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16237                                + ps.codePathString);
16238                    }
16239                }
16240            }
16241
16242            Arrays.sort(uidArr);
16243        }
16244
16245        // Process packages with valid entries.
16246        if (isMounted) {
16247            if (DEBUG_SD_INSTALL)
16248                Log.i(TAG, "Loading packages");
16249            loadMediaPackages(processCids, uidArr, externalStorage);
16250            startCleaningPackages();
16251            mInstallerService.onSecureContainersAvailable();
16252        } else {
16253            if (DEBUG_SD_INSTALL)
16254                Log.i(TAG, "Unloading packages");
16255            unloadMediaPackages(processCids, uidArr, reportStatus);
16256        }
16257    }
16258
16259    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16260            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16261        final int size = infos.size();
16262        final String[] packageNames = new String[size];
16263        final int[] packageUids = new int[size];
16264        for (int i = 0; i < size; i++) {
16265            final ApplicationInfo info = infos.get(i);
16266            packageNames[i] = info.packageName;
16267            packageUids[i] = info.uid;
16268        }
16269        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16270                finishedReceiver);
16271    }
16272
16273    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16274            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16275        sendResourcesChangedBroadcast(mediaStatus, replacing,
16276                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16277    }
16278
16279    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16280            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16281        int size = pkgList.length;
16282        if (size > 0) {
16283            // Send broadcasts here
16284            Bundle extras = new Bundle();
16285            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16286            if (uidArr != null) {
16287                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16288            }
16289            if (replacing) {
16290                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16291            }
16292            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16293                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16294            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16295        }
16296    }
16297
16298   /*
16299     * Look at potentially valid container ids from processCids If package
16300     * information doesn't match the one on record or package scanning fails,
16301     * the cid is added to list of removeCids. We currently don't delete stale
16302     * containers.
16303     */
16304    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16305            boolean externalStorage) {
16306        ArrayList<String> pkgList = new ArrayList<String>();
16307        Set<AsecInstallArgs> keys = processCids.keySet();
16308
16309        for (AsecInstallArgs args : keys) {
16310            String codePath = processCids.get(args);
16311            if (DEBUG_SD_INSTALL)
16312                Log.i(TAG, "Loading container : " + args.cid);
16313            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16314            try {
16315                // Make sure there are no container errors first.
16316                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16317                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16318                            + " when installing from sdcard");
16319                    continue;
16320                }
16321                // Check code path here.
16322                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16323                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16324                            + " does not match one in settings " + codePath);
16325                    continue;
16326                }
16327                // Parse package
16328                int parseFlags = mDefParseFlags;
16329                if (args.isExternalAsec()) {
16330                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16331                }
16332                if (args.isFwdLocked()) {
16333                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16334                }
16335
16336                synchronized (mInstallLock) {
16337                    PackageParser.Package pkg = null;
16338                    try {
16339                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16340                    } catch (PackageManagerException e) {
16341                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16342                    }
16343                    // Scan the package
16344                    if (pkg != null) {
16345                        /*
16346                         * TODO why is the lock being held? doPostInstall is
16347                         * called in other places without the lock. This needs
16348                         * to be straightened out.
16349                         */
16350                        // writer
16351                        synchronized (mPackages) {
16352                            retCode = PackageManager.INSTALL_SUCCEEDED;
16353                            pkgList.add(pkg.packageName);
16354                            // Post process args
16355                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16356                                    pkg.applicationInfo.uid);
16357                        }
16358                    } else {
16359                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16360                    }
16361                }
16362
16363            } finally {
16364                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16365                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16366                }
16367            }
16368        }
16369        // writer
16370        synchronized (mPackages) {
16371            // If the platform SDK has changed since the last time we booted,
16372            // we need to re-grant app permission to catch any new ones that
16373            // appear. This is really a hack, and means that apps can in some
16374            // cases get permissions that the user didn't initially explicitly
16375            // allow... it would be nice to have some better way to handle
16376            // this situation.
16377            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16378                    : mSettings.getInternalVersion();
16379            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16380                    : StorageManager.UUID_PRIVATE_INTERNAL;
16381
16382            int updateFlags = UPDATE_PERMISSIONS_ALL;
16383            if (ver.sdkVersion != mSdkVersion) {
16384                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16385                        + mSdkVersion + "; regranting permissions for external");
16386                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16387            }
16388            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16389
16390            // Yay, everything is now upgraded
16391            ver.forceCurrent();
16392
16393            // can downgrade to reader
16394            // Persist settings
16395            mSettings.writeLPr();
16396        }
16397        // Send a broadcast to let everyone know we are done processing
16398        if (pkgList.size() > 0) {
16399            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16400        }
16401    }
16402
16403   /*
16404     * Utility method to unload a list of specified containers
16405     */
16406    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16407        // Just unmount all valid containers.
16408        for (AsecInstallArgs arg : cidArgs) {
16409            synchronized (mInstallLock) {
16410                arg.doPostDeleteLI(false);
16411           }
16412       }
16413   }
16414
16415    /*
16416     * Unload packages mounted on external media. This involves deleting package
16417     * data from internal structures, sending broadcasts about diabled packages,
16418     * gc'ing to free up references, unmounting all secure containers
16419     * corresponding to packages on external media, and posting a
16420     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16421     * that we always have to post this message if status has been requested no
16422     * matter what.
16423     */
16424    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16425            final boolean reportStatus) {
16426        if (DEBUG_SD_INSTALL)
16427            Log.i(TAG, "unloading media packages");
16428        ArrayList<String> pkgList = new ArrayList<String>();
16429        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16430        final Set<AsecInstallArgs> keys = processCids.keySet();
16431        for (AsecInstallArgs args : keys) {
16432            String pkgName = args.getPackageName();
16433            if (DEBUG_SD_INSTALL)
16434                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16435            // Delete package internally
16436            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16437            synchronized (mInstallLock) {
16438                boolean res = deletePackageLI(pkgName, null, false, null, null,
16439                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16440                if (res) {
16441                    pkgList.add(pkgName);
16442                } else {
16443                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16444                    failedList.add(args);
16445                }
16446            }
16447        }
16448
16449        // reader
16450        synchronized (mPackages) {
16451            // We didn't update the settings after removing each package;
16452            // write them now for all packages.
16453            mSettings.writeLPr();
16454        }
16455
16456        // We have to absolutely send UPDATED_MEDIA_STATUS only
16457        // after confirming that all the receivers processed the ordered
16458        // broadcast when packages get disabled, force a gc to clean things up.
16459        // and unload all the containers.
16460        if (pkgList.size() > 0) {
16461            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16462                    new IIntentReceiver.Stub() {
16463                public void performReceive(Intent intent, int resultCode, String data,
16464                        Bundle extras, boolean ordered, boolean sticky,
16465                        int sendingUser) throws RemoteException {
16466                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16467                            reportStatus ? 1 : 0, 1, keys);
16468                    mHandler.sendMessage(msg);
16469                }
16470            });
16471        } else {
16472            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16473                    keys);
16474            mHandler.sendMessage(msg);
16475        }
16476    }
16477
16478    private void loadPrivatePackages(final VolumeInfo vol) {
16479        mHandler.post(new Runnable() {
16480            @Override
16481            public void run() {
16482                loadPrivatePackagesInner(vol);
16483            }
16484        });
16485    }
16486
16487    private void loadPrivatePackagesInner(VolumeInfo vol) {
16488        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16489        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16490
16491        final VersionInfo ver;
16492        final List<PackageSetting> packages;
16493        synchronized (mPackages) {
16494            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16495            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16496        }
16497
16498        for (PackageSetting ps : packages) {
16499            synchronized (mInstallLock) {
16500                final PackageParser.Package pkg;
16501                try {
16502                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16503                    loaded.add(pkg.applicationInfo);
16504                } catch (PackageManagerException e) {
16505                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16506                }
16507
16508                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16509                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16510                }
16511            }
16512        }
16513
16514        synchronized (mPackages) {
16515            int updateFlags = UPDATE_PERMISSIONS_ALL;
16516            if (ver.sdkVersion != mSdkVersion) {
16517                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16518                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16519                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16520            }
16521            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16522
16523            // Yay, everything is now upgraded
16524            ver.forceCurrent();
16525
16526            mSettings.writeLPr();
16527        }
16528
16529        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16530        sendResourcesChangedBroadcast(true, false, loaded, null);
16531    }
16532
16533    private void unloadPrivatePackages(final VolumeInfo vol) {
16534        mHandler.post(new Runnable() {
16535            @Override
16536            public void run() {
16537                unloadPrivatePackagesInner(vol);
16538            }
16539        });
16540    }
16541
16542    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16543        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16544        synchronized (mInstallLock) {
16545        synchronized (mPackages) {
16546            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16547            for (PackageSetting ps : packages) {
16548                if (ps.pkg == null) continue;
16549
16550                final ApplicationInfo info = ps.pkg.applicationInfo;
16551                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16552                if (deletePackageLI(ps.name, null, false, null, null,
16553                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16554                    unloaded.add(info);
16555                } else {
16556                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16557                }
16558            }
16559
16560            mSettings.writeLPr();
16561        }
16562        }
16563
16564        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16565        sendResourcesChangedBroadcast(false, false, unloaded, null);
16566    }
16567
16568    /**
16569     * Examine all users present on given mounted volume, and destroy data
16570     * belonging to users that are no longer valid, or whose user ID has been
16571     * recycled.
16572     */
16573    private void reconcileUsers(String volumeUuid) {
16574        final File[] files = FileUtils
16575                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16576        for (File file : files) {
16577            if (!file.isDirectory()) continue;
16578
16579            final int userId;
16580            final UserInfo info;
16581            try {
16582                userId = Integer.parseInt(file.getName());
16583                info = sUserManager.getUserInfo(userId);
16584            } catch (NumberFormatException e) {
16585                Slog.w(TAG, "Invalid user directory " + file);
16586                continue;
16587            }
16588
16589            boolean destroyUser = false;
16590            if (info == null) {
16591                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16592                        + " because no matching user was found");
16593                destroyUser = true;
16594            } else {
16595                try {
16596                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16597                } catch (IOException e) {
16598                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16599                            + " because we failed to enforce serial number: " + e);
16600                    destroyUser = true;
16601                }
16602            }
16603
16604            if (destroyUser) {
16605                synchronized (mInstallLock) {
16606                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16607                }
16608            }
16609        }
16610
16611        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16612        final UserManager um = mContext.getSystemService(UserManager.class);
16613        for (UserInfo user : um.getUsers()) {
16614            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16615            if (userDir.exists()) continue;
16616
16617            try {
16618                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16619                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16620            } catch (IOException e) {
16621                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16622            }
16623        }
16624    }
16625
16626    /**
16627     * Examine all apps present on given mounted volume, and destroy apps that
16628     * aren't expected, either due to uninstallation or reinstallation on
16629     * another volume.
16630     */
16631    private void reconcileApps(String volumeUuid) {
16632        final File[] files = FileUtils
16633                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16634        for (File file : files) {
16635            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16636                    && !PackageInstallerService.isStageName(file.getName());
16637            if (!isPackage) {
16638                // Ignore entries which are not packages
16639                continue;
16640            }
16641
16642            boolean destroyApp = false;
16643            String packageName = null;
16644            try {
16645                final PackageLite pkg = PackageParser.parsePackageLite(file,
16646                        PackageParser.PARSE_MUST_BE_APK);
16647                packageName = pkg.packageName;
16648
16649                synchronized (mPackages) {
16650                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16651                    if (ps == null) {
16652                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16653                                + volumeUuid + " because we found no install record");
16654                        destroyApp = true;
16655                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16656                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16657                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16658                        destroyApp = true;
16659                    }
16660                }
16661
16662            } catch (PackageParserException e) {
16663                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16664                destroyApp = true;
16665            }
16666
16667            if (destroyApp) {
16668                synchronized (mInstallLock) {
16669                    if (packageName != null) {
16670                        removeDataDirsLI(volumeUuid, packageName);
16671                    }
16672                    if (file.isDirectory()) {
16673                        mInstaller.rmPackageDir(file.getAbsolutePath());
16674                    } else {
16675                        file.delete();
16676                    }
16677                }
16678            }
16679        }
16680    }
16681
16682    private void unfreezePackage(String packageName) {
16683        synchronized (mPackages) {
16684            final PackageSetting ps = mSettings.mPackages.get(packageName);
16685            if (ps != null) {
16686                ps.frozen = false;
16687            }
16688        }
16689    }
16690
16691    @Override
16692    public int movePackage(final String packageName, final String volumeUuid) {
16693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16694
16695        final int moveId = mNextMoveId.getAndIncrement();
16696        mHandler.post(new Runnable() {
16697            @Override
16698            public void run() {
16699                try {
16700                    movePackageInternal(packageName, volumeUuid, moveId);
16701                } catch (PackageManagerException e) {
16702                    Slog.w(TAG, "Failed to move " + packageName, e);
16703                    mMoveCallbacks.notifyStatusChanged(moveId,
16704                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16705                }
16706            }
16707        });
16708        return moveId;
16709    }
16710
16711    private void movePackageInternal(final String packageName, final String volumeUuid,
16712            final int moveId) throws PackageManagerException {
16713        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16714        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16715        final PackageManager pm = mContext.getPackageManager();
16716
16717        final boolean currentAsec;
16718        final String currentVolumeUuid;
16719        final File codeFile;
16720        final String installerPackageName;
16721        final String packageAbiOverride;
16722        final int appId;
16723        final String seinfo;
16724        final String label;
16725
16726        // reader
16727        synchronized (mPackages) {
16728            final PackageParser.Package pkg = mPackages.get(packageName);
16729            final PackageSetting ps = mSettings.mPackages.get(packageName);
16730            if (pkg == null || ps == null) {
16731                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16732            }
16733
16734            if (pkg.applicationInfo.isSystemApp()) {
16735                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16736                        "Cannot move system application");
16737            }
16738
16739            if (pkg.applicationInfo.isExternalAsec()) {
16740                currentAsec = true;
16741                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16742            } else if (pkg.applicationInfo.isForwardLocked()) {
16743                currentAsec = true;
16744                currentVolumeUuid = "forward_locked";
16745            } else {
16746                currentAsec = false;
16747                currentVolumeUuid = ps.volumeUuid;
16748
16749                final File probe = new File(pkg.codePath);
16750                final File probeOat = new File(probe, "oat");
16751                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16752                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16753                            "Move only supported for modern cluster style installs");
16754                }
16755            }
16756
16757            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16759                        "Package already moved to " + volumeUuid);
16760            }
16761
16762            if (ps.frozen) {
16763                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16764                        "Failed to move already frozen package");
16765            }
16766            ps.frozen = true;
16767
16768            codeFile = new File(pkg.codePath);
16769            installerPackageName = ps.installerPackageName;
16770            packageAbiOverride = ps.cpuAbiOverrideString;
16771            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16772            seinfo = pkg.applicationInfo.seinfo;
16773            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16774        }
16775
16776        // Now that we're guarded by frozen state, kill app during move
16777        final long token = Binder.clearCallingIdentity();
16778        try {
16779            killApplication(packageName, appId, "move pkg");
16780        } finally {
16781            Binder.restoreCallingIdentity(token);
16782        }
16783
16784        final Bundle extras = new Bundle();
16785        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16786        extras.putString(Intent.EXTRA_TITLE, label);
16787        mMoveCallbacks.notifyCreated(moveId, extras);
16788
16789        int installFlags;
16790        final boolean moveCompleteApp;
16791        final File measurePath;
16792
16793        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16794            installFlags = INSTALL_INTERNAL;
16795            moveCompleteApp = !currentAsec;
16796            measurePath = Environment.getDataAppDirectory(volumeUuid);
16797        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16798            installFlags = INSTALL_EXTERNAL;
16799            moveCompleteApp = false;
16800            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16801        } else {
16802            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16803            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16804                    || !volume.isMountedWritable()) {
16805                unfreezePackage(packageName);
16806                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16807                        "Move location not mounted private volume");
16808            }
16809
16810            Preconditions.checkState(!currentAsec);
16811
16812            installFlags = INSTALL_INTERNAL;
16813            moveCompleteApp = true;
16814            measurePath = Environment.getDataAppDirectory(volumeUuid);
16815        }
16816
16817        final PackageStats stats = new PackageStats(null, -1);
16818        synchronized (mInstaller) {
16819            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16820                unfreezePackage(packageName);
16821                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16822                        "Failed to measure package size");
16823            }
16824        }
16825
16826        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16827                + stats.dataSize);
16828
16829        final long startFreeBytes = measurePath.getFreeSpace();
16830        final long sizeBytes;
16831        if (moveCompleteApp) {
16832            sizeBytes = stats.codeSize + stats.dataSize;
16833        } else {
16834            sizeBytes = stats.codeSize;
16835        }
16836
16837        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16838            unfreezePackage(packageName);
16839            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16840                    "Not enough free space to move");
16841        }
16842
16843        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16844
16845        final CountDownLatch installedLatch = new CountDownLatch(1);
16846        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16847            @Override
16848            public void onUserActionRequired(Intent intent) throws RemoteException {
16849                throw new IllegalStateException();
16850            }
16851
16852            @Override
16853            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16854                    Bundle extras) throws RemoteException {
16855                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16856                        + PackageManager.installStatusToString(returnCode, msg));
16857
16858                installedLatch.countDown();
16859
16860                // Regardless of success or failure of the move operation,
16861                // always unfreeze the package
16862                unfreezePackage(packageName);
16863
16864                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16865                switch (status) {
16866                    case PackageInstaller.STATUS_SUCCESS:
16867                        mMoveCallbacks.notifyStatusChanged(moveId,
16868                                PackageManager.MOVE_SUCCEEDED);
16869                        break;
16870                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16871                        mMoveCallbacks.notifyStatusChanged(moveId,
16872                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16873                        break;
16874                    default:
16875                        mMoveCallbacks.notifyStatusChanged(moveId,
16876                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16877                        break;
16878                }
16879            }
16880        };
16881
16882        final MoveInfo move;
16883        if (moveCompleteApp) {
16884            // Kick off a thread to report progress estimates
16885            new Thread() {
16886                @Override
16887                public void run() {
16888                    while (true) {
16889                        try {
16890                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16891                                break;
16892                            }
16893                        } catch (InterruptedException ignored) {
16894                        }
16895
16896                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16897                        final int progress = 10 + (int) MathUtils.constrain(
16898                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16899                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16900                    }
16901                }
16902            }.start();
16903
16904            final String dataAppName = codeFile.getName();
16905            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16906                    dataAppName, appId, seinfo);
16907        } else {
16908            move = null;
16909        }
16910
16911        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16912
16913        final Message msg = mHandler.obtainMessage(INIT_COPY);
16914        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16915        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16916                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16917        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16918        msg.obj = params;
16919
16920        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16921                System.identityHashCode(msg.obj));
16922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16923                System.identityHashCode(msg.obj));
16924
16925        mHandler.sendMessage(msg);
16926    }
16927
16928    @Override
16929    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16930        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16931
16932        final int realMoveId = mNextMoveId.getAndIncrement();
16933        final Bundle extras = new Bundle();
16934        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16935        mMoveCallbacks.notifyCreated(realMoveId, extras);
16936
16937        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16938            @Override
16939            public void onCreated(int moveId, Bundle extras) {
16940                // Ignored
16941            }
16942
16943            @Override
16944            public void onStatusChanged(int moveId, int status, long estMillis) {
16945                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16946            }
16947        };
16948
16949        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16950        storage.setPrimaryStorageUuid(volumeUuid, callback);
16951        return realMoveId;
16952    }
16953
16954    @Override
16955    public int getMoveStatus(int moveId) {
16956        mContext.enforceCallingOrSelfPermission(
16957                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16958        return mMoveCallbacks.mLastStatus.get(moveId);
16959    }
16960
16961    @Override
16962    public void registerMoveCallback(IPackageMoveObserver callback) {
16963        mContext.enforceCallingOrSelfPermission(
16964                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16965        mMoveCallbacks.register(callback);
16966    }
16967
16968    @Override
16969    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16970        mContext.enforceCallingOrSelfPermission(
16971                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16972        mMoveCallbacks.unregister(callback);
16973    }
16974
16975    @Override
16976    public boolean setInstallLocation(int loc) {
16977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16978                null);
16979        if (getInstallLocation() == loc) {
16980            return true;
16981        }
16982        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16983                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16984            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16985                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16986            return true;
16987        }
16988        return false;
16989   }
16990
16991    @Override
16992    public int getInstallLocation() {
16993        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16994                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16995                PackageHelper.APP_INSTALL_AUTO);
16996    }
16997
16998    /** Called by UserManagerService */
16999    void cleanUpUser(UserManagerService userManager, int userHandle) {
17000        synchronized (mPackages) {
17001            mDirtyUsers.remove(userHandle);
17002            mUserNeedsBadging.delete(userHandle);
17003            mSettings.removeUserLPw(userHandle);
17004            mPendingBroadcasts.remove(userHandle);
17005            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17006        }
17007        synchronized (mInstallLock) {
17008            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17009            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17010                final String volumeUuid = vol.getFsUuid();
17011                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17012                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17013            }
17014            synchronized (mPackages) {
17015                removeUnusedPackagesLILPw(userManager, userHandle);
17016            }
17017        }
17018    }
17019
17020    /**
17021     * We're removing userHandle and would like to remove any downloaded packages
17022     * that are no longer in use by any other user.
17023     * @param userHandle the user being removed
17024     */
17025    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17026        final boolean DEBUG_CLEAN_APKS = false;
17027        int [] users = userManager.getUserIds();
17028        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17029        while (psit.hasNext()) {
17030            PackageSetting ps = psit.next();
17031            if (ps.pkg == null) {
17032                continue;
17033            }
17034            final String packageName = ps.pkg.packageName;
17035            // Skip over if system app
17036            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17037                continue;
17038            }
17039            if (DEBUG_CLEAN_APKS) {
17040                Slog.i(TAG, "Checking package " + packageName);
17041            }
17042            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17043            if (keep) {
17044                if (DEBUG_CLEAN_APKS) {
17045                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17046                }
17047            } else {
17048                for (int i = 0; i < users.length; i++) {
17049                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17050                        keep = true;
17051                        if (DEBUG_CLEAN_APKS) {
17052                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17053                                    + users[i]);
17054                        }
17055                        break;
17056                    }
17057                }
17058            }
17059            if (!keep) {
17060                if (DEBUG_CLEAN_APKS) {
17061                    Slog.i(TAG, "  Removing package " + packageName);
17062                }
17063                mHandler.post(new Runnable() {
17064                    public void run() {
17065                        deletePackageX(packageName, userHandle, 0);
17066                    } //end run
17067                });
17068            }
17069        }
17070    }
17071
17072    /** Called by UserManagerService */
17073    void createNewUser(int userHandle) {
17074        synchronized (mInstallLock) {
17075            mInstaller.createUserConfig(userHandle);
17076            mSettings.createNewUserLI(this, mInstaller, userHandle);
17077        }
17078        synchronized (mPackages) {
17079            applyFactoryDefaultBrowserLPw(userHandle);
17080            primeDomainVerificationsLPw(userHandle);
17081        }
17082    }
17083
17084    void newUserCreated(final int userHandle) {
17085        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17086        // If permission review for legacy apps is required, we represent
17087        // dagerous permissions for such apps as always granted runtime
17088        // permissions to keep per user flag state whether review is needed.
17089        // Hence, if a new user is added we have to propagate dangerous
17090        // permission grants for these legacy apps.
17091        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17092            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17093                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17094        }
17095    }
17096
17097    @Override
17098    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17099        mContext.enforceCallingOrSelfPermission(
17100                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17101                "Only package verification agents can read the verifier device identity");
17102
17103        synchronized (mPackages) {
17104            return mSettings.getVerifierDeviceIdentityLPw();
17105        }
17106    }
17107
17108    @Override
17109    public void setPermissionEnforced(String permission, boolean enforced) {
17110        // TODO: Now that we no longer change GID for storage, this should to away.
17111        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17112                "setPermissionEnforced");
17113        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17114            synchronized (mPackages) {
17115                if (mSettings.mReadExternalStorageEnforced == null
17116                        || mSettings.mReadExternalStorageEnforced != enforced) {
17117                    mSettings.mReadExternalStorageEnforced = enforced;
17118                    mSettings.writeLPr();
17119                }
17120            }
17121            // kill any non-foreground processes so we restart them and
17122            // grant/revoke the GID.
17123            final IActivityManager am = ActivityManagerNative.getDefault();
17124            if (am != null) {
17125                final long token = Binder.clearCallingIdentity();
17126                try {
17127                    am.killProcessesBelowForeground("setPermissionEnforcement");
17128                } catch (RemoteException e) {
17129                } finally {
17130                    Binder.restoreCallingIdentity(token);
17131                }
17132            }
17133        } else {
17134            throw new IllegalArgumentException("No selective enforcement for " + permission);
17135        }
17136    }
17137
17138    @Override
17139    @Deprecated
17140    public boolean isPermissionEnforced(String permission) {
17141        return true;
17142    }
17143
17144    @Override
17145    public boolean isStorageLow() {
17146        final long token = Binder.clearCallingIdentity();
17147        try {
17148            final DeviceStorageMonitorInternal
17149                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17150            if (dsm != null) {
17151                return dsm.isMemoryLow();
17152            } else {
17153                return false;
17154            }
17155        } finally {
17156            Binder.restoreCallingIdentity(token);
17157        }
17158    }
17159
17160    @Override
17161    public IPackageInstaller getPackageInstaller() {
17162        return mInstallerService;
17163    }
17164
17165    private boolean userNeedsBadging(int userId) {
17166        int index = mUserNeedsBadging.indexOfKey(userId);
17167        if (index < 0) {
17168            final UserInfo userInfo;
17169            final long token = Binder.clearCallingIdentity();
17170            try {
17171                userInfo = sUserManager.getUserInfo(userId);
17172            } finally {
17173                Binder.restoreCallingIdentity(token);
17174            }
17175            final boolean b;
17176            if (userInfo != null && userInfo.isManagedProfile()) {
17177                b = true;
17178            } else {
17179                b = false;
17180            }
17181            mUserNeedsBadging.put(userId, b);
17182            return b;
17183        }
17184        return mUserNeedsBadging.valueAt(index);
17185    }
17186
17187    @Override
17188    public KeySet getKeySetByAlias(String packageName, String alias) {
17189        if (packageName == null || alias == null) {
17190            return null;
17191        }
17192        synchronized(mPackages) {
17193            final PackageParser.Package pkg = mPackages.get(packageName);
17194            if (pkg == null) {
17195                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17196                throw new IllegalArgumentException("Unknown package: " + packageName);
17197            }
17198            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17199            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17200        }
17201    }
17202
17203    @Override
17204    public KeySet getSigningKeySet(String packageName) {
17205        if (packageName == null) {
17206            return null;
17207        }
17208        synchronized(mPackages) {
17209            final PackageParser.Package pkg = mPackages.get(packageName);
17210            if (pkg == null) {
17211                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17212                throw new IllegalArgumentException("Unknown package: " + packageName);
17213            }
17214            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17215                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17216                throw new SecurityException("May not access signing KeySet of other apps.");
17217            }
17218            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17219            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17220        }
17221    }
17222
17223    @Override
17224    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17225        if (packageName == null || ks == null) {
17226            return false;
17227        }
17228        synchronized(mPackages) {
17229            final PackageParser.Package pkg = mPackages.get(packageName);
17230            if (pkg == null) {
17231                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17232                throw new IllegalArgumentException("Unknown package: " + packageName);
17233            }
17234            IBinder ksh = ks.getToken();
17235            if (ksh instanceof KeySetHandle) {
17236                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17237                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17238            }
17239            return false;
17240        }
17241    }
17242
17243    @Override
17244    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17245        if (packageName == null || ks == null) {
17246            return false;
17247        }
17248        synchronized(mPackages) {
17249            final PackageParser.Package pkg = mPackages.get(packageName);
17250            if (pkg == null) {
17251                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17252                throw new IllegalArgumentException("Unknown package: " + packageName);
17253            }
17254            IBinder ksh = ks.getToken();
17255            if (ksh instanceof KeySetHandle) {
17256                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17257                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17258            }
17259            return false;
17260        }
17261    }
17262
17263    private void deletePackageIfUnusedLPr(final String packageName) {
17264        PackageSetting ps = mSettings.mPackages.get(packageName);
17265        if (ps == null) {
17266            return;
17267        }
17268        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17269            // TODO Implement atomic delete if package is unused
17270            // It is currently possible that the package will be deleted even if it is installed
17271            // after this method returns.
17272            mHandler.post(new Runnable() {
17273                public void run() {
17274                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17275                }
17276            });
17277        }
17278    }
17279
17280    /**
17281     * Check and throw if the given before/after packages would be considered a
17282     * downgrade.
17283     */
17284    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17285            throws PackageManagerException {
17286        if (after.versionCode < before.mVersionCode) {
17287            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17288                    "Update version code " + after.versionCode + " is older than current "
17289                    + before.mVersionCode);
17290        } else if (after.versionCode == before.mVersionCode) {
17291            if (after.baseRevisionCode < before.baseRevisionCode) {
17292                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17293                        "Update base revision code " + after.baseRevisionCode
17294                        + " is older than current " + before.baseRevisionCode);
17295            }
17296
17297            if (!ArrayUtils.isEmpty(after.splitNames)) {
17298                for (int i = 0; i < after.splitNames.length; i++) {
17299                    final String splitName = after.splitNames[i];
17300                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17301                    if (j != -1) {
17302                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17303                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17304                                    "Update split " + splitName + " revision code "
17305                                    + after.splitRevisionCodes[i] + " is older than current "
17306                                    + before.splitRevisionCodes[j]);
17307                        }
17308                    }
17309                }
17310            }
17311        }
17312    }
17313
17314    private static class MoveCallbacks extends Handler {
17315        private static final int MSG_CREATED = 1;
17316        private static final int MSG_STATUS_CHANGED = 2;
17317
17318        private final RemoteCallbackList<IPackageMoveObserver>
17319                mCallbacks = new RemoteCallbackList<>();
17320
17321        private final SparseIntArray mLastStatus = new SparseIntArray();
17322
17323        public MoveCallbacks(Looper looper) {
17324            super(looper);
17325        }
17326
17327        public void register(IPackageMoveObserver callback) {
17328            mCallbacks.register(callback);
17329        }
17330
17331        public void unregister(IPackageMoveObserver callback) {
17332            mCallbacks.unregister(callback);
17333        }
17334
17335        @Override
17336        public void handleMessage(Message msg) {
17337            final SomeArgs args = (SomeArgs) msg.obj;
17338            final int n = mCallbacks.beginBroadcast();
17339            for (int i = 0; i < n; i++) {
17340                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17341                try {
17342                    invokeCallback(callback, msg.what, args);
17343                } catch (RemoteException ignored) {
17344                }
17345            }
17346            mCallbacks.finishBroadcast();
17347            args.recycle();
17348        }
17349
17350        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17351                throws RemoteException {
17352            switch (what) {
17353                case MSG_CREATED: {
17354                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17355                    break;
17356                }
17357                case MSG_STATUS_CHANGED: {
17358                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17359                    break;
17360                }
17361            }
17362        }
17363
17364        private void notifyCreated(int moveId, Bundle extras) {
17365            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17366
17367            final SomeArgs args = SomeArgs.obtain();
17368            args.argi1 = moveId;
17369            args.arg2 = extras;
17370            obtainMessage(MSG_CREATED, args).sendToTarget();
17371        }
17372
17373        private void notifyStatusChanged(int moveId, int status) {
17374            notifyStatusChanged(moveId, status, -1);
17375        }
17376
17377        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17378            Slog.v(TAG, "Move " + moveId + " status " + status);
17379
17380            final SomeArgs args = SomeArgs.obtain();
17381            args.argi1 = moveId;
17382            args.argi2 = status;
17383            args.arg3 = estMillis;
17384            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17385
17386            synchronized (mLastStatus) {
17387                mLastStatus.put(moveId, status);
17388            }
17389        }
17390    }
17391
17392    private final static class OnPermissionChangeListeners extends Handler {
17393        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17394
17395        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17396                new RemoteCallbackList<>();
17397
17398        public OnPermissionChangeListeners(Looper looper) {
17399            super(looper);
17400        }
17401
17402        @Override
17403        public void handleMessage(Message msg) {
17404            switch (msg.what) {
17405                case MSG_ON_PERMISSIONS_CHANGED: {
17406                    final int uid = msg.arg1;
17407                    handleOnPermissionsChanged(uid);
17408                } break;
17409            }
17410        }
17411
17412        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17413            mPermissionListeners.register(listener);
17414
17415        }
17416
17417        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17418            mPermissionListeners.unregister(listener);
17419        }
17420
17421        public void onPermissionsChanged(int uid) {
17422            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17423                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17424            }
17425        }
17426
17427        private void handleOnPermissionsChanged(int uid) {
17428            final int count = mPermissionListeners.beginBroadcast();
17429            try {
17430                for (int i = 0; i < count; i++) {
17431                    IOnPermissionsChangeListener callback = mPermissionListeners
17432                            .getBroadcastItem(i);
17433                    try {
17434                        callback.onPermissionsChanged(uid);
17435                    } catch (RemoteException e) {
17436                        Log.e(TAG, "Permission listener is dead", e);
17437                    }
17438                }
17439            } finally {
17440                mPermissionListeners.finishBroadcast();
17441            }
17442        }
17443    }
17444
17445    private class PackageManagerInternalImpl extends PackageManagerInternal {
17446        @Override
17447        public void setLocationPackagesProvider(PackagesProvider provider) {
17448            synchronized (mPackages) {
17449                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17450            }
17451        }
17452
17453        @Override
17454        public void setImePackagesProvider(PackagesProvider provider) {
17455            synchronized (mPackages) {
17456                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17457            }
17458        }
17459
17460        @Override
17461        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17462            synchronized (mPackages) {
17463                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17464            }
17465        }
17466
17467        @Override
17468        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17469            synchronized (mPackages) {
17470                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17471            }
17472        }
17473
17474        @Override
17475        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17476            synchronized (mPackages) {
17477                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17478            }
17479        }
17480
17481        @Override
17482        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17483            synchronized (mPackages) {
17484                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17485            }
17486        }
17487
17488        @Override
17489        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17490            synchronized (mPackages) {
17491                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17492            }
17493        }
17494
17495        @Override
17496        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17497            synchronized (mPackages) {
17498                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17499                        packageName, userId);
17500            }
17501        }
17502
17503        @Override
17504        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17505            synchronized (mPackages) {
17506                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17507                        packageName, userId);
17508            }
17509        }
17510
17511        @Override
17512        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17513            synchronized (mPackages) {
17514                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17515                        packageName, userId);
17516            }
17517        }
17518
17519        @Override
17520        public void setKeepUninstalledPackages(final List<String> packageList) {
17521            Preconditions.checkNotNull(packageList);
17522            List<String> removedFromList = null;
17523            synchronized (mPackages) {
17524                if (mKeepUninstalledPackages != null) {
17525                    final int packagesCount = mKeepUninstalledPackages.size();
17526                    for (int i = 0; i < packagesCount; i++) {
17527                        String oldPackage = mKeepUninstalledPackages.get(i);
17528                        if (packageList != null && packageList.contains(oldPackage)) {
17529                            continue;
17530                        }
17531                        if (removedFromList == null) {
17532                            removedFromList = new ArrayList<>();
17533                        }
17534                        removedFromList.add(oldPackage);
17535                    }
17536                }
17537                mKeepUninstalledPackages = new ArrayList<>(packageList);
17538                if (removedFromList != null) {
17539                    final int removedCount = removedFromList.size();
17540                    for (int i = 0; i < removedCount; i++) {
17541                        deletePackageIfUnusedLPr(removedFromList.get(i));
17542                    }
17543                }
17544            }
17545        }
17546
17547        @Override
17548        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17549            synchronized (mPackages) {
17550                // If we do not support permission review, done.
17551                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17552                    return false;
17553                }
17554
17555                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17556                if (packageSetting == null) {
17557                    return false;
17558                }
17559
17560                // Permission review applies only to apps not supporting the new permission model.
17561                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17562                    return false;
17563                }
17564
17565                // Legacy apps have the permission and get user consent on launch.
17566                PermissionsState permissionsState = packageSetting.getPermissionsState();
17567                return permissionsState.isPermissionReviewRequired(userId);
17568            }
17569        }
17570    }
17571
17572    @Override
17573    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17574        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17575        synchronized (mPackages) {
17576            final long identity = Binder.clearCallingIdentity();
17577            try {
17578                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17579                        packageNames, userId);
17580            } finally {
17581                Binder.restoreCallingIdentity(identity);
17582            }
17583        }
17584    }
17585
17586    private static void enforceSystemOrPhoneCaller(String tag) {
17587        int callingUid = Binder.getCallingUid();
17588        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17589            throw new SecurityException(
17590                    "Cannot call " + tag + " from UID " + callingUid);
17591        }
17592    }
17593}
17594